1 //===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "asan"
18 #include "llvm/Transforms/Instrumentation.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DepthFirstIterator.h"
22 #include "llvm/ADT/OwningPtr.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/DIBuilder.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/IRBuilder.h"
32 #include "llvm/IR/InlineAsm.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/LLVMContext.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/Type.h"
37 #include "llvm/InstVisitor.h"
38 #include "llvm/Support/CallSite.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/DataTypes.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/Endian.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Support/system_error.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/Cloning.h"
47 #include "llvm/Transforms/Utils/Local.h"
48 #include "llvm/Transforms/Utils/ModuleUtils.h"
49 #include "llvm/Transforms/Utils/SpecialCaseList.h"
55 static const uint64_t kDefaultShadowScale = 3;
56 static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
57 static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
58 static const uint64_t kDefaultShort64bitShadowOffset = 0x7FFF8000; // < 2G.
59 static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
60 static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa8000;
62 static const size_t kMinStackMallocSize = 1 << 6; // 64B
63 static const size_t kMaxStackMallocSize = 1 << 16; // 64K
64 static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
65 static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
67 static const char *const kAsanModuleCtorName = "asan.module_ctor";
68 static const char *const kAsanModuleDtorName = "asan.module_dtor";
69 static const int kAsanCtorAndCtorPriority = 1;
70 static const char *const kAsanReportErrorTemplate = "__asan_report_";
71 static const char *const kAsanReportLoadN = "__asan_report_load_n";
72 static const char *const kAsanReportStoreN = "__asan_report_store_n";
73 static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
74 static const char *const kAsanUnregisterGlobalsName =
75 "__asan_unregister_globals";
76 static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
77 static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
78 static const char *const kAsanInitName = "__asan_init_v3";
79 static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
80 static const char *const kAsanMappingOffsetName = "__asan_mapping_offset";
81 static const char *const kAsanMappingScaleName = "__asan_mapping_scale";
82 static const int kMaxAsanStackMallocSizeClass = 10;
83 static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
84 static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
85 static const char *const kAsanGenPrefix = "__asan_gen_";
86 static const char *const kAsanPoisonStackMemoryName =
87 "__asan_poison_stack_memory";
88 static const char *const kAsanUnpoisonStackMemoryName =
89 "__asan_unpoison_stack_memory";
91 static const char *const kAsanOptionDetectUAR =
92 "__asan_option_detect_stack_use_after_return";
94 // These constants must match the definitions in the run-time library.
95 static const int kAsanStackLeftRedzoneMagic = 0xf1;
96 static const int kAsanStackMidRedzoneMagic = 0xf2;
97 static const int kAsanStackRightRedzoneMagic = 0xf3;
98 static const int kAsanStackPartialRedzoneMagic = 0xf4;
100 static const int kAsanStackAfterReturnMagic = 0xf5;
103 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
104 static const size_t kNumberOfAccessSizes = 5;
106 // Command-line flags.
108 // This flag may need to be replaced with -f[no-]asan-reads.
109 static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
110 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
111 static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
112 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
113 static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
114 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
115 cl::Hidden, cl::init(true));
116 static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
117 cl::desc("use instrumentation with slow path for all accesses"),
118 cl::Hidden, cl::init(false));
119 // This flag limits the number of instructions to be instrumented
120 // in any given BB. Normally, this should be set to unlimited (INT_MAX),
121 // but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
123 static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
125 cl::desc("maximal number of instructions to instrument in any given BB"),
127 // This flag may need to be replaced with -f[no]asan-stack.
128 static cl::opt<bool> ClStack("asan-stack",
129 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
130 // This flag may need to be replaced with -f[no]asan-use-after-return.
131 static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
132 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
133 // This flag may need to be replaced with -f[no]asan-globals.
134 static cl::opt<bool> ClGlobals("asan-globals",
135 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
136 static cl::opt<bool> ClInitializers("asan-initialization-order",
137 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
138 static cl::opt<bool> ClMemIntrin("asan-memintrin",
139 cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
140 static cl::opt<bool> ClRealignStack("asan-realign-stack",
141 cl::desc("Realign stack to 32"), cl::Hidden, cl::init(true));
142 static cl::opt<std::string> ClBlacklistFile("asan-blacklist",
143 cl::desc("File containing the list of objects to ignore "
144 "during instrumentation"), cl::Hidden);
146 // This is an experimental feature that will allow to choose between
147 // instrumented and non-instrumented code at link-time.
148 // If this option is on, just before instrumenting a function we create its
149 // clone; if the function is not changed by asan the clone is deleted.
150 // If we end up with a clone, we put the instrumented function into a section
151 // called "ASAN" and the uninstrumented function into a section called "NOASAN".
153 // This is still a prototype, we need to figure out a way to keep two copies of
154 // a function so that the linker can easily choose one of them.
155 static cl::opt<bool> ClKeepUninstrumented("asan-keep-uninstrumented-functions",
156 cl::desc("Keep uninstrumented copies of functions"),
157 cl::Hidden, cl::init(false));
159 // These flags allow to change the shadow mapping.
160 // The shadow mapping looks like
161 // Shadow = (Mem >> scale) + (1 << offset_log)
162 static cl::opt<int> ClMappingScale("asan-mapping-scale",
163 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
164 static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
165 cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
166 static cl::opt<bool> ClShort64BitOffset("asan-short-64bit-mapping-offset",
167 cl::desc("Use short immediate constant as the mapping offset for 64bit"),
168 cl::Hidden, cl::init(true));
170 // Optimization flags. Not user visible, used mostly for testing
171 // and benchmarking the tool.
172 static cl::opt<bool> ClOpt("asan-opt",
173 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
174 static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
175 cl::desc("Instrument the same temp just once"), cl::Hidden,
177 static cl::opt<bool> ClOptGlobals("asan-opt-globals",
178 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
180 static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
181 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
182 cl::Hidden, cl::init(false));
185 static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
187 static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
188 cl::Hidden, cl::init(0));
189 static cl::opt<std::string> ClDebugFunc("asan-debug-func",
190 cl::Hidden, cl::desc("Debug func"));
191 static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
192 cl::Hidden, cl::init(-1));
193 static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
194 cl::Hidden, cl::init(-1));
197 /// A set of dynamically initialized globals extracted from metadata.
198 class SetOfDynamicallyInitializedGlobals {
200 void Init(Module& M) {
201 // Clang generates metadata identifying all dynamically initialized globals.
202 NamedMDNode *DynamicGlobals =
203 M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
206 for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
207 MDNode *MDN = DynamicGlobals->getOperand(i);
208 assert(MDN->getNumOperands() == 1);
209 Value *VG = MDN->getOperand(0);
210 // The optimizer may optimize away a global entirely, in which case we
211 // cannot instrument access to it.
214 DynInitGlobals.insert(cast<GlobalVariable>(VG));
217 bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
219 SmallSet<GlobalValue*, 32> DynInitGlobals;
222 /// This struct defines the shadow mapping using the rule:
223 /// shadow = (mem >> Scale) ADD-or-OR Offset.
224 struct ShadowMapping {
230 static ShadowMapping getShadowMapping(const Module &M, int LongSize,
231 bool ZeroBaseShadow) {
232 llvm::Triple TargetTriple(M.getTargetTriple());
233 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
234 bool IsMacOSX = TargetTriple.getOS() == llvm::Triple::MacOSX;
235 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
236 TargetTriple.getArch() == llvm::Triple::ppc64le;
237 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
238 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
239 TargetTriple.getArch() == llvm::Triple::mipsel;
241 ShadowMapping Mapping;
243 // OR-ing shadow offset if more efficient (at least on x86),
244 // but on ppc64 we have to use add since the shadow offset is not neccesary
245 // 1/8-th of the address space.
246 Mapping.OrShadowOffset = !IsPPC64 && !ClShort64BitOffset;
248 Mapping.Offset = (IsAndroid || ZeroBaseShadow) ? 0 :
250 (IsMIPS32 ? kMIPS32_ShadowOffset32 : kDefaultShadowOffset32) :
251 IsPPC64 ? kPPC64_ShadowOffset64 : kDefaultShadowOffset64);
252 if (!ZeroBaseShadow && ClShort64BitOffset && IsX86_64 && !IsMacOSX) {
253 assert(LongSize == 64);
254 Mapping.Offset = kDefaultShort64bitShadowOffset;
256 if (!ZeroBaseShadow && ClMappingOffsetLog >= 0) {
257 // Zero offset log is the special case.
258 Mapping.Offset = (ClMappingOffsetLog == 0) ? 0 : 1ULL << ClMappingOffsetLog;
261 Mapping.Scale = kDefaultShadowScale;
262 if (ClMappingScale) {
263 Mapping.Scale = ClMappingScale;
269 static size_t RedzoneSizeForScale(int MappingScale) {
270 // Redzone used for stack and globals is at least 32 bytes.
271 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
272 return std::max(32U, 1U << MappingScale);
275 /// AddressSanitizer: instrument the code in module to find memory bugs.
276 struct AddressSanitizer : public FunctionPass {
277 AddressSanitizer(bool CheckInitOrder = true,
278 bool CheckUseAfterReturn = false,
279 bool CheckLifetime = false,
280 StringRef BlacklistFile = StringRef(),
281 bool ZeroBaseShadow = false)
283 CheckInitOrder(CheckInitOrder || ClInitializers),
284 CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
285 CheckLifetime(CheckLifetime || ClCheckLifetime),
286 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
288 ZeroBaseShadow(ZeroBaseShadow) {}
289 virtual const char *getPassName() const {
290 return "AddressSanitizerFunctionPass";
292 void instrumentMop(Instruction *I);
293 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
294 Value *Addr, uint32_t TypeSize, bool IsWrite,
295 Value *SizeArgument);
296 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
297 Value *ShadowValue, uint32_t TypeSize);
298 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
299 bool IsWrite, size_t AccessSizeIndex,
300 Value *SizeArgument);
301 bool instrumentMemIntrinsic(MemIntrinsic *MI);
302 void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
304 Instruction *InsertBefore, bool IsWrite);
305 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
306 bool runOnFunction(Function &F);
307 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
308 void emitShadowMapping(Module &M, IRBuilder<> &IRB) const;
309 virtual bool doInitialization(Module &M);
310 static char ID; // Pass identification, replacement for typeid
313 void initializeCallbacks(Module &M);
315 bool ShouldInstrumentGlobal(GlobalVariable *G);
316 bool LooksLikeCodeInBug11395(Instruction *I);
317 void FindDynamicInitializers(Module &M);
320 bool CheckUseAfterReturn;
322 SmallString<64> BlacklistFile;
329 ShadowMapping Mapping;
330 Function *AsanCtorFunction;
331 Function *AsanInitFunction;
332 Function *AsanHandleNoReturnFunc;
333 OwningPtr<SpecialCaseList> BL;
334 // This array is indexed by AccessIsWrite and log2(AccessSize).
335 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
336 // This array is indexed by AccessIsWrite.
337 Function *AsanErrorCallbackSized[2];
339 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
341 friend struct FunctionStackPoisoner;
344 class AddressSanitizerModule : public ModulePass {
346 AddressSanitizerModule(bool CheckInitOrder = true,
347 StringRef BlacklistFile = StringRef(),
348 bool ZeroBaseShadow = false)
350 CheckInitOrder(CheckInitOrder || ClInitializers),
351 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
353 ZeroBaseShadow(ZeroBaseShadow) {}
354 bool runOnModule(Module &M);
355 static char ID; // Pass identification, replacement for typeid
356 virtual const char *getPassName() const {
357 return "AddressSanitizerModule";
361 void initializeCallbacks(Module &M);
363 bool ShouldInstrumentGlobal(GlobalVariable *G);
364 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
365 size_t RedzoneSize() const {
366 return RedzoneSizeForScale(Mapping.Scale);
370 SmallString<64> BlacklistFile;
373 OwningPtr<SpecialCaseList> BL;
374 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
378 ShadowMapping Mapping;
379 Function *AsanPoisonGlobals;
380 Function *AsanUnpoisonGlobals;
381 Function *AsanRegisterGlobals;
382 Function *AsanUnregisterGlobals;
385 // Stack poisoning does not play well with exception handling.
386 // When an exception is thrown, we essentially bypass the code
387 // that unpoisones the stack. This is why the run-time library has
388 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
389 // stack in the interceptor. This however does not work inside the
390 // actual function which catches the exception. Most likely because the
391 // compiler hoists the load of the shadow value somewhere too high.
392 // This causes asan to report a non-existing bug on 453.povray.
393 // It sounds like an LLVM bug.
394 struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
396 AddressSanitizer &ASan;
401 ShadowMapping Mapping;
403 SmallVector<AllocaInst*, 16> AllocaVec;
404 SmallVector<Instruction*, 8> RetVec;
405 uint64_t TotalStackSize;
406 unsigned StackAlignment;
408 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
409 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
410 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
412 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
413 struct AllocaPoisonCall {
414 IntrinsicInst *InsBefore;
418 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
420 // Maps Value to an AllocaInst from which the Value is originated.
421 typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
422 AllocaForValueMapTy AllocaForValue;
424 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
425 : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
426 IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
427 Mapping(ASan.Mapping),
428 TotalStackSize(0), StackAlignment(1 << Mapping.Scale) {}
430 bool runOnFunction() {
431 if (!ClStack) return false;
432 // Collect alloca, ret, lifetime instructions etc.
433 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
434 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
435 BasicBlock *BB = *DI;
438 if (AllocaVec.empty()) return false;
440 initializeCallbacks(*F.getParent());
450 // Finds all static Alloca instructions and puts
451 // poisoned red zones around all of them.
452 // Then unpoison everything back before the function returns.
455 // ----------------------- Visitors.
456 /// \brief Collect all Ret instructions.
457 void visitReturnInst(ReturnInst &RI) {
458 RetVec.push_back(&RI);
461 /// \brief Collect Alloca instructions we want (and can) handle.
462 void visitAllocaInst(AllocaInst &AI) {
463 if (!isInterestingAlloca(AI)) return;
465 StackAlignment = std::max(StackAlignment, AI.getAlignment());
466 AllocaVec.push_back(&AI);
467 uint64_t AlignedSize = getAlignedAllocaSize(&AI);
468 TotalStackSize += AlignedSize;
471 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
473 void visitIntrinsicInst(IntrinsicInst &II) {
474 if (!ASan.CheckLifetime) return;
475 Intrinsic::ID ID = II.getIntrinsicID();
476 if (ID != Intrinsic::lifetime_start &&
477 ID != Intrinsic::lifetime_end)
479 // Found lifetime intrinsic, add ASan instrumentation if necessary.
480 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
481 // If size argument is undefined, don't do anything.
482 if (Size->isMinusOne()) return;
483 // Check that size doesn't saturate uint64_t and can
484 // be stored in IntptrTy.
485 const uint64_t SizeValue = Size->getValue().getLimitedValue();
486 if (SizeValue == ~0ULL ||
487 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
489 // Find alloca instruction that corresponds to llvm.lifetime argument.
490 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
492 bool DoPoison = (ID == Intrinsic::lifetime_end);
493 AllocaPoisonCall APC = {&II, SizeValue, DoPoison};
494 AllocaPoisonCallVec.push_back(APC);
497 // ---------------------- Helpers.
498 void initializeCallbacks(Module &M);
500 // Check if we want (and can) handle this alloca.
501 bool isInterestingAlloca(AllocaInst &AI) const {
502 return (!AI.isArrayAllocation() &&
503 AI.isStaticAlloca() &&
504 AI.getAlignment() <= RedzoneSize() &&
505 AI.getAllocatedType()->isSized());
508 size_t RedzoneSize() const {
509 return RedzoneSizeForScale(Mapping.Scale);
511 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
512 Type *Ty = AI->getAllocatedType();
513 uint64_t SizeInBytes = ASan.TD->getTypeAllocSize(Ty);
516 uint64_t getAlignedSize(uint64_t SizeInBytes) const {
517 size_t RZ = RedzoneSize();
518 return ((SizeInBytes + RZ - 1) / RZ) * RZ;
520 uint64_t getAlignedAllocaSize(AllocaInst *AI) const {
521 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
522 return getAlignedSize(SizeInBytes);
524 /// Finds alloca where the value comes from.
525 AllocaInst *findAllocaForValue(Value *V);
526 void poisonRedZones(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> &IRB,
527 Value *ShadowBase, bool DoPoison);
528 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
530 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
536 char AddressSanitizer::ID = 0;
537 INITIALIZE_PASS(AddressSanitizer, "asan",
538 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
540 FunctionPass *llvm::createAddressSanitizerFunctionPass(
541 bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime,
542 StringRef BlacklistFile, bool ZeroBaseShadow) {
543 return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
544 CheckLifetime, BlacklistFile, ZeroBaseShadow);
547 char AddressSanitizerModule::ID = 0;
548 INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
549 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
550 "ModulePass", false, false)
551 ModulePass *llvm::createAddressSanitizerModulePass(
552 bool CheckInitOrder, StringRef BlacklistFile, bool ZeroBaseShadow) {
553 return new AddressSanitizerModule(CheckInitOrder, BlacklistFile,
557 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
558 size_t Res = countTrailingZeros(TypeSize / 8);
559 assert(Res < kNumberOfAccessSizes);
563 // \brief Create a constant for Str so that we can pass it to the run-time lib.
564 static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
565 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
566 GlobalVariable *GV = new GlobalVariable(M, StrConst->getType(), true,
567 GlobalValue::InternalLinkage, StrConst,
569 GV->setUnnamedAddr(true); // Ok to merge these.
570 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
574 static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
575 return G->getName().find(kAsanGenPrefix) == 0;
578 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
580 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
581 if (Mapping.Offset == 0)
583 // (Shadow >> scale) | offset
584 if (Mapping.OrShadowOffset)
585 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
587 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
590 void AddressSanitizer::instrumentMemIntrinsicParam(
591 Instruction *OrigIns,
592 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
593 IRBuilder<> IRB(InsertBefore);
594 if (Size->getType() != IntptrTy)
595 Size = IRB.CreateIntCast(Size, IntptrTy, false);
596 // Check the first byte.
597 instrumentAddress(OrigIns, InsertBefore, Addr, 8, IsWrite, Size);
598 // Check the last byte.
599 IRB.SetInsertPoint(InsertBefore);
600 Value *SizeMinusOne = IRB.CreateSub(Size, ConstantInt::get(IntptrTy, 1));
601 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
602 Value *AddrLast = IRB.CreateAdd(AddrLong, SizeMinusOne);
603 instrumentAddress(OrigIns, InsertBefore, AddrLast, 8, IsWrite, Size);
606 // Instrument memset/memmove/memcpy
607 bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
608 Value *Dst = MI->getDest();
609 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
610 Value *Src = MemTran ? MemTran->getSource() : 0;
611 Value *Length = MI->getLength();
613 Constant *ConstLength = dyn_cast<Constant>(Length);
614 Instruction *InsertBefore = MI;
616 if (ConstLength->isNullValue()) return false;
618 // The size is not a constant so it could be zero -- check at run-time.
619 IRBuilder<> IRB(InsertBefore);
621 Value *Cmp = IRB.CreateICmpNE(Length,
622 Constant::getNullValue(Length->getType()));
623 InsertBefore = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
626 instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
628 instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
632 // If I is an interesting memory access, return the PointerOperand
633 // and set IsWrite. Otherwise return NULL.
634 static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
635 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
636 if (!ClInstrumentReads) return NULL;
638 return LI->getPointerOperand();
640 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
641 if (!ClInstrumentWrites) return NULL;
643 return SI->getPointerOperand();
645 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
646 if (!ClInstrumentAtomics) return NULL;
648 return RMW->getPointerOperand();
650 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
651 if (!ClInstrumentAtomics) return NULL;
653 return XCHG->getPointerOperand();
658 void AddressSanitizer::instrumentMop(Instruction *I) {
659 bool IsWrite = false;
660 Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
662 if (ClOpt && ClOptGlobals) {
663 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
664 // If initialization order checking is disabled, a simple access to a
665 // dynamically initialized global is always valid.
668 // If a global variable does not have dynamic initialization we don't
669 // have to instrument it. However, if a global does not have initailizer
670 // at all, we assume it has dynamic initializer (in other TU).
671 if (G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G))
676 Type *OrigPtrTy = Addr->getType();
677 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
679 assert(OrigTy->isSized());
680 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
682 assert((TypeSize % 8) == 0);
684 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check.
685 if (TypeSize == 8 || TypeSize == 16 ||
686 TypeSize == 32 || TypeSize == 64 || TypeSize == 128)
687 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, 0);
688 // Instrument unusual size (but still multiple of 8).
689 // We can not do it with a single check, so we do 1-byte check for the first
690 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
691 // to report the actual access size.
693 Value *LastByte = IRB.CreateIntToPtr(
694 IRB.CreateAdd(IRB.CreatePointerCast(Addr, IntptrTy),
695 ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
697 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
698 instrumentAddress(I, I, Addr, 8, IsWrite, Size);
699 instrumentAddress(I, I, LastByte, 8, IsWrite, Size);
702 // Validate the result of Module::getOrInsertFunction called for an interface
703 // function of AddressSanitizer. If the instrumented module defines a function
704 // with the same name, their prototypes must match, otherwise
705 // getOrInsertFunction returns a bitcast.
706 static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
707 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
708 FuncOrBitcast->dump();
709 report_fatal_error("trying to redefine an AddressSanitizer "
710 "interface function");
713 Instruction *AddressSanitizer::generateCrashCode(
714 Instruction *InsertBefore, Value *Addr,
715 bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
716 IRBuilder<> IRB(InsertBefore);
717 CallInst *Call = SizeArgument
718 ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
719 : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
721 // We don't do Call->setDoesNotReturn() because the BB already has
722 // UnreachableInst at the end.
723 // This EmptyAsm is required to avoid callback merge.
724 IRB.CreateCall(EmptyAsm);
728 Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
731 size_t Granularity = 1 << Mapping.Scale;
732 // Addr & (Granularity - 1)
733 Value *LastAccessedByte = IRB.CreateAnd(
734 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
735 // (Addr & (Granularity - 1)) + size - 1
736 if (TypeSize / 8 > 1)
737 LastAccessedByte = IRB.CreateAdd(
738 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
739 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
740 LastAccessedByte = IRB.CreateIntCast(
741 LastAccessedByte, ShadowValue->getType(), false);
742 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
743 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
746 void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
747 Instruction *InsertBefore,
748 Value *Addr, uint32_t TypeSize,
749 bool IsWrite, Value *SizeArgument) {
750 IRBuilder<> IRB(InsertBefore);
751 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
753 Type *ShadowTy = IntegerType::get(
754 *C, std::max(8U, TypeSize >> Mapping.Scale));
755 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
756 Value *ShadowPtr = memToShadow(AddrLong, IRB);
757 Value *CmpVal = Constant::getNullValue(ShadowTy);
758 Value *ShadowValue = IRB.CreateLoad(
759 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
761 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
762 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
763 size_t Granularity = 1 << Mapping.Scale;
764 TerminatorInst *CrashTerm = 0;
766 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
767 TerminatorInst *CheckTerm =
768 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
769 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
770 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
771 IRB.SetInsertPoint(CheckTerm);
772 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
773 BasicBlock *CrashBlock =
774 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
775 CrashTerm = new UnreachableInst(*C, CrashBlock);
776 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
777 ReplaceInstWithInst(CheckTerm, NewTerm);
779 CrashTerm = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), true);
782 Instruction *Crash = generateCrashCode(
783 CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
784 Crash->setDebugLoc(OrigIns->getDebugLoc());
787 void AddressSanitizerModule::createInitializerPoisonCalls(
788 Module &M, GlobalValue *ModuleName) {
789 // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
790 Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
791 // If that function is not present, this TU contains no globals, or they have
792 // all been optimized away
796 // Set up the arguments to our poison/unpoison functions.
797 IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
799 // Add a call to poison all external globals before the given function starts.
800 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
801 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
803 // Add calls to unpoison all globals before each return instruction.
804 for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
806 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
807 CallInst::Create(AsanUnpoisonGlobals, "", RI);
812 bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
813 Type *Ty = cast<PointerType>(G->getType())->getElementType();
814 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
816 if (BL->isIn(*G)) return false;
817 if (!Ty->isSized()) return false;
818 if (!G->hasInitializer()) return false;
819 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
820 // Touch only those globals that will not be defined in other modules.
821 // Don't handle ODR type linkages since other modules may be built w/o asan.
822 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
823 G->getLinkage() != GlobalVariable::PrivateLinkage &&
824 G->getLinkage() != GlobalVariable::InternalLinkage)
826 // Two problems with thread-locals:
827 // - The address of the main thread's copy can't be computed at link-time.
828 // - Need to poison all copies, not just the main thread's one.
829 if (G->isThreadLocal())
831 // For now, just ignore this Alloca if the alignment is large.
832 if (G->getAlignment() > RedzoneSize()) return false;
834 // Ignore all the globals with the names starting with "\01L_OBJC_".
835 // Many of those are put into the .cstring section. The linker compresses
836 // that section by removing the spare \0s after the string terminator, so
837 // our redzones get broken.
838 if ((G->getName().find("\01L_OBJC_") == 0) ||
839 (G->getName().find("\01l_OBJC_") == 0)) {
840 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
844 if (G->hasSection()) {
845 StringRef Section(G->getSection());
846 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
847 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
849 if ((Section.find("__OBJC,") == 0) ||
850 (Section.find("__DATA, __objc_") == 0)) {
851 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
854 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
855 // Constant CFString instances are compiled in the following way:
856 // -- the string buffer is emitted into
857 // __TEXT,__cstring,cstring_literals
858 // -- the constant NSConstantString structure referencing that buffer
859 // is placed into __DATA,__cfstring
860 // Therefore there's no point in placing redzones into __DATA,__cfstring.
861 // Moreover, it causes the linker to crash on OS X 10.7
862 if (Section.find("__DATA,__cfstring") == 0) {
863 DEBUG(dbgs() << "Ignoring CFString: " << *G);
871 void AddressSanitizerModule::initializeCallbacks(Module &M) {
873 // Declare our poisoning and unpoisoning functions.
874 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
875 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, NULL));
876 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
877 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
878 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
879 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
880 // Declare functions that register/unregister globals.
881 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
882 kAsanRegisterGlobalsName, IRB.getVoidTy(),
883 IntptrTy, IntptrTy, NULL));
884 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
885 AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
886 kAsanUnregisterGlobalsName,
887 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
888 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
891 // This function replaces all global variables with new variables that have
892 // trailing redzones. It also creates a function that poisons
893 // redzones and inserts this function into llvm.global_ctors.
894 bool AddressSanitizerModule::runOnModule(Module &M) {
895 if (!ClGlobals) return false;
896 TD = getAnalysisIfAvailable<DataLayout>();
899 BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
900 if (BL->isIn(M)) return false;
901 C = &(M.getContext());
902 int LongSize = TD->getPointerSizeInBits();
903 IntptrTy = Type::getIntNTy(*C, LongSize);
904 Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
905 initializeCallbacks(M);
906 DynamicallyInitializedGlobals.Init(M);
908 SmallVector<GlobalVariable *, 16> GlobalsToChange;
910 for (Module::GlobalListType::iterator G = M.global_begin(),
911 E = M.global_end(); G != E; ++G) {
912 if (ShouldInstrumentGlobal(G))
913 GlobalsToChange.push_back(G);
916 size_t n = GlobalsToChange.size();
917 if (n == 0) return false;
919 // A global is described by a structure
922 // size_t size_with_redzone;
924 // const char *module_name;
925 // size_t has_dynamic_init;
926 // We initialize an array of such structures and pass it to a run-time call.
927 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
929 IntptrTy, IntptrTy, NULL);
930 SmallVector<Constant *, 16> Initializers(n), DynamicInit;
933 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
935 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
937 bool HasDynamicallyInitializedGlobals = false;
939 GlobalVariable *ModuleName = createPrivateGlobalForString(
940 M, M.getModuleIdentifier());
941 // We shouldn't merge same module names, as this string serves as unique
942 // module ID in runtime.
943 ModuleName->setUnnamedAddr(false);
945 for (size_t i = 0; i < n; i++) {
946 static const uint64_t kMaxGlobalRedzone = 1 << 18;
947 GlobalVariable *G = GlobalsToChange[i];
948 PointerType *PtrTy = cast<PointerType>(G->getType());
949 Type *Ty = PtrTy->getElementType();
950 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
951 uint64_t MinRZ = RedzoneSize();
952 // MinRZ <= RZ <= kMaxGlobalRedzone
953 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
954 uint64_t RZ = std::max(MinRZ,
955 std::min(kMaxGlobalRedzone,
956 (SizeInBytes / MinRZ / 4) * MinRZ));
957 uint64_t RightRedzoneSize = RZ;
959 if (SizeInBytes % MinRZ)
960 RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
961 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
962 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
963 // Determine whether this global should be poisoned in initialization.
964 bool GlobalHasDynamicInitializer =
965 DynamicallyInitializedGlobals.Contains(G);
966 // Don't check initialization order if this global is blacklisted.
967 GlobalHasDynamicInitializer &= !BL->isIn(*G, "init");
969 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
970 Constant *NewInitializer = ConstantStruct::get(
971 NewTy, G->getInitializer(),
972 Constant::getNullValue(RightRedZoneTy), NULL);
974 GlobalVariable *Name = createPrivateGlobalForString(M, G->getName());
976 // Create a new global variable with enough space for a redzone.
977 GlobalValue::LinkageTypes Linkage = G->getLinkage();
978 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
979 Linkage = GlobalValue::InternalLinkage;
980 GlobalVariable *NewGlobal = new GlobalVariable(
981 M, NewTy, G->isConstant(), Linkage,
982 NewInitializer, "", G, G->getThreadLocalMode());
983 NewGlobal->copyAttributesFrom(G);
984 NewGlobal->setAlignment(MinRZ);
987 Indices2[0] = IRB.getInt32(0);
988 Indices2[1] = IRB.getInt32(0);
990 G->replaceAllUsesWith(
991 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
992 NewGlobal->takeName(G);
993 G->eraseFromParent();
995 Initializers[i] = ConstantStruct::get(
997 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
998 ConstantInt::get(IntptrTy, SizeInBytes),
999 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1000 ConstantExpr::getPointerCast(Name, IntptrTy),
1001 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
1002 ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
1005 // Populate the first and last globals declared in this TU.
1006 if (CheckInitOrder && GlobalHasDynamicInitializer)
1007 HasDynamicallyInitializedGlobals = true;
1009 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
1012 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1013 GlobalVariable *AllGlobals = new GlobalVariable(
1014 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1015 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1017 // Create calls for poisoning before initializers run and unpoisoning after.
1018 if (CheckInitOrder && HasDynamicallyInitializedGlobals)
1019 createInitializerPoisonCalls(M, ModuleName);
1020 IRB.CreateCall2(AsanRegisterGlobals,
1021 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1022 ConstantInt::get(IntptrTy, n));
1024 // We also need to unregister globals at the end, e.g. when a shared library
1026 Function *AsanDtorFunction = Function::Create(
1027 FunctionType::get(Type::getVoidTy(*C), false),
1028 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1029 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1030 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
1031 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
1032 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1033 ConstantInt::get(IntptrTy, n));
1034 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
1040 void AddressSanitizer::initializeCallbacks(Module &M) {
1041 IRBuilder<> IRB(*C);
1042 // Create __asan_report* callbacks.
1043 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1044 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1045 AccessSizeIndex++) {
1046 // IsWrite and TypeSize are encoded in the function name.
1047 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
1048 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
1049 // If we are merging crash callbacks, they have two parameters.
1050 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
1051 checkInterfaceFunction(M.getOrInsertFunction(
1052 FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
1055 AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
1056 kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1057 AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
1058 kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1060 AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
1061 kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
1062 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1063 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1064 StringRef(""), StringRef(""),
1065 /*hasSideEffects=*/true);
1068 void AddressSanitizer::emitShadowMapping(Module &M, IRBuilder<> &IRB) const {
1069 // Tell the values of mapping offset and scale to the run-time.
1070 GlobalValue *asan_mapping_offset =
1071 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1072 ConstantInt::get(IntptrTy, Mapping.Offset),
1073 kAsanMappingOffsetName);
1074 // Read the global, otherwise it may be optimized away.
1075 IRB.CreateLoad(asan_mapping_offset, true);
1077 GlobalValue *asan_mapping_scale =
1078 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1079 ConstantInt::get(IntptrTy, Mapping.Scale),
1080 kAsanMappingScaleName);
1081 // Read the global, otherwise it may be optimized away.
1082 IRB.CreateLoad(asan_mapping_scale, true);
1086 bool AddressSanitizer::doInitialization(Module &M) {
1087 // Initialize the private fields. No one has accessed them before.
1088 TD = getAnalysisIfAvailable<DataLayout>();
1092 BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
1093 DynamicallyInitializedGlobals.Init(M);
1095 C = &(M.getContext());
1096 LongSize = TD->getPointerSizeInBits();
1097 IntptrTy = Type::getIntNTy(*C, LongSize);
1099 AsanCtorFunction = Function::Create(
1100 FunctionType::get(Type::getVoidTy(*C), false),
1101 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1102 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1103 // call __asan_init in the module ctor.
1104 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1105 AsanInitFunction = checkInterfaceFunction(
1106 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
1107 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1108 IRB.CreateCall(AsanInitFunction);
1110 Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
1111 emitShadowMapping(M, IRB);
1113 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
1117 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1118 // For each NSObject descendant having a +load method, this method is invoked
1119 // by the ObjC runtime before any of the static constructors is called.
1120 // Therefore we need to instrument such methods with a call to __asan_init
1121 // at the beginning in order to initialize our runtime before any access to
1122 // the shadow memory.
1123 // We cannot just ignore these methods, because they may call other
1124 // instrumented functions.
1125 if (F.getName().find(" load]") != std::string::npos) {
1126 IRBuilder<> IRB(F.begin()->begin());
1127 IRB.CreateCall(AsanInitFunction);
1133 bool AddressSanitizer::runOnFunction(Function &F) {
1134 if (BL->isIn(F)) return false;
1135 if (&F == AsanCtorFunction) return false;
1136 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
1137 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
1138 initializeCallbacks(*F.getParent());
1140 // If needed, insert __asan_init before checking for SanitizeAddress attr.
1141 maybeInsertAsanInitAtFunctionEntry(F);
1143 if (!F.hasFnAttribute(Attribute::SanitizeAddress))
1146 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1149 // We want to instrument every address only once per basic block (unless there
1150 // are calls between uses).
1151 SmallSet<Value*, 16> TempsToInstrument;
1152 SmallVector<Instruction*, 16> ToInstrument;
1153 SmallVector<Instruction*, 8> NoReturnCalls;
1157 // Fill the set of memory operations to instrument.
1158 for (Function::iterator FI = F.begin(), FE = F.end();
1160 TempsToInstrument.clear();
1161 int NumInsnsPerBB = 0;
1162 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1164 if (LooksLikeCodeInBug11395(BI)) return false;
1165 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
1166 if (ClOpt && ClOptSameTemp) {
1167 if (!TempsToInstrument.insert(Addr))
1168 continue; // We've seen this temp in the current BB.
1170 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
1173 if (isa<AllocaInst>(BI))
1177 // A call inside BB.
1178 TempsToInstrument.clear();
1179 if (CS.doesNotReturn())
1180 NoReturnCalls.push_back(CS.getInstruction());
1184 ToInstrument.push_back(BI);
1186 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1191 Function *UninstrumentedDuplicate = 0;
1192 bool LikelyToInstrument =
1193 !NoReturnCalls.empty() || !ToInstrument.empty() || (NumAllocas > 0);
1194 if (ClKeepUninstrumented && LikelyToInstrument) {
1195 ValueToValueMapTy VMap;
1196 UninstrumentedDuplicate = CloneFunction(&F, VMap, false);
1197 UninstrumentedDuplicate->removeFnAttr(Attribute::SanitizeAddress);
1198 UninstrumentedDuplicate->setName("NOASAN_" + F.getName());
1199 F.getParent()->getFunctionList().push_back(UninstrumentedDuplicate);
1203 int NumInstrumented = 0;
1204 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
1205 Instruction *Inst = ToInstrument[i];
1206 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1207 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
1208 if (isInterestingMemoryAccess(Inst, &IsWrite))
1209 instrumentMop(Inst);
1211 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
1216 FunctionStackPoisoner FSP(F, *this);
1217 bool ChangedStack = FSP.runOnFunction();
1219 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1220 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1221 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
1222 Instruction *CI = NoReturnCalls[i];
1223 IRBuilder<> IRB(CI);
1224 IRB.CreateCall(AsanHandleNoReturnFunc);
1227 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
1228 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1230 if (ClKeepUninstrumented) {
1232 // No instrumentation is done, no need for the duplicate.
1233 if (UninstrumentedDuplicate)
1234 UninstrumentedDuplicate->eraseFromParent();
1236 // The function was instrumented. We must have the duplicate.
1237 assert(UninstrumentedDuplicate);
1238 UninstrumentedDuplicate->setSection("NOASAN");
1239 assert(!F.hasSection());
1240 F.setSection("ASAN");
1247 static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
1248 if (ShadowRedzoneSize == 1) return PoisonByte;
1249 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
1250 if (ShadowRedzoneSize == 4)
1251 return (PoisonByte << 24) + (PoisonByte << 16) +
1252 (PoisonByte << 8) + (PoisonByte);
1253 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
1256 static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
1259 size_t ShadowGranularity,
1261 for (size_t i = 0; i < RZSize;
1262 i+= ShadowGranularity, Shadow++) {
1263 if (i + ShadowGranularity <= Size) {
1264 *Shadow = 0; // fully addressable
1265 } else if (i >= Size) {
1266 *Shadow = Magic; // unaddressable
1268 *Shadow = Size - i; // first Size-i bytes are addressable
1273 // Workaround for bug 11395: we don't want to instrument stack in functions
1274 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1275 // FIXME: remove once the bug 11395 is fixed.
1276 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1277 if (LongSize != 32) return false;
1278 CallInst *CI = dyn_cast<CallInst>(I);
1279 if (!CI || !CI->isInlineAsm()) return false;
1280 if (CI->getNumArgOperands() <= 5) return false;
1281 // We have inline assembly with quite a few arguments.
1285 void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1286 IRBuilder<> IRB(*C);
1287 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1288 std::string Suffix = itostr(i);
1289 AsanStackMallocFunc[i] = checkInterfaceFunction(
1290 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1291 IntptrTy, IntptrTy, NULL));
1292 AsanStackFreeFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
1293 kAsanStackFreeNameTemplate + Suffix, IRB.getVoidTy(), IntptrTy,
1294 IntptrTy, IntptrTy, NULL));
1296 AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1297 kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1298 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1299 kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1302 void FunctionStackPoisoner::poisonRedZones(
1303 const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> &IRB, Value *ShadowBase,
1305 size_t ShadowRZSize = RedzoneSize() >> Mapping.Scale;
1306 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
1307 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
1308 Type *RZPtrTy = PointerType::get(RZTy, 0);
1310 Value *PoisonLeft = ConstantInt::get(RZTy,
1311 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
1312 Value *PoisonMid = ConstantInt::get(RZTy,
1313 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
1314 Value *PoisonRight = ConstantInt::get(RZTy,
1315 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
1317 // poison the first red zone.
1318 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
1320 // poison all other red zones.
1321 uint64_t Pos = RedzoneSize();
1322 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1323 AllocaInst *AI = AllocaVec[i];
1324 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1325 uint64_t AlignedSize = getAlignedAllocaSize(AI);
1326 assert(AlignedSize - SizeInBytes < RedzoneSize());
1331 assert(ShadowBase->getType() == IntptrTy);
1332 if (SizeInBytes < AlignedSize) {
1333 // Poison the partial redzone at right
1334 Ptr = IRB.CreateAdd(
1335 ShadowBase, ConstantInt::get(IntptrTy,
1336 (Pos >> Mapping.Scale) - ShadowRZSize));
1337 size_t AddressableBytes = RedzoneSize() - (AlignedSize - SizeInBytes);
1338 uint32_t Poison = 0;
1340 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
1342 1ULL << Mapping.Scale,
1343 kAsanStackPartialRedzoneMagic);
1345 ASan.TD->isLittleEndian()
1346 ? support::endian::byte_swap<uint32_t, support::little>(Poison)
1347 : support::endian::byte_swap<uint32_t, support::big>(Poison);
1349 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
1350 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1353 // Poison the full redzone at right.
1354 Ptr = IRB.CreateAdd(ShadowBase,
1355 ConstantInt::get(IntptrTy, Pos >> Mapping.Scale));
1356 bool LastAlloca = (i == AllocaVec.size() - 1);
1357 Value *Poison = LastAlloca ? PoisonRight : PoisonMid;
1358 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1360 Pos += RedzoneSize();
1364 // Fake stack allocator (asan_fake_stack.h) has 11 size classes
1365 // for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1366 static int StackMallocSizeClass(uint64_t LocalStackSize) {
1367 assert(LocalStackSize <= kMaxStackMallocSize);
1368 uint64_t MaxSize = kMinStackMallocSize;
1369 for (int i = 0; ; i++, MaxSize *= 2)
1370 if (LocalStackSize <= MaxSize)
1372 llvm_unreachable("impossible LocalStackSize");
1375 // Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1376 // We can not use MemSet intrinsic because it may end up calling the actual
1377 // memset. Size is a multiple of 8.
1378 // Currently this generates 8-byte stores on x86_64; it may be better to
1379 // generate wider stores.
1380 void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1381 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1382 assert(!(Size % 8));
1383 assert(kAsanStackAfterReturnMagic == 0xf5);
1384 for (int i = 0; i < Size; i += 8) {
1385 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1386 IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
1387 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1391 void FunctionStackPoisoner::poisonStack() {
1392 uint64_t LocalStackSize = TotalStackSize +
1393 (AllocaVec.size() + 1) * RedzoneSize();
1395 bool DoStackMalloc = ASan.CheckUseAfterReturn
1396 && LocalStackSize <= kMaxStackMallocSize;
1397 int StackMallocIdx = -1;
1399 assert(AllocaVec.size() > 0);
1400 Instruction *InsBefore = AllocaVec[0];
1401 IRBuilder<> IRB(InsBefore);
1404 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1405 AllocaInst *MyAlloca =
1406 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
1407 if (ClRealignStack && StackAlignment < RedzoneSize())
1408 StackAlignment = RedzoneSize();
1409 MyAlloca->setAlignment(StackAlignment);
1410 assert(MyAlloca->isStaticAlloca());
1411 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1412 Value *LocalStackBase = OrigStackBase;
1414 if (DoStackMalloc) {
1415 // LocalStackBase = OrigStackBase
1416 // if (__asan_option_detect_stack_use_after_return)
1417 // LocalStackBase = __asan_stack_malloc_N(LocalStackBase, OrigStackBase);
1418 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1419 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
1420 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1421 kAsanOptionDetectUAR, IRB.getInt32Ty());
1422 Value *Cmp = IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1423 Constant::getNullValue(IRB.getInt32Ty()));
1425 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
1426 BasicBlock *CmpBlock = cast<Instruction>(Cmp)->getParent();
1427 IRBuilder<> IRBIf(Term);
1428 LocalStackBase = IRBIf.CreateCall2(
1429 AsanStackMallocFunc[StackMallocIdx],
1430 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1431 BasicBlock *SetBlock = cast<Instruction>(LocalStackBase)->getParent();
1432 IRB.SetInsertPoint(InsBefore);
1433 PHINode *Phi = IRB.CreatePHI(IntptrTy, 2);
1434 Phi->addIncoming(OrigStackBase, CmpBlock);
1435 Phi->addIncoming(LocalStackBase, SetBlock);
1436 LocalStackBase = Phi;
1439 // This string will be parsed by the run-time (DescribeAddressIfStack).
1440 SmallString<2048> StackDescriptionStorage;
1441 raw_svector_ostream StackDescription(StackDescriptionStorage);
1442 StackDescription << AllocaVec.size() << " ";
1444 // Insert poison calls for lifetime intrinsics for alloca.
1445 bool HavePoisonedAllocas = false;
1446 for (size_t i = 0, n = AllocaPoisonCallVec.size(); i < n; i++) {
1447 const AllocaPoisonCall &APC = AllocaPoisonCallVec[i];
1448 IntrinsicInst *II = APC.InsBefore;
1449 AllocaInst *AI = findAllocaForValue(II->getArgOperand(1));
1451 IRBuilder<> IRB(II);
1452 poisonAlloca(AI, APC.Size, IRB, APC.DoPoison);
1453 HavePoisonedAllocas |= APC.DoPoison;
1456 uint64_t Pos = RedzoneSize();
1457 // Replace Alloca instructions with base+offset.
1458 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1459 AllocaInst *AI = AllocaVec[i];
1460 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1461 StringRef Name = AI->getName();
1462 StackDescription << Pos << " " << SizeInBytes << " "
1463 << Name.size() << " " << Name << " ";
1464 uint64_t AlignedSize = getAlignedAllocaSize(AI);
1465 assert((AlignedSize % RedzoneSize()) == 0);
1466 Value *NewAllocaPtr = IRB.CreateIntToPtr(
1467 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
1469 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
1470 AI->replaceAllUsesWith(NewAllocaPtr);
1471 Pos += AlignedSize + RedzoneSize();
1473 assert(Pos == LocalStackSize);
1475 // The left-most redzone has enough space for at least 4 pointers.
1476 // Write the Magic value to redzone[0].
1477 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1478 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1480 // Write the frame description constant to redzone[1].
1481 Value *BasePlus1 = IRB.CreateIntToPtr(
1482 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
1484 GlobalVariable *StackDescriptionGlobal =
1485 createPrivateGlobalForString(*F.getParent(), StackDescription.str());
1486 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1488 IRB.CreateStore(Description, BasePlus1);
1489 // Write the PC to redzone[2].
1490 Value *BasePlus2 = IRB.CreateIntToPtr(
1491 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
1492 2 * ASan.LongSize/8)),
1494 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
1496 // Poison the stack redzones at the entry.
1497 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1498 poisonRedZones(AllocaVec, IRB, ShadowBase, true);
1500 // Unpoison the stack before all ret instructions.
1501 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1502 Instruction *Ret = RetVec[i];
1503 IRBuilder<> IRBRet(Ret);
1504 // Mark the current frame as retired.
1505 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1507 // Unpoison the stack.
1508 poisonRedZones(AllocaVec, IRBRet, ShadowBase, false);
1509 if (DoStackMalloc) {
1510 assert(StackMallocIdx >= 0);
1511 // In use-after-return mode, mark the whole stack frame unaddressable.
1512 if (StackMallocIdx <= 4) {
1513 // For small sizes inline the whole thing:
1514 // if LocalStackBase != OrigStackBase:
1515 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
1516 // **SavedFlagPtr(LocalStackBase) = 0
1517 // FIXME: if LocalStackBase != OrigStackBase don't call poisonRedZones.
1518 Value *Cmp = IRBRet.CreateICmpNE(LocalStackBase, OrigStackBase);
1519 TerminatorInst *PoisonTerm =
1520 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
1521 IRBuilder<> IRBPoison(PoisonTerm);
1522 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1523 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1524 ClassSize >> Mapping.Scale);
1525 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
1527 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1528 Value *SavedFlagPtr = IRBPoison.CreateLoad(
1529 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1530 IRBPoison.CreateStore(
1531 Constant::getNullValue(IRBPoison.getInt8Ty()),
1532 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1534 // For larger frames call __asan_stack_free_*.
1535 IRBRet.CreateCall3(AsanStackFreeFunc[StackMallocIdx], LocalStackBase,
1536 ConstantInt::get(IntptrTy, LocalStackSize),
1539 } else if (HavePoisonedAllocas) {
1540 // If we poisoned some allocas in llvm.lifetime analysis,
1541 // unpoison whole stack frame now.
1542 assert(LocalStackBase == OrigStackBase);
1543 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
1547 // We are done. Remove the old unused alloca instructions.
1548 for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1549 AllocaVec[i]->eraseFromParent();
1552 void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
1553 IRBuilder<> &IRB, bool DoPoison) {
1554 // For now just insert the call to ASan runtime.
1555 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1556 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1557 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1558 : AsanUnpoisonStackMemoryFunc,
1562 // Handling llvm.lifetime intrinsics for a given %alloca:
1563 // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1564 // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1565 // invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1566 // could be poisoned by previous llvm.lifetime.end instruction, as the
1567 // variable may go in and out of scope several times, e.g. in loops).
1568 // (3) if we poisoned at least one %alloca in a function,
1569 // unpoison the whole stack frame at function exit.
1571 AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1572 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1573 // We're intested only in allocas we can handle.
1574 return isInterestingAlloca(*AI) ? AI : 0;
1575 // See if we've already calculated (or started to calculate) alloca for a
1577 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1578 if (I != AllocaForValue.end())
1580 // Store 0 while we're calculating alloca for value V to avoid
1581 // infinite recursion if the value references itself.
1582 AllocaForValue[V] = 0;
1583 AllocaInst *Res = 0;
1584 if (CastInst *CI = dyn_cast<CastInst>(V))
1585 Res = findAllocaForValue(CI->getOperand(0));
1586 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1587 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1588 Value *IncValue = PN->getIncomingValue(i);
1589 // Allow self-referencing phi-nodes.
1590 if (IncValue == PN) continue;
1591 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1592 // AI for incoming values should exist and should all be equal.
1593 if (IncValueAI == 0 || (Res != 0 && IncValueAI != Res))
1599 AllocaForValue[V] = Res;