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/Utils/ASanStackFrameLayout.h"
44 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
45 #include "llvm/Transforms/Utils/Cloning.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Transforms/Utils/ModuleUtils.h"
50 #include <system_error>
54 #define DEBUG_TYPE "asan"
56 static const uint64_t kDefaultShadowScale = 3;
57 static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
58 static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
59 static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
60 static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
61 static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
62 static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa8000;
63 static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
64 static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
66 static const size_t kMinStackMallocSize = 1 << 6; // 64B
67 static const size_t kMaxStackMallocSize = 1 << 16; // 64K
68 static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
69 static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
71 static const char *const kAsanModuleCtorName = "asan.module_ctor";
72 static const char *const kAsanModuleDtorName = "asan.module_dtor";
73 static const int kAsanCtorAndDtorPriority = 1;
74 static const char *const kAsanReportErrorTemplate = "__asan_report_";
75 static const char *const kAsanReportLoadN = "__asan_report_load_n";
76 static const char *const kAsanReportStoreN = "__asan_report_store_n";
77 static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
78 static const char *const kAsanUnregisterGlobalsName =
79 "__asan_unregister_globals";
80 static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
81 static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
82 static const char *const kAsanInitName = "__asan_init_v4";
83 static const char *const kAsanCovModuleInitName = "__sanitizer_cov_module_init";
84 static const char *const kAsanCovName = "__sanitizer_cov";
85 static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
86 static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
87 static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
88 static const int kMaxAsanStackMallocSizeClass = 10;
89 static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
90 static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
91 static const char *const kAsanGenPrefix = "__asan_gen_";
92 static const char *const kAsanPoisonStackMemoryName =
93 "__asan_poison_stack_memory";
94 static const char *const kAsanUnpoisonStackMemoryName =
95 "__asan_unpoison_stack_memory";
97 static const char *const kAsanOptionDetectUAR =
98 "__asan_option_detect_stack_use_after_return";
101 static const int kAsanStackAfterReturnMagic = 0xf5;
104 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
105 static const size_t kNumberOfAccessSizes = 5;
107 // Command-line flags.
109 // This flag may need to be replaced with -f[no-]asan-reads.
110 static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
111 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
112 static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
113 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
114 static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
115 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
116 cl::Hidden, cl::init(true));
117 static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
118 cl::desc("use instrumentation with slow path for all accesses"),
119 cl::Hidden, cl::init(false));
120 // This flag limits the number of instructions to be instrumented
121 // in any given BB. Normally, this should be set to unlimited (INT_MAX),
122 // but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
124 static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
126 cl::desc("maximal number of instructions to instrument in any given BB"),
128 // This flag may need to be replaced with -f[no]asan-stack.
129 static cl::opt<bool> ClStack("asan-stack",
130 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
131 static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
132 cl::desc("Check return-after-free"), cl::Hidden, cl::init(true));
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<int> ClCoverage("asan-coverage",
137 cl::desc("ASan coverage. 0: none, 1: entry block, 2: all blocks"),
138 cl::Hidden, cl::init(false));
139 static cl::opt<int> ClCoverageBlockThreshold("asan-coverage-block-threshold",
140 cl::desc("Add coverage instrumentation only to the entry block if there "
141 "are more than this number of blocks."),
142 cl::Hidden, cl::init(1500));
143 static cl::opt<bool> ClInitializers("asan-initialization-order",
144 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(true));
145 static cl::opt<bool> ClInvalidPointerPairs("asan-detect-invalid-pointer-pair",
146 cl::desc("Instrument <, <=, >, >=, - with pointer operands"),
147 cl::Hidden, cl::init(false));
148 static cl::opt<unsigned> ClRealignStack("asan-realign-stack",
149 cl::desc("Realign stack to the value of this flag (power of two)"),
150 cl::Hidden, cl::init(32));
151 static cl::opt<int> ClInstrumentationWithCallsThreshold(
152 "asan-instrumentation-with-call-threshold",
153 cl::desc("If the function being instrumented contains more than "
154 "this number of memory accesses, use callbacks instead of "
155 "inline checks (-1 means never use callbacks)."),
156 cl::Hidden, cl::init(7000));
157 static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
158 "asan-memory-access-callback-prefix",
159 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
160 cl::init("__asan_"));
162 // This is an experimental feature that will allow to choose between
163 // instrumented and non-instrumented code at link-time.
164 // If this option is on, just before instrumenting a function we create its
165 // clone; if the function is not changed by asan the clone is deleted.
166 // If we end up with a clone, we put the instrumented function into a section
167 // called "ASAN" and the uninstrumented function into a section called "NOASAN".
169 // This is still a prototype, we need to figure out a way to keep two copies of
170 // a function so that the linker can easily choose one of them.
171 static cl::opt<bool> ClKeepUninstrumented("asan-keep-uninstrumented-functions",
172 cl::desc("Keep uninstrumented copies of functions"),
173 cl::Hidden, cl::init(false));
175 // These flags allow to change the shadow mapping.
176 // The shadow mapping looks like
177 // Shadow = (Mem >> scale) + (1 << offset_log)
178 static cl::opt<int> ClMappingScale("asan-mapping-scale",
179 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
181 // Optimization flags. Not user visible, used mostly for testing
182 // and benchmarking the tool.
183 static cl::opt<bool> ClOpt("asan-opt",
184 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
185 static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
186 cl::desc("Instrument the same temp just once"), cl::Hidden,
188 static cl::opt<bool> ClOptGlobals("asan-opt-globals",
189 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
191 static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
192 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
193 cl::Hidden, cl::init(false));
196 static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
198 static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
199 cl::Hidden, cl::init(0));
200 static cl::opt<std::string> ClDebugFunc("asan-debug-func",
201 cl::Hidden, cl::desc("Debug func"));
202 static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
203 cl::Hidden, cl::init(-1));
204 static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
205 cl::Hidden, cl::init(-1));
207 STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
208 STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
209 STATISTIC(NumOptimizedAccessesToGlobalArray,
210 "Number of optimized accesses to global arrays");
211 STATISTIC(NumOptimizedAccessesToGlobalVar,
212 "Number of optimized accesses to global vars");
215 /// Frontend-provided metadata for global variables.
216 class GlobalsMetadata {
220 : SourceLoc(nullptr), Name(nullptr), IsDynInit(false),
221 IsBlacklisted(false) {}
222 GlobalVariable *SourceLoc;
223 GlobalVariable *Name;
228 GlobalsMetadata() : inited_(false) {}
230 void init(Module& M) {
233 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
236 for (auto MDN : Globals->operands()) {
237 // Metadata node contains the global and the fields of "Entry".
238 assert(MDN->getNumOperands() == 5);
239 Value *V = MDN->getOperand(0);
240 // The optimizer may optimize away a global entirely.
243 GlobalVariable *GV = cast<GlobalVariable>(V);
244 // We can already have an entry for GV if it was merged with another
246 Entry &E = Entries[GV];
247 if (Value *Loc = MDN->getOperand(1)) {
248 GlobalVariable *GVLoc = cast<GlobalVariable>(Loc);
250 addSourceLocationGlobal(GVLoc);
252 if (Value *Name = MDN->getOperand(2)) {
253 GlobalVariable *GVName = cast<GlobalVariable>(Name);
255 InstrumentationGlobals.insert(GVName);
257 ConstantInt *IsDynInit = cast<ConstantInt>(MDN->getOperand(3));
258 E.IsDynInit |= IsDynInit->isOne();
259 ConstantInt *IsBlacklisted = cast<ConstantInt>(MDN->getOperand(4));
260 E.IsBlacklisted |= IsBlacklisted->isOne();
264 /// Returns metadata entry for a given global.
265 Entry get(GlobalVariable *G) const {
266 auto Pos = Entries.find(G);
267 return (Pos != Entries.end()) ? Pos->second : Entry();
270 /// Check if the global was generated by the instrumentation
271 /// (we don't want to instrument it again in this case).
272 bool isInstrumentationGlobal(GlobalVariable *G) const {
273 return InstrumentationGlobals.count(G);
278 DenseMap<GlobalVariable*, Entry> Entries;
279 // Globals generated by the frontend instrumentation.
280 DenseSet<GlobalVariable*> InstrumentationGlobals;
282 void addSourceLocationGlobal(GlobalVariable *SourceLocGV) {
283 // Source location global is a struct with layout:
287 // i32 column_number,
289 InstrumentationGlobals.insert(SourceLocGV);
290 ConstantStruct *Contents =
291 cast<ConstantStruct>(SourceLocGV->getInitializer());
292 GlobalVariable *FilenameGV = cast<GlobalVariable>(Contents->getOperand(0));
293 InstrumentationGlobals.insert(FilenameGV);
297 /// This struct defines the shadow mapping using the rule:
298 /// shadow = (mem >> Scale) ADD-or-OR Offset.
299 struct ShadowMapping {
305 static ShadowMapping getShadowMapping(const Module &M, int LongSize) {
306 llvm::Triple TargetTriple(M.getTargetTriple());
307 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
308 bool IsIOS = TargetTriple.getOS() == llvm::Triple::IOS;
309 bool IsFreeBSD = TargetTriple.getOS() == llvm::Triple::FreeBSD;
310 bool IsLinux = TargetTriple.getOS() == llvm::Triple::Linux;
311 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
312 TargetTriple.getArch() == llvm::Triple::ppc64le;
313 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
314 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
315 TargetTriple.getArch() == llvm::Triple::mipsel;
317 ShadowMapping Mapping;
319 if (LongSize == 32) {
323 Mapping.Offset = kMIPS32_ShadowOffset32;
325 Mapping.Offset = kFreeBSD_ShadowOffset32;
327 Mapping.Offset = kIOSShadowOffset32;
329 Mapping.Offset = kDefaultShadowOffset32;
330 } else { // LongSize == 64
332 Mapping.Offset = kPPC64_ShadowOffset64;
334 Mapping.Offset = kFreeBSD_ShadowOffset64;
335 else if (IsLinux && IsX86_64)
336 Mapping.Offset = kSmallX86_64ShadowOffset;
338 Mapping.Offset = kDefaultShadowOffset64;
341 Mapping.Scale = kDefaultShadowScale;
342 if (ClMappingScale) {
343 Mapping.Scale = ClMappingScale;
346 // OR-ing shadow offset if more efficient (at least on x86) if the offset
347 // is a power of two, but on ppc64 we have to use add since the shadow
348 // offset is not necessary 1/8-th of the address space.
349 Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
354 static size_t RedzoneSizeForScale(int MappingScale) {
355 // Redzone used for stack and globals is at least 32 bytes.
356 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
357 return std::max(32U, 1U << MappingScale);
360 /// AddressSanitizer: instrument the code in module to find memory bugs.
361 struct AddressSanitizer : public FunctionPass {
362 AddressSanitizer() : FunctionPass(ID) {}
363 const char *getPassName() const override {
364 return "AddressSanitizerFunctionPass";
366 void instrumentMop(Instruction *I, bool UseCalls);
367 void instrumentPointerComparisonOrSubtraction(Instruction *I);
368 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
369 Value *Addr, uint32_t TypeSize, bool IsWrite,
370 Value *SizeArgument, bool UseCalls);
371 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
372 Value *ShadowValue, uint32_t TypeSize);
373 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
374 bool IsWrite, size_t AccessSizeIndex,
375 Value *SizeArgument);
376 void instrumentMemIntrinsic(MemIntrinsic *MI);
377 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
378 bool runOnFunction(Function &F) override;
379 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
380 bool doInitialization(Module &M) override;
381 static char ID; // Pass identification, replacement for typeid
384 void initializeCallbacks(Module &M);
386 bool LooksLikeCodeInBug11395(Instruction *I);
387 bool GlobalIsLinkerInitialized(GlobalVariable *G);
388 bool InjectCoverage(Function &F, const ArrayRef<BasicBlock*> AllBlocks);
389 void InjectCoverageAtBlock(Function &F, BasicBlock &BB);
392 const DataLayout *DL;
395 ShadowMapping Mapping;
396 Function *AsanCtorFunction;
397 Function *AsanInitFunction;
398 Function *AsanHandleNoReturnFunc;
399 Function *AsanCovFunction;
400 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
401 // This array is indexed by AccessIsWrite and log2(AccessSize).
402 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
403 Function *AsanMemoryAccessCallback[2][kNumberOfAccessSizes];
404 // This array is indexed by AccessIsWrite.
405 Function *AsanErrorCallbackSized[2],
406 *AsanMemoryAccessCallbackSized[2];
407 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
409 GlobalsMetadata GlobalsMD;
411 friend struct FunctionStackPoisoner;
414 class AddressSanitizerModule : public ModulePass {
416 AddressSanitizerModule() : ModulePass(ID) {}
417 bool runOnModule(Module &M) override;
418 static char ID; // Pass identification, replacement for typeid
419 const char *getPassName() const override {
420 return "AddressSanitizerModule";
424 void initializeCallbacks(Module &M);
426 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
427 bool ShouldInstrumentGlobal(GlobalVariable *G);
428 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
429 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
430 size_t MinRedzoneSizeForGlobal() const {
431 return RedzoneSizeForScale(Mapping.Scale);
434 GlobalsMetadata GlobalsMD;
437 const DataLayout *DL;
438 ShadowMapping Mapping;
439 Function *AsanPoisonGlobals;
440 Function *AsanUnpoisonGlobals;
441 Function *AsanRegisterGlobals;
442 Function *AsanUnregisterGlobals;
443 Function *AsanCovModuleInit;
446 // Stack poisoning does not play well with exception handling.
447 // When an exception is thrown, we essentially bypass the code
448 // that unpoisones the stack. This is why the run-time library has
449 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
450 // stack in the interceptor. This however does not work inside the
451 // actual function which catches the exception. Most likely because the
452 // compiler hoists the load of the shadow value somewhere too high.
453 // This causes asan to report a non-existing bug on 453.povray.
454 // It sounds like an LLVM bug.
455 struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
457 AddressSanitizer &ASan;
462 ShadowMapping Mapping;
464 SmallVector<AllocaInst*, 16> AllocaVec;
465 SmallVector<Instruction*, 8> RetVec;
466 unsigned StackAlignment;
468 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
469 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
470 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
472 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
473 struct AllocaPoisonCall {
474 IntrinsicInst *InsBefore;
479 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
481 // Maps Value to an AllocaInst from which the Value is originated.
482 typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
483 AllocaForValueMapTy AllocaForValue;
485 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
486 : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
487 IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
488 Mapping(ASan.Mapping),
489 StackAlignment(1 << Mapping.Scale) {}
491 bool runOnFunction() {
492 if (!ClStack) return false;
493 // Collect alloca, ret, lifetime instructions etc.
494 for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
497 if (AllocaVec.empty()) return false;
499 initializeCallbacks(*F.getParent());
509 // Finds all static Alloca instructions and puts
510 // poisoned red zones around all of them.
511 // Then unpoison everything back before the function returns.
514 // ----------------------- Visitors.
515 /// \brief Collect all Ret instructions.
516 void visitReturnInst(ReturnInst &RI) {
517 RetVec.push_back(&RI);
520 /// \brief Collect Alloca instructions we want (and can) handle.
521 void visitAllocaInst(AllocaInst &AI) {
522 if (!isInterestingAlloca(AI)) return;
524 StackAlignment = std::max(StackAlignment, AI.getAlignment());
525 AllocaVec.push_back(&AI);
528 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
530 void visitIntrinsicInst(IntrinsicInst &II) {
531 if (!ClCheckLifetime) return;
532 Intrinsic::ID ID = II.getIntrinsicID();
533 if (ID != Intrinsic::lifetime_start &&
534 ID != Intrinsic::lifetime_end)
536 // Found lifetime intrinsic, add ASan instrumentation if necessary.
537 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
538 // If size argument is undefined, don't do anything.
539 if (Size->isMinusOne()) return;
540 // Check that size doesn't saturate uint64_t and can
541 // be stored in IntptrTy.
542 const uint64_t SizeValue = Size->getValue().getLimitedValue();
543 if (SizeValue == ~0ULL ||
544 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
546 // Find alloca instruction that corresponds to llvm.lifetime argument.
547 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
549 bool DoPoison = (ID == Intrinsic::lifetime_end);
550 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
551 AllocaPoisonCallVec.push_back(APC);
554 // ---------------------- Helpers.
555 void initializeCallbacks(Module &M);
557 // Check if we want (and can) handle this alloca.
558 bool isInterestingAlloca(AllocaInst &AI) const {
559 return (!AI.isArrayAllocation() && AI.isStaticAlloca() &&
560 AI.getAllocatedType()->isSized() &&
561 // alloca() may be called with 0 size, ignore it.
562 getAllocaSizeInBytes(&AI) > 0);
565 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
566 Type *Ty = AI->getAllocatedType();
567 uint64_t SizeInBytes = ASan.DL->getTypeAllocSize(Ty);
570 /// Finds alloca where the value comes from.
571 AllocaInst *findAllocaForValue(Value *V);
572 void poisonRedZones(const ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
573 Value *ShadowBase, bool DoPoison);
574 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
576 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
582 char AddressSanitizer::ID = 0;
583 INITIALIZE_PASS(AddressSanitizer, "asan",
584 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
586 FunctionPass *llvm::createAddressSanitizerFunctionPass() {
587 return new AddressSanitizer();
590 char AddressSanitizerModule::ID = 0;
591 INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
592 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
593 "ModulePass", false, false)
594 ModulePass *llvm::createAddressSanitizerModulePass() {
595 return new AddressSanitizerModule();
598 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
599 size_t Res = countTrailingZeros(TypeSize / 8);
600 assert(Res < kNumberOfAccessSizes);
604 // \brief Create a constant for Str so that we can pass it to the run-time lib.
605 static GlobalVariable *createPrivateGlobalForString(
606 Module &M, StringRef Str, bool AllowMerging) {
607 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
608 // We use private linkage for module-local strings. If they can be merged
609 // with another one, we set the unnamed_addr attribute.
611 new GlobalVariable(M, StrConst->getType(), true,
612 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
614 GV->setUnnamedAddr(true);
615 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
619 static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
620 return G->getName().find(kAsanGenPrefix) == 0;
623 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
625 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
626 if (Mapping.Offset == 0)
628 // (Shadow >> scale) | offset
629 if (Mapping.OrShadowOffset)
630 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
632 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
635 // Instrument memset/memmove/memcpy
636 void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
638 if (isa<MemTransferInst>(MI)) {
640 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
641 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
642 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
643 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
644 } else if (isa<MemSetInst>(MI)) {
647 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
648 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
649 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
651 MI->eraseFromParent();
654 // If I is an interesting memory access, return the PointerOperand
655 // and set IsWrite/Alignment. Otherwise return NULL.
656 static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
657 unsigned *Alignment) {
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 TerminatorInst *CheckTerm =
862 SplitBlockAndInsertIfThen(Cmp, InsertBefore, false);
863 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
864 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
865 IRB.SetInsertPoint(CheckTerm);
866 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
867 BasicBlock *CrashBlock =
868 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
869 CrashTerm = new UnreachableInst(*C, CrashBlock);
870 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
871 ReplaceInstWithInst(CheckTerm, NewTerm);
873 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
876 Instruction *Crash = generateCrashCode(
877 CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
878 Crash->setDebugLoc(OrigIns->getDebugLoc());
881 void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
882 GlobalValue *ModuleName) {
883 // Set up the arguments to our poison/unpoison functions.
884 IRBuilder<> IRB(GlobalInit.begin()->getFirstInsertionPt());
886 // Add a call to poison all external globals before the given function starts.
887 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
888 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
890 // Add calls to unpoison all globals before each return instruction.
891 for (auto &BB : GlobalInit.getBasicBlockList())
892 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
893 CallInst::Create(AsanUnpoisonGlobals, "", RI);
896 void AddressSanitizerModule::createInitializerPoisonCalls(
897 Module &M, GlobalValue *ModuleName) {
898 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
900 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
901 for (Use &OP : CA->operands()) {
902 if (isa<ConstantAggregateZero>(OP))
904 ConstantStruct *CS = cast<ConstantStruct>(OP);
906 // Must have a function or null ptr.
907 // (CS->getOperand(0) is the init priority.)
908 if (Function* F = dyn_cast<Function>(CS->getOperand(1))) {
909 if (F->getName() != kAsanModuleCtorName)
910 poisonOneInitializer(*F, ModuleName);
915 bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
916 Type *Ty = cast<PointerType>(G->getType())->getElementType();
917 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
919 if (GlobalsMD.get(G).IsBlacklisted) return false;
920 if (GlobalsMD.isInstrumentationGlobal(G)) return false;
921 if (!Ty->isSized()) return false;
922 if (!G->hasInitializer()) return false;
923 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
924 // Touch only those globals that will not be defined in other modules.
925 // Don't handle ODR linkage types and COMDATs since other modules may be built
927 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
928 G->getLinkage() != GlobalVariable::PrivateLinkage &&
929 G->getLinkage() != GlobalVariable::InternalLinkage)
933 // Two problems with thread-locals:
934 // - The address of the main thread's copy can't be computed at link-time.
935 // - Need to poison all copies, not just the main thread's one.
936 if (G->isThreadLocal())
938 // For now, just ignore this Global if the alignment is large.
939 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
941 // Ignore all the globals with the names starting with "\01L_OBJC_".
942 // Many of those are put into the .cstring section. The linker compresses
943 // that section by removing the spare \0s after the string terminator, so
944 // our redzones get broken.
945 if ((G->getName().find("\01L_OBJC_") == 0) ||
946 (G->getName().find("\01l_OBJC_") == 0)) {
947 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G << "\n");
951 if (G->hasSection()) {
952 StringRef Section(G->getSection());
953 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
954 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
956 if (Section.startswith("__OBJC,") ||
957 Section.startswith("__DATA, __objc_")) {
958 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
961 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
962 // Constant CFString instances are compiled in the following way:
963 // -- the string buffer is emitted into
964 // __TEXT,__cstring,cstring_literals
965 // -- the constant NSConstantString structure referencing that buffer
966 // is placed into __DATA,__cfstring
967 // Therefore there's no point in placing redzones into __DATA,__cfstring.
968 // Moreover, it causes the linker to crash on OS X 10.7
969 if (Section.startswith("__DATA,__cfstring")) {
970 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
973 // The linker merges the contents of cstring_literals and removes the
975 if (Section.startswith("__TEXT,__cstring,cstring_literals")) {
976 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
980 // Callbacks put into the CRT initializer/terminator sections
981 // should not be instrumented.
982 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
983 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
984 if (Section.startswith(".CRT")) {
985 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
989 // Globals from llvm.metadata aren't emitted, do not instrument them.
990 if (Section == "llvm.metadata") return false;
996 void AddressSanitizerModule::initializeCallbacks(Module &M) {
998 // Declare our poisoning and unpoisoning functions.
999 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1000 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, NULL));
1001 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
1002 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1003 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
1004 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1005 // Declare functions that register/unregister globals.
1006 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1007 kAsanRegisterGlobalsName, IRB.getVoidTy(),
1008 IntptrTy, IntptrTy, NULL));
1009 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
1010 AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1011 kAsanUnregisterGlobalsName,
1012 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1013 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1014 AsanCovModuleInit = checkInterfaceFunction(M.getOrInsertFunction(
1015 kAsanCovModuleInitName,
1016 IRB.getVoidTy(), IntptrTy, NULL));
1017 AsanCovModuleInit->setLinkage(Function::ExternalLinkage);
1020 // This function replaces all global variables with new variables that have
1021 // trailing redzones. It also creates a function that poisons
1022 // redzones and inserts this function into llvm.global_ctors.
1023 bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
1026 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1028 for (auto &G : M.globals()) {
1029 if (ShouldInstrumentGlobal(&G))
1030 GlobalsToChange.push_back(&G);
1033 size_t n = GlobalsToChange.size();
1034 if (n == 0) return false;
1036 // A global is described by a structure
1039 // size_t size_with_redzone;
1040 // const char *name;
1041 // const char *module_name;
1042 // size_t has_dynamic_init;
1043 // void *source_location;
1044 // We initialize an array of such structures and pass it to a run-time call.
1045 StructType *GlobalStructTy =
1046 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
1047 IntptrTy, IntptrTy, NULL);
1048 SmallVector<Constant *, 16> Initializers(n);
1050 bool HasDynamicallyInitializedGlobals = false;
1052 // We shouldn't merge same module names, as this string serves as unique
1053 // module ID in runtime.
1054 GlobalVariable *ModuleName = createPrivateGlobalForString(
1055 M, M.getModuleIdentifier(), /*AllowMerging*/false);
1057 for (size_t i = 0; i < n; i++) {
1058 static const uint64_t kMaxGlobalRedzone = 1 << 18;
1059 GlobalVariable *G = GlobalsToChange[i];
1061 auto MD = GlobalsMD.get(G);
1062 // Create string holding the global name unless it was provided by
1064 GlobalVariable *Name =
1065 MD.Name ? MD.Name : createPrivateGlobalForString(M, G->getName(),
1066 /*AllowMerging*/ true);
1068 PointerType *PtrTy = cast<PointerType>(G->getType());
1069 Type *Ty = PtrTy->getElementType();
1070 uint64_t SizeInBytes = DL->getTypeAllocSize(Ty);
1071 uint64_t MinRZ = MinRedzoneSizeForGlobal();
1072 // MinRZ <= RZ <= kMaxGlobalRedzone
1073 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
1074 uint64_t RZ = std::max(MinRZ,
1075 std::min(kMaxGlobalRedzone,
1076 (SizeInBytes / MinRZ / 4) * MinRZ));
1077 uint64_t RightRedzoneSize = RZ;
1078 // Round up to MinRZ
1079 if (SizeInBytes % MinRZ)
1080 RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
1081 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
1082 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1084 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
1085 Constant *NewInitializer = ConstantStruct::get(
1086 NewTy, G->getInitializer(),
1087 Constant::getNullValue(RightRedZoneTy), NULL);
1089 // Create a new global variable with enough space for a redzone.
1090 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1091 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1092 Linkage = GlobalValue::InternalLinkage;
1093 GlobalVariable *NewGlobal = new GlobalVariable(
1094 M, NewTy, G->isConstant(), Linkage,
1095 NewInitializer, "", G, G->getThreadLocalMode());
1096 NewGlobal->copyAttributesFrom(G);
1097 NewGlobal->setAlignment(MinRZ);
1100 Indices2[0] = IRB.getInt32(0);
1101 Indices2[1] = IRB.getInt32(0);
1103 G->replaceAllUsesWith(
1104 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
1105 NewGlobal->takeName(G);
1106 G->eraseFromParent();
1108 Initializers[i] = ConstantStruct::get(
1109 GlobalStructTy, ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
1110 ConstantInt::get(IntptrTy, SizeInBytes),
1111 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1112 ConstantExpr::getPointerCast(Name, IntptrTy),
1113 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
1114 ConstantInt::get(IntptrTy, MD.IsDynInit),
1115 MD.SourceLoc ? ConstantExpr::getPointerCast(MD.SourceLoc, IntptrTy)
1116 : ConstantInt::get(IntptrTy, 0),
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());
1170 if (ClCoverage > 0) {
1171 Function *CovFunc = M.getFunction(kAsanCovName);
1172 int nCov = CovFunc ? CovFunc->getNumUses() : 0;
1173 IRB.CreateCall(AsanCovModuleInit, ConstantInt::get(IntptrTy, nCov));
1178 Changed |= InstrumentGlobals(IRB, M);
1183 void AddressSanitizer::initializeCallbacks(Module &M) {
1184 IRBuilder<> IRB(*C);
1185 // Create __asan_report* callbacks.
1186 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1187 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1188 AccessSizeIndex++) {
1189 // IsWrite and TypeSize are encoded in the function name.
1190 std::string Suffix =
1191 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
1192 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
1193 checkInterfaceFunction(
1194 M.getOrInsertFunction(kAsanReportErrorTemplate + Suffix,
1195 IRB.getVoidTy(), IntptrTy, NULL));
1196 AsanMemoryAccessCallback[AccessIsWrite][AccessSizeIndex] =
1197 checkInterfaceFunction(
1198 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + Suffix,
1199 IRB.getVoidTy(), IntptrTy, NULL));
1202 AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
1203 kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1204 AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
1205 kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1207 AsanMemoryAccessCallbackSized[0] = checkInterfaceFunction(
1208 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "loadN",
1209 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1210 AsanMemoryAccessCallbackSized[1] = checkInterfaceFunction(
1211 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "storeN",
1212 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1214 AsanMemmove = checkInterfaceFunction(M.getOrInsertFunction(
1215 ClMemoryAccessCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
1216 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, NULL));
1217 AsanMemcpy = checkInterfaceFunction(M.getOrInsertFunction(
1218 ClMemoryAccessCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
1219 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, NULL));
1220 AsanMemset = checkInterfaceFunction(M.getOrInsertFunction(
1221 ClMemoryAccessCallbackPrefix + "memset", IRB.getInt8PtrTy(),
1222 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, NULL));
1224 AsanHandleNoReturnFunc = checkInterfaceFunction(
1225 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
1226 AsanCovFunction = checkInterfaceFunction(M.getOrInsertFunction(
1227 kAsanCovName, IRB.getVoidTy(), NULL));
1228 AsanPtrCmpFunction = checkInterfaceFunction(M.getOrInsertFunction(
1229 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1230 AsanPtrSubFunction = checkInterfaceFunction(M.getOrInsertFunction(
1231 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1232 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1233 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1234 StringRef(""), StringRef(""),
1235 /*hasSideEffects=*/true);
1239 bool AddressSanitizer::doInitialization(Module &M) {
1240 // Initialize the private fields. No one has accessed them before.
1241 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1243 report_fatal_error("data layout missing");
1244 DL = &DLP->getDataLayout();
1248 C = &(M.getContext());
1249 LongSize = DL->getPointerSizeInBits();
1250 IntptrTy = Type::getIntNTy(*C, LongSize);
1252 AsanCtorFunction = Function::Create(
1253 FunctionType::get(Type::getVoidTy(*C), false),
1254 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1255 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1256 // call __asan_init in the module ctor.
1257 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1258 AsanInitFunction = checkInterfaceFunction(
1259 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
1260 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1261 IRB.CreateCall(AsanInitFunction);
1263 Mapping = getShadowMapping(M, LongSize);
1265 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
1269 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1270 // For each NSObject descendant having a +load method, this method is invoked
1271 // by the ObjC runtime before any of the static constructors is called.
1272 // Therefore we need to instrument such methods with a call to __asan_init
1273 // at the beginning in order to initialize our runtime before any access to
1274 // the shadow memory.
1275 // We cannot just ignore these methods, because they may call other
1276 // instrumented functions.
1277 if (F.getName().find(" load]") != std::string::npos) {
1278 IRBuilder<> IRB(F.begin()->begin());
1279 IRB.CreateCall(AsanInitFunction);
1285 void AddressSanitizer::InjectCoverageAtBlock(Function &F, BasicBlock &BB) {
1286 BasicBlock::iterator IP = BB.getFirstInsertionPt(), BE = BB.end();
1287 // Skip static allocas at the top of the entry block so they don't become
1288 // dynamic when we split the block. If we used our optimized stack layout,
1289 // then there will only be one alloca and it will come first.
1290 for (; IP != BE; ++IP) {
1291 AllocaInst *AI = dyn_cast<AllocaInst>(IP);
1292 if (!AI || !AI->isStaticAlloca())
1296 DebugLoc EntryLoc = IP->getDebugLoc().getFnDebugLoc(*C);
1297 IRBuilder<> IRB(IP);
1298 IRB.SetCurrentDebugLocation(EntryLoc);
1299 Type *Int8Ty = IRB.getInt8Ty();
1300 GlobalVariable *Guard = new GlobalVariable(
1301 *F.getParent(), Int8Ty, false, GlobalValue::PrivateLinkage,
1302 Constant::getNullValue(Int8Ty), "__asan_gen_cov_" + F.getName());
1303 LoadInst *Load = IRB.CreateLoad(Guard);
1304 Load->setAtomic(Monotonic);
1305 Load->setAlignment(1);
1306 Value *Cmp = IRB.CreateICmpEQ(Constant::getNullValue(Int8Ty), Load);
1307 Instruction *Ins = SplitBlockAndInsertIfThen(
1308 Cmp, IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
1309 IRB.SetInsertPoint(Ins);
1310 IRB.SetCurrentDebugLocation(EntryLoc);
1311 // We pass &F to __sanitizer_cov. We could avoid this and rely on
1312 // GET_CALLER_PC, but having the PC of the first instruction is just nice.
1313 IRB.CreateCall(AsanCovFunction);
1314 StoreInst *Store = IRB.CreateStore(ConstantInt::get(Int8Ty, 1), Guard);
1315 Store->setAtomic(Monotonic);
1316 Store->setAlignment(1);
1319 // Poor man's coverage that works with ASan.
1320 // We create a Guard boolean variable with the same linkage
1321 // as the function and inject this code into the entry block (-asan-coverage=1)
1322 // or all blocks (-asan-coverage=2):
1324 // __sanitizer_cov(&F);
1327 // The accesses to Guard are atomic. The rest of the logic is
1328 // in __sanitizer_cov (it's fine to call it more than once).
1330 // This coverage implementation provides very limited data:
1331 // it only tells if a given function (block) was ever executed.
1332 // No counters, no per-edge data.
1333 // But for many use cases this is what we need and the added slowdown
1334 // is negligible. This simple implementation will probably be obsoleted
1335 // by the upcoming Clang-based coverage implementation.
1336 // By having it here and now we hope to
1337 // a) get the functionality to users earlier and
1338 // b) collect usage statistics to help improve Clang coverage design.
1339 bool AddressSanitizer::InjectCoverage(Function &F,
1340 const ArrayRef<BasicBlock *> AllBlocks) {
1341 if (!ClCoverage) return false;
1343 if (ClCoverage == 1 ||
1344 (unsigned)ClCoverageBlockThreshold < AllBlocks.size()) {
1345 InjectCoverageAtBlock(F, F.getEntryBlock());
1347 for (auto BB : AllBlocks)
1348 InjectCoverageAtBlock(F, *BB);
1353 bool AddressSanitizer::runOnFunction(Function &F) {
1354 if (&F == AsanCtorFunction) return false;
1355 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
1356 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
1357 initializeCallbacks(*F.getParent());
1359 // If needed, insert __asan_init before checking for SanitizeAddress attr.
1360 maybeInsertAsanInitAtFunctionEntry(F);
1362 if (!F.hasFnAttribute(Attribute::SanitizeAddress))
1365 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1368 // We want to instrument every address only once per basic block (unless there
1369 // are calls between uses).
1370 SmallSet<Value*, 16> TempsToInstrument;
1371 SmallVector<Instruction*, 16> ToInstrument;
1372 SmallVector<Instruction*, 8> NoReturnCalls;
1373 SmallVector<BasicBlock*, 16> AllBlocks;
1374 SmallVector<Instruction*, 16> PointerComparisonsOrSubtracts;
1379 // Fill the set of memory operations to instrument.
1380 for (auto &BB : F) {
1381 AllBlocks.push_back(&BB);
1382 TempsToInstrument.clear();
1383 int NumInsnsPerBB = 0;
1384 for (auto &Inst : BB) {
1385 if (LooksLikeCodeInBug11395(&Inst)) return false;
1387 isInterestingMemoryAccess(&Inst, &IsWrite, &Alignment)) {
1388 if (ClOpt && ClOptSameTemp) {
1389 if (!TempsToInstrument.insert(Addr))
1390 continue; // We've seen this temp in the current BB.
1392 } else if (ClInvalidPointerPairs &&
1393 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1394 PointerComparisonsOrSubtracts.push_back(&Inst);
1396 } else if (isa<MemIntrinsic>(Inst)) {
1399 if (isa<AllocaInst>(Inst))
1403 // A call inside BB.
1404 TempsToInstrument.clear();
1405 if (CS.doesNotReturn())
1406 NoReturnCalls.push_back(CS.getInstruction());
1410 ToInstrument.push_back(&Inst);
1412 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1417 Function *UninstrumentedDuplicate = nullptr;
1418 bool LikelyToInstrument =
1419 !NoReturnCalls.empty() || !ToInstrument.empty() || (NumAllocas > 0);
1420 if (ClKeepUninstrumented && LikelyToInstrument) {
1421 ValueToValueMapTy VMap;
1422 UninstrumentedDuplicate = CloneFunction(&F, VMap, false);
1423 UninstrumentedDuplicate->removeFnAttr(Attribute::SanitizeAddress);
1424 UninstrumentedDuplicate->setName("NOASAN_" + F.getName());
1425 F.getParent()->getFunctionList().push_back(UninstrumentedDuplicate);
1428 bool UseCalls = false;
1429 if (ClInstrumentationWithCallsThreshold >= 0 &&
1430 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold)
1434 int NumInstrumented = 0;
1435 for (auto Inst : ToInstrument) {
1436 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1437 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
1438 if (isInterestingMemoryAccess(Inst, &IsWrite, &Alignment))
1439 instrumentMop(Inst, UseCalls);
1441 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
1446 FunctionStackPoisoner FSP(F, *this);
1447 bool ChangedStack = FSP.runOnFunction();
1449 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1450 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1451 for (auto CI : NoReturnCalls) {
1452 IRBuilder<> IRB(CI);
1453 IRB.CreateCall(AsanHandleNoReturnFunc);
1456 for (auto Inst : PointerComparisonsOrSubtracts) {
1457 instrumentPointerComparisonOrSubtraction(Inst);
1461 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
1463 if (InjectCoverage(F, AllBlocks))
1466 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1468 if (ClKeepUninstrumented) {
1470 // No instrumentation is done, no need for the duplicate.
1471 if (UninstrumentedDuplicate)
1472 UninstrumentedDuplicate->eraseFromParent();
1474 // The function was instrumented. We must have the duplicate.
1475 assert(UninstrumentedDuplicate);
1476 UninstrumentedDuplicate->setSection("NOASAN");
1477 assert(!F.hasSection());
1478 F.setSection("ASAN");
1485 // Workaround for bug 11395: we don't want to instrument stack in functions
1486 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1487 // FIXME: remove once the bug 11395 is fixed.
1488 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1489 if (LongSize != 32) return false;
1490 CallInst *CI = dyn_cast<CallInst>(I);
1491 if (!CI || !CI->isInlineAsm()) return false;
1492 if (CI->getNumArgOperands() <= 5) return false;
1493 // We have inline assembly with quite a few arguments.
1497 void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1498 IRBuilder<> IRB(*C);
1499 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1500 std::string Suffix = itostr(i);
1501 AsanStackMallocFunc[i] = checkInterfaceFunction(
1502 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1503 IntptrTy, IntptrTy, NULL));
1504 AsanStackFreeFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
1505 kAsanStackFreeNameTemplate + Suffix, IRB.getVoidTy(), IntptrTy,
1506 IntptrTy, IntptrTy, NULL));
1508 AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1509 kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1510 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1511 kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1515 FunctionStackPoisoner::poisonRedZones(const ArrayRef<uint8_t> ShadowBytes,
1516 IRBuilder<> &IRB, Value *ShadowBase,
1518 size_t n = ShadowBytes.size();
1520 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1521 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1522 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1523 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1524 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1525 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1527 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
1528 if (ASan.DL->isLittleEndian())
1529 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1531 Val = (Val << 8) | ShadowBytes[i + j];
1534 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1535 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1536 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1537 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
1542 // Fake stack allocator (asan_fake_stack.h) has 11 size classes
1543 // for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1544 static int StackMallocSizeClass(uint64_t LocalStackSize) {
1545 assert(LocalStackSize <= kMaxStackMallocSize);
1546 uint64_t MaxSize = kMinStackMallocSize;
1547 for (int i = 0; ; i++, MaxSize *= 2)
1548 if (LocalStackSize <= MaxSize)
1550 llvm_unreachable("impossible LocalStackSize");
1553 // Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1554 // We can not use MemSet intrinsic because it may end up calling the actual
1555 // memset. Size is a multiple of 8.
1556 // Currently this generates 8-byte stores on x86_64; it may be better to
1557 // generate wider stores.
1558 void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1559 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1560 assert(!(Size % 8));
1561 assert(kAsanStackAfterReturnMagic == 0xf5);
1562 for (int i = 0; i < Size; i += 8) {
1563 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1564 IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
1565 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1569 static DebugLoc getFunctionEntryDebugLocation(Function &F) {
1570 for (const auto &Inst : F.getEntryBlock())
1571 if (!isa<AllocaInst>(Inst))
1572 return Inst.getDebugLoc();
1576 void FunctionStackPoisoner::poisonStack() {
1577 int StackMallocIdx = -1;
1578 DebugLoc EntryDebugLocation = getFunctionEntryDebugLocation(F);
1580 assert(AllocaVec.size() > 0);
1581 Instruction *InsBefore = AllocaVec[0];
1582 IRBuilder<> IRB(InsBefore);
1583 IRB.SetCurrentDebugLocation(EntryDebugLocation);
1585 SmallVector<ASanStackVariableDescription, 16> SVD;
1586 SVD.reserve(AllocaVec.size());
1587 for (AllocaInst *AI : AllocaVec) {
1588 ASanStackVariableDescription D = { AI->getName().data(),
1589 getAllocaSizeInBytes(AI),
1590 AI->getAlignment(), AI, 0};
1593 // Minimal header size (left redzone) is 4 pointers,
1594 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1595 size_t MinHeaderSize = ASan.LongSize / 2;
1596 ASanStackFrameLayout L;
1597 ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1598 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1599 uint64_t LocalStackSize = L.FrameSize;
1600 bool DoStackMalloc =
1601 ClUseAfterReturn && LocalStackSize <= kMaxStackMallocSize;
1603 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1604 AllocaInst *MyAlloca =
1605 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
1606 MyAlloca->setDebugLoc(EntryDebugLocation);
1607 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1608 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1609 MyAlloca->setAlignment(FrameAlignment);
1610 assert(MyAlloca->isStaticAlloca());
1611 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1612 Value *LocalStackBase = OrigStackBase;
1614 if (DoStackMalloc) {
1615 // LocalStackBase = OrigStackBase
1616 // if (__asan_option_detect_stack_use_after_return)
1617 // LocalStackBase = __asan_stack_malloc_N(LocalStackBase, OrigStackBase);
1618 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1619 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
1620 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1621 kAsanOptionDetectUAR, IRB.getInt32Ty());
1622 Value *Cmp = IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1623 Constant::getNullValue(IRB.getInt32Ty()));
1624 Instruction *Term = SplitBlockAndInsertIfThen(Cmp, InsBefore, false);
1625 BasicBlock *CmpBlock = cast<Instruction>(Cmp)->getParent();
1626 IRBuilder<> IRBIf(Term);
1627 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
1628 LocalStackBase = IRBIf.CreateCall2(
1629 AsanStackMallocFunc[StackMallocIdx],
1630 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1631 BasicBlock *SetBlock = cast<Instruction>(LocalStackBase)->getParent();
1632 IRB.SetInsertPoint(InsBefore);
1633 IRB.SetCurrentDebugLocation(EntryDebugLocation);
1634 PHINode *Phi = IRB.CreatePHI(IntptrTy, 2);
1635 Phi->addIncoming(OrigStackBase, CmpBlock);
1636 Phi->addIncoming(LocalStackBase, SetBlock);
1637 LocalStackBase = Phi;
1640 // Insert poison calls for lifetime intrinsics for alloca.
1641 bool HavePoisonedAllocas = false;
1642 for (const auto &APC : AllocaPoisonCallVec) {
1643 assert(APC.InsBefore);
1645 IRBuilder<> IRB(APC.InsBefore);
1646 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
1647 HavePoisonedAllocas |= APC.DoPoison;
1650 // Replace Alloca instructions with base+offset.
1651 for (const auto &Desc : SVD) {
1652 AllocaInst *AI = Desc.AI;
1653 Value *NewAllocaPtr = IRB.CreateIntToPtr(
1654 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
1656 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
1657 AI->replaceAllUsesWith(NewAllocaPtr);
1660 // The left-most redzone has enough space for at least 4 pointers.
1661 // Write the Magic value to redzone[0].
1662 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1663 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1665 // Write the frame description constant to redzone[1].
1666 Value *BasePlus1 = IRB.CreateIntToPtr(
1667 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
1669 GlobalVariable *StackDescriptionGlobal =
1670 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
1671 /*AllowMerging*/true);
1672 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1674 IRB.CreateStore(Description, BasePlus1);
1675 // Write the PC to redzone[2].
1676 Value *BasePlus2 = IRB.CreateIntToPtr(
1677 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
1678 2 * ASan.LongSize/8)),
1680 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
1682 // Poison the stack redzones at the entry.
1683 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1684 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
1686 // (Un)poison the stack before all ret instructions.
1687 for (auto Ret : RetVec) {
1688 IRBuilder<> IRBRet(Ret);
1689 // Mark the current frame as retired.
1690 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1692 if (DoStackMalloc) {
1693 assert(StackMallocIdx >= 0);
1694 // if LocalStackBase != OrigStackBase:
1695 // // In use-after-return mode, poison the whole stack frame.
1696 // if StackMallocIdx <= 4
1697 // // For small sizes inline the whole thing:
1698 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
1699 // **SavedFlagPtr(LocalStackBase) = 0
1701 // __asan_stack_free_N(LocalStackBase, OrigStackBase)
1703 // <This is not a fake stack; unpoison the redzones>
1704 Value *Cmp = IRBRet.CreateICmpNE(LocalStackBase, OrigStackBase);
1705 TerminatorInst *ThenTerm, *ElseTerm;
1706 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1708 IRBuilder<> IRBPoison(ThenTerm);
1709 if (StackMallocIdx <= 4) {
1710 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1711 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1712 ClassSize >> Mapping.Scale);
1713 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
1715 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1716 Value *SavedFlagPtr = IRBPoison.CreateLoad(
1717 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1718 IRBPoison.CreateStore(
1719 Constant::getNullValue(IRBPoison.getInt8Ty()),
1720 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1722 // For larger frames call __asan_stack_free_*.
1723 IRBPoison.CreateCall3(AsanStackFreeFunc[StackMallocIdx], LocalStackBase,
1724 ConstantInt::get(IntptrTy, LocalStackSize),
1728 IRBuilder<> IRBElse(ElseTerm);
1729 poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
1730 } else if (HavePoisonedAllocas) {
1731 // If we poisoned some allocas in llvm.lifetime analysis,
1732 // unpoison whole stack frame now.
1733 assert(LocalStackBase == OrigStackBase);
1734 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
1736 poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
1740 // We are done. Remove the old unused alloca instructions.
1741 for (auto AI : AllocaVec)
1742 AI->eraseFromParent();
1745 void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
1746 IRBuilder<> &IRB, bool DoPoison) {
1747 // For now just insert the call to ASan runtime.
1748 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1749 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1750 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1751 : AsanUnpoisonStackMemoryFunc,
1755 // Handling llvm.lifetime intrinsics for a given %alloca:
1756 // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1757 // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1758 // invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1759 // could be poisoned by previous llvm.lifetime.end instruction, as the
1760 // variable may go in and out of scope several times, e.g. in loops).
1761 // (3) if we poisoned at least one %alloca in a function,
1762 // unpoison the whole stack frame at function exit.
1764 AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1765 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1766 // We're intested only in allocas we can handle.
1767 return isInterestingAlloca(*AI) ? AI : nullptr;
1768 // See if we've already calculated (or started to calculate) alloca for a
1770 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1771 if (I != AllocaForValue.end())
1773 // Store 0 while we're calculating alloca for value V to avoid
1774 // infinite recursion if the value references itself.
1775 AllocaForValue[V] = nullptr;
1776 AllocaInst *Res = nullptr;
1777 if (CastInst *CI = dyn_cast<CastInst>(V))
1778 Res = findAllocaForValue(CI->getOperand(0));
1779 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1780 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1781 Value *IncValue = PN->getIncomingValue(i);
1782 // Allow self-referencing phi-nodes.
1783 if (IncValue == PN) continue;
1784 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1785 // AI for incoming values should exist and should all be equal.
1786 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
1792 AllocaForValue[V] = Res;