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 #include "llvm/Transforms/Instrumentation.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/DenseSet.h"
20 #include "llvm/ADT/DepthFirstIterator.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/Triple.h"
27 #include "llvm/IR/CallSite.h"
28 #include "llvm/IR/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/InstVisitor.h"
34 #include "llvm/IR/IntrinsicInst.h"
35 #include "llvm/IR/LLVMContext.h"
36 #include "llvm/IR/MDBuilder.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/IR/Type.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/Transforms/Scalar.h"
44 #include "llvm/Transforms/Utils/ASanStackFrameLayout.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"
51 #include <system_error>
55 #define DEBUG_TYPE "asan"
57 static const uint64_t kDefaultShadowScale = 3;
58 static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
59 static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
60 static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
61 static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
62 static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
63 static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
64 static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
65 static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
67 static const size_t kMinStackMallocSize = 1 << 6; // 64B
68 static const size_t kMaxStackMallocSize = 1 << 16; // 64K
69 static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
70 static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
72 static const char *const kAsanModuleCtorName = "asan.module_ctor";
73 static const char *const kAsanModuleDtorName = "asan.module_dtor";
74 static const uint64_t kAsanCtorAndDtorPriority = 1;
75 static const char *const kAsanReportErrorTemplate = "__asan_report_";
76 static const char *const kAsanReportLoadN = "__asan_report_load_n";
77 static const char *const kAsanReportStoreN = "__asan_report_store_n";
78 static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
79 static const char *const kAsanUnregisterGlobalsName =
80 "__asan_unregister_globals";
81 static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
82 static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
83 static const char *const kAsanInitName = "__asan_init_v4";
84 static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
85 static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
86 static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
87 static const int kMaxAsanStackMallocSizeClass = 10;
88 static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
89 static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
90 static const char *const kAsanGenPrefix = "__asan_gen_";
91 static const char *const kAsanPoisonStackMemoryName =
92 "__asan_poison_stack_memory";
93 static const char *const kAsanUnpoisonStackMemoryName =
94 "__asan_unpoison_stack_memory";
96 static const char *const kAsanOptionDetectUAR =
97 "__asan_option_detect_stack_use_after_return";
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 static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
131 cl::desc("Check return-after-free"), cl::Hidden, cl::init(true));
132 // This flag may need to be replaced with -f[no]asan-globals.
133 static cl::opt<bool> ClGlobals("asan-globals",
134 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
135 static cl::opt<bool> ClInitializers("asan-initialization-order",
136 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(true));
137 static cl::opt<bool> ClInvalidPointerPairs("asan-detect-invalid-pointer-pair",
138 cl::desc("Instrument <, <=, >, >=, - with pointer operands"),
139 cl::Hidden, cl::init(false));
140 static cl::opt<unsigned> ClRealignStack("asan-realign-stack",
141 cl::desc("Realign stack to the value of this flag (power of two)"),
142 cl::Hidden, cl::init(32));
143 static cl::opt<int> ClInstrumentationWithCallsThreshold(
144 "asan-instrumentation-with-call-threshold",
145 cl::desc("If the function being instrumented contains more than "
146 "this number of memory accesses, use callbacks instead of "
147 "inline checks (-1 means never use callbacks)."),
148 cl::Hidden, cl::init(7000));
149 static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
150 "asan-memory-access-callback-prefix",
151 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
152 cl::init("__asan_"));
154 // This is an experimental feature that will allow to choose between
155 // instrumented and non-instrumented code at link-time.
156 // If this option is on, just before instrumenting a function we create its
157 // clone; if the function is not changed by asan the clone is deleted.
158 // If we end up with a clone, we put the instrumented function into a section
159 // called "ASAN" and the uninstrumented function into a section called "NOASAN".
161 // This is still a prototype, we need to figure out a way to keep two copies of
162 // a function so that the linker can easily choose one of them.
163 static cl::opt<bool> ClKeepUninstrumented("asan-keep-uninstrumented-functions",
164 cl::desc("Keep uninstrumented copies of functions"),
165 cl::Hidden, cl::init(false));
167 // These flags allow to change the shadow mapping.
168 // The shadow mapping looks like
169 // Shadow = (Mem >> scale) + (1 << offset_log)
170 static cl::opt<int> ClMappingScale("asan-mapping-scale",
171 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
173 // Optimization flags. Not user visible, used mostly for testing
174 // and benchmarking the tool.
175 static cl::opt<bool> ClOpt("asan-opt",
176 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
177 static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
178 cl::desc("Instrument the same temp just once"), cl::Hidden,
180 static cl::opt<bool> ClOptGlobals("asan-opt-globals",
181 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
183 static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
184 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
185 cl::Hidden, cl::init(false));
188 static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
190 static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
191 cl::Hidden, cl::init(0));
192 static cl::opt<std::string> ClDebugFunc("asan-debug-func",
193 cl::Hidden, cl::desc("Debug func"));
194 static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
195 cl::Hidden, cl::init(-1));
196 static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
197 cl::Hidden, cl::init(-1));
199 STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
200 STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
201 STATISTIC(NumOptimizedAccessesToGlobalArray,
202 "Number of optimized accesses to global arrays");
203 STATISTIC(NumOptimizedAccessesToGlobalVar,
204 "Number of optimized accesses to global vars");
207 /// Frontend-provided metadata for source location.
208 struct LocationMetadata {
213 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
215 bool empty() const { return Filename.empty(); }
217 void parse(MDNode *MDN) {
218 assert(MDN->getNumOperands() == 3);
219 MDString *MDFilename = cast<MDString>(MDN->getOperand(0));
220 Filename = MDFilename->getString();
221 LineNo = cast<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
222 ColumnNo = cast<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
226 /// Frontend-provided metadata for global variables.
227 class GlobalsMetadata {
231 : SourceLoc(), Name(), IsDynInit(false),
232 IsBlacklisted(false) {}
233 LocationMetadata SourceLoc;
239 GlobalsMetadata() : inited_(false) {}
241 void init(Module& M) {
244 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
247 for (auto MDN : Globals->operands()) {
248 // Metadata node contains the global and the fields of "Entry".
249 assert(MDN->getNumOperands() == 5);
250 Value *V = MDN->getOperand(0);
251 // The optimizer may optimize away a global entirely.
254 GlobalVariable *GV = cast<GlobalVariable>(V);
255 // We can already have an entry for GV if it was merged with another
257 Entry &E = Entries[GV];
258 if (Value *Loc = MDN->getOperand(1))
259 E.SourceLoc.parse(cast<MDNode>(Loc));
260 if (Value *Name = MDN->getOperand(2)) {
261 MDString *MDName = cast<MDString>(Name);
262 E.Name = MDName->getString();
264 ConstantInt *IsDynInit = cast<ConstantInt>(MDN->getOperand(3));
265 E.IsDynInit |= IsDynInit->isOne();
266 ConstantInt *IsBlacklisted = cast<ConstantInt>(MDN->getOperand(4));
267 E.IsBlacklisted |= IsBlacklisted->isOne();
271 /// Returns metadata entry for a given global.
272 Entry get(GlobalVariable *G) const {
273 auto Pos = Entries.find(G);
274 return (Pos != Entries.end()) ? Pos->second : Entry();
279 DenseMap<GlobalVariable*, Entry> Entries;
282 /// This struct defines the shadow mapping using the rule:
283 /// shadow = (mem >> Scale) ADD-or-OR Offset.
284 struct ShadowMapping {
290 static ShadowMapping getShadowMapping(const Module &M, int LongSize) {
291 llvm::Triple TargetTriple(M.getTargetTriple());
292 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
293 bool IsIOS = TargetTriple.isiOS();
294 bool IsFreeBSD = TargetTriple.getOS() == llvm::Triple::FreeBSD;
295 bool IsLinux = TargetTriple.getOS() == llvm::Triple::Linux;
296 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
297 TargetTriple.getArch() == llvm::Triple::ppc64le;
298 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
299 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
300 TargetTriple.getArch() == llvm::Triple::mipsel;
302 ShadowMapping Mapping;
304 if (LongSize == 32) {
308 Mapping.Offset = kMIPS32_ShadowOffset32;
310 Mapping.Offset = kFreeBSD_ShadowOffset32;
312 Mapping.Offset = kIOSShadowOffset32;
314 Mapping.Offset = kDefaultShadowOffset32;
315 } else { // LongSize == 64
317 Mapping.Offset = kPPC64_ShadowOffset64;
319 Mapping.Offset = kFreeBSD_ShadowOffset64;
320 else if (IsLinux && IsX86_64)
321 Mapping.Offset = kSmallX86_64ShadowOffset;
323 Mapping.Offset = kDefaultShadowOffset64;
326 Mapping.Scale = kDefaultShadowScale;
327 if (ClMappingScale) {
328 Mapping.Scale = ClMappingScale;
331 // OR-ing shadow offset if more efficient (at least on x86) if the offset
332 // is a power of two, but on ppc64 we have to use add since the shadow
333 // offset is not necessary 1/8-th of the address space.
334 Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
339 static size_t RedzoneSizeForScale(int MappingScale) {
340 // Redzone used for stack and globals is at least 32 bytes.
341 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
342 return std::max(32U, 1U << MappingScale);
345 /// AddressSanitizer: instrument the code in module to find memory bugs.
346 struct AddressSanitizer : public FunctionPass {
347 AddressSanitizer() : FunctionPass(ID) {}
348 const char *getPassName() const override {
349 return "AddressSanitizerFunctionPass";
351 void instrumentMop(Instruction *I, bool UseCalls);
352 void instrumentPointerComparisonOrSubtraction(Instruction *I);
353 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
354 Value *Addr, uint32_t TypeSize, bool IsWrite,
355 Value *SizeArgument, bool UseCalls);
356 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
357 Value *ShadowValue, uint32_t TypeSize);
358 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
359 bool IsWrite, size_t AccessSizeIndex,
360 Value *SizeArgument);
361 void instrumentMemIntrinsic(MemIntrinsic *MI);
362 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
363 bool runOnFunction(Function &F) override;
364 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
365 bool doInitialization(Module &M) override;
366 static char ID; // Pass identification, replacement for typeid
369 void initializeCallbacks(Module &M);
371 bool LooksLikeCodeInBug11395(Instruction *I);
372 bool GlobalIsLinkerInitialized(GlobalVariable *G);
375 const DataLayout *DL;
378 ShadowMapping Mapping;
379 Function *AsanCtorFunction;
380 Function *AsanInitFunction;
381 Function *AsanHandleNoReturnFunc;
382 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
383 // This array is indexed by AccessIsWrite and log2(AccessSize).
384 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
385 Function *AsanMemoryAccessCallback[2][kNumberOfAccessSizes];
386 // This array is indexed by AccessIsWrite.
387 Function *AsanErrorCallbackSized[2],
388 *AsanMemoryAccessCallbackSized[2];
389 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
391 GlobalsMetadata GlobalsMD;
393 friend struct FunctionStackPoisoner;
396 class AddressSanitizerModule : public ModulePass {
398 AddressSanitizerModule() : ModulePass(ID) {}
399 bool runOnModule(Module &M) override;
400 static char ID; // Pass identification, replacement for typeid
401 const char *getPassName() const override {
402 return "AddressSanitizerModule";
406 void initializeCallbacks(Module &M);
408 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
409 bool ShouldInstrumentGlobal(GlobalVariable *G);
410 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
411 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
412 size_t MinRedzoneSizeForGlobal() const {
413 return RedzoneSizeForScale(Mapping.Scale);
416 GlobalsMetadata GlobalsMD;
419 const DataLayout *DL;
420 ShadowMapping Mapping;
421 Function *AsanPoisonGlobals;
422 Function *AsanUnpoisonGlobals;
423 Function *AsanRegisterGlobals;
424 Function *AsanUnregisterGlobals;
427 // Stack poisoning does not play well with exception handling.
428 // When an exception is thrown, we essentially bypass the code
429 // that unpoisones the stack. This is why the run-time library has
430 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
431 // stack in the interceptor. This however does not work inside the
432 // actual function which catches the exception. Most likely because the
433 // compiler hoists the load of the shadow value somewhere too high.
434 // This causes asan to report a non-existing bug on 453.povray.
435 // It sounds like an LLVM bug.
436 struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
438 AddressSanitizer &ASan;
443 ShadowMapping Mapping;
445 SmallVector<AllocaInst*, 16> AllocaVec;
446 SmallVector<Instruction*, 8> RetVec;
447 unsigned StackAlignment;
449 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
450 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
451 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
453 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
454 struct AllocaPoisonCall {
455 IntrinsicInst *InsBefore;
460 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
462 // Maps Value to an AllocaInst from which the Value is originated.
463 typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
464 AllocaForValueMapTy AllocaForValue;
466 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
467 : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
468 IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
469 Mapping(ASan.Mapping),
470 StackAlignment(1 << Mapping.Scale) {}
472 bool runOnFunction() {
473 if (!ClStack) return false;
474 // Collect alloca, ret, lifetime instructions etc.
475 for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
478 if (AllocaVec.empty()) return false;
480 initializeCallbacks(*F.getParent());
490 // Finds all static Alloca instructions and puts
491 // poisoned red zones around all of them.
492 // Then unpoison everything back before the function returns.
495 // ----------------------- Visitors.
496 /// \brief Collect all Ret instructions.
497 void visitReturnInst(ReturnInst &RI) {
498 RetVec.push_back(&RI);
501 /// \brief Collect Alloca instructions we want (and can) handle.
502 void visitAllocaInst(AllocaInst &AI) {
503 if (!isInterestingAlloca(AI)) return;
505 StackAlignment = std::max(StackAlignment, AI.getAlignment());
506 AllocaVec.push_back(&AI);
509 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
511 void visitIntrinsicInst(IntrinsicInst &II) {
512 if (!ClCheckLifetime) return;
513 Intrinsic::ID ID = II.getIntrinsicID();
514 if (ID != Intrinsic::lifetime_start &&
515 ID != Intrinsic::lifetime_end)
517 // Found lifetime intrinsic, add ASan instrumentation if necessary.
518 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
519 // If size argument is undefined, don't do anything.
520 if (Size->isMinusOne()) return;
521 // Check that size doesn't saturate uint64_t and can
522 // be stored in IntptrTy.
523 const uint64_t SizeValue = Size->getValue().getLimitedValue();
524 if (SizeValue == ~0ULL ||
525 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
527 // Find alloca instruction that corresponds to llvm.lifetime argument.
528 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
530 bool DoPoison = (ID == Intrinsic::lifetime_end);
531 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
532 AllocaPoisonCallVec.push_back(APC);
535 // ---------------------- Helpers.
536 void initializeCallbacks(Module &M);
538 // Check if we want (and can) handle this alloca.
539 bool isInterestingAlloca(AllocaInst &AI) const {
540 return (!AI.isArrayAllocation() && AI.isStaticAlloca() &&
541 AI.getAllocatedType()->isSized() &&
542 // alloca() may be called with 0 size, ignore it.
543 getAllocaSizeInBytes(&AI) > 0);
546 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
547 Type *Ty = AI->getAllocatedType();
548 uint64_t SizeInBytes = ASan.DL->getTypeAllocSize(Ty);
551 /// Finds alloca where the value comes from.
552 AllocaInst *findAllocaForValue(Value *V);
553 void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
554 Value *ShadowBase, bool DoPoison);
555 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
557 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
563 char AddressSanitizer::ID = 0;
564 INITIALIZE_PASS(AddressSanitizer, "asan",
565 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
567 FunctionPass *llvm::createAddressSanitizerFunctionPass() {
568 return new AddressSanitizer();
571 char AddressSanitizerModule::ID = 0;
572 INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
573 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
574 "ModulePass", false, false)
575 ModulePass *llvm::createAddressSanitizerModulePass() {
576 return new AddressSanitizerModule();
579 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
580 size_t Res = countTrailingZeros(TypeSize / 8);
581 assert(Res < kNumberOfAccessSizes);
585 // \brief Create a constant for Str so that we can pass it to the run-time lib.
586 static GlobalVariable *createPrivateGlobalForString(
587 Module &M, StringRef Str, bool AllowMerging) {
588 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
589 // We use private linkage for module-local strings. If they can be merged
590 // with another one, we set the unnamed_addr attribute.
592 new GlobalVariable(M, StrConst->getType(), true,
593 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
595 GV->setUnnamedAddr(true);
596 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
600 /// \brief Create a global describing a source location.
601 static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
602 LocationMetadata MD) {
603 Constant *LocData[] = {
604 createPrivateGlobalForString(M, MD.Filename, true),
605 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
606 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
608 auto LocStruct = ConstantStruct::getAnon(LocData);
609 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
610 GlobalValue::PrivateLinkage, LocStruct,
612 GV->setUnnamedAddr(true);
616 static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
617 return G->getName().find(kAsanGenPrefix) == 0;
620 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
622 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
623 if (Mapping.Offset == 0)
625 // (Shadow >> scale) | offset
626 if (Mapping.OrShadowOffset)
627 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
629 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
632 // Instrument memset/memmove/memcpy
633 void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
635 if (isa<MemTransferInst>(MI)) {
637 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
638 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
639 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
640 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
641 } else if (isa<MemSetInst>(MI)) {
644 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
645 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
646 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
648 MI->eraseFromParent();
651 // If I is an interesting memory access, return the PointerOperand
652 // and set IsWrite/Alignment. Otherwise return NULL.
653 static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
654 unsigned *Alignment) {
655 // Skip memory accesses inserted by another instrumentation.
656 if (I->getMetadata("nosanitize"))
658 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
659 if (!ClInstrumentReads) return nullptr;
661 *Alignment = LI->getAlignment();
662 return LI->getPointerOperand();
664 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
665 if (!ClInstrumentWrites) return nullptr;
667 *Alignment = SI->getAlignment();
668 return SI->getPointerOperand();
670 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
671 if (!ClInstrumentAtomics) return nullptr;
674 return RMW->getPointerOperand();
676 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
677 if (!ClInstrumentAtomics) return nullptr;
680 return XCHG->getPointerOperand();
685 static bool isPointerOperand(Value *V) {
686 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
689 // This is a rough heuristic; it may cause both false positives and
690 // false negatives. The proper implementation requires cooperation with
692 static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
693 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
694 if (!Cmp->isRelational())
696 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
697 if (BO->getOpcode() != Instruction::Sub)
702 if (!isPointerOperand(I->getOperand(0)) ||
703 !isPointerOperand(I->getOperand(1)))
708 bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
709 // If a global variable does not have dynamic initialization we don't
710 // have to instrument it. However, if a global does not have initializer
711 // at all, we assume it has dynamic initializer (in other TU).
712 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
716 AddressSanitizer::instrumentPointerComparisonOrSubtraction(Instruction *I) {
718 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
719 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
720 for (int i = 0; i < 2; i++) {
721 if (Param[i]->getType()->isPointerTy())
722 Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
724 IRB.CreateCall2(F, Param[0], Param[1]);
727 void AddressSanitizer::instrumentMop(Instruction *I, bool UseCalls) {
728 bool IsWrite = false;
729 unsigned Alignment = 0;
730 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &Alignment);
732 if (ClOpt && ClOptGlobals) {
733 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
734 // If initialization order checking is disabled, a simple access to a
735 // dynamically initialized global is always valid.
736 if (!ClInitializers || GlobalIsLinkerInitialized(G)) {
737 NumOptimizedAccessesToGlobalVar++;
741 ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr);
742 if (CE && CE->isGEPWithNoNotionalOverIndexing()) {
743 if (GlobalVariable *G = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
744 if (CE->getOperand(1)->isNullValue() && GlobalIsLinkerInitialized(G)) {
745 NumOptimizedAccessesToGlobalArray++;
752 Type *OrigPtrTy = Addr->getType();
753 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
755 assert(OrigTy->isSized());
756 uint32_t TypeSize = DL->getTypeStoreSizeInBits(OrigTy);
758 assert((TypeSize % 8) == 0);
761 NumInstrumentedWrites++;
763 NumInstrumentedReads++;
765 unsigned Granularity = 1 << Mapping.Scale;
766 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
767 // if the data is properly aligned.
768 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
770 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
771 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls);
772 // Instrument unusual size or unusual alignment.
773 // We can not do it with a single check, so we do 1-byte check for the first
774 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
775 // to report the actual access size.
777 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
778 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
780 IRB.CreateCall2(AsanMemoryAccessCallbackSized[IsWrite], AddrLong, Size);
782 Value *LastByte = IRB.CreateIntToPtr(
783 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
785 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false);
786 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false);
790 // Validate the result of Module::getOrInsertFunction called for an interface
791 // function of AddressSanitizer. If the instrumented module defines a function
792 // with the same name, their prototypes must match, otherwise
793 // getOrInsertFunction returns a bitcast.
794 static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
795 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
796 FuncOrBitcast->dump();
797 report_fatal_error("trying to redefine an AddressSanitizer "
798 "interface function");
801 Instruction *AddressSanitizer::generateCrashCode(
802 Instruction *InsertBefore, Value *Addr,
803 bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
804 IRBuilder<> IRB(InsertBefore);
805 CallInst *Call = SizeArgument
806 ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
807 : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
809 // We don't do Call->setDoesNotReturn() because the BB already has
810 // UnreachableInst at the end.
811 // This EmptyAsm is required to avoid callback merge.
812 IRB.CreateCall(EmptyAsm);
816 Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
819 size_t Granularity = 1 << Mapping.Scale;
820 // Addr & (Granularity - 1)
821 Value *LastAccessedByte = IRB.CreateAnd(
822 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
823 // (Addr & (Granularity - 1)) + size - 1
824 if (TypeSize / 8 > 1)
825 LastAccessedByte = IRB.CreateAdd(
826 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
827 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
828 LastAccessedByte = IRB.CreateIntCast(
829 LastAccessedByte, ShadowValue->getType(), false);
830 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
831 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
834 void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
835 Instruction *InsertBefore, Value *Addr,
836 uint32_t TypeSize, bool IsWrite,
837 Value *SizeArgument, bool UseCalls) {
838 IRBuilder<> IRB(InsertBefore);
839 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
840 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
843 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][AccessSizeIndex],
848 Type *ShadowTy = IntegerType::get(
849 *C, std::max(8U, TypeSize >> Mapping.Scale));
850 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
851 Value *ShadowPtr = memToShadow(AddrLong, IRB);
852 Value *CmpVal = Constant::getNullValue(ShadowTy);
853 Value *ShadowValue = IRB.CreateLoad(
854 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
856 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
857 size_t Granularity = 1 << Mapping.Scale;
858 TerminatorInst *CrashTerm = nullptr;
860 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
861 // We use branch weights for the slow path check, to indicate that the slow
862 // path is rarely taken. This seems to be the case for SPEC benchmarks.
863 TerminatorInst *CheckTerm =
864 SplitBlockAndInsertIfThen(Cmp, InsertBefore, false,
865 MDBuilder(*C).createBranchWeights(1, 100000));
866 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
867 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
868 IRB.SetInsertPoint(CheckTerm);
869 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
870 BasicBlock *CrashBlock =
871 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
872 CrashTerm = new UnreachableInst(*C, CrashBlock);
873 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
874 ReplaceInstWithInst(CheckTerm, NewTerm);
876 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
879 Instruction *Crash = generateCrashCode(
880 CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
881 Crash->setDebugLoc(OrigIns->getDebugLoc());
884 void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
885 GlobalValue *ModuleName) {
886 // Set up the arguments to our poison/unpoison functions.
887 IRBuilder<> IRB(GlobalInit.begin()->getFirstInsertionPt());
889 // Add a call to poison all external globals before the given function starts.
890 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
891 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
893 // Add calls to unpoison all globals before each return instruction.
894 for (auto &BB : GlobalInit.getBasicBlockList())
895 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
896 CallInst::Create(AsanUnpoisonGlobals, "", RI);
899 void AddressSanitizerModule::createInitializerPoisonCalls(
900 Module &M, GlobalValue *ModuleName) {
901 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
903 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
904 for (Use &OP : CA->operands()) {
905 if (isa<ConstantAggregateZero>(OP))
907 ConstantStruct *CS = cast<ConstantStruct>(OP);
909 // Must have a function or null ptr.
910 if (Function* F = dyn_cast<Function>(CS->getOperand(1))) {
911 if (F->getName() == kAsanModuleCtorName) continue;
912 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
913 // Don't instrument CTORs that will run before asan.module_ctor.
914 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
915 poisonOneInitializer(*F, ModuleName);
920 bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
921 Type *Ty = cast<PointerType>(G->getType())->getElementType();
922 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
924 if (GlobalsMD.get(G).IsBlacklisted) return false;
925 if (!Ty->isSized()) return false;
926 if (!G->hasInitializer()) return false;
927 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
928 // Touch only those globals that will not be defined in other modules.
929 // Don't handle ODR linkage types and COMDATs since other modules may be built
931 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
932 G->getLinkage() != GlobalVariable::PrivateLinkage &&
933 G->getLinkage() != GlobalVariable::InternalLinkage)
937 // Two problems with thread-locals:
938 // - The address of the main thread's copy can't be computed at link-time.
939 // - Need to poison all copies, not just the main thread's one.
940 if (G->isThreadLocal())
942 // For now, just ignore this Global if the alignment is large.
943 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
945 if (G->hasSection()) {
946 StringRef Section(G->getSection());
947 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
948 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
950 if (Section.startswith("__OBJC,") ||
951 Section.startswith("__DATA, __objc_")) {
952 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
955 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
956 // Constant CFString instances are compiled in the following way:
957 // -- the string buffer is emitted into
958 // __TEXT,__cstring,cstring_literals
959 // -- the constant NSConstantString structure referencing that buffer
960 // is placed into __DATA,__cfstring
961 // Therefore there's no point in placing redzones into __DATA,__cfstring.
962 // Moreover, it causes the linker to crash on OS X 10.7
963 if (Section.startswith("__DATA,__cfstring")) {
964 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
967 // The linker merges the contents of cstring_literals and removes the
969 if (Section.startswith("__TEXT,__cstring,cstring_literals")) {
970 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
973 if (Section.startswith("__TEXT,__objc_methname,cstring_literals")) {
974 DEBUG(dbgs() << "Ignoring objc_methname cstring global: " << *G << "\n");
979 // Callbacks put into the CRT initializer/terminator sections
980 // should not be instrumented.
981 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
982 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
983 if (Section.startswith(".CRT")) {
984 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
988 // Globals from llvm.metadata aren't emitted, do not instrument them.
989 if (Section == "llvm.metadata") return false;
995 void AddressSanitizerModule::initializeCallbacks(Module &M) {
997 // Declare our poisoning and unpoisoning functions.
998 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
999 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, NULL));
1000 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
1001 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1002 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
1003 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1004 // Declare functions that register/unregister globals.
1005 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1006 kAsanRegisterGlobalsName, IRB.getVoidTy(),
1007 IntptrTy, IntptrTy, NULL));
1008 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
1009 AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1010 kAsanUnregisterGlobalsName,
1011 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1012 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1015 // This function replaces all global variables with new variables that have
1016 // trailing redzones. It also creates a function that poisons
1017 // redzones and inserts this function into llvm.global_ctors.
1018 bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
1021 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1023 for (auto &G : M.globals()) {
1024 if (ShouldInstrumentGlobal(&G))
1025 GlobalsToChange.push_back(&G);
1028 size_t n = GlobalsToChange.size();
1029 if (n == 0) return false;
1031 // A global is described by a structure
1034 // size_t size_with_redzone;
1035 // const char *name;
1036 // const char *module_name;
1037 // size_t has_dynamic_init;
1038 // void *source_location;
1039 // We initialize an array of such structures and pass it to a run-time call.
1040 StructType *GlobalStructTy =
1041 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
1042 IntptrTy, IntptrTy, NULL);
1043 SmallVector<Constant *, 16> Initializers(n);
1045 bool HasDynamicallyInitializedGlobals = false;
1047 // We shouldn't merge same module names, as this string serves as unique
1048 // module ID in runtime.
1049 GlobalVariable *ModuleName = createPrivateGlobalForString(
1050 M, M.getModuleIdentifier(), /*AllowMerging*/false);
1052 for (size_t i = 0; i < n; i++) {
1053 static const uint64_t kMaxGlobalRedzone = 1 << 18;
1054 GlobalVariable *G = GlobalsToChange[i];
1056 auto MD = GlobalsMD.get(G);
1057 // Create string holding the global name (use global name from metadata
1058 // if it's available, otherwise just write the name of global variable).
1059 GlobalVariable *Name = createPrivateGlobalForString(
1060 M, MD.Name.empty() ? G->getName() : MD.Name,
1061 /*AllowMerging*/ true);
1063 PointerType *PtrTy = cast<PointerType>(G->getType());
1064 Type *Ty = PtrTy->getElementType();
1065 uint64_t SizeInBytes = DL->getTypeAllocSize(Ty);
1066 uint64_t MinRZ = MinRedzoneSizeForGlobal();
1067 // MinRZ <= RZ <= kMaxGlobalRedzone
1068 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
1069 uint64_t RZ = std::max(MinRZ,
1070 std::min(kMaxGlobalRedzone,
1071 (SizeInBytes / MinRZ / 4) * MinRZ));
1072 uint64_t RightRedzoneSize = RZ;
1073 // Round up to MinRZ
1074 if (SizeInBytes % MinRZ)
1075 RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
1076 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
1077 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1079 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
1080 Constant *NewInitializer = ConstantStruct::get(
1081 NewTy, G->getInitializer(),
1082 Constant::getNullValue(RightRedZoneTy), NULL);
1084 // Create a new global variable with enough space for a redzone.
1085 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1086 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1087 Linkage = GlobalValue::InternalLinkage;
1088 GlobalVariable *NewGlobal = new GlobalVariable(
1089 M, NewTy, G->isConstant(), Linkage,
1090 NewInitializer, "", G, G->getThreadLocalMode());
1091 NewGlobal->copyAttributesFrom(G);
1092 NewGlobal->setAlignment(MinRZ);
1095 Indices2[0] = IRB.getInt32(0);
1096 Indices2[1] = IRB.getInt32(0);
1098 G->replaceAllUsesWith(
1099 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
1100 NewGlobal->takeName(G);
1101 G->eraseFromParent();
1103 Constant *SourceLoc;
1104 if (!MD.SourceLoc.empty()) {
1105 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1106 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1108 SourceLoc = ConstantInt::get(IntptrTy, 0);
1111 Initializers[i] = ConstantStruct::get(
1112 GlobalStructTy, ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
1113 ConstantInt::get(IntptrTy, SizeInBytes),
1114 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1115 ConstantExpr::getPointerCast(Name, IntptrTy),
1116 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
1117 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc, NULL);
1119 if (ClInitializers && MD.IsDynInit)
1120 HasDynamicallyInitializedGlobals = true;
1122 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
1125 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1126 GlobalVariable *AllGlobals = new GlobalVariable(
1127 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1128 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1130 // Create calls for poisoning before initializers run and unpoisoning after.
1131 if (HasDynamicallyInitializedGlobals)
1132 createInitializerPoisonCalls(M, ModuleName);
1133 IRB.CreateCall2(AsanRegisterGlobals,
1134 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1135 ConstantInt::get(IntptrTy, n));
1137 // We also need to unregister globals at the end, e.g. when a shared library
1139 Function *AsanDtorFunction = Function::Create(
1140 FunctionType::get(Type::getVoidTy(*C), false),
1141 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1142 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1143 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
1144 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
1145 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1146 ConstantInt::get(IntptrTy, n));
1147 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
1153 bool AddressSanitizerModule::runOnModule(Module &M) {
1154 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1157 DL = &DLP->getDataLayout();
1158 C = &(M.getContext());
1159 int LongSize = DL->getPointerSizeInBits();
1160 IntptrTy = Type::getIntNTy(*C, LongSize);
1161 Mapping = getShadowMapping(M, LongSize);
1162 initializeCallbacks(M);
1164 bool Changed = false;
1166 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1168 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1171 Changed |= InstrumentGlobals(IRB, M);
1176 void AddressSanitizer::initializeCallbacks(Module &M) {
1177 IRBuilder<> IRB(*C);
1178 // Create __asan_report* callbacks.
1179 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1180 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1181 AccessSizeIndex++) {
1182 // IsWrite and TypeSize are encoded in the function name.
1183 std::string Suffix =
1184 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
1185 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
1186 checkInterfaceFunction(
1187 M.getOrInsertFunction(kAsanReportErrorTemplate + Suffix,
1188 IRB.getVoidTy(), IntptrTy, NULL));
1189 AsanMemoryAccessCallback[AccessIsWrite][AccessSizeIndex] =
1190 checkInterfaceFunction(
1191 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + Suffix,
1192 IRB.getVoidTy(), IntptrTy, NULL));
1195 AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
1196 kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1197 AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
1198 kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1200 AsanMemoryAccessCallbackSized[0] = checkInterfaceFunction(
1201 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "loadN",
1202 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1203 AsanMemoryAccessCallbackSized[1] = checkInterfaceFunction(
1204 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "storeN",
1205 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1207 AsanMemmove = checkInterfaceFunction(M.getOrInsertFunction(
1208 ClMemoryAccessCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
1209 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, NULL));
1210 AsanMemcpy = checkInterfaceFunction(M.getOrInsertFunction(
1211 ClMemoryAccessCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
1212 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, NULL));
1213 AsanMemset = checkInterfaceFunction(M.getOrInsertFunction(
1214 ClMemoryAccessCallbackPrefix + "memset", IRB.getInt8PtrTy(),
1215 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, NULL));
1217 AsanHandleNoReturnFunc = checkInterfaceFunction(
1218 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
1220 AsanPtrCmpFunction = checkInterfaceFunction(M.getOrInsertFunction(
1221 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1222 AsanPtrSubFunction = checkInterfaceFunction(M.getOrInsertFunction(
1223 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1224 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1225 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1226 StringRef(""), StringRef(""),
1227 /*hasSideEffects=*/true);
1231 bool AddressSanitizer::doInitialization(Module &M) {
1232 // Initialize the private fields. No one has accessed them before.
1233 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1235 report_fatal_error("data layout missing");
1236 DL = &DLP->getDataLayout();
1240 C = &(M.getContext());
1241 LongSize = DL->getPointerSizeInBits();
1242 IntptrTy = Type::getIntNTy(*C, LongSize);
1244 AsanCtorFunction = Function::Create(
1245 FunctionType::get(Type::getVoidTy(*C), false),
1246 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1247 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1248 // call __asan_init in the module ctor.
1249 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1250 AsanInitFunction = checkInterfaceFunction(
1251 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
1252 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1253 IRB.CreateCall(AsanInitFunction);
1255 Mapping = getShadowMapping(M, LongSize);
1257 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
1261 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1262 // For each NSObject descendant having a +load method, this method is invoked
1263 // by the ObjC runtime before any of the static constructors is called.
1264 // Therefore we need to instrument such methods with a call to __asan_init
1265 // at the beginning in order to initialize our runtime before any access to
1266 // the shadow memory.
1267 // We cannot just ignore these methods, because they may call other
1268 // instrumented functions.
1269 if (F.getName().find(" load]") != std::string::npos) {
1270 IRBuilder<> IRB(F.begin()->begin());
1271 IRB.CreateCall(AsanInitFunction);
1277 bool AddressSanitizer::runOnFunction(Function &F) {
1278 if (&F == AsanCtorFunction) return false;
1279 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
1280 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
1281 initializeCallbacks(*F.getParent());
1283 // If needed, insert __asan_init before checking for SanitizeAddress attr.
1284 maybeInsertAsanInitAtFunctionEntry(F);
1286 if (!F.hasFnAttribute(Attribute::SanitizeAddress))
1289 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1292 // We want to instrument every address only once per basic block (unless there
1293 // are calls between uses).
1294 SmallSet<Value*, 16> TempsToInstrument;
1295 SmallVector<Instruction*, 16> ToInstrument;
1296 SmallVector<Instruction*, 8> NoReturnCalls;
1297 SmallVector<BasicBlock*, 16> AllBlocks;
1298 SmallVector<Instruction*, 16> PointerComparisonsOrSubtracts;
1303 // Fill the set of memory operations to instrument.
1304 for (auto &BB : F) {
1305 AllBlocks.push_back(&BB);
1306 TempsToInstrument.clear();
1307 int NumInsnsPerBB = 0;
1308 for (auto &Inst : BB) {
1309 if (LooksLikeCodeInBug11395(&Inst)) return false;
1311 isInterestingMemoryAccess(&Inst, &IsWrite, &Alignment)) {
1312 if (ClOpt && ClOptSameTemp) {
1313 if (!TempsToInstrument.insert(Addr))
1314 continue; // We've seen this temp in the current BB.
1316 } else if (ClInvalidPointerPairs &&
1317 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1318 PointerComparisonsOrSubtracts.push_back(&Inst);
1320 } else if (isa<MemIntrinsic>(Inst)) {
1323 if (isa<AllocaInst>(Inst))
1327 // A call inside BB.
1328 TempsToInstrument.clear();
1329 if (CS.doesNotReturn())
1330 NoReturnCalls.push_back(CS.getInstruction());
1334 ToInstrument.push_back(&Inst);
1336 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1341 Function *UninstrumentedDuplicate = nullptr;
1342 bool LikelyToInstrument =
1343 !NoReturnCalls.empty() || !ToInstrument.empty() || (NumAllocas > 0);
1344 if (ClKeepUninstrumented && LikelyToInstrument) {
1345 ValueToValueMapTy VMap;
1346 UninstrumentedDuplicate = CloneFunction(&F, VMap, false);
1347 UninstrumentedDuplicate->removeFnAttr(Attribute::SanitizeAddress);
1348 UninstrumentedDuplicate->setName("NOASAN_" + F.getName());
1349 F.getParent()->getFunctionList().push_back(UninstrumentedDuplicate);
1352 bool UseCalls = false;
1353 if (ClInstrumentationWithCallsThreshold >= 0 &&
1354 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold)
1358 int NumInstrumented = 0;
1359 for (auto Inst : ToInstrument) {
1360 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1361 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
1362 if (isInterestingMemoryAccess(Inst, &IsWrite, &Alignment))
1363 instrumentMop(Inst, UseCalls);
1365 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
1370 FunctionStackPoisoner FSP(F, *this);
1371 bool ChangedStack = FSP.runOnFunction();
1373 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1374 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1375 for (auto CI : NoReturnCalls) {
1376 IRBuilder<> IRB(CI);
1377 IRB.CreateCall(AsanHandleNoReturnFunc);
1380 for (auto Inst : PointerComparisonsOrSubtracts) {
1381 instrumentPointerComparisonOrSubtraction(Inst);
1385 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
1387 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1389 if (ClKeepUninstrumented) {
1391 // No instrumentation is done, no need for the duplicate.
1392 if (UninstrumentedDuplicate)
1393 UninstrumentedDuplicate->eraseFromParent();
1395 // The function was instrumented. We must have the duplicate.
1396 assert(UninstrumentedDuplicate);
1397 UninstrumentedDuplicate->setSection("NOASAN");
1398 assert(!F.hasSection());
1399 F.setSection("ASAN");
1406 // Workaround for bug 11395: we don't want to instrument stack in functions
1407 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1408 // FIXME: remove once the bug 11395 is fixed.
1409 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1410 if (LongSize != 32) return false;
1411 CallInst *CI = dyn_cast<CallInst>(I);
1412 if (!CI || !CI->isInlineAsm()) return false;
1413 if (CI->getNumArgOperands() <= 5) return false;
1414 // We have inline assembly with quite a few arguments.
1418 void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1419 IRBuilder<> IRB(*C);
1420 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1421 std::string Suffix = itostr(i);
1422 AsanStackMallocFunc[i] = checkInterfaceFunction(
1423 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1424 IntptrTy, IntptrTy, NULL));
1425 AsanStackFreeFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
1426 kAsanStackFreeNameTemplate + Suffix, IRB.getVoidTy(), IntptrTy,
1427 IntptrTy, IntptrTy, NULL));
1429 AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1430 kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1431 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1432 kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1436 FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
1437 IRBuilder<> &IRB, Value *ShadowBase,
1439 size_t n = ShadowBytes.size();
1441 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1442 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1443 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1444 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1445 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1446 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1448 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
1449 if (ASan.DL->isLittleEndian())
1450 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1452 Val = (Val << 8) | ShadowBytes[i + j];
1455 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1456 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1457 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1458 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
1463 // Fake stack allocator (asan_fake_stack.h) has 11 size classes
1464 // for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1465 static int StackMallocSizeClass(uint64_t LocalStackSize) {
1466 assert(LocalStackSize <= kMaxStackMallocSize);
1467 uint64_t MaxSize = kMinStackMallocSize;
1468 for (int i = 0; ; i++, MaxSize *= 2)
1469 if (LocalStackSize <= MaxSize)
1471 llvm_unreachable("impossible LocalStackSize");
1474 // Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1475 // We can not use MemSet intrinsic because it may end up calling the actual
1476 // memset. Size is a multiple of 8.
1477 // Currently this generates 8-byte stores on x86_64; it may be better to
1478 // generate wider stores.
1479 void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1480 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1481 assert(!(Size % 8));
1482 assert(kAsanStackAfterReturnMagic == 0xf5);
1483 for (int i = 0; i < Size; i += 8) {
1484 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1485 IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
1486 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1490 static DebugLoc getFunctionEntryDebugLocation(Function &F) {
1491 for (const auto &Inst : F.getEntryBlock())
1492 if (!isa<AllocaInst>(Inst))
1493 return Inst.getDebugLoc();
1497 void FunctionStackPoisoner::poisonStack() {
1498 int StackMallocIdx = -1;
1499 DebugLoc EntryDebugLocation = getFunctionEntryDebugLocation(F);
1501 assert(AllocaVec.size() > 0);
1502 Instruction *InsBefore = AllocaVec[0];
1503 IRBuilder<> IRB(InsBefore);
1504 IRB.SetCurrentDebugLocation(EntryDebugLocation);
1506 SmallVector<ASanStackVariableDescription, 16> SVD;
1507 SVD.reserve(AllocaVec.size());
1508 for (AllocaInst *AI : AllocaVec) {
1509 ASanStackVariableDescription D = { AI->getName().data(),
1510 getAllocaSizeInBytes(AI),
1511 AI->getAlignment(), AI, 0};
1514 // Minimal header size (left redzone) is 4 pointers,
1515 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1516 size_t MinHeaderSize = ASan.LongSize / 2;
1517 ASanStackFrameLayout L;
1518 ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1519 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1520 uint64_t LocalStackSize = L.FrameSize;
1521 bool DoStackMalloc =
1522 ClUseAfterReturn && LocalStackSize <= kMaxStackMallocSize;
1524 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1525 AllocaInst *MyAlloca =
1526 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
1527 MyAlloca->setDebugLoc(EntryDebugLocation);
1528 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1529 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1530 MyAlloca->setAlignment(FrameAlignment);
1531 assert(MyAlloca->isStaticAlloca());
1532 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1533 Value *LocalStackBase = OrigStackBase;
1535 if (DoStackMalloc) {
1536 // LocalStackBase = OrigStackBase
1537 // if (__asan_option_detect_stack_use_after_return)
1538 // LocalStackBase = __asan_stack_malloc_N(LocalStackBase, OrigStackBase);
1539 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1540 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
1541 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1542 kAsanOptionDetectUAR, IRB.getInt32Ty());
1543 Value *Cmp = IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1544 Constant::getNullValue(IRB.getInt32Ty()));
1545 Instruction *Term = SplitBlockAndInsertIfThen(Cmp, InsBefore, false);
1546 BasicBlock *CmpBlock = cast<Instruction>(Cmp)->getParent();
1547 IRBuilder<> IRBIf(Term);
1548 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
1549 LocalStackBase = IRBIf.CreateCall2(
1550 AsanStackMallocFunc[StackMallocIdx],
1551 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1552 BasicBlock *SetBlock = cast<Instruction>(LocalStackBase)->getParent();
1553 IRB.SetInsertPoint(InsBefore);
1554 IRB.SetCurrentDebugLocation(EntryDebugLocation);
1555 PHINode *Phi = IRB.CreatePHI(IntptrTy, 2);
1556 Phi->addIncoming(OrigStackBase, CmpBlock);
1557 Phi->addIncoming(LocalStackBase, SetBlock);
1558 LocalStackBase = Phi;
1561 // Insert poison calls for lifetime intrinsics for alloca.
1562 bool HavePoisonedAllocas = false;
1563 for (const auto &APC : AllocaPoisonCallVec) {
1564 assert(APC.InsBefore);
1566 IRBuilder<> IRB(APC.InsBefore);
1567 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
1568 HavePoisonedAllocas |= APC.DoPoison;
1571 // Replace Alloca instructions with base+offset.
1572 for (const auto &Desc : SVD) {
1573 AllocaInst *AI = Desc.AI;
1574 Value *NewAllocaPtr = IRB.CreateIntToPtr(
1575 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
1577 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
1578 AI->replaceAllUsesWith(NewAllocaPtr);
1581 // The left-most redzone has enough space for at least 4 pointers.
1582 // Write the Magic value to redzone[0].
1583 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1584 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1586 // Write the frame description constant to redzone[1].
1587 Value *BasePlus1 = IRB.CreateIntToPtr(
1588 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
1590 GlobalVariable *StackDescriptionGlobal =
1591 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
1592 /*AllowMerging*/true);
1593 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1595 IRB.CreateStore(Description, BasePlus1);
1596 // Write the PC to redzone[2].
1597 Value *BasePlus2 = IRB.CreateIntToPtr(
1598 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
1599 2 * ASan.LongSize/8)),
1601 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
1603 // Poison the stack redzones at the entry.
1604 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1605 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
1607 // (Un)poison the stack before all ret instructions.
1608 for (auto Ret : RetVec) {
1609 IRBuilder<> IRBRet(Ret);
1610 // Mark the current frame as retired.
1611 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1613 if (DoStackMalloc) {
1614 assert(StackMallocIdx >= 0);
1615 // if LocalStackBase != OrigStackBase:
1616 // // In use-after-return mode, poison the whole stack frame.
1617 // if StackMallocIdx <= 4
1618 // // For small sizes inline the whole thing:
1619 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
1620 // **SavedFlagPtr(LocalStackBase) = 0
1622 // __asan_stack_free_N(LocalStackBase, OrigStackBase)
1624 // <This is not a fake stack; unpoison the redzones>
1625 Value *Cmp = IRBRet.CreateICmpNE(LocalStackBase, OrigStackBase);
1626 TerminatorInst *ThenTerm, *ElseTerm;
1627 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1629 IRBuilder<> IRBPoison(ThenTerm);
1630 if (StackMallocIdx <= 4) {
1631 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1632 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1633 ClassSize >> Mapping.Scale);
1634 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
1636 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1637 Value *SavedFlagPtr = IRBPoison.CreateLoad(
1638 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1639 IRBPoison.CreateStore(
1640 Constant::getNullValue(IRBPoison.getInt8Ty()),
1641 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1643 // For larger frames call __asan_stack_free_*.
1644 IRBPoison.CreateCall3(AsanStackFreeFunc[StackMallocIdx], LocalStackBase,
1645 ConstantInt::get(IntptrTy, LocalStackSize),
1649 IRBuilder<> IRBElse(ElseTerm);
1650 poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
1651 } else if (HavePoisonedAllocas) {
1652 // If we poisoned some allocas in llvm.lifetime analysis,
1653 // unpoison whole stack frame now.
1654 assert(LocalStackBase == OrigStackBase);
1655 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
1657 poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
1661 // We are done. Remove the old unused alloca instructions.
1662 for (auto AI : AllocaVec)
1663 AI->eraseFromParent();
1666 void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
1667 IRBuilder<> &IRB, bool DoPoison) {
1668 // For now just insert the call to ASan runtime.
1669 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1670 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1671 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1672 : AsanUnpoisonStackMemoryFunc,
1676 // Handling llvm.lifetime intrinsics for a given %alloca:
1677 // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1678 // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1679 // invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1680 // could be poisoned by previous llvm.lifetime.end instruction, as the
1681 // variable may go in and out of scope several times, e.g. in loops).
1682 // (3) if we poisoned at least one %alloca in a function,
1683 // unpoison the whole stack frame at function exit.
1685 AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1686 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1687 // We're intested only in allocas we can handle.
1688 return isInterestingAlloca(*AI) ? AI : nullptr;
1689 // See if we've already calculated (or started to calculate) alloca for a
1691 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1692 if (I != AllocaForValue.end())
1694 // Store 0 while we're calculating alloca for value V to avoid
1695 // infinite recursion if the value references itself.
1696 AllocaForValue[V] = nullptr;
1697 AllocaInst *Res = nullptr;
1698 if (CastInst *CI = dyn_cast<CastInst>(V))
1699 Res = findAllocaForValue(CI->getOperand(0));
1700 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1701 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1702 Value *IncValue = PN->getIncomingValue(i);
1703 // Allow self-referencing phi-nodes.
1704 if (IncValue == PN) continue;
1705 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1706 // AI for incoming values should exist and should all be equal.
1707 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
1713 AllocaForValue[V] = Res;