blob: d3969f70980981068b93318b8950a0227fdc5968 [file] [log] [blame]
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001//===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file is a part of AddressSanitizer, an address sanity checker.
11// Details of the algorithm:
12// http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm
13//
14//===----------------------------------------------------------------------===//
15
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000016#include "llvm/ADT/ArrayRef.h"
Alexey Samsonov29dd7f22012-12-27 08:50:58 +000017#include "llvm/ADT/DenseMap.h"
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +000018#include "llvm/ADT/DepthFirstIterator.h"
Kuba Brecka8ec94ea2015-07-22 10:25:38 +000019#include "llvm/ADT/SetVector.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000020#include "llvm/ADT/SmallSet.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000021#include "llvm/ADT/SmallVector.h"
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +000022#include "llvm/ADT/Statistic.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000023#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanov617232f2012-05-23 11:52:12 +000024#include "llvm/ADT/Triple.h"
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000025#include "llvm/Analysis/MemoryBuiltins.h"
26#include "llvm/Analysis/TargetLibraryInfo.h"
27#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000028#include "llvm/IR/CallSite.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000029#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/DataLayout.h"
Yury Gribov3ae427d2014-12-01 08:47:58 +000031#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/Function.h"
33#include "llvm/IR/IRBuilder.h"
34#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000035#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000036#include "llvm/IR/IntrinsicInst.h"
37#include "llvm/IR/LLVMContext.h"
Kostya Serebryany714c67c2014-01-17 11:00:30 +000038#include "llvm/IR/MDBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/Module.h"
40#include "llvm/IR/Type.h"
Kuba Brecka1001bb52014-12-05 22:19:18 +000041#include "llvm/MC/MCSectionMachO.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000042#include "llvm/Support/CommandLine.h"
43#include "llvm/Support/DataTypes.h"
44#include "llvm/Support/Debug.h"
Kostya Serebryany9e62b302013-06-03 14:46:56 +000045#include "llvm/Support/Endian.h"
Yury Gribov55441bb2014-11-21 10:29:50 +000046#include "llvm/Support/SwapByteOrder.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000047#include "llvm/Support/raw_ostream.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000048#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany351b0782014-09-03 22:37:37 +000049#include "llvm/Transforms/Scalar.h"
Kostya Serebryany4fb78012013-12-06 09:00:17 +000050#include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000051#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Kostya Serebryany9f5213f2013-06-26 09:18:17 +000052#include "llvm/Transforms/Utils/Cloning.h"
Alexey Samsonov3d43b632012-12-12 14:31:53 +000053#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000054#include "llvm/Transforms/Utils/ModuleUtils.h"
Anna Zaks8ed1d812015-02-27 03:12:36 +000055#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000056#include <algorithm>
Chandler Carruthed0881b2012-12-03 16:50:05 +000057#include <string>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000058#include <system_error>
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000059
60using namespace llvm;
61
Chandler Carruth964daaa2014-04-22 02:55:47 +000062#define DEBUG_TYPE "asan"
63
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000064static const uint64_t kDefaultShadowScale = 3;
65static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
66static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Anna Zaks3b50e702016-02-02 22:05:07 +000067static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
68static const uint64_t kIOSShadowOffset64 = 0x120200000;
69static const uint64_t kIOSSimShadowOffset32 = 1ULL << 30;
70static const uint64_t kIOSSimShadowOffset64 = kDefaultShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +000071static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +000072static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;
Kostya Serebryany4766fe62013-01-23 12:54:55 +000073static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
Kostya Serebryanyc5bd9812014-11-04 19:46:15 +000074static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
Kumar Sukhani9559a5c2015-01-31 10:43:18 +000075static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
Renato Golinaf213722015-02-03 11:20:45 +000076static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
Kostya Serebryany8baa3862014-02-10 07:37:04 +000077static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
78static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
Timur Iskhodzhanovb4b6b742015-01-22 12:24:21 +000079static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000080
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000081static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000082static const size_t kMaxStackMallocSize = 1 << 16; // 64K
83static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
84static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
85
Craig Topperd3a34f82013-07-16 01:17:10 +000086static const char *const kAsanModuleCtorName = "asan.module_ctor";
87static const char *const kAsanModuleDtorName = "asan.module_dtor";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000088static const uint64_t kAsanCtorAndDtorPriority = 1;
Craig Topperd3a34f82013-07-16 01:17:10 +000089static const char *const kAsanReportErrorTemplate = "__asan_report_";
Craig Topperd3a34f82013-07-16 01:17:10 +000090static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonovf52b7172013-08-05 13:19:49 +000091static const char *const kAsanUnregisterGlobalsName =
92 "__asan_unregister_globals";
Ryan Govostes653f9d02016-03-28 20:28:57 +000093static const char *const kAsanRegisterImageGlobalsName =
94 "__asan_register_image_globals";
95static const char *const kAsanUnregisterImageGlobalsName =
96 "__asan_unregister_image_globals";
Craig Topperd3a34f82013-07-16 01:17:10 +000097static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
98static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Kuba Brecka45dbffd2015-07-23 10:54:06 +000099static const char *const kAsanInitName = "__asan_init";
100static const char *const kAsanVersionCheckName =
Ryan Govostes653f9d02016-03-28 20:28:57 +0000101 "__asan_version_mismatch_check_v8";
Kostya Serebryany796f6552014-02-27 12:45:36 +0000102static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
103static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
Craig Topperd3a34f82013-07-16 01:17:10 +0000104static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000105static const int kMaxAsanStackMallocSizeClass = 10;
Kostya Serebryany6805de52013-09-10 13:16:56 +0000106static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
107static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000108static const char *const kAsanGenPrefix = "__asan_gen_";
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000109static const char *const kODRGenPrefix = "__odr_asan_gen_";
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000110static const char *const kSanCovGenPrefix = "__sancov_gen_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000111static const char *const kAsanPoisonStackMemoryName =
112 "__asan_poison_stack_memory";
113static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonov261177a2012-12-04 01:34:23 +0000114 "__asan_unpoison_stack_memory";
Ryan Govostes653f9d02016-03-28 20:28:57 +0000115static const char *const kAsanGlobalsRegisteredFlagName =
116 "__asan_globals_registered";
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000117
Kostya Serebryanyf3223822013-09-18 14:07:14 +0000118static const char *const kAsanOptionDetectUAR =
119 "__asan_option_detect_stack_use_after_return";
120
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000121static const char *const kAsanAllocaPoison = "__asan_alloca_poison";
122static const char *const kAsanAllocasUnpoison = "__asan_allocas_unpoison";
Yury Gribov98b18592015-05-28 07:51:49 +0000123
Kostya Serebryany874dae62012-07-16 16:15:40 +0000124// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
125static const size_t kNumberOfAccessSizes = 5;
126
Yury Gribov55441bb2014-11-21 10:29:50 +0000127static const unsigned kAllocaRzSize = 32;
Yury Gribov55441bb2014-11-21 10:29:50 +0000128
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000129// Command-line flags.
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000130static cl::opt<bool> ClEnableKasan(
131 "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
132 cl::Hidden, cl::init(false));
Yury Gribovd7731982015-11-11 10:36:49 +0000133static cl::opt<bool> ClRecover(
134 "asan-recover",
135 cl::desc("Enable recovery mode (continue-after-error)."),
136 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000137
138// This flag may need to be replaced with -f[no-]asan-reads.
139static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000140 cl::desc("instrument read instructions"),
141 cl::Hidden, cl::init(true));
142static cl::opt<bool> ClInstrumentWrites(
143 "asan-instrument-writes", cl::desc("instrument write instructions"),
144 cl::Hidden, cl::init(true));
145static cl::opt<bool> ClInstrumentAtomics(
146 "asan-instrument-atomics",
147 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
148 cl::init(true));
149static cl::opt<bool> ClAlwaysSlowPath(
150 "asan-always-slow-path",
151 cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
152 cl::init(false));
Kostya Serebryany874dae62012-07-16 16:15:40 +0000153// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-06-28 09:34:41 +0000154// in any given BB. Normally, this should be set to unlimited (INT_MAX),
155// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
156// set it to 10000.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000157static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
158 "asan-max-ins-per-bb", cl::init(10000),
159 cl::desc("maximal number of instructions to instrument in any given BB"),
160 cl::Hidden);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000161// This flag may need to be replaced with -f[no]asan-stack.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000162static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
163 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000164static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000165 cl::desc("Check return-after-free"),
166 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000167// This flag may need to be replaced with -f[no]asan-globals.
168static cl::opt<bool> ClGlobals("asan-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000169 cl::desc("Handle global objects"), cl::Hidden,
170 cl::init(true));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000171static cl::opt<bool> ClInitializers("asan-initialization-order",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000172 cl::desc("Handle C++ initializer order"),
173 cl::Hidden, cl::init(true));
174static cl::opt<bool> ClInvalidPointerPairs(
175 "asan-detect-invalid-pointer-pair",
176 cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
177 cl::init(false));
178static cl::opt<unsigned> ClRealignStack(
179 "asan-realign-stack",
180 cl::desc("Realign stack to the value of this flag (power of two)"),
181 cl::Hidden, cl::init(32));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000182static cl::opt<int> ClInstrumentationWithCallsThreshold(
183 "asan-instrumentation-with-call-threshold",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000184 cl::desc(
185 "If the function being instrumented contains more than "
186 "this number of memory accesses, use callbacks instead of "
187 "inline checks (-1 means never use callbacks)."),
188 cl::Hidden, cl::init(7000));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000189static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000190 "asan-memory-access-callback-prefix",
191 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
192 cl::init("__asan_"));
Yury Gribov55441bb2014-11-21 10:29:50 +0000193static cl::opt<bool> ClInstrumentAllocas("asan-instrument-allocas",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000194 cl::desc("instrument dynamic allocas"),
Alexey Samsonovf4fb5f52015-10-22 20:07:28 +0000195 cl::Hidden, cl::init(true));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000196static cl::opt<bool> ClSkipPromotableAllocas(
197 "asan-skip-promotable-allocas",
198 cl::desc("Do not instrument promotable allocas"), cl::Hidden,
199 cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000200
201// These flags allow to change the shadow mapping.
202// The shadow mapping looks like
203// Shadow = (Mem >> scale) + (1 << offset_log)
204static cl::opt<int> ClMappingScale("asan-mapping-scale",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000205 cl::desc("scale of asan shadow mapping"),
206 cl::Hidden, cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000207
208// Optimization flags. Not user visible, used mostly for testing
209// and benchmarking the tool.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000210static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
211 cl::Hidden, cl::init(true));
212static cl::opt<bool> ClOptSameTemp(
213 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
214 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000215static cl::opt<bool> ClOptGlobals("asan-opt-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000216 cl::desc("Don't instrument scalar globals"),
217 cl::Hidden, cl::init(true));
218static cl::opt<bool> ClOptStack(
219 "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
220 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000221
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000222static cl::opt<bool> ClCheckLifetime(
223 "asan-check-lifetime",
224 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"), cl::Hidden,
225 cl::init(false));
Alexey Samsonovdf624522012-11-29 18:14:24 +0000226
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000227static cl::opt<bool> ClDynamicAllocaStack(
228 "asan-stack-dynamic-alloca",
229 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
Alexey Samsonov19763c42015-02-05 19:39:20 +0000230 cl::init(true));
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000231
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000232static cl::opt<uint32_t> ClForceExperiment(
233 "asan-force-experiment",
234 cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
235 cl::init(0));
236
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000237static cl::opt<bool>
238 ClUsePrivateAliasForGlobals("asan-use-private-alias",
239 cl::desc("Use private aliases for global"
240 " variables"),
241 cl::Hidden, cl::init(false));
242
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000243// Debug flags.
244static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
245 cl::init(0));
246static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
247 cl::Hidden, cl::init(0));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000248static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
249 cl::desc("Debug func"));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000250static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
251 cl::Hidden, cl::init(-1));
252static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
253 cl::Hidden, cl::init(-1));
254
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000255STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
256STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000257STATISTIC(NumOptimizedAccessesToGlobalVar,
258 "Number of optimized accesses to global vars");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000259STATISTIC(NumOptimizedAccessesToStackVar,
260 "Number of optimized accesses to stack vars");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000261
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000262namespace {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000263/// Frontend-provided metadata for source location.
264struct LocationMetadata {
265 StringRef Filename;
266 int LineNo;
267 int ColumnNo;
268
269 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
270
271 bool empty() const { return Filename.empty(); }
272
273 void parse(MDNode *MDN) {
274 assert(MDN->getNumOperands() == 3);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000275 MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
276 Filename = DIFilename->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000277 LineNo =
278 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
279 ColumnNo =
280 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000281 }
282};
283
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000284/// Frontend-provided metadata for global variables.
285class GlobalsMetadata {
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000286 public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000287 struct Entry {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000288 Entry() : SourceLoc(), Name(), IsDynInit(false), IsBlacklisted(false) {}
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000289 LocationMetadata SourceLoc;
290 StringRef Name;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000291 bool IsDynInit;
292 bool IsBlacklisted;
293 };
294
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000295 GlobalsMetadata() : inited_(false) {}
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000296
Keno Fischere03fae42015-12-05 14:42:34 +0000297 void reset() {
298 inited_ = false;
299 Entries.clear();
300 }
301
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000302 void init(Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000303 assert(!inited_);
304 inited_ = true;
305 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000306 if (!Globals) return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000307 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000308 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000309 assert(MDN->getNumOperands() == 5);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000310 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000311 // The optimizer may optimize away a global entirely.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000312 if (!GV) continue;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000313 // We can already have an entry for GV if it was merged with another
314 // global.
315 Entry &E = Entries[GV];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000316 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
317 E.SourceLoc.parse(Loc);
318 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
319 E.Name = Name->getString();
320 ConstantInt *IsDynInit =
321 mdconst::extract<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000322 E.IsDynInit |= IsDynInit->isOne();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000323 ConstantInt *IsBlacklisted =
324 mdconst::extract<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000325 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000326 }
327 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000328
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000329 /// Returns metadata entry for a given global.
330 Entry get(GlobalVariable *G) const {
331 auto Pos = Entries.find(G);
332 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000333 }
334
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000335 private:
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000336 bool inited_;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000337 DenseMap<GlobalVariable *, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000338};
339
Alexey Samsonov1345d352013-01-16 13:23:28 +0000340/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000341/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000342struct ShadowMapping {
343 int Scale;
344 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000345 bool OrShadowOffset;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000346};
347
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000348static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
349 bool IsKasan) {
Evgeniy Stepanov5fe279e2015-10-08 21:21:24 +0000350 bool IsAndroid = TargetTriple.isAndroid();
Anna Zaks3b50e702016-02-02 22:05:07 +0000351 bool IsIOS = TargetTriple.isiOS() || TargetTriple.isWatchOS();
Simon Pilgrima2794102014-11-22 19:12:10 +0000352 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
353 bool IsLinux = TargetTriple.isOSLinux();
Bill Schmidt0a9170d2013-07-26 01:35:43 +0000354 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
355 TargetTriple.getArch() == llvm::Triple::ppc64le;
Anna Zaks3b50e702016-02-02 22:05:07 +0000356 bool IsX86 = TargetTriple.getArch() == llvm::Triple::x86;
Kostya Serebryanybe733372013-02-12 11:11:02 +0000357 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany9e62b302013-06-03 14:46:56 +0000358 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
359 TargetTriple.getArch() == llvm::Triple::mipsel;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000360 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
361 TargetTriple.getArch() == llvm::Triple::mips64el;
Renato Golinaf213722015-02-03 11:20:45 +0000362 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000363 bool IsWindows = TargetTriple.isOSWindows();
Alexey Samsonov1345d352013-01-16 13:23:28 +0000364
365 ShadowMapping Mapping;
366
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000367 if (LongSize == 32) {
Evgeniy Stepanov9cb08f82015-07-17 23:51:18 +0000368 // Android is always PIE, which means that the beginning of the address
369 // space is always available.
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000370 if (IsAndroid)
371 Mapping.Offset = 0;
372 else if (IsMIPS32)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000373 Mapping.Offset = kMIPS32_ShadowOffset32;
374 else if (IsFreeBSD)
375 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000376 else if (IsIOS)
Anna Zaks3b50e702016-02-02 22:05:07 +0000377 // If we're targeting iOS and x86, the binary is built for iOS simulator.
378 Mapping.Offset = IsX86 ? kIOSSimShadowOffset32 : kIOSShadowOffset32;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000379 else if (IsWindows)
380 Mapping.Offset = kWindowsShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000381 else
382 Mapping.Offset = kDefaultShadowOffset32;
383 } else { // LongSize == 64
384 if (IsPPC64)
385 Mapping.Offset = kPPC64_ShadowOffset64;
386 else if (IsFreeBSD)
387 Mapping.Offset = kFreeBSD_ShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000388 else if (IsLinux && IsX86_64) {
389 if (IsKasan)
390 Mapping.Offset = kLinuxKasan_ShadowOffset64;
391 else
392 Mapping.Offset = kSmallX86_64ShadowOffset;
393 } else if (IsMIPS64)
Kostya Serebryany231bd082014-11-11 23:02:57 +0000394 Mapping.Offset = kMIPS64_ShadowOffset64;
Anna Zaks3b50e702016-02-02 22:05:07 +0000395 else if (IsIOS)
396 // If we're targeting iOS and x86, the binary is built for iOS simulator.
397 Mapping.Offset = IsX86_64 ? kIOSSimShadowOffset64 : kIOSShadowOffset64;
Renato Golinaf213722015-02-03 11:20:45 +0000398 else if (IsAArch64)
399 Mapping.Offset = kAArch64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000400 else
401 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000402 }
403
404 Mapping.Scale = kDefaultShadowScale;
405 if (ClMappingScale) {
406 Mapping.Scale = ClMappingScale;
407 }
408
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000409 // OR-ing shadow offset if more efficient (at least on x86) if the offset
410 // is a power of two, but on ppc64 we have to use add since the shadow
411 // offset is not necessary 1/8-th of the address space.
Adhemerval Zanella35891fe2015-11-09 18:03:48 +0000412 Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64
413 && !(Mapping.Offset & (Mapping.Offset - 1));
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000414
Alexey Samsonov1345d352013-01-16 13:23:28 +0000415 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000416}
417
Alexey Samsonov1345d352013-01-16 13:23:28 +0000418static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000419 // Redzone used for stack and globals is at least 32 bytes.
420 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000421 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000422}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000423
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000424/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000425struct AddressSanitizer : public FunctionPass {
Yury Gribovd7731982015-11-11 10:36:49 +0000426 explicit AddressSanitizer(bool CompileKernel = false, bool Recover = false)
427 : FunctionPass(ID), CompileKernel(CompileKernel || ClEnableKasan),
428 Recover(Recover || ClRecover) {
Yury Gribov3ae427d2014-12-01 08:47:58 +0000429 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
430 }
Craig Topper3e4c6972014-03-05 09:10:37 +0000431 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000432 return "AddressSanitizerFunctionPass";
433 }
Yury Gribov3ae427d2014-12-01 08:47:58 +0000434 void getAnalysisUsage(AnalysisUsage &AU) const override {
435 AU.addRequired<DominatorTreeWrapperPass>();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000436 AU.addRequired<TargetLibraryInfoWrapperPass>();
Yury Gribov3ae427d2014-12-01 08:47:58 +0000437 }
Anna Zaks8ed1d812015-02-27 03:12:36 +0000438 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
439 Type *Ty = AI->getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000440 uint64_t SizeInBytes =
441 AI->getModule()->getDataLayout().getTypeAllocSize(Ty);
Anna Zaks8ed1d812015-02-27 03:12:36 +0000442 return SizeInBytes;
443 }
444 /// Check if we want (and can) handle this alloca.
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000445 bool isInterestingAlloca(AllocaInst &AI);
Yury Gribov98b18592015-05-28 07:51:49 +0000446
447 // Check if we have dynamic alloca.
448 bool isDynamicAlloca(AllocaInst &AI) const {
449 return AI.isArrayAllocation() || !AI.isStaticAlloca();
450 }
451
Anna Zaks8ed1d812015-02-27 03:12:36 +0000452 /// If it is an interesting memory access, return the PointerOperand
453 /// and set IsWrite/Alignment. Otherwise return nullptr.
454 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000455 uint64_t *TypeSize, unsigned *Alignment);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000456 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000457 bool UseCalls, const DataLayout &DL);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000458 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000459 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
460 Value *Addr, uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000461 Value *SizeArgument, bool UseCalls, uint32_t Exp);
462 void instrumentUnusualSizeOrAlignment(Instruction *I, Value *Addr,
463 uint32_t TypeSize, bool IsWrite,
464 Value *SizeArgument, bool UseCalls,
465 uint32_t Exp);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000466 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
467 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000468 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000469 bool IsWrite, size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000470 Value *SizeArgument, uint32_t Exp);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000471 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000472 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000473 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000474 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Reid Kleckner2f907552015-07-21 17:40:14 +0000475 void markEscapedLocalAllocas(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000476 bool doInitialization(Module &M) override;
Keno Fischere03fae42015-12-05 14:42:34 +0000477 bool doFinalization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000478 static char ID; // Pass identification, replacement for typeid
479
Yury Gribov3ae427d2014-12-01 08:47:58 +0000480 DominatorTree &getDominatorTree() const { return *DT; }
481
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000482 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000483 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000484
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000485 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000486 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000487 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
488 uint64_t TypeSize) const;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000489
Reid Kleckner2f907552015-07-21 17:40:14 +0000490 /// Helper to cleanup per-function state.
491 struct FunctionStateRAII {
492 AddressSanitizer *Pass;
493 FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
494 assert(Pass->ProcessedAllocas.empty() &&
495 "last pass forgot to clear cache");
496 }
497 ~FunctionStateRAII() { Pass->ProcessedAllocas.clear(); }
498 };
499
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000500 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000501 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000502 int LongSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000503 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000504 bool Recover;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000505 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000506 ShadowMapping Mapping;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000507 DominatorTree *DT;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000508 Function *AsanCtorFunction = nullptr;
509 Function *AsanInitFunction = nullptr;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000510 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000511 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000512 // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
513 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
514 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
515 // This array is indexed by AccessIsWrite and Experiment.
516 Function *AsanErrorCallbackSized[2][2];
517 Function *AsanMemoryAccessCallbackSized[2][2];
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000518 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000519 InlineAsm *EmptyAsm;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000520 GlobalsMetadata GlobalsMD;
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000521 DenseMap<AllocaInst *, bool> ProcessedAllocas;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000522
523 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000524};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000525
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000526class AddressSanitizerModule : public ModulePass {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000527 public:
Yury Gribovd7731982015-11-11 10:36:49 +0000528 explicit AddressSanitizerModule(bool CompileKernel = false,
529 bool Recover = false)
530 : ModulePass(ID), CompileKernel(CompileKernel || ClEnableKasan),
531 Recover(Recover || ClRecover) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000532 bool runOnModule(Module &M) override;
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000533 static char ID; // Pass identification, replacement for typeid
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000534 const char *getPassName() const override { return "AddressSanitizerModule"; }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000535
Kostya Serebryany20a79972012-11-22 03:18:50 +0000536 private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000537 void initializeCallbacks(Module &M);
538
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +0000539 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000540 bool ShouldInstrumentGlobal(GlobalVariable *G);
Ryan Govostes653f9d02016-03-28 20:28:57 +0000541 bool ShouldUseMachOGlobalsSection() const;
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000542 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000543 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000544 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000545 return RedzoneSizeForScale(Mapping.Scale);
546 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000547
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000548 GlobalsMetadata GlobalsMD;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000549 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000550 bool Recover;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000551 Type *IntptrTy;
552 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000553 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000554 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000555 Function *AsanPoisonGlobals;
556 Function *AsanUnpoisonGlobals;
557 Function *AsanRegisterGlobals;
558 Function *AsanUnregisterGlobals;
Ryan Govostes653f9d02016-03-28 20:28:57 +0000559 Function *AsanRegisterImageGlobals;
560 Function *AsanUnregisterImageGlobals;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000561};
562
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000563// Stack poisoning does not play well with exception handling.
564// When an exception is thrown, we essentially bypass the code
565// that unpoisones the stack. This is why the run-time library has
566// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
567// stack in the interceptor. This however does not work inside the
568// actual function which catches the exception. Most likely because the
569// compiler hoists the load of the shadow value somewhere too high.
570// This causes asan to report a non-existing bug on 453.povray.
571// It sounds like an LLVM bug.
572struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
573 Function &F;
574 AddressSanitizer &ASan;
575 DIBuilder DIB;
576 LLVMContext *C;
577 Type *IntptrTy;
578 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000579 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000580
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000581 SmallVector<AllocaInst *, 16> AllocaVec;
Kuba Brecka8ec94ea2015-07-22 10:25:38 +0000582 SmallSetVector<AllocaInst *, 16> NonInstrumentedStaticAllocaVec;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000583 SmallVector<Instruction *, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000584 unsigned StackAlignment;
585
Kostya Serebryany6805de52013-09-10 13:16:56 +0000586 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000587 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000588 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
Yury Gribov98b18592015-05-28 07:51:49 +0000589 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000590
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000591 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
592 struct AllocaPoisonCall {
593 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000594 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000595 uint64_t Size;
596 bool DoPoison;
597 };
598 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
599
Yury Gribov98b18592015-05-28 07:51:49 +0000600 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
601 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
602 AllocaInst *DynamicAllocaLayout = nullptr;
Reid Kleckner2f907552015-07-21 17:40:14 +0000603 IntrinsicInst *LocalEscapeCall = nullptr;
Yury Gribov55441bb2014-11-21 10:29:50 +0000604
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000605 // Maps Value to an AllocaInst from which the Value is originated.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000606 typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000607 AllocaForValueMapTy AllocaForValue;
608
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000609 bool HasNonEmptyInlineAsm = false;
610 bool HasReturnsTwiceCall = false;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000611 std::unique_ptr<CallInst> EmptyInlineAsm;
612
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000613 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000614 : F(F),
615 ASan(ASan),
616 DIB(*F.getParent(), /*AllowUnresolved*/ false),
617 C(ASan.C),
618 IntptrTy(ASan.IntptrTy),
619 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
620 Mapping(ASan.Mapping),
621 StackAlignment(1 << Mapping.Scale),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000622 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000623
624 bool runOnFunction() {
625 if (!ClStack) return false;
626 // Collect alloca, ret, lifetime instructions etc.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000627 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000628
Yury Gribov55441bb2014-11-21 10:29:50 +0000629 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000630
631 initializeCallbacks(*F.getParent());
632
633 poisonStack();
634
635 if (ClDebugStack) {
636 DEBUG(dbgs() << F);
637 }
638 return true;
639 }
640
Yury Gribov55441bb2014-11-21 10:29:50 +0000641 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000642 // poisoned red zones around all of them.
643 // Then unpoison everything back before the function returns.
644 void poisonStack();
645
Yury Gribov98b18592015-05-28 07:51:49 +0000646 void createDynamicAllocasInitStorage();
647
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000648 // ----------------------- Visitors.
649 /// \brief Collect all Ret instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000650 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000651
Yury Gribov98b18592015-05-28 07:51:49 +0000652 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
653 Value *SavedStack) {
654 IRBuilder<> IRB(InstBefore);
Yury Gribov6ff0a662015-12-04 09:19:14 +0000655 Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
656 // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
657 // need to adjust extracted SP to compute the address of the most recent
658 // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
659 // this purpose.
660 if (!isa<ReturnInst>(InstBefore)) {
661 Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
662 InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
663 {IntptrTy});
664
665 Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
666
667 DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
668 DynamicAreaOffset);
669 }
670
Yury Gribov781bce22015-05-28 08:03:28 +0000671 IRB.CreateCall(AsanAllocasUnpoisonFunc,
Yury Gribov6ff0a662015-12-04 09:19:14 +0000672 {IRB.CreateLoad(DynamicAllocaLayout), DynamicAreaPtr});
Yury Gribov98b18592015-05-28 07:51:49 +0000673 }
674
Yury Gribov55441bb2014-11-21 10:29:50 +0000675 // Unpoison dynamic allocas redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000676 void unpoisonDynamicAllocas() {
677 for (auto &Ret : RetVec)
678 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
Yury Gribov55441bb2014-11-21 10:29:50 +0000679
Yury Gribov98b18592015-05-28 07:51:49 +0000680 for (auto &StackRestoreInst : StackRestoreVec)
681 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
682 StackRestoreInst->getOperand(0));
Yury Gribov55441bb2014-11-21 10:29:50 +0000683 }
684
Yury Gribov55441bb2014-11-21 10:29:50 +0000685 // Deploy and poison redzones around dynamic alloca call. To do this, we
686 // should replace this call with another one with changed parameters and
687 // replace all its uses with new address, so
688 // addr = alloca type, old_size, align
689 // is replaced by
690 // new_size = (old_size + additional_size) * sizeof(type)
691 // tmp = alloca i8, new_size, max(align, 32)
692 // addr = tmp + 32 (first 32 bytes are for the left redzone).
693 // Additional_size is added to make new memory allocation contain not only
694 // requested memory, but also left, partial and right redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000695 void handleDynamicAllocaCall(AllocaInst *AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000696
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000697 /// \brief Collect Alloca instructions we want (and can) handle.
698 void visitAllocaInst(AllocaInst &AI) {
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000699 if (!ASan.isInterestingAlloca(AI)) {
Kuba Brecka8ec94ea2015-07-22 10:25:38 +0000700 if (AI.isStaticAlloca()) NonInstrumentedStaticAllocaVec.insert(&AI);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000701 return;
702 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000703
704 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Yury Gribov98b18592015-05-28 07:51:49 +0000705 if (ASan.isDynamicAlloca(AI))
706 DynamicAllocaVec.push_back(&AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000707 else
708 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000709 }
710
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000711 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
712 /// errors.
713 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000714 Intrinsic::ID ID = II.getIntrinsicID();
Yury Gribov98b18592015-05-28 07:51:49 +0000715 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
Reid Kleckner2f907552015-07-21 17:40:14 +0000716 if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
Yury Gribov98b18592015-05-28 07:51:49 +0000717 if (!ClCheckLifetime) return;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000718 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000719 return;
720 // Found lifetime intrinsic, add ASan instrumentation if necessary.
721 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
722 // If size argument is undefined, don't do anything.
723 if (Size->isMinusOne()) return;
724 // Check that size doesn't saturate uint64_t and can
725 // be stored in IntptrTy.
726 const uint64_t SizeValue = Size->getValue().getLimitedValue();
727 if (SizeValue == ~0ULL ||
728 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
729 return;
730 // Find alloca instruction that corresponds to llvm.lifetime argument.
731 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
732 if (!AI) return;
733 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000734 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000735 AllocaPoisonCallVec.push_back(APC);
736 }
737
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000738 void visitCallSite(CallSite CS) {
739 Instruction *I = CS.getInstruction();
740 if (CallInst *CI = dyn_cast<CallInst>(I)) {
741 HasNonEmptyInlineAsm |=
742 CI->isInlineAsm() && !CI->isIdenticalTo(EmptyInlineAsm.get());
743 HasReturnsTwiceCall |= CI->canReturnTwice();
744 }
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000745 }
746
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000747 // ---------------------- Helpers.
748 void initializeCallbacks(Module &M);
749
Yury Gribov3ae427d2014-12-01 08:47:58 +0000750 bool doesDominateAllExits(const Instruction *I) const {
751 for (auto Ret : RetVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000752 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000753 }
754 return true;
755 }
756
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000757 /// Finds alloca where the value comes from.
758 AllocaInst *findAllocaForValue(Value *V);
Craig Topper3af97222014-08-27 05:25:00 +0000759 void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000760 Value *ShadowBase, bool DoPoison);
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000761 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000762
763 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
764 int Size);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000765 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
766 bool Dynamic);
767 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
768 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000769};
770
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000771} // anonymous namespace
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000772
773char AddressSanitizer::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000774INITIALIZE_PASS_BEGIN(
775 AddressSanitizer, "asan",
776 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
777 false)
Yury Gribov3ae427d2014-12-01 08:47:58 +0000778INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Keno Fischera010cfa2015-10-20 10:13:55 +0000779INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000780INITIALIZE_PASS_END(
781 AddressSanitizer, "asan",
782 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
783 false)
Yury Gribovd7731982015-11-11 10:36:49 +0000784FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel,
785 bool Recover) {
786 assert(!CompileKernel || Recover);
787 return new AddressSanitizer(CompileKernel, Recover);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000788}
789
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000790char AddressSanitizerModule::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000791INITIALIZE_PASS(
792 AddressSanitizerModule, "asan-module",
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000793 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000794 "ModulePass",
795 false, false)
Yury Gribovd7731982015-11-11 10:36:49 +0000796ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel,
797 bool Recover) {
798 assert(!CompileKernel || Recover);
799 return new AddressSanitizerModule(CompileKernel, Recover);
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000800}
801
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000802static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000803 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000804 assert(Res < kNumberOfAccessSizes);
805 return Res;
806}
807
Bill Wendling58f8cef2013-08-06 22:52:42 +0000808// \brief Create a constant for Str so that we can pass it to the run-time lib.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000809static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
810 bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000811 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000812 // We use private linkage for module-local strings. If they can be merged
813 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000814 GlobalVariable *GV =
815 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000816 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000817 if (AllowMerging) GV->setUnnamedAddr(true);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000818 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
819 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000820}
821
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000822/// \brief Create a global describing a source location.
823static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
824 LocationMetadata MD) {
825 Constant *LocData[] = {
826 createPrivateGlobalForString(M, MD.Filename, true),
827 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
828 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
829 };
830 auto LocStruct = ConstantStruct::getAnon(LocData);
831 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
832 GlobalValue::PrivateLinkage, LocStruct,
833 kAsanGenPrefix);
834 GV->setUnnamedAddr(true);
835 return GV;
836}
837
Kostya Serebryany139a9372012-11-20 14:16:08 +0000838static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000839 return G->getName().find(kAsanGenPrefix) == 0 ||
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000840 G->getName().find(kSanCovGenPrefix) == 0 ||
841 G->getName().find(kODRGenPrefix) == 0;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000842}
843
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000844Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
845 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +0000846 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000847 if (Mapping.Offset == 0) return Shadow;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000848 // (Shadow >> scale) | offset
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000849 if (Mapping.OrShadowOffset)
850 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
851 else
852 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000853}
854
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000855// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000856void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
857 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000858 if (isa<MemTransferInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000859 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000860 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
David Blaikieff6409d2015-05-18 22:13:54 +0000861 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
862 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
863 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000864 } else if (isa<MemSetInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000865 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000866 AsanMemset,
David Blaikieff6409d2015-05-18 22:13:54 +0000867 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
868 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
869 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000870 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000871 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000872}
873
Anna Zaks8ed1d812015-02-27 03:12:36 +0000874/// Check if we want (and can) handle this alloca.
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000875bool AddressSanitizer::isInterestingAlloca(AllocaInst &AI) {
876 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
877
878 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
879 return PreviouslySeenAllocaInfo->getSecond();
880
Yury Gribov98b18592015-05-28 07:51:49 +0000881 bool IsInteresting =
882 (AI.getAllocatedType()->isSized() &&
883 // alloca() may be called with 0 size, ignore it.
884 getAllocaSizeInBytes(&AI) > 0 &&
885 // We are only interested in allocas not promotable to registers.
886 // Promotable allocas are common under -O0.
Alexey Samsonov55fda1b2015-11-05 21:18:41 +0000887 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
888 // inalloca allocas are not treated as static, and we don't want
889 // dynamic alloca instrumentation for them as well.
890 !AI.isUsedWithInAlloca());
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000891
892 ProcessedAllocas[&AI] = IsInteresting;
893 return IsInteresting;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000894}
895
896/// If I is an interesting memory access, return the PointerOperand
897/// and set IsWrite/Alignment. Otherwise return nullptr.
898Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
899 bool *IsWrite,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000900 uint64_t *TypeSize,
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000901 unsigned *Alignment) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +0000902 // Skip memory accesses inserted by another instrumentation.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000903 if (I->getMetadata("nosanitize")) return nullptr;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000904
905 Value *PtrOperand = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000906 const DataLayout &DL = I->getModule()->getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000907 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000908 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000909 *IsWrite = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000910 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000911 *Alignment = LI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +0000912 PtrOperand = LI->getPointerOperand();
913 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000914 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000915 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000916 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000917 *Alignment = SI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +0000918 PtrOperand = SI->getPointerOperand();
919 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000920 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000921 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000922 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000923 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000924 PtrOperand = RMW->getPointerOperand();
925 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000926 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000927 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000928 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000929 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000930 PtrOperand = XCHG->getPointerOperand();
Kostya Serebryany90241602012-05-30 09:04:06 +0000931 }
Anna Zaks8ed1d812015-02-27 03:12:36 +0000932
933 // Treat memory accesses to promotable allocas as non-interesting since they
934 // will not cause memory violations. This greatly speeds up the instrumented
935 // executable at -O0.
936 if (ClSkipPromotableAllocas)
937 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
938 return isInterestingAlloca(*AI) ? AI : nullptr;
939
940 return PtrOperand;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000941}
942
Kostya Serebryany796f6552014-02-27 12:45:36 +0000943static bool isPointerOperand(Value *V) {
944 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
945}
946
947// This is a rough heuristic; it may cause both false positives and
948// false negatives. The proper implementation requires cooperation with
949// the frontend.
950static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
951 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000952 if (!Cmp->isRelational()) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000953 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000954 if (BO->getOpcode() != Instruction::Sub) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000955 } else {
956 return false;
957 }
Alexey Samsonov145b0fd2015-10-26 18:06:40 +0000958 return isPointerOperand(I->getOperand(0)) &&
959 isPointerOperand(I->getOperand(1));
Kostya Serebryany796f6552014-02-27 12:45:36 +0000960}
961
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000962bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
963 // If a global variable does not have dynamic initialization we don't
964 // have to instrument it. However, if a global does not have initializer
965 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000966 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000967}
968
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000969void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
970 Instruction *I) {
Kostya Serebryany796f6552014-02-27 12:45:36 +0000971 IRBuilder<> IRB(I);
972 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
973 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
974 for (int i = 0; i < 2; i++) {
975 if (Param[i]->getType()->isPointerTy())
976 Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
977 }
David Blaikieff6409d2015-05-18 22:13:54 +0000978 IRB.CreateCall(F, Param);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000979}
980
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000981void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000982 Instruction *I, bool UseCalls,
983 const DataLayout &DL) {
Axel Naumann4a127062012-09-17 14:20:57 +0000984 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000985 unsigned Alignment = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000986 uint64_t TypeSize = 0;
987 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment);
Kostya Serebryany90241602012-05-30 09:04:06 +0000988 assert(Addr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000989
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000990 // Optimization experiments.
991 // The experiments can be used to evaluate potential optimizations that remove
992 // instrumentation (assess false negatives). Instead of completely removing
993 // some instrumentation, you set Exp to a non-zero value (mask of optimization
994 // experiments that want to remove instrumentation of this instruction).
995 // If Exp is non-zero, this pass will emit special calls into runtime
996 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
997 // make runtime terminate the program in a special way (with a different
998 // exit status). Then you run the new compiler on a buggy corpus, collect
999 // the special terminations (ideally, you don't see them at all -- no false
1000 // negatives) and make the decision on the optimization.
1001 uint32_t Exp = ClForceExperiment;
1002
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001003 if (ClOpt && ClOptGlobals) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001004 // If initialization order checking is disabled, a simple access to a
1005 // dynamically initialized global is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001006 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001007 if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001008 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1009 NumOptimizedAccessesToGlobalVar++;
1010 return;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001011 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001012 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001013
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001014 if (ClOpt && ClOptStack) {
1015 // A direct inbounds access to a stack variable is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001016 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001017 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1018 NumOptimizedAccessesToStackVar++;
1019 return;
1020 }
1021 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001022
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001023 if (IsWrite)
1024 NumInstrumentedWrites++;
1025 else
1026 NumInstrumentedReads++;
1027
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001028 unsigned Granularity = 1 << Mapping.Scale;
1029 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
1030 // if the data is properly aligned.
1031 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1032 TypeSize == 128) &&
1033 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001034 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls,
1035 Exp);
1036 instrumentUnusualSizeOrAlignment(I, Addr, TypeSize, IsWrite, nullptr,
1037 UseCalls, Exp);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001038}
1039
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001040Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
1041 Value *Addr, bool IsWrite,
1042 size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001043 Value *SizeArgument,
1044 uint32_t Exp) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001045 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001046 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1047 CallInst *Call = nullptr;
1048 if (SizeArgument) {
1049 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001050 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1051 {Addr, SizeArgument});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001052 else
David Blaikieff6409d2015-05-18 22:13:54 +00001053 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1054 {Addr, SizeArgument, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001055 } else {
1056 if (Exp == 0)
1057 Call =
1058 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1059 else
David Blaikieff6409d2015-05-18 22:13:54 +00001060 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1061 {Addr, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001062 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001063
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001064 // We don't do Call->setDoesNotReturn() because the BB already has
1065 // UnreachableInst at the end.
1066 // This EmptyAsm is required to avoid callback merge.
David Blaikieff6409d2015-05-18 22:13:54 +00001067 IRB.CreateCall(EmptyAsm, {});
Kostya Serebryany3411f2e2012-01-06 18:09:21 +00001068 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001069}
1070
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001071Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001072 Value *ShadowValue,
1073 uint32_t TypeSize) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001074 size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +00001075 // Addr & (Granularity - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001076 Value *LastAccessedByte =
1077 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
Kostya Serebryany874dae62012-07-16 16:15:40 +00001078 // (Addr & (Granularity - 1)) + size - 1
1079 if (TypeSize / 8 > 1)
1080 LastAccessedByte = IRB.CreateAdd(
1081 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1082 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001083 LastAccessedByte =
1084 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001085 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1086 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1087}
1088
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001089void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001090 Instruction *InsertBefore, Value *Addr,
1091 uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001092 Value *SizeArgument, bool UseCalls,
1093 uint32_t Exp) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001094 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001095 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001096 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1097
1098 if (UseCalls) {
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001099 if (Exp == 0)
1100 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1101 AddrLong);
1102 else
David Blaikieff6409d2015-05-18 22:13:54 +00001103 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1104 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001105 return;
1106 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001107
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001108 Type *ShadowTy =
1109 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001110 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1111 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1112 Value *CmpVal = Constant::getNullValue(ShadowTy);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001113 Value *ShadowValue =
1114 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001115
1116 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001117 size_t Granularity = 1ULL << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +00001118 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001119
Kostya Serebryany1e575ab2012-08-15 08:58:58 +00001120 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +00001121 // We use branch weights for the slow path check, to indicate that the slow
1122 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001123 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1124 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001125 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001126 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001127 IRB.SetInsertPoint(CheckTerm);
1128 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Yury Gribovd7731982015-11-11 10:36:49 +00001129 if (Recover) {
1130 CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
1131 } else {
1132 BasicBlock *CrashBlock =
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001133 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Yury Gribovd7731982015-11-11 10:36:49 +00001134 CrashTerm = new UnreachableInst(*C, CrashBlock);
1135 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1136 ReplaceInstWithInst(CheckTerm, NewTerm);
1137 }
Kostya Serebryany874dae62012-07-16 16:15:40 +00001138 } else {
Yury Gribovd7731982015-11-11 10:36:49 +00001139 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001140 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001141
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001142 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001143 AccessSizeIndex, SizeArgument, Exp);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001144 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001145}
1146
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001147// Instrument unusual size or unusual alignment.
1148// We can not do it with a single check, so we do 1-byte check for the first
1149// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1150// to report the actual access size.
1151void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1152 Instruction *I, Value *Addr, uint32_t TypeSize, bool IsWrite,
1153 Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1154 IRBuilder<> IRB(I);
1155 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1156 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1157 if (UseCalls) {
1158 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001159 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1160 {AddrLong, Size});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001161 else
David Blaikieff6409d2015-05-18 22:13:54 +00001162 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1163 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001164 } else {
1165 Value *LastByte = IRB.CreateIntToPtr(
1166 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1167 Addr->getType());
1168 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false, Exp);
1169 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false, Exp);
1170 }
1171}
1172
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001173void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1174 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001175 // Set up the arguments to our poison/unpoison functions.
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001176 IRBuilder<> IRB(&GlobalInit.front(),
1177 GlobalInit.front().getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001178
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001179 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001180 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1181 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001182
1183 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001184 for (auto &BB : GlobalInit.getBasicBlockList())
1185 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001186 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001187}
1188
1189void AddressSanitizerModule::createInitializerPoisonCalls(
1190 Module &M, GlobalValue *ModuleName) {
1191 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1192
1193 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1194 for (Use &OP : CA->operands()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001195 if (isa<ConstantAggregateZero>(OP)) continue;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001196 ConstantStruct *CS = cast<ConstantStruct>(OP);
1197
1198 // Must have a function or null ptr.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001199 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001200 if (F->getName() == kAsanModuleCtorName) continue;
1201 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1202 // Don't instrument CTORs that will run before asan.module_ctor.
1203 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1204 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001205 }
1206 }
1207}
1208
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001209bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001210 Type *Ty = G->getValueType();
Kostya Serebryany20343352012-10-17 13:40:06 +00001211 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001212
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001213 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001214 if (!Ty->isSized()) return false;
1215 if (!G->hasInitializer()) return false;
Kostya Serebryany139a9372012-11-20 14:16:08 +00001216 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001217 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001218 // Don't handle ODR linkage types and COMDATs since other modules may be built
1219 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001220 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1221 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1222 G->getLinkage() != GlobalVariable::InternalLinkage)
1223 return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001224 if (G->hasComdat()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001225 // Two problems with thread-locals:
1226 // - The address of the main thread's copy can't be computed at link-time.
1227 // - Need to poison all copies, not just the main thread's one.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001228 if (G->isThreadLocal()) return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001229 // For now, just ignore this Global if the alignment is large.
1230 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001231
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001232 if (G->hasSection()) {
1233 StringRef Section(G->getSection());
Kuba Brecka086e34b2014-12-05 21:32:46 +00001234
Anna Zaks11904602015-06-09 00:58:08 +00001235 // Globals from llvm.metadata aren't emitted, do not instrument them.
1236 if (Section == "llvm.metadata") return false;
Anna Zaks785c0752015-06-25 23:35:48 +00001237 // Do not instrument globals from special LLVM sections.
Anna Zaks40148f12016-02-24 22:12:18 +00001238 if (Section.find("__llvm") != StringRef::npos || Section.find("__LLVM") != StringRef::npos) return false;
Anna Zaks11904602015-06-09 00:58:08 +00001239
Alexey Samsonovc1603b62015-09-15 23:05:48 +00001240 // Do not instrument function pointers to initialization and termination
1241 // routines: dynamic linker will not properly handle redzones.
1242 if (Section.startswith(".preinit_array") ||
1243 Section.startswith(".init_array") ||
1244 Section.startswith(".fini_array")) {
1245 return false;
1246 }
1247
Anna Zaks11904602015-06-09 00:58:08 +00001248 // Callbacks put into the CRT initializer/terminator sections
1249 // should not be instrumented.
1250 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1251 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1252 if (Section.startswith(".CRT")) {
1253 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1254 return false;
1255 }
1256
Kuba Brecka1001bb52014-12-05 22:19:18 +00001257 if (TargetTriple.isOSBinFormatMachO()) {
1258 StringRef ParsedSegment, ParsedSection;
1259 unsigned TAA = 0, StubSize = 0;
1260 bool TAAParsed;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001261 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1262 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
Davide Italianoc807f482015-11-19 21:50:08 +00001263 assert(ErrorCode.empty() && "Invalid section specifier.");
Kuba Brecka1001bb52014-12-05 22:19:18 +00001264
1265 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1266 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1267 // them.
1268 if (ParsedSegment == "__OBJC" ||
1269 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1270 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1271 return false;
1272 }
1273 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1274 // Constant CFString instances are compiled in the following way:
1275 // -- the string buffer is emitted into
1276 // __TEXT,__cstring,cstring_literals
1277 // -- the constant NSConstantString structure referencing that buffer
1278 // is placed into __DATA,__cfstring
1279 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1280 // Moreover, it causes the linker to crash on OS X 10.7
1281 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1282 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1283 return false;
1284 }
1285 // The linker merges the contents of cstring_literals and removes the
1286 // trailing zeroes.
1287 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1288 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1289 return false;
1290 }
1291 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001292 }
1293
1294 return true;
1295}
1296
Ryan Govostes653f9d02016-03-28 20:28:57 +00001297// On Mach-O platforms, we emit global metadata in a separate section of the
1298// binary in order to allow the linker to properly dead strip. This is only
1299// supported on recent versions of ld64.
1300bool AddressSanitizerModule::ShouldUseMachOGlobalsSection() const {
1301 if (!TargetTriple.isOSBinFormatMachO())
1302 return false;
1303
1304 if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
1305 return true;
1306 if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
1307 return true;
1308 if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
1309 return true;
1310
1311 return false;
1312}
1313
Alexey Samsonov788381b2012-12-25 12:28:20 +00001314void AddressSanitizerModule::initializeCallbacks(Module &M) {
1315 IRBuilder<> IRB(*C);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001316
Alexey Samsonov788381b2012-12-25 12:28:20 +00001317 // Declare our poisoning and unpoisoning functions.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001318 AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001319 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001320 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001321 AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001322 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001323 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001324
Alexey Samsonov788381b2012-12-25 12:28:20 +00001325 // Declare functions that register/unregister globals.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001326 AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001327 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001328 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001329 AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001330 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1331 IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001332 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001333
1334 // Declare the functions that find globals in a shared object and then invoke
1335 // the (un)register function on them.
1336 AsanRegisterImageGlobals = checkSanitizerInterfaceFunction(
1337 M.getOrInsertFunction(kAsanRegisterImageGlobalsName,
1338 IRB.getVoidTy(), IntptrTy, nullptr));
1339 AsanRegisterImageGlobals->setLinkage(Function::ExternalLinkage);
1340
1341 AsanUnregisterImageGlobals = checkSanitizerInterfaceFunction(
1342 M.getOrInsertFunction(kAsanUnregisterImageGlobalsName,
1343 IRB.getVoidTy(), IntptrTy, nullptr));
1344 AsanUnregisterImageGlobals->setLinkage(Function::ExternalLinkage);
Alexey Samsonov788381b2012-12-25 12:28:20 +00001345}
1346
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001347// This function replaces all global variables with new variables that have
1348// trailing redzones. It also creates a function that poisons
1349// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001350bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001351 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001352
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001353 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1354
Alexey Samsonova02e6642014-05-29 18:40:48 +00001355 for (auto &G : M.globals()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001356 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001357 }
1358
1359 size_t n = GlobalsToChange.size();
1360 if (n == 0) return false;
1361
1362 // A global is described by a structure
1363 // size_t beg;
1364 // size_t size;
1365 // size_t size_with_redzone;
1366 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001367 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001368 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001369 // void *source_location;
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001370 // size_t odr_indicator;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001371 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001372 StructType *GlobalStructTy =
1373 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001374 IntptrTy, IntptrTy, IntptrTy, nullptr);
Rafael Espindola44fee4e2013-10-01 13:32:03 +00001375 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001376
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001377 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001378
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001379 // We shouldn't merge same module names, as this string serves as unique
1380 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001381 GlobalVariable *ModuleName = createPrivateGlobalForString(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001382 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001383
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001384 auto &DL = M.getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001385 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001386 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001387 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00001388
1389 auto MD = GlobalsMD.get(G);
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001390 StringRef NameForGlobal = G->getName();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001391 // Create string holding the global name (use global name from metadata
1392 // if it's available, otherwise just write the name of global variable).
1393 GlobalVariable *Name = createPrivateGlobalForString(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001394 M, MD.Name.empty() ? NameForGlobal : MD.Name,
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001395 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00001396
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001397 Type *Ty = G->getValueType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001398 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001399 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00001400 // MinRZ <= RZ <= kMaxGlobalRedzone
1401 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001402 uint64_t RZ = std::max(
1403 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
Kostya Serebryany87191f62013-01-24 10:35:40 +00001404 uint64_t RightRedzoneSize = RZ;
1405 // Round up to MinRZ
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001406 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001407 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001408 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1409
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001410 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001411 Constant *NewInitializer =
1412 ConstantStruct::get(NewTy, G->getInitializer(),
1413 Constant::getNullValue(RightRedZoneTy), nullptr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001414
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001415 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00001416 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1417 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1418 Linkage = GlobalValue::InternalLinkage;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001419 GlobalVariable *NewGlobal =
1420 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1421 "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001422 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001423 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001424
1425 Value *Indices2[2];
1426 Indices2[0] = IRB.getInt32(0);
1427 Indices2[1] = IRB.getInt32(0);
1428
1429 G->replaceAllUsesWith(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001430 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001431 NewGlobal->takeName(G);
1432 G->eraseFromParent();
1433
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001434 Constant *SourceLoc;
1435 if (!MD.SourceLoc.empty()) {
1436 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1437 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1438 } else {
1439 SourceLoc = ConstantInt::get(IntptrTy, 0);
1440 }
1441
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001442 Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
1443 GlobalValue *InstrumentedGlobal = NewGlobal;
1444
1445 bool CanUsePrivateAliases = TargetTriple.isOSBinFormatELF();
1446 if (CanUsePrivateAliases && ClUsePrivateAliasForGlobals) {
1447 // Create local alias for NewGlobal to avoid crash on ODR between
1448 // instrumented and non-instrumented libraries.
1449 auto *GA = GlobalAlias::create(GlobalValue::InternalLinkage,
1450 NameForGlobal + M.getName(), NewGlobal);
1451
1452 // With local aliases, we need to provide another externally visible
1453 // symbol __odr_asan_XXX to detect ODR violation.
1454 auto *ODRIndicatorSym =
1455 new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
1456 Constant::getNullValue(IRB.getInt8Ty()),
1457 kODRGenPrefix + NameForGlobal, nullptr,
1458 NewGlobal->getThreadLocalMode());
1459
1460 // Set meaningful attributes for indicator symbol.
1461 ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
1462 ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
1463 ODRIndicatorSym->setAlignment(1);
1464 ODRIndicator = ODRIndicatorSym;
1465 InstrumentedGlobal = GA;
1466 }
1467
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001468 Initializers[i] = ConstantStruct::get(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001469 GlobalStructTy,
1470 ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001471 ConstantInt::get(IntptrTy, SizeInBytes),
1472 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1473 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001474 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001475 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
1476 ConstantExpr::getPointerCast(ODRIndicator, IntptrTy), nullptr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001477
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001478 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001479
Kostya Serebryany20343352012-10-17 13:40:06 +00001480 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001481 }
1482
Ryan Govostes653f9d02016-03-28 20:28:57 +00001483
1484 GlobalVariable *AllGlobals = nullptr;
1485 GlobalVariable *RegisteredFlag = nullptr;
1486
1487 // On recent Mach-O platforms, we emit the global metadata in a way that
1488 // allows the linker to properly strip dead globals.
1489 if (ShouldUseMachOGlobalsSection()) {
1490 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1491 // to look up the loaded image that contains it. Second, we can store in it
1492 // whether registration has already occurred, to prevent duplicate
1493 // registration.
1494 //
1495 // Common linkage allows us to coalesce needles defined in each object
1496 // file so that there's only one per shared library.
1497 RegisteredFlag = new GlobalVariable(
1498 M, IntptrTy, false, GlobalVariable::CommonLinkage,
1499 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1500
1501 // We also emit a structure which binds the liveness of the global
1502 // variable to the metadata struct.
1503 StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy, nullptr);
1504
1505 for (size_t i = 0; i < n; i++) {
1506 GlobalVariable *Metadata = new GlobalVariable(
1507 M, GlobalStructTy, false, GlobalVariable::InternalLinkage,
1508 Initializers[i], "");
1509 Metadata->setSection("__DATA,__asan_globals,regular");
1510 Metadata->setAlignment(1); // don't leave padding in between
1511
1512 auto LivenessBinder = ConstantStruct::get(LivenessTy,
1513 Initializers[i]->getAggregateElement(0u),
1514 ConstantExpr::getPointerCast(Metadata, IntptrTy),
1515 nullptr);
1516 GlobalVariable *Liveness = new GlobalVariable(
1517 M, LivenessTy, false, GlobalVariable::InternalLinkage,
1518 LivenessBinder, "");
1519 Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
1520 }
1521 } else {
1522 // On all other platfoms, we just emit an array of global metadata
1523 // structures.
1524 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1525 AllGlobals = new GlobalVariable(
1526 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1527 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1528 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001529
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001530 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001531 if (HasDynamicallyInitializedGlobals)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001532 createInitializerPoisonCalls(M, ModuleName);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001533
Ryan Govostes653f9d02016-03-28 20:28:57 +00001534 // Create a call to register the globals with the runtime.
1535 if (ShouldUseMachOGlobalsSection()) {
1536 IRB.CreateCall(AsanRegisterImageGlobals,
1537 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1538 } else {
1539 IRB.CreateCall(AsanRegisterGlobals,
1540 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1541 ConstantInt::get(IntptrTy, n)});
1542 }
1543
1544 // We also need to unregister globals at the end, e.g., when a shared library
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001545 // gets closed.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001546 Function *AsanDtorFunction =
1547 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1548 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001549 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1550 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Ryan Govostes653f9d02016-03-28 20:28:57 +00001551
1552 if (ShouldUseMachOGlobalsSection()) {
1553 IRB_Dtor.CreateCall(AsanUnregisterImageGlobals,
1554 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1555 } else {
1556 IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1557 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1558 ConstantInt::get(IntptrTy, n)});
1559 }
1560
Alexey Samsonov1f647502014-05-29 01:10:14 +00001561 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001562
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001563 DEBUG(dbgs() << M);
1564 return true;
1565}
1566
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001567bool AddressSanitizerModule::runOnModule(Module &M) {
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001568 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001569 int LongSize = M.getDataLayout().getPointerSizeInBits();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001570 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001571 TargetTriple = Triple(M.getTargetTriple());
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001572 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001573 initializeCallbacks(M);
1574
1575 bool Changed = false;
1576
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001577 // TODO(glider): temporarily disabled globals instrumentation for KASan.
1578 if (ClGlobals && !CompileKernel) {
1579 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1580 assert(CtorFunc);
1581 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1582 Changed |= InstrumentGlobals(IRB, M);
1583 }
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001584
1585 return Changed;
1586}
1587
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001588void AddressSanitizer::initializeCallbacks(Module &M) {
1589 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001590 // Create __asan_report* callbacks.
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001591 // IsWrite, TypeSize and Exp are encoded in the function name.
1592 for (int Exp = 0; Exp < 2; Exp++) {
1593 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1594 const std::string TypeStr = AccessIsWrite ? "store" : "load";
1595 const std::string ExpStr = Exp ? "exp_" : "";
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001596 const std::string SuffixStr = CompileKernel ? "N" : "_n";
Yury Gribovd7731982015-11-11 10:36:49 +00001597 const std::string EndingStr = Recover ? "_noabort" : "";
Craig Toppere3dcce92015-08-01 22:20:21 +00001598 Type *ExpType = Exp ? Type::getInt32Ty(*C) : nullptr;
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001599 AsanErrorCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001600 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Yury Gribovd7731982015-11-11 10:36:49 +00001601 kAsanReportErrorTemplate + ExpStr + TypeStr + SuffixStr + EndingStr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001602 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1603 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001604 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001605 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001606 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1607 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1608 AccessSizeIndex++) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001609 const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001610 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001611 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Yury Gribovd7731982015-11-11 10:36:49 +00001612 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001613 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001614 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001615 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001616 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
1617 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001618 }
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001619 }
1620 }
Kostya Serebryany86332c02014-04-21 07:10:43 +00001621
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001622 const std::string MemIntrinCallbackPrefix =
1623 CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001624 AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001625 MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001626 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001627 AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001628 MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001629 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001630 AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001631 MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001632 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001633
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001634 AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001635 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00001636
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001637 AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001638 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001639 AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001640 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001641 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1642 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1643 StringRef(""), StringRef(""),
1644 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001645}
1646
1647// virtual
1648bool AddressSanitizer::doInitialization(Module &M) {
1649 // Initialize the private fields. No one has accessed them before.
Rafael Espindola93512512014-02-25 17:30:31 +00001650
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001651 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001652
1653 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001654 LongSize = M.getDataLayout().getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001655 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001656 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001657
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001658 if (!CompileKernel) {
1659 std::tie(AsanCtorFunction, AsanInitFunction) =
Kuba Brecka45dbffd2015-07-23 10:54:06 +00001660 createSanitizerCtorAndInitFunctions(
1661 M, kAsanModuleCtorName, kAsanInitName,
1662 /*InitArgTypes=*/{}, /*InitArgs=*/{}, kAsanVersionCheckName);
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001663 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
1664 }
1665 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001666 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001667}
1668
Keno Fischere03fae42015-12-05 14:42:34 +00001669bool AddressSanitizer::doFinalization(Module &M) {
1670 GlobalsMD.reset();
1671 return false;
1672}
1673
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001674bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1675 // For each NSObject descendant having a +load method, this method is invoked
1676 // by the ObjC runtime before any of the static constructors is called.
1677 // Therefore we need to instrument such methods with a call to __asan_init
1678 // at the beginning in order to initialize our runtime before any access to
1679 // the shadow memory.
1680 // We cannot just ignore these methods, because they may call other
1681 // instrumented functions.
1682 if (F.getName().find(" load]") != std::string::npos) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001683 IRBuilder<> IRB(&F.front(), F.front().begin());
David Blaikieff6409d2015-05-18 22:13:54 +00001684 IRB.CreateCall(AsanInitFunction, {});
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001685 return true;
1686 }
1687 return false;
1688}
1689
Reid Kleckner2f907552015-07-21 17:40:14 +00001690void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
1691 // Find the one possible call to llvm.localescape and pre-mark allocas passed
1692 // to it as uninteresting. This assumes we haven't started processing allocas
1693 // yet. This check is done up front because iterating the use list in
1694 // isInterestingAlloca would be algorithmically slower.
1695 assert(ProcessedAllocas.empty() && "must process localescape before allocas");
1696
1697 // Try to get the declaration of llvm.localescape. If it's not in the module,
1698 // we can exit early.
1699 if (!F.getParent()->getFunction("llvm.localescape")) return;
1700
1701 // Look for a call to llvm.localescape call in the entry block. It can't be in
1702 // any other block.
1703 for (Instruction &I : F.getEntryBlock()) {
1704 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
1705 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
1706 // We found a call. Mark all the allocas passed in as uninteresting.
1707 for (Value *Arg : II->arg_operands()) {
1708 AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
1709 assert(AI && AI->isStaticAlloca() &&
1710 "non-static alloca arg to localescape");
1711 ProcessedAllocas[AI] = false;
1712 }
1713 break;
1714 }
1715 }
1716}
1717
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001718bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001719 if (&F == AsanCtorFunction) return false;
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00001720 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany20343352012-10-17 13:40:06 +00001721 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001722 initializeCallbacks(*F.getParent());
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001723
Yury Gribov3ae427d2014-12-01 08:47:58 +00001724 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1725
Kostya Serebryanycf880b92013-02-26 06:58:09 +00001726 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001727 maybeInsertAsanInitAtFunctionEntry(F);
1728
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001729 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001730
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001731 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName()) return false;
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001732
Reid Kleckner2f907552015-07-21 17:40:14 +00001733 FunctionStateRAII CleanupObj(this);
1734
1735 // We can't instrument allocas used with llvm.localescape. Only static allocas
1736 // can be passed to that intrinsic.
1737 markEscapedLocalAllocas(F);
1738
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001739 // We want to instrument every address only once per basic block (unless there
1740 // are calls between uses).
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001741 SmallSet<Value *, 16> TempsToInstrument;
1742 SmallVector<Instruction *, 16> ToInstrument;
1743 SmallVector<Instruction *, 8> NoReturnCalls;
1744 SmallVector<BasicBlock *, 16> AllBlocks;
1745 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001746 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00001747 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001748 unsigned Alignment;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001749 uint64_t TypeSize;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001750
1751 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001752 for (auto &BB : F) {
1753 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001754 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001755 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001756 for (auto &Inst : BB) {
1757 if (LooksLikeCodeInBug11395(&Inst)) return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001758 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
1759 &Alignment)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001760 if (ClOpt && ClOptSameTemp) {
David Blaikie70573dc2014-11-19 07:49:26 +00001761 if (!TempsToInstrument.insert(Addr).second)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001762 continue; // We've seen this temp in the current BB.
1763 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00001764 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00001765 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1766 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001767 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001768 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001769 // ok, take it.
1770 } else {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001771 if (isa<AllocaInst>(Inst)) NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001772 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00001773 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001774 // A call inside BB.
1775 TempsToInstrument.clear();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001776 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001777 }
1778 continue;
1779 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00001780 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001781 NumInsnsPerBB++;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001782 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001783 }
1784 }
1785
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001786 bool UseCalls =
1787 CompileKernel ||
1788 (ClInstrumentationWithCallsThreshold >= 0 &&
1789 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001790 const TargetLibraryInfo *TLI =
1791 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001792 const DataLayout &DL = F.getParent()->getDataLayout();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001793 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(),
1794 /*RoundToAlign=*/true);
1795
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001796 // Instrument.
1797 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001798 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001799 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1800 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001801 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001802 instrumentMop(ObjSizeVis, Inst, UseCalls,
1803 F.getParent()->getDataLayout());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001804 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001805 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001806 }
1807 NumInstrumented++;
1808 }
1809
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001810 FunctionStackPoisoner FSP(F, *this);
1811 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001812
1813 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1814 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00001815 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001816 IRBuilder<> IRB(CI);
David Blaikieff6409d2015-05-18 22:13:54 +00001817 IRB.CreateCall(AsanHandleNoReturnFunc, {});
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001818 }
1819
Alexey Samsonova02e6642014-05-29 18:40:48 +00001820 for (auto Inst : PointerComparisonsOrSubtracts) {
1821 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001822 NumInstrumented++;
1823 }
1824
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001825 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Bob Wilsonda4147c2013-11-15 07:16:09 +00001826
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001827 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1828
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001829 return res;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001830}
1831
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001832// Workaround for bug 11395: we don't want to instrument stack in functions
1833// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1834// FIXME: remove once the bug 11395 is fixed.
1835bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1836 if (LongSize != 32) return false;
1837 CallInst *CI = dyn_cast<CallInst>(I);
1838 if (!CI || !CI->isInlineAsm()) return false;
1839 if (CI->getNumArgOperands() <= 5) return false;
1840 // We have inline assembly with quite a few arguments.
1841 return true;
1842}
1843
1844void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1845 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001846 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1847 std::string Suffix = itostr(i);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001848 AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
1849 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1850 IntptrTy, nullptr));
1851 AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001852 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
1853 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany6805de52013-09-10 13:16:56 +00001854 }
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001855 AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
David Blaikiea92765c2014-11-14 00:41:42 +00001856 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
1857 IntptrTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001858 AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
David Blaikiea92765c2014-11-14 00:41:42 +00001859 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
1860 IntptrTy, IntptrTy, nullptr));
Yury Gribov98b18592015-05-28 07:51:49 +00001861 AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1862 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1863 AsanAllocasUnpoisonFunc =
1864 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1865 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001866}
1867
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001868void FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
1869 IRBuilder<> &IRB, Value *ShadowBase,
1870 bool DoPoison) {
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001871 size_t n = ShadowBytes.size();
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001872 size_t i = 0;
1873 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1874 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1875 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1876 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1877 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1878 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1879 uint64_t Val = 0;
1880 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001881 if (F.getParent()->getDataLayout().isLittleEndian())
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001882 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1883 else
1884 Val = (Val << 8) | ShadowBytes[i + j];
1885 }
1886 if (!Val) continue;
1887 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1888 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1889 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1890 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001891 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001892 }
1893}
1894
Kostya Serebryany6805de52013-09-10 13:16:56 +00001895// Fake stack allocator (asan_fake_stack.h) has 11 size classes
1896// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1897static int StackMallocSizeClass(uint64_t LocalStackSize) {
1898 assert(LocalStackSize <= kMaxStackMallocSize);
1899 uint64_t MaxSize = kMinStackMallocSize;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001900 for (int i = 0;; i++, MaxSize *= 2)
1901 if (LocalStackSize <= MaxSize) return i;
Kostya Serebryany6805de52013-09-10 13:16:56 +00001902 llvm_unreachable("impossible LocalStackSize");
1903}
1904
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001905// Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1906// We can not use MemSet intrinsic because it may end up calling the actual
1907// memset. Size is a multiple of 8.
1908// Currently this generates 8-byte stores on x86_64; it may be better to
1909// generate wider stores.
1910void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1911 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1912 assert(!(Size % 8));
Gabor Horvathfee04342015-03-16 09:53:42 +00001913
Kostya Serebryanyb1870a62015-03-17 19:13:23 +00001914 // kAsanStackAfterReturnMagic is 0xf5.
1915 const uint64_t kAsanStackAfterReturnMagic64 = 0xf5f5f5f5f5f5f5f5ULL;
Gabor Horvathfee04342015-03-16 09:53:42 +00001916
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001917 for (int i = 0; i < Size; i += 8) {
1918 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
Kostya Serebryanyb1870a62015-03-17 19:13:23 +00001919 IRB.CreateStore(
1920 ConstantInt::get(IRB.getInt64Ty(), kAsanStackAfterReturnMagic64),
1921 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001922 }
1923}
1924
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001925PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
1926 Value *ValueIfTrue,
1927 Instruction *ThenTerm,
1928 Value *ValueIfFalse) {
1929 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
1930 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
1931 PHI->addIncoming(ValueIfFalse, CondBlock);
1932 BasicBlock *ThenBlock = ThenTerm->getParent();
1933 PHI->addIncoming(ValueIfTrue, ThenBlock);
1934 return PHI;
1935}
1936
1937Value *FunctionStackPoisoner::createAllocaForLayout(
1938 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
1939 AllocaInst *Alloca;
1940 if (Dynamic) {
1941 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
1942 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
1943 "MyAlloca");
1944 } else {
1945 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
1946 nullptr, "MyAlloca");
1947 assert(Alloca->isStaticAlloca());
1948 }
1949 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1950 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1951 Alloca->setAlignment(FrameAlignment);
1952 return IRB.CreatePointerCast(Alloca, IntptrTy);
1953}
1954
Yury Gribov98b18592015-05-28 07:51:49 +00001955void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
1956 BasicBlock &FirstBB = *F.begin();
1957 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
1958 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
1959 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
1960 DynamicAllocaLayout->setAlignment(32);
1961}
1962
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001963void FunctionStackPoisoner::poisonStack() {
Yury Gribov55441bb2014-11-21 10:29:50 +00001964 assert(AllocaVec.size() > 0 || DynamicAllocaVec.size() > 0);
1965
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00001966 // Insert poison calls for lifetime intrinsics for alloca.
1967 bool HavePoisonedAllocas = false;
1968 for (const auto &APC : AllocaPoisonCallVec) {
1969 assert(APC.InsBefore);
1970 assert(APC.AI);
1971 IRBuilder<> IRB(APC.InsBefore);
1972 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
1973 HavePoisonedAllocas |= APC.DoPoison;
1974 }
1975
Yury Gribov98b18592015-05-28 07:51:49 +00001976 if (ClInstrumentAllocas && DynamicAllocaVec.size() > 0) {
Yury Gribov55441bb2014-11-21 10:29:50 +00001977 // Handle dynamic allocas.
Yury Gribov98b18592015-05-28 07:51:49 +00001978 createDynamicAllocasInitStorage();
Alexander Potapenkof90556e2015-06-12 11:27:06 +00001979 for (auto &AI : DynamicAllocaVec) handleDynamicAllocaCall(AI);
Yury Gribov98b18592015-05-28 07:51:49 +00001980
1981 unpoisonDynamicAllocas();
Kuba Breckaf5875d32015-02-24 09:47:05 +00001982 }
Yury Gribov55441bb2014-11-21 10:29:50 +00001983
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001984 if (AllocaVec.empty()) return;
Yury Gribov55441bb2014-11-21 10:29:50 +00001985
Kostya Serebryany6805de52013-09-10 13:16:56 +00001986 int StackMallocIdx = -1;
Alexey Samsonov773e8c32015-06-26 00:00:47 +00001987 DebugLoc EntryDebugLocation;
Pete Cooperadebb932016-03-11 02:14:16 +00001988 if (auto SP = F.getSubprogram())
Alexey Samsonov773e8c32015-06-26 00:00:47 +00001989 EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001990
1991 Instruction *InsBefore = AllocaVec[0];
1992 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001993 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001994
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00001995 // Make sure non-instrumented allocas stay in the entry block. Otherwise,
1996 // debug info is broken, because only entry-block allocas are treated as
1997 // regular stack slots.
1998 auto InsBeforeB = InsBefore->getParent();
1999 assert(InsBeforeB == &F.getEntryBlock());
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00002000 for (BasicBlock::iterator I(InsBefore); I != InsBeforeB->end(); ++I)
2001 if (auto *AI = dyn_cast<AllocaInst>(I))
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00002002 if (NonInstrumentedStaticAllocaVec.count(AI) > 0)
2003 AI->moveBefore(InsBefore);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +00002004
Reid Kleckner2f907552015-07-21 17:40:14 +00002005 // If we have a call to llvm.localescape, keep it in the entry block.
2006 if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
2007
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002008 SmallVector<ASanStackVariableDescription, 16> SVD;
2009 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00002010 for (AllocaInst *AI : AllocaVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002011 ASanStackVariableDescription D = {AI->getName().data(),
2012 ASan.getAllocaSizeInBytes(AI),
2013 AI->getAlignment(), AI, 0};
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002014 SVD.push_back(D);
2015 }
2016 // Minimal header size (left redzone) is 4 pointers,
2017 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
2018 size_t MinHeaderSize = ASan.LongSize / 2;
2019 ASanStackFrameLayout L;
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00002020 ComputeASanStackFrameLayout(SVD, 1ULL << Mapping.Scale, MinHeaderSize, &L);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002021 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
2022 uint64_t LocalStackSize = L.FrameSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002023 bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
2024 LocalStackSize <= kMaxStackMallocSize;
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00002025 bool DoDynamicAlloca = ClDynamicAllocaStack;
2026 // Don't do dynamic alloca or stack malloc if:
2027 // 1) There is inline asm: too often it makes assumptions on which registers
2028 // are available.
2029 // 2) There is a returns_twice call (typically setjmp), which is
2030 // optimization-hostile, and doesn't play well with introduced indirect
2031 // register-relative calculation of local variable addresses.
2032 DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2033 DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002034
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002035 Value *StaticAlloca =
2036 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
2037
2038 Value *FakeStack;
2039 Value *LocalStackBase;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002040
2041 if (DoStackMalloc) {
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002042 // void *FakeStack = __asan_option_detect_stack_use_after_return
2043 // ? __asan_stack_malloc_N(LocalStackSize)
2044 // : nullptr;
2045 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002046 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
2047 kAsanOptionDetectUAR, IRB.getInt32Ty());
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002048 Value *UARIsEnabled =
2049 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
2050 Constant::getNullValue(IRB.getInt32Ty()));
2051 Instruction *Term =
2052 SplitBlockAndInsertIfThen(UARIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002053 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002054 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002055 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
2056 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
2057 Value *FakeStackValue =
2058 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
2059 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002060 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002061 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002062 FakeStack = createPHI(IRB, UARIsEnabled, FakeStackValue, Term,
2063 ConstantInt::get(IntptrTy, 0));
2064
2065 Value *NoFakeStack =
2066 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
2067 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
2068 IRBIf.SetInsertPoint(Term);
2069 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2070 Value *AllocaValue =
2071 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
2072 IRB.SetInsertPoint(InsBefore);
2073 IRB.SetCurrentDebugLocation(EntryDebugLocation);
2074 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
2075 } else {
2076 // void *FakeStack = nullptr;
2077 // void *LocalStackBase = alloca(LocalStackSize);
2078 FakeStack = ConstantInt::get(IntptrTy, 0);
2079 LocalStackBase =
2080 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002081 }
2082
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002083 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002084 for (const auto &Desc : SVD) {
2085 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00002086 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00002087 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002088 AI->getType());
Adrian Prantl3e2659e2015-01-30 19:37:48 +00002089 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true);
Alexey Samsonov261177a2012-12-04 01:34:23 +00002090 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002091 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002092
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002093 // The left-most redzone has enough space for at least 4 pointers.
2094 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002095 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
2096 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
2097 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002098 // Write the frame description constant to redzone[1].
2099 Value *BasePlus1 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002100 IRB.CreateAdd(LocalStackBase,
2101 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
2102 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00002103 GlobalVariable *StackDescriptionGlobal =
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00002104 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002105 /*AllowMerging*/ true);
2106 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002107 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002108 // Write the PC to redzone[2].
2109 Value *BasePlus2 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002110 IRB.CreateAdd(LocalStackBase,
2111 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
2112 IntptrPtrTy);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002113 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002114
2115 // Poison the stack redzones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002116 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002117 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002118
Kostya Serebryany530e2072013-12-23 14:15:08 +00002119 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002120 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002121 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002122 // Mark the current frame as retired.
2123 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
2124 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002125 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00002126 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002127 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00002128 // // In use-after-return mode, poison the whole stack frame.
2129 // if StackMallocIdx <= 4
2130 // // For small sizes inline the whole thing:
2131 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002132 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00002133 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002134 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00002135 // else
2136 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002137 Value *Cmp =
2138 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Kostya Serebryany530e2072013-12-23 14:15:08 +00002139 TerminatorInst *ThenTerm, *ElseTerm;
2140 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
2141
2142 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002143 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002144 int ClassSize = kMinStackMallocSize << StackMallocIdx;
2145 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
2146 ClassSize >> Mapping.Scale);
2147 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002148 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002149 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
2150 Value *SavedFlagPtr = IRBPoison.CreateLoad(
2151 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
2152 IRBPoison.CreateStore(
2153 Constant::getNullValue(IRBPoison.getInt8Ty()),
2154 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
2155 } else {
2156 // For larger frames call __asan_stack_free_*.
David Blaikieff6409d2015-05-18 22:13:54 +00002157 IRBPoison.CreateCall(
2158 AsanStackFreeFunc[StackMallocIdx],
2159 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002160 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00002161
2162 IRBuilder<> IRBElse(ElseTerm);
2163 poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
Alexey Samsonov261177a2012-12-04 01:34:23 +00002164 } else if (HavePoisonedAllocas) {
2165 // If we poisoned some allocas in llvm.lifetime analysis,
2166 // unpoison whole stack frame now.
Alexey Samsonov261177a2012-12-04 01:34:23 +00002167 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany530e2072013-12-23 14:15:08 +00002168 } else {
2169 poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002170 }
2171 }
2172
Kostya Serebryany09959942012-10-19 06:20:53 +00002173 // We are done. Remove the old unused alloca instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002174 for (auto AI : AllocaVec) AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002175}
Alexey Samsonov261177a2012-12-04 01:34:23 +00002176
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002177void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00002178 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00002179 // For now just insert the call to ASan runtime.
2180 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
2181 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
Alexander Potapenkof90556e2015-06-12 11:27:06 +00002182 IRB.CreateCall(
2183 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
2184 {AddrArg, SizeArg});
Alexey Samsonov261177a2012-12-04 01:34:23 +00002185}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002186
2187// Handling llvm.lifetime intrinsics for a given %alloca:
2188// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
2189// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
2190// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
2191// could be poisoned by previous llvm.lifetime.end instruction, as the
2192// variable may go in and out of scope several times, e.g. in loops).
2193// (3) if we poisoned at least one %alloca in a function,
2194// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002195
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002196AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
2197 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
2198 // We're intested only in allocas we can handle.
Anna Zaks8ed1d812015-02-27 03:12:36 +00002199 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002200 // See if we've already calculated (or started to calculate) alloca for a
2201 // given value.
2202 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002203 if (I != AllocaForValue.end()) return I->second;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002204 // Store 0 while we're calculating alloca for value V to avoid
2205 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00002206 AllocaForValue[V] = nullptr;
2207 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002208 if (CastInst *CI = dyn_cast<CastInst>(V))
2209 Res = findAllocaForValue(CI->getOperand(0));
2210 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00002211 for (Value *IncValue : PN->incoming_values()) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002212 // Allow self-referencing phi-nodes.
2213 if (IncValue == PN) continue;
2214 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
2215 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00002216 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
2217 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002218 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002219 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002220 }
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002221 if (Res) AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002222 return Res;
2223}
Yury Gribov55441bb2014-11-21 10:29:50 +00002224
Yury Gribov98b18592015-05-28 07:51:49 +00002225void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
Yury Gribov55441bb2014-11-21 10:29:50 +00002226 IRBuilder<> IRB(AI);
2227
Yury Gribov55441bb2014-11-21 10:29:50 +00002228 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
2229 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
2230
2231 Value *Zero = Constant::getNullValue(IntptrTy);
2232 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
2233 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
Yury Gribov55441bb2014-11-21 10:29:50 +00002234
2235 // Since we need to extend alloca with additional memory to locate
2236 // redzones, and OldSize is number of allocated blocks with
2237 // ElementSize size, get allocated memory size in bytes by
2238 // OldSize * ElementSize.
Yury Gribov98b18592015-05-28 07:51:49 +00002239 const unsigned ElementSize =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002240 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
Yury Gribov98b18592015-05-28 07:51:49 +00002241 Value *OldSize =
2242 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
2243 ConstantInt::get(IntptrTy, ElementSize));
Yury Gribov55441bb2014-11-21 10:29:50 +00002244
2245 // PartialSize = OldSize % 32
2246 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
2247
2248 // Misalign = kAllocaRzSize - PartialSize;
2249 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
2250
2251 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
2252 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
2253 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
2254
2255 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
2256 // Align is added to locate left redzone, PartialPadding for possible
2257 // partial redzone and kAllocaRzSize for right redzone respectively.
2258 Value *AdditionalChunkSize = IRB.CreateAdd(
2259 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
2260
2261 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
2262
2263 // Insert new alloca with new NewSize and Align params.
2264 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
2265 NewAlloca->setAlignment(Align);
2266
2267 // NewAddress = Address + Align
2268 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
2269 ConstantInt::get(IntptrTy, Align));
2270
Yury Gribov98b18592015-05-28 07:51:49 +00002271 // Insert __asan_alloca_poison call for new created alloca.
Yury Gribov781bce22015-05-28 08:03:28 +00002272 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
Yury Gribov98b18592015-05-28 07:51:49 +00002273
2274 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
2275 // for unpoisoning stuff.
2276 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
2277
Yury Gribov55441bb2014-11-21 10:29:50 +00002278 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2279
Yury Gribov98b18592015-05-28 07:51:49 +00002280 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
Yury Gribov55441bb2014-11-21 10:29:50 +00002281 AI->replaceAllUsesWith(NewAddressPtr);
2282
Yury Gribov98b18592015-05-28 07:51:49 +00002283 // We are done. Erase old alloca from parent.
Yury Gribov55441bb2014-11-21 10:29:50 +00002284 AI->eraseFromParent();
2285}
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002286
2287// isSafeAccess returns true if Addr is always inbounds with respect to its
2288// base object. For example, it is a field access or an array access with
2289// constant inbounds index.
2290bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
2291 Value *Addr, uint64_t TypeSize) const {
2292 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
2293 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
Dmitry Vyukovee842382015-03-16 08:04:26 +00002294 uint64_t Size = SizeOffset.first.getZExtValue();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002295 int64_t Offset = SizeOffset.second.getSExtValue();
2296 // Three checks are required to ensure safety:
2297 // . Offset >= 0 (since the offset is given from the base ptr)
2298 // . Size >= Offset (unsigned)
2299 // . Size - Offset >= NeededSize (unsigned)
Dmitry Vyukovee842382015-03-16 08:04:26 +00002300 return Offset >= 0 && Size >= uint64_t(Offset) &&
2301 Size - uint64_t(Offset) >= TypeSize / 8;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002302}