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 kAsanCovModuleInitName = "__sanitizer_cov_module_init";
85 static const char *const kAsanCovName = "__sanitizer_cov";
86 static const char *const kAsanCovIndirCallName = "__sanitizer_cov_indir_call16";
87 static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
88 static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
89 static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
90 static const int kMaxAsanStackMallocSizeClass = 10;
91 static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
92 static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
93 static const char *const kAsanGenPrefix = "__asan_gen_";
94 static const char *const kAsanPoisonStackMemoryName =
95 "__asan_poison_stack_memory";
96 static const char *const kAsanUnpoisonStackMemoryName =
97 "__asan_unpoison_stack_memory";
99 static const char *const kAsanOptionDetectUAR =
100 "__asan_option_detect_stack_use_after_return";
103 static const int kAsanStackAfterReturnMagic = 0xf5;
106 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
107 static const size_t kNumberOfAccessSizes = 5;
109 // Command-line flags.
111 // This flag may need to be replaced with -f[no-]asan-reads.
112 static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
113 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
114 static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
115 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
116 static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
117 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
118 cl::Hidden, cl::init(true));
119 static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
120 cl::desc("use instrumentation with slow path for all accesses"),
121 cl::Hidden, cl::init(false));
122 // This flag limits the number of instructions to be instrumented
123 // in any given BB. Normally, this should be set to unlimited (INT_MAX),
124 // but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
126 static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
128 cl::desc("maximal number of instructions to instrument in any given BB"),
130 // This flag may need to be replaced with -f[no]asan-stack.
131 static cl::opt<bool> ClStack("asan-stack",
132 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
133 static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
134 cl::desc("Check return-after-free"), cl::Hidden, cl::init(true));
135 // This flag may need to be replaced with -f[no]asan-globals.
136 static cl::opt<bool> ClGlobals("asan-globals",
137 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
138 static cl::opt<int> ClCoverage("asan-coverage",
139 cl::desc("ASan coverage. 0: none, 1: entry block, 2: all blocks, "
140 "3: all blocks and critical edges, "
141 "4: above plus indirect calls"),
142 cl::Hidden, cl::init(false));
143 static cl::opt<int> ClCoverageBlockThreshold("asan-coverage-block-threshold",
144 cl::desc("Add coverage instrumentation only to the entry block if there "
145 "are more than this number of blocks."),
146 cl::Hidden, cl::init(1500));
147 static cl::opt<bool> ClInitializers("asan-initialization-order",
148 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(true));
149 static cl::opt<bool> ClInvalidPointerPairs("asan-detect-invalid-pointer-pair",
150 cl::desc("Instrument <, <=, >, >=, - with pointer operands"),
151 cl::Hidden, cl::init(false));
152 static cl::opt<unsigned> ClRealignStack("asan-realign-stack",
153 cl::desc("Realign stack to the value of this flag (power of two)"),
154 cl::Hidden, cl::init(32));
155 static cl::opt<int> ClInstrumentationWithCallsThreshold(
156 "asan-instrumentation-with-call-threshold",
157 cl::desc("If the function being instrumented contains more than "
158 "this number of memory accesses, use callbacks instead of "
159 "inline checks (-1 means never use callbacks)."),
160 cl::Hidden, cl::init(7000));
161 static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
162 "asan-memory-access-callback-prefix",
163 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
164 cl::init("__asan_"));
166 // This is an experimental feature that will allow to choose between
167 // instrumented and non-instrumented code at link-time.
168 // If this option is on, just before instrumenting a function we create its
169 // clone; if the function is not changed by asan the clone is deleted.
170 // If we end up with a clone, we put the instrumented function into a section
171 // called "ASAN" and the uninstrumented function into a section called "NOASAN".
173 // This is still a prototype, we need to figure out a way to keep two copies of
174 // a function so that the linker can easily choose one of them.
175 static cl::opt<bool> ClKeepUninstrumented("asan-keep-uninstrumented-functions",
176 cl::desc("Keep uninstrumented copies of functions"),
177 cl::Hidden, cl::init(false));
179 // These flags allow to change the shadow mapping.
180 // The shadow mapping looks like
181 // Shadow = (Mem >> scale) + (1 << offset_log)
182 static cl::opt<int> ClMappingScale("asan-mapping-scale",
183 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
185 // Optimization flags. Not user visible, used mostly for testing
186 // and benchmarking the tool.
187 static cl::opt<bool> ClOpt("asan-opt",
188 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
189 static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
190 cl::desc("Instrument the same temp just once"), cl::Hidden,
192 static cl::opt<bool> ClOptGlobals("asan-opt-globals",
193 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
195 static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
196 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
197 cl::Hidden, cl::init(false));
200 static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
202 static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
203 cl::Hidden, cl::init(0));
204 static cl::opt<std::string> ClDebugFunc("asan-debug-func",
205 cl::Hidden, cl::desc("Debug func"));
206 static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
207 cl::Hidden, cl::init(-1));
208 static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
209 cl::Hidden, cl::init(-1));
211 STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
212 STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
213 STATISTIC(NumOptimizedAccessesToGlobalArray,
214 "Number of optimized accesses to global arrays");
215 STATISTIC(NumOptimizedAccessesToGlobalVar,
216 "Number of optimized accesses to global vars");
219 /// Frontend-provided metadata for source location.
220 struct LocationMetadata {
225 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
227 bool empty() const { return Filename.empty(); }
229 void parse(MDNode *MDN) {
230 assert(MDN->getNumOperands() == 3);
231 MDString *MDFilename = cast<MDString>(MDN->getOperand(0));
232 Filename = MDFilename->getString();
233 LineNo = cast<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
234 ColumnNo = cast<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
238 /// Frontend-provided metadata for global variables.
239 class GlobalsMetadata {
243 : SourceLoc(), Name(), IsDynInit(false),
244 IsBlacklisted(false) {}
245 LocationMetadata SourceLoc;
251 GlobalsMetadata() : inited_(false) {}
253 void init(Module& M) {
256 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
259 for (auto MDN : Globals->operands()) {
260 // Metadata node contains the global and the fields of "Entry".
261 assert(MDN->getNumOperands() == 5);
262 Value *V = MDN->getOperand(0);
263 // The optimizer may optimize away a global entirely.
266 GlobalVariable *GV = cast<GlobalVariable>(V);
267 // We can already have an entry for GV if it was merged with another
269 Entry &E = Entries[GV];
270 if (Value *Loc = MDN->getOperand(1))
271 E.SourceLoc.parse(cast<MDNode>(Loc));
272 if (Value *Name = MDN->getOperand(2)) {
273 MDString *MDName = cast<MDString>(Name);
274 E.Name = MDName->getString();
276 ConstantInt *IsDynInit = cast<ConstantInt>(MDN->getOperand(3));
277 E.IsDynInit |= IsDynInit->isOne();
278 ConstantInt *IsBlacklisted = cast<ConstantInt>(MDN->getOperand(4));
279 E.IsBlacklisted |= IsBlacklisted->isOne();
283 /// Returns metadata entry for a given global.
284 Entry get(GlobalVariable *G) const {
285 auto Pos = Entries.find(G);
286 return (Pos != Entries.end()) ? Pos->second : Entry();
291 DenseMap<GlobalVariable*, Entry> Entries;
294 /// This struct defines the shadow mapping using the rule:
295 /// shadow = (mem >> Scale) ADD-or-OR Offset.
296 struct ShadowMapping {
302 static ShadowMapping getShadowMapping(const Module &M, int LongSize) {
303 llvm::Triple TargetTriple(M.getTargetTriple());
304 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
305 bool IsIOS = TargetTriple.isiOS();
306 bool IsFreeBSD = TargetTriple.getOS() == llvm::Triple::FreeBSD;
307 bool IsLinux = TargetTriple.getOS() == llvm::Triple::Linux;
308 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
309 TargetTriple.getArch() == llvm::Triple::ppc64le;
310 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
311 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
312 TargetTriple.getArch() == llvm::Triple::mipsel;
314 ShadowMapping Mapping;
316 if (LongSize == 32) {
320 Mapping.Offset = kMIPS32_ShadowOffset32;
322 Mapping.Offset = kFreeBSD_ShadowOffset32;
324 Mapping.Offset = kIOSShadowOffset32;
326 Mapping.Offset = kDefaultShadowOffset32;
327 } else { // LongSize == 64
329 Mapping.Offset = kPPC64_ShadowOffset64;
331 Mapping.Offset = kFreeBSD_ShadowOffset64;
332 else if (IsLinux && IsX86_64)
333 Mapping.Offset = kSmallX86_64ShadowOffset;
335 Mapping.Offset = kDefaultShadowOffset64;
338 Mapping.Scale = kDefaultShadowScale;
339 if (ClMappingScale) {
340 Mapping.Scale = ClMappingScale;
343 // OR-ing shadow offset if more efficient (at least on x86) if the offset
344 // is a power of two, but on ppc64 we have to use add since the shadow
345 // offset is not necessary 1/8-th of the address space.
346 Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
351 static size_t RedzoneSizeForScale(int MappingScale) {
352 // Redzone used for stack and globals is at least 32 bytes.
353 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
354 return std::max(32U, 1U << MappingScale);
357 /// AddressSanitizer: instrument the code in module to find memory bugs.
358 struct AddressSanitizer : public FunctionPass {
359 AddressSanitizer() : FunctionPass(ID) {
360 initializeBreakCriticalEdgesPass(*PassRegistry::getPassRegistry());
362 const char *getPassName() const override {
363 return "AddressSanitizerFunctionPass";
365 void instrumentMop(Instruction *I, bool UseCalls);
366 void instrumentPointerComparisonOrSubtraction(Instruction *I);
367 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
368 Value *Addr, uint32_t TypeSize, bool IsWrite,
369 Value *SizeArgument, bool UseCalls);
370 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
371 Value *ShadowValue, uint32_t TypeSize);
372 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
373 bool IsWrite, size_t AccessSizeIndex,
374 Value *SizeArgument);
375 void instrumentMemIntrinsic(MemIntrinsic *MI);
376 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
377 bool runOnFunction(Function &F) override;
378 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
379 bool doInitialization(Module &M) override;
380 static char ID; // Pass identification, replacement for typeid
382 void getAnalysisUsage(AnalysisUsage &AU) const override {
384 AU.addRequiredID(BreakCriticalEdgesID);
388 void initializeCallbacks(Module &M);
390 bool LooksLikeCodeInBug11395(Instruction *I);
391 bool GlobalIsLinkerInitialized(GlobalVariable *G);
392 void InjectCoverageForIndirectCalls(Function &F,
393 ArrayRef<Instruction *> IndirCalls);
394 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks,
395 ArrayRef<Instruction *> IndirCalls);
396 void InjectCoverageAtBlock(Function &F, BasicBlock &BB);
399 const DataLayout *DL;
402 ShadowMapping Mapping;
403 Function *AsanCtorFunction;
404 Function *AsanInitFunction;
405 Function *AsanHandleNoReturnFunc;
406 Function *AsanCovFunction;
407 Function *AsanCovIndirCallFunction;
408 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
409 // This array is indexed by AccessIsWrite and log2(AccessSize).
410 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
411 Function *AsanMemoryAccessCallback[2][kNumberOfAccessSizes];
412 // This array is indexed by AccessIsWrite.
413 Function *AsanErrorCallbackSized[2],
414 *AsanMemoryAccessCallbackSized[2];
415 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
417 GlobalsMetadata GlobalsMD;
419 friend struct FunctionStackPoisoner;
422 class AddressSanitizerModule : public ModulePass {
424 AddressSanitizerModule() : ModulePass(ID) {}
425 bool runOnModule(Module &M) override;
426 static char ID; // Pass identification, replacement for typeid
427 const char *getPassName() const override {
428 return "AddressSanitizerModule";
432 void initializeCallbacks(Module &M);
434 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
435 bool ShouldInstrumentGlobal(GlobalVariable *G);
436 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
437 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
438 size_t MinRedzoneSizeForGlobal() const {
439 return RedzoneSizeForScale(Mapping.Scale);
442 GlobalsMetadata GlobalsMD;
445 const DataLayout *DL;
446 ShadowMapping Mapping;
447 Function *AsanPoisonGlobals;
448 Function *AsanUnpoisonGlobals;
449 Function *AsanRegisterGlobals;
450 Function *AsanUnregisterGlobals;
451 Function *AsanCovModuleInit;
454 // Stack poisoning does not play well with exception handling.
455 // When an exception is thrown, we essentially bypass the code
456 // that unpoisones the stack. This is why the run-time library has
457 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
458 // stack in the interceptor. This however does not work inside the
459 // actual function which catches the exception. Most likely because the
460 // compiler hoists the load of the shadow value somewhere too high.
461 // This causes asan to report a non-existing bug on 453.povray.
462 // It sounds like an LLVM bug.
463 struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
465 AddressSanitizer &ASan;
470 ShadowMapping Mapping;
472 SmallVector<AllocaInst*, 16> AllocaVec;
473 SmallVector<Instruction*, 8> RetVec;
474 unsigned StackAlignment;
476 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
477 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
478 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
480 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
481 struct AllocaPoisonCall {
482 IntrinsicInst *InsBefore;
487 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
489 // Maps Value to an AllocaInst from which the Value is originated.
490 typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
491 AllocaForValueMapTy AllocaForValue;
493 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
494 : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
495 IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
496 Mapping(ASan.Mapping),
497 StackAlignment(1 << Mapping.Scale) {}
499 bool runOnFunction() {
500 if (!ClStack) return false;
501 // Collect alloca, ret, lifetime instructions etc.
502 for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
505 if (AllocaVec.empty()) return false;
507 initializeCallbacks(*F.getParent());
517 // Finds all static Alloca instructions and puts
518 // poisoned red zones around all of them.
519 // Then unpoison everything back before the function returns.
522 // ----------------------- Visitors.
523 /// \brief Collect all Ret instructions.
524 void visitReturnInst(ReturnInst &RI) {
525 RetVec.push_back(&RI);
528 /// \brief Collect Alloca instructions we want (and can) handle.
529 void visitAllocaInst(AllocaInst &AI) {
530 if (!isInterestingAlloca(AI)) return;
532 StackAlignment = std::max(StackAlignment, AI.getAlignment());
533 AllocaVec.push_back(&AI);
536 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
538 void visitIntrinsicInst(IntrinsicInst &II) {
539 if (!ClCheckLifetime) return;
540 Intrinsic::ID ID = II.getIntrinsicID();
541 if (ID != Intrinsic::lifetime_start &&
542 ID != Intrinsic::lifetime_end)
544 // Found lifetime intrinsic, add ASan instrumentation if necessary.
545 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
546 // If size argument is undefined, don't do anything.
547 if (Size->isMinusOne()) return;
548 // Check that size doesn't saturate uint64_t and can
549 // be stored in IntptrTy.
550 const uint64_t SizeValue = Size->getValue().getLimitedValue();
551 if (SizeValue == ~0ULL ||
552 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
554 // Find alloca instruction that corresponds to llvm.lifetime argument.
555 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
557 bool DoPoison = (ID == Intrinsic::lifetime_end);
558 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
559 AllocaPoisonCallVec.push_back(APC);
562 // ---------------------- Helpers.
563 void initializeCallbacks(Module &M);
565 // Check if we want (and can) handle this alloca.
566 bool isInterestingAlloca(AllocaInst &AI) const {
567 return (!AI.isArrayAllocation() && AI.isStaticAlloca() &&
568 AI.getAllocatedType()->isSized() &&
569 // alloca() may be called with 0 size, ignore it.
570 getAllocaSizeInBytes(&AI) > 0);
573 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
574 Type *Ty = AI->getAllocatedType();
575 uint64_t SizeInBytes = ASan.DL->getTypeAllocSize(Ty);
578 /// Finds alloca where the value comes from.
579 AllocaInst *findAllocaForValue(Value *V);
580 void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
581 Value *ShadowBase, bool DoPoison);
582 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
584 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
590 char AddressSanitizer::ID = 0;
591 INITIALIZE_PASS(AddressSanitizer, "asan",
592 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
594 FunctionPass *llvm::createAddressSanitizerFunctionPass() {
595 return new AddressSanitizer();
598 char AddressSanitizerModule::ID = 0;
599 INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
600 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
601 "ModulePass", false, false)
602 ModulePass *llvm::createAddressSanitizerModulePass() {
603 return new AddressSanitizerModule();
606 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
607 size_t Res = countTrailingZeros(TypeSize / 8);
608 assert(Res < kNumberOfAccessSizes);
612 // \brief Create a constant for Str so that we can pass it to the run-time lib.
613 static GlobalVariable *createPrivateGlobalForString(
614 Module &M, StringRef Str, bool AllowMerging) {
615 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
616 // We use private linkage for module-local strings. If they can be merged
617 // with another one, we set the unnamed_addr attribute.
619 new GlobalVariable(M, StrConst->getType(), true,
620 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
622 GV->setUnnamedAddr(true);
623 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
627 /// \brief Create a global describing a source location.
628 static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
629 LocationMetadata MD) {
630 Constant *LocData[] = {
631 createPrivateGlobalForString(M, MD.Filename, true),
632 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
633 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
635 auto LocStruct = ConstantStruct::getAnon(LocData);
636 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
637 GlobalValue::PrivateLinkage, LocStruct,
639 GV->setUnnamedAddr(true);
643 static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
644 return G->getName().find(kAsanGenPrefix) == 0;
647 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
649 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
650 if (Mapping.Offset == 0)
652 // (Shadow >> scale) | offset
653 if (Mapping.OrShadowOffset)
654 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
656 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
659 // Instrument memset/memmove/memcpy
660 void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
662 if (isa<MemTransferInst>(MI)) {
664 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
665 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
666 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
667 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
668 } else if (isa<MemSetInst>(MI)) {
671 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
672 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
673 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
675 MI->eraseFromParent();
678 // If I is an interesting memory access, return the PointerOperand
679 // and set IsWrite/Alignment. Otherwise return NULL.
680 static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
681 unsigned *Alignment) {
682 // Skip memory accesses inserted by another instrumentation.
683 if (I->getMetadata("nosanitize"))
685 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
686 if (!ClInstrumentReads) return nullptr;
688 *Alignment = LI->getAlignment();
689 return LI->getPointerOperand();
691 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
692 if (!ClInstrumentWrites) return nullptr;
694 *Alignment = SI->getAlignment();
695 return SI->getPointerOperand();
697 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
698 if (!ClInstrumentAtomics) return nullptr;
701 return RMW->getPointerOperand();
703 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
704 if (!ClInstrumentAtomics) return nullptr;
707 return XCHG->getPointerOperand();
712 static bool isPointerOperand(Value *V) {
713 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
716 // This is a rough heuristic; it may cause both false positives and
717 // false negatives. The proper implementation requires cooperation with
719 static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
720 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
721 if (!Cmp->isRelational())
723 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
724 if (BO->getOpcode() != Instruction::Sub)
729 if (!isPointerOperand(I->getOperand(0)) ||
730 !isPointerOperand(I->getOperand(1)))
735 bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
736 // If a global variable does not have dynamic initialization we don't
737 // have to instrument it. However, if a global does not have initializer
738 // at all, we assume it has dynamic initializer (in other TU).
739 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
743 AddressSanitizer::instrumentPointerComparisonOrSubtraction(Instruction *I) {
745 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
746 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
747 for (int i = 0; i < 2; i++) {
748 if (Param[i]->getType()->isPointerTy())
749 Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
751 IRB.CreateCall2(F, Param[0], Param[1]);
754 void AddressSanitizer::instrumentMop(Instruction *I, bool UseCalls) {
755 bool IsWrite = false;
756 unsigned Alignment = 0;
757 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &Alignment);
759 if (ClOpt && ClOptGlobals) {
760 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
761 // If initialization order checking is disabled, a simple access to a
762 // dynamically initialized global is always valid.
763 if (!ClInitializers || GlobalIsLinkerInitialized(G)) {
764 NumOptimizedAccessesToGlobalVar++;
768 ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr);
769 if (CE && CE->isGEPWithNoNotionalOverIndexing()) {
770 if (GlobalVariable *G = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
771 if (CE->getOperand(1)->isNullValue() && GlobalIsLinkerInitialized(G)) {
772 NumOptimizedAccessesToGlobalArray++;
779 Type *OrigPtrTy = Addr->getType();
780 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
782 assert(OrigTy->isSized());
783 uint32_t TypeSize = DL->getTypeStoreSizeInBits(OrigTy);
785 assert((TypeSize % 8) == 0);
788 NumInstrumentedWrites++;
790 NumInstrumentedReads++;
792 unsigned Granularity = 1 << Mapping.Scale;
793 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
794 // if the data is properly aligned.
795 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
797 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
798 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls);
799 // Instrument unusual size or unusual alignment.
800 // We can not do it with a single check, so we do 1-byte check for the first
801 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
802 // to report the actual access size.
804 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
805 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
807 IRB.CreateCall2(AsanMemoryAccessCallbackSized[IsWrite], AddrLong, Size);
809 Value *LastByte = IRB.CreateIntToPtr(
810 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
812 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false);
813 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false);
817 // Validate the result of Module::getOrInsertFunction called for an interface
818 // function of AddressSanitizer. If the instrumented module defines a function
819 // with the same name, their prototypes must match, otherwise
820 // getOrInsertFunction returns a bitcast.
821 static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
822 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
823 FuncOrBitcast->dump();
824 report_fatal_error("trying to redefine an AddressSanitizer "
825 "interface function");
828 Instruction *AddressSanitizer::generateCrashCode(
829 Instruction *InsertBefore, Value *Addr,
830 bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
831 IRBuilder<> IRB(InsertBefore);
832 CallInst *Call = SizeArgument
833 ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
834 : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
836 // We don't do Call->setDoesNotReturn() because the BB already has
837 // UnreachableInst at the end.
838 // This EmptyAsm is required to avoid callback merge.
839 IRB.CreateCall(EmptyAsm);
843 Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
846 size_t Granularity = 1 << Mapping.Scale;
847 // Addr & (Granularity - 1)
848 Value *LastAccessedByte = IRB.CreateAnd(
849 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
850 // (Addr & (Granularity - 1)) + size - 1
851 if (TypeSize / 8 > 1)
852 LastAccessedByte = IRB.CreateAdd(
853 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
854 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
855 LastAccessedByte = IRB.CreateIntCast(
856 LastAccessedByte, ShadowValue->getType(), false);
857 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
858 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
861 void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
862 Instruction *InsertBefore, Value *Addr,
863 uint32_t TypeSize, bool IsWrite,
864 Value *SizeArgument, bool UseCalls) {
865 IRBuilder<> IRB(InsertBefore);
866 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
867 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
870 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][AccessSizeIndex],
875 Type *ShadowTy = IntegerType::get(
876 *C, std::max(8U, TypeSize >> Mapping.Scale));
877 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
878 Value *ShadowPtr = memToShadow(AddrLong, IRB);
879 Value *CmpVal = Constant::getNullValue(ShadowTy);
880 Value *ShadowValue = IRB.CreateLoad(
881 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
883 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
884 size_t Granularity = 1 << Mapping.Scale;
885 TerminatorInst *CrashTerm = nullptr;
887 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
888 // We use branch weights for the slow path check, to indicate that the slow
889 // path is rarely taken. This seems to be the case for SPEC benchmarks.
890 TerminatorInst *CheckTerm =
891 SplitBlockAndInsertIfThen(Cmp, InsertBefore, false,
892 MDBuilder(*C).createBranchWeights(1, 100000));
893 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
894 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
895 IRB.SetInsertPoint(CheckTerm);
896 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
897 BasicBlock *CrashBlock =
898 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
899 CrashTerm = new UnreachableInst(*C, CrashBlock);
900 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
901 ReplaceInstWithInst(CheckTerm, NewTerm);
903 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
906 Instruction *Crash = generateCrashCode(
907 CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
908 Crash->setDebugLoc(OrigIns->getDebugLoc());
911 void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
912 GlobalValue *ModuleName) {
913 // Set up the arguments to our poison/unpoison functions.
914 IRBuilder<> IRB(GlobalInit.begin()->getFirstInsertionPt());
916 // Add a call to poison all external globals before the given function starts.
917 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
918 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
920 // Add calls to unpoison all globals before each return instruction.
921 for (auto &BB : GlobalInit.getBasicBlockList())
922 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
923 CallInst::Create(AsanUnpoisonGlobals, "", RI);
926 void AddressSanitizerModule::createInitializerPoisonCalls(
927 Module &M, GlobalValue *ModuleName) {
928 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
930 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
931 for (Use &OP : CA->operands()) {
932 if (isa<ConstantAggregateZero>(OP))
934 ConstantStruct *CS = cast<ConstantStruct>(OP);
936 // Must have a function or null ptr.
937 if (Function* F = dyn_cast<Function>(CS->getOperand(1))) {
938 if (F->getName() == kAsanModuleCtorName) continue;
939 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
940 // Don't instrument CTORs that will run before asan.module_ctor.
941 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
942 poisonOneInitializer(*F, ModuleName);
947 bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
948 Type *Ty = cast<PointerType>(G->getType())->getElementType();
949 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
951 if (GlobalsMD.get(G).IsBlacklisted) return false;
952 if (!Ty->isSized()) return false;
953 if (!G->hasInitializer()) return false;
954 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
955 // Touch only those globals that will not be defined in other modules.
956 // Don't handle ODR linkage types and COMDATs since other modules may be built
958 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
959 G->getLinkage() != GlobalVariable::PrivateLinkage &&
960 G->getLinkage() != GlobalVariable::InternalLinkage)
964 // Two problems with thread-locals:
965 // - The address of the main thread's copy can't be computed at link-time.
966 // - Need to poison all copies, not just the main thread's one.
967 if (G->isThreadLocal())
969 // For now, just ignore this Global if the alignment is large.
970 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
972 // Ignore all the globals with the names starting with "\01L_OBJC_".
973 // Many of those are put into the .cstring section. The linker compresses
974 // that section by removing the spare \0s after the string terminator, so
975 // our redzones get broken.
976 if ((G->getName().find("\01L_OBJC_") == 0) ||
977 (G->getName().find("\01l_OBJC_") == 0)) {
978 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G << "\n");
982 if (G->hasSection()) {
983 StringRef Section(G->getSection());
984 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
985 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
987 if (Section.startswith("__OBJC,") ||
988 Section.startswith("__DATA, __objc_")) {
989 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
992 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
993 // Constant CFString instances are compiled in the following way:
994 // -- the string buffer is emitted into
995 // __TEXT,__cstring,cstring_literals
996 // -- the constant NSConstantString structure referencing that buffer
997 // is placed into __DATA,__cfstring
998 // Therefore there's no point in placing redzones into __DATA,__cfstring.
999 // Moreover, it causes the linker to crash on OS X 10.7
1000 if (Section.startswith("__DATA,__cfstring")) {
1001 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1004 // The linker merges the contents of cstring_literals and removes the
1006 if (Section.startswith("__TEXT,__cstring,cstring_literals")) {
1007 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1011 // Callbacks put into the CRT initializer/terminator sections
1012 // should not be instrumented.
1013 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1014 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1015 if (Section.startswith(".CRT")) {
1016 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1020 // Globals from llvm.metadata aren't emitted, do not instrument them.
1021 if (Section == "llvm.metadata") return false;
1027 void AddressSanitizerModule::initializeCallbacks(Module &M) {
1028 IRBuilder<> IRB(*C);
1029 // Declare our poisoning and unpoisoning functions.
1030 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1031 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, NULL));
1032 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
1033 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1034 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
1035 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1036 // Declare functions that register/unregister globals.
1037 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1038 kAsanRegisterGlobalsName, IRB.getVoidTy(),
1039 IntptrTy, IntptrTy, NULL));
1040 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
1041 AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1042 kAsanUnregisterGlobalsName,
1043 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1044 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1045 AsanCovModuleInit = checkInterfaceFunction(M.getOrInsertFunction(
1046 kAsanCovModuleInitName,
1047 IRB.getVoidTy(), IntptrTy, NULL));
1048 AsanCovModuleInit->setLinkage(Function::ExternalLinkage);
1051 // This function replaces all global variables with new variables that have
1052 // trailing redzones. It also creates a function that poisons
1053 // redzones and inserts this function into llvm.global_ctors.
1054 bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
1057 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1059 for (auto &G : M.globals()) {
1060 if (ShouldInstrumentGlobal(&G))
1061 GlobalsToChange.push_back(&G);
1064 size_t n = GlobalsToChange.size();
1065 if (n == 0) return false;
1067 // A global is described by a structure
1070 // size_t size_with_redzone;
1071 // const char *name;
1072 // const char *module_name;
1073 // size_t has_dynamic_init;
1074 // void *source_location;
1075 // We initialize an array of such structures and pass it to a run-time call.
1076 StructType *GlobalStructTy =
1077 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
1078 IntptrTy, IntptrTy, NULL);
1079 SmallVector<Constant *, 16> Initializers(n);
1081 bool HasDynamicallyInitializedGlobals = false;
1083 // We shouldn't merge same module names, as this string serves as unique
1084 // module ID in runtime.
1085 GlobalVariable *ModuleName = createPrivateGlobalForString(
1086 M, M.getModuleIdentifier(), /*AllowMerging*/false);
1088 for (size_t i = 0; i < n; i++) {
1089 static const uint64_t kMaxGlobalRedzone = 1 << 18;
1090 GlobalVariable *G = GlobalsToChange[i];
1092 auto MD = GlobalsMD.get(G);
1093 // Create string holding the global name (use global name from metadata
1094 // if it's available, otherwise just write the name of global variable).
1095 GlobalVariable *Name = createPrivateGlobalForString(
1096 M, MD.Name.empty() ? G->getName() : MD.Name,
1097 /*AllowMerging*/ true);
1099 PointerType *PtrTy = cast<PointerType>(G->getType());
1100 Type *Ty = PtrTy->getElementType();
1101 uint64_t SizeInBytes = DL->getTypeAllocSize(Ty);
1102 uint64_t MinRZ = MinRedzoneSizeForGlobal();
1103 // MinRZ <= RZ <= kMaxGlobalRedzone
1104 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
1105 uint64_t RZ = std::max(MinRZ,
1106 std::min(kMaxGlobalRedzone,
1107 (SizeInBytes / MinRZ / 4) * MinRZ));
1108 uint64_t RightRedzoneSize = RZ;
1109 // Round up to MinRZ
1110 if (SizeInBytes % MinRZ)
1111 RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
1112 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
1113 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1115 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
1116 Constant *NewInitializer = ConstantStruct::get(
1117 NewTy, G->getInitializer(),
1118 Constant::getNullValue(RightRedZoneTy), NULL);
1120 // Create a new global variable with enough space for a redzone.
1121 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1122 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1123 Linkage = GlobalValue::InternalLinkage;
1124 GlobalVariable *NewGlobal = new GlobalVariable(
1125 M, NewTy, G->isConstant(), Linkage,
1126 NewInitializer, "", G, G->getThreadLocalMode());
1127 NewGlobal->copyAttributesFrom(G);
1128 NewGlobal->setAlignment(MinRZ);
1131 Indices2[0] = IRB.getInt32(0);
1132 Indices2[1] = IRB.getInt32(0);
1134 G->replaceAllUsesWith(
1135 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
1136 NewGlobal->takeName(G);
1137 G->eraseFromParent();
1139 Constant *SourceLoc;
1140 if (!MD.SourceLoc.empty()) {
1141 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1142 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1144 SourceLoc = ConstantInt::get(IntptrTy, 0);
1147 Initializers[i] = ConstantStruct::get(
1148 GlobalStructTy, ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
1149 ConstantInt::get(IntptrTy, SizeInBytes),
1150 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1151 ConstantExpr::getPointerCast(Name, IntptrTy),
1152 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
1153 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc, NULL);
1155 if (ClInitializers && MD.IsDynInit)
1156 HasDynamicallyInitializedGlobals = true;
1158 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
1161 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1162 GlobalVariable *AllGlobals = new GlobalVariable(
1163 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1164 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1166 // Create calls for poisoning before initializers run and unpoisoning after.
1167 if (HasDynamicallyInitializedGlobals)
1168 createInitializerPoisonCalls(M, ModuleName);
1169 IRB.CreateCall2(AsanRegisterGlobals,
1170 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1171 ConstantInt::get(IntptrTy, n));
1173 // We also need to unregister globals at the end, e.g. when a shared library
1175 Function *AsanDtorFunction = Function::Create(
1176 FunctionType::get(Type::getVoidTy(*C), false),
1177 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1178 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1179 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
1180 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
1181 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1182 ConstantInt::get(IntptrTy, n));
1183 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
1189 bool AddressSanitizerModule::runOnModule(Module &M) {
1190 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1193 DL = &DLP->getDataLayout();
1194 C = &(M.getContext());
1195 int LongSize = DL->getPointerSizeInBits();
1196 IntptrTy = Type::getIntNTy(*C, LongSize);
1197 Mapping = getShadowMapping(M, LongSize);
1198 initializeCallbacks(M);
1200 bool Changed = false;
1202 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1204 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1206 if (ClCoverage > 0) {
1207 Function *CovFunc = M.getFunction(kAsanCovName);
1208 int nCov = CovFunc ? CovFunc->getNumUses() : 0;
1209 IRB.CreateCall(AsanCovModuleInit, ConstantInt::get(IntptrTy, nCov));
1214 Changed |= InstrumentGlobals(IRB, M);
1219 void AddressSanitizer::initializeCallbacks(Module &M) {
1220 IRBuilder<> IRB(*C);
1221 // Create __asan_report* callbacks.
1222 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1223 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1224 AccessSizeIndex++) {
1225 // IsWrite and TypeSize are encoded in the function name.
1226 std::string Suffix =
1227 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
1228 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
1229 checkInterfaceFunction(
1230 M.getOrInsertFunction(kAsanReportErrorTemplate + Suffix,
1231 IRB.getVoidTy(), IntptrTy, NULL));
1232 AsanMemoryAccessCallback[AccessIsWrite][AccessSizeIndex] =
1233 checkInterfaceFunction(
1234 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + Suffix,
1235 IRB.getVoidTy(), IntptrTy, NULL));
1238 AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
1239 kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1240 AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
1241 kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1243 AsanMemoryAccessCallbackSized[0] = checkInterfaceFunction(
1244 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "loadN",
1245 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1246 AsanMemoryAccessCallbackSized[1] = checkInterfaceFunction(
1247 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "storeN",
1248 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1250 AsanMemmove = checkInterfaceFunction(M.getOrInsertFunction(
1251 ClMemoryAccessCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
1252 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, NULL));
1253 AsanMemcpy = checkInterfaceFunction(M.getOrInsertFunction(
1254 ClMemoryAccessCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
1255 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, NULL));
1256 AsanMemset = checkInterfaceFunction(M.getOrInsertFunction(
1257 ClMemoryAccessCallbackPrefix + "memset", IRB.getInt8PtrTy(),
1258 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, NULL));
1260 AsanHandleNoReturnFunc = checkInterfaceFunction(
1261 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
1262 AsanCovFunction = checkInterfaceFunction(M.getOrInsertFunction(
1263 kAsanCovName, IRB.getVoidTy(), NULL));
1264 AsanCovIndirCallFunction = checkInterfaceFunction(M.getOrInsertFunction(
1265 kAsanCovIndirCallName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1267 AsanPtrCmpFunction = checkInterfaceFunction(M.getOrInsertFunction(
1268 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1269 AsanPtrSubFunction = checkInterfaceFunction(M.getOrInsertFunction(
1270 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1271 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1272 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1273 StringRef(""), StringRef(""),
1274 /*hasSideEffects=*/true);
1278 bool AddressSanitizer::doInitialization(Module &M) {
1279 // Initialize the private fields. No one has accessed them before.
1280 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1282 report_fatal_error("data layout missing");
1283 DL = &DLP->getDataLayout();
1287 C = &(M.getContext());
1288 LongSize = DL->getPointerSizeInBits();
1289 IntptrTy = Type::getIntNTy(*C, LongSize);
1291 AsanCtorFunction = Function::Create(
1292 FunctionType::get(Type::getVoidTy(*C), false),
1293 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1294 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1295 // call __asan_init in the module ctor.
1296 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1297 AsanInitFunction = checkInterfaceFunction(
1298 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
1299 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1300 IRB.CreateCall(AsanInitFunction);
1302 Mapping = getShadowMapping(M, LongSize);
1304 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
1308 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1309 // For each NSObject descendant having a +load method, this method is invoked
1310 // by the ObjC runtime before any of the static constructors is called.
1311 // Therefore we need to instrument such methods with a call to __asan_init
1312 // at the beginning in order to initialize our runtime before any access to
1313 // the shadow memory.
1314 // We cannot just ignore these methods, because they may call other
1315 // instrumented functions.
1316 if (F.getName().find(" load]") != std::string::npos) {
1317 IRBuilder<> IRB(F.begin()->begin());
1318 IRB.CreateCall(AsanInitFunction);
1324 void AddressSanitizer::InjectCoverageAtBlock(Function &F, BasicBlock &BB) {
1325 BasicBlock::iterator IP = BB.getFirstInsertionPt(), BE = BB.end();
1326 // Skip static allocas at the top of the entry block so they don't become
1327 // dynamic when we split the block. If we used our optimized stack layout,
1328 // then there will only be one alloca and it will come first.
1329 for (; IP != BE; ++IP) {
1330 AllocaInst *AI = dyn_cast<AllocaInst>(IP);
1331 if (!AI || !AI->isStaticAlloca())
1335 DebugLoc EntryLoc = &BB == &F.getEntryBlock()
1336 ? IP->getDebugLoc().getFnDebugLoc(*C)
1337 : IP->getDebugLoc();
1338 IRBuilder<> IRB(IP);
1339 IRB.SetCurrentDebugLocation(EntryLoc);
1340 Type *Int8Ty = IRB.getInt8Ty();
1341 GlobalVariable *Guard = new GlobalVariable(
1342 *F.getParent(), Int8Ty, false, GlobalValue::PrivateLinkage,
1343 Constant::getNullValue(Int8Ty), "__asan_gen_cov_" + F.getName());
1344 LoadInst *Load = IRB.CreateLoad(Guard);
1345 Load->setAtomic(Monotonic);
1346 Load->setAlignment(1);
1347 Value *Cmp = IRB.CreateICmpEQ(Constant::getNullValue(Int8Ty), Load);
1348 Instruction *Ins = SplitBlockAndInsertIfThen(
1349 Cmp, IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
1350 IRB.SetInsertPoint(Ins);
1351 IRB.SetCurrentDebugLocation(EntryLoc);
1352 // __sanitizer_cov gets the PC of the instruction using GET_CALLER_PC.
1353 IRB.CreateCall(AsanCovFunction);
1354 StoreInst *Store = IRB.CreateStore(ConstantInt::get(Int8Ty, 1), Guard);
1355 Store->setAtomic(Monotonic);
1356 Store->setAlignment(1);
1359 // Poor man's coverage that works with ASan.
1360 // We create a Guard boolean variable with the same linkage
1361 // as the function and inject this code into the entry block (-asan-coverage=1)
1362 // or all blocks (-asan-coverage=2):
1364 // __sanitizer_cov();
1367 // The accesses to Guard are atomic. The rest of the logic is
1368 // in __sanitizer_cov (it's fine to call it more than once).
1370 // This coverage implementation provides very limited data:
1371 // it only tells if a given function (block) was ever executed.
1372 // No counters, no per-edge data.
1373 // But for many use cases this is what we need and the added slowdown
1374 // is negligible. This simple implementation will probably be obsoleted
1375 // by the upcoming Clang-based coverage implementation.
1376 // By having it here and now we hope to
1377 // a) get the functionality to users earlier and
1378 // b) collect usage statistics to help improve Clang coverage design.
1379 bool AddressSanitizer::InjectCoverage(Function &F,
1380 ArrayRef<BasicBlock *> AllBlocks,
1381 ArrayRef<Instruction*> IndirCalls) {
1382 if (!ClCoverage) return false;
1384 if (ClCoverage == 1 ||
1385 (unsigned)ClCoverageBlockThreshold < AllBlocks.size()) {
1386 InjectCoverageAtBlock(F, F.getEntryBlock());
1388 for (auto BB : AllBlocks)
1389 InjectCoverageAtBlock(F, *BB);
1391 InjectCoverageForIndirectCalls(F, IndirCalls);
1395 // On every indirect call we call a run-time function
1396 // __sanitizer_cov_indir_call* with two parameters:
1397 // - callee address,
1398 // - global cache array that contains kCacheSize pointers (zero-initialed).
1399 // The cache is used to speed up recording the caller-callee pairs.
1400 // The address of the caller is passed implicitly via caller PC.
1401 // kCacheSize is encoded in the name of the run-time function.
1402 void AddressSanitizer::InjectCoverageForIndirectCalls(
1403 Function &F, ArrayRef<Instruction *> IndirCalls) {
1404 if (ClCoverage < 4 || IndirCalls.empty()) return;
1405 const int kCacheSize = 16;
1406 const int kCacheAlignment = 64; // Align for better performance.
1407 Type *Ty = ArrayType::get(IntptrTy, kCacheSize);
1408 for (auto I : IndirCalls) {
1411 Value *Callee = CS.getCalledValue();
1412 if (dyn_cast<InlineAsm>(Callee)) continue;
1413 GlobalVariable *CalleeCache = new GlobalVariable(
1414 *F.getParent(), Ty, false, GlobalValue::PrivateLinkage,
1415 Constant::getNullValue(Ty), "__asan_gen_callee_cache");
1416 CalleeCache->setAlignment(kCacheAlignment);
1417 IRB.CreateCall2(AsanCovIndirCallFunction,
1418 IRB.CreatePointerCast(Callee, IntptrTy),
1419 IRB.CreatePointerCast(CalleeCache, IntptrTy));
1423 bool AddressSanitizer::runOnFunction(Function &F) {
1424 if (&F == AsanCtorFunction) return false;
1425 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
1426 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
1427 initializeCallbacks(*F.getParent());
1429 // If needed, insert __asan_init before checking for SanitizeAddress attr.
1430 maybeInsertAsanInitAtFunctionEntry(F);
1432 if (!F.hasFnAttribute(Attribute::SanitizeAddress))
1435 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1438 // We want to instrument every address only once per basic block (unless there
1439 // are calls between uses).
1440 SmallSet<Value*, 16> TempsToInstrument;
1441 SmallVector<Instruction*, 16> ToInstrument;
1442 SmallVector<Instruction*, 8> NoReturnCalls;
1443 SmallVector<BasicBlock*, 16> AllBlocks;
1444 SmallVector<Instruction*, 16> PointerComparisonsOrSubtracts;
1445 SmallVector<Instruction*, 8> IndirCalls;
1450 // Fill the set of memory operations to instrument.
1451 for (auto &BB : F) {
1452 AllBlocks.push_back(&BB);
1453 TempsToInstrument.clear();
1454 int NumInsnsPerBB = 0;
1455 for (auto &Inst : BB) {
1456 if (LooksLikeCodeInBug11395(&Inst)) return false;
1458 isInterestingMemoryAccess(&Inst, &IsWrite, &Alignment)) {
1459 if (ClOpt && ClOptSameTemp) {
1460 if (!TempsToInstrument.insert(Addr))
1461 continue; // We've seen this temp in the current BB.
1463 } else if (ClInvalidPointerPairs &&
1464 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1465 PointerComparisonsOrSubtracts.push_back(&Inst);
1467 } else if (isa<MemIntrinsic>(Inst)) {
1470 if (isa<AllocaInst>(Inst))
1474 // A call inside BB.
1475 TempsToInstrument.clear();
1476 if (CS.doesNotReturn())
1477 NoReturnCalls.push_back(CS.getInstruction());
1478 if (ClCoverage >= 4 && !CS.getCalledFunction())
1479 IndirCalls.push_back(&Inst);
1483 ToInstrument.push_back(&Inst);
1485 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1490 Function *UninstrumentedDuplicate = nullptr;
1491 bool LikelyToInstrument =
1492 !NoReturnCalls.empty() || !ToInstrument.empty() || (NumAllocas > 0);
1493 if (ClKeepUninstrumented && LikelyToInstrument) {
1494 ValueToValueMapTy VMap;
1495 UninstrumentedDuplicate = CloneFunction(&F, VMap, false);
1496 UninstrumentedDuplicate->removeFnAttr(Attribute::SanitizeAddress);
1497 UninstrumentedDuplicate->setName("NOASAN_" + F.getName());
1498 F.getParent()->getFunctionList().push_back(UninstrumentedDuplicate);
1501 bool UseCalls = false;
1502 if (ClInstrumentationWithCallsThreshold >= 0 &&
1503 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold)
1507 int NumInstrumented = 0;
1508 for (auto Inst : ToInstrument) {
1509 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1510 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
1511 if (isInterestingMemoryAccess(Inst, &IsWrite, &Alignment))
1512 instrumentMop(Inst, UseCalls);
1514 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
1519 FunctionStackPoisoner FSP(F, *this);
1520 bool ChangedStack = FSP.runOnFunction();
1522 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1523 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1524 for (auto CI : NoReturnCalls) {
1525 IRBuilder<> IRB(CI);
1526 IRB.CreateCall(AsanHandleNoReturnFunc);
1529 for (auto Inst : PointerComparisonsOrSubtracts) {
1530 instrumentPointerComparisonOrSubtraction(Inst);
1534 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
1536 if (InjectCoverage(F, AllBlocks, IndirCalls))
1539 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1541 if (ClKeepUninstrumented) {
1543 // No instrumentation is done, no need for the duplicate.
1544 if (UninstrumentedDuplicate)
1545 UninstrumentedDuplicate->eraseFromParent();
1547 // The function was instrumented. We must have the duplicate.
1548 assert(UninstrumentedDuplicate);
1549 UninstrumentedDuplicate->setSection("NOASAN");
1550 assert(!F.hasSection());
1551 F.setSection("ASAN");
1558 // Workaround for bug 11395: we don't want to instrument stack in functions
1559 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1560 // FIXME: remove once the bug 11395 is fixed.
1561 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1562 if (LongSize != 32) return false;
1563 CallInst *CI = dyn_cast<CallInst>(I);
1564 if (!CI || !CI->isInlineAsm()) return false;
1565 if (CI->getNumArgOperands() <= 5) return false;
1566 // We have inline assembly with quite a few arguments.
1570 void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1571 IRBuilder<> IRB(*C);
1572 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1573 std::string Suffix = itostr(i);
1574 AsanStackMallocFunc[i] = checkInterfaceFunction(
1575 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1576 IntptrTy, IntptrTy, NULL));
1577 AsanStackFreeFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
1578 kAsanStackFreeNameTemplate + Suffix, IRB.getVoidTy(), IntptrTy,
1579 IntptrTy, IntptrTy, NULL));
1581 AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1582 kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1583 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1584 kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1588 FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
1589 IRBuilder<> &IRB, Value *ShadowBase,
1591 size_t n = ShadowBytes.size();
1593 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1594 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1595 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1596 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1597 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1598 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1600 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
1601 if (ASan.DL->isLittleEndian())
1602 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1604 Val = (Val << 8) | ShadowBytes[i + j];
1607 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1608 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1609 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1610 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
1615 // Fake stack allocator (asan_fake_stack.h) has 11 size classes
1616 // for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1617 static int StackMallocSizeClass(uint64_t LocalStackSize) {
1618 assert(LocalStackSize <= kMaxStackMallocSize);
1619 uint64_t MaxSize = kMinStackMallocSize;
1620 for (int i = 0; ; i++, MaxSize *= 2)
1621 if (LocalStackSize <= MaxSize)
1623 llvm_unreachable("impossible LocalStackSize");
1626 // Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1627 // We can not use MemSet intrinsic because it may end up calling the actual
1628 // memset. Size is a multiple of 8.
1629 // Currently this generates 8-byte stores on x86_64; it may be better to
1630 // generate wider stores.
1631 void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1632 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1633 assert(!(Size % 8));
1634 assert(kAsanStackAfterReturnMagic == 0xf5);
1635 for (int i = 0; i < Size; i += 8) {
1636 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1637 IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
1638 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1642 static DebugLoc getFunctionEntryDebugLocation(Function &F) {
1643 for (const auto &Inst : F.getEntryBlock())
1644 if (!isa<AllocaInst>(Inst))
1645 return Inst.getDebugLoc();
1649 void FunctionStackPoisoner::poisonStack() {
1650 int StackMallocIdx = -1;
1651 DebugLoc EntryDebugLocation = getFunctionEntryDebugLocation(F);
1653 assert(AllocaVec.size() > 0);
1654 Instruction *InsBefore = AllocaVec[0];
1655 IRBuilder<> IRB(InsBefore);
1656 IRB.SetCurrentDebugLocation(EntryDebugLocation);
1658 SmallVector<ASanStackVariableDescription, 16> SVD;
1659 SVD.reserve(AllocaVec.size());
1660 for (AllocaInst *AI : AllocaVec) {
1661 ASanStackVariableDescription D = { AI->getName().data(),
1662 getAllocaSizeInBytes(AI),
1663 AI->getAlignment(), AI, 0};
1666 // Minimal header size (left redzone) is 4 pointers,
1667 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1668 size_t MinHeaderSize = ASan.LongSize / 2;
1669 ASanStackFrameLayout L;
1670 ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1671 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1672 uint64_t LocalStackSize = L.FrameSize;
1673 bool DoStackMalloc =
1674 ClUseAfterReturn && LocalStackSize <= kMaxStackMallocSize;
1676 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1677 AllocaInst *MyAlloca =
1678 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
1679 MyAlloca->setDebugLoc(EntryDebugLocation);
1680 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1681 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1682 MyAlloca->setAlignment(FrameAlignment);
1683 assert(MyAlloca->isStaticAlloca());
1684 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1685 Value *LocalStackBase = OrigStackBase;
1687 if (DoStackMalloc) {
1688 // LocalStackBase = OrigStackBase
1689 // if (__asan_option_detect_stack_use_after_return)
1690 // LocalStackBase = __asan_stack_malloc_N(LocalStackBase, OrigStackBase);
1691 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1692 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
1693 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1694 kAsanOptionDetectUAR, IRB.getInt32Ty());
1695 Value *Cmp = IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1696 Constant::getNullValue(IRB.getInt32Ty()));
1697 Instruction *Term = SplitBlockAndInsertIfThen(Cmp, InsBefore, false);
1698 BasicBlock *CmpBlock = cast<Instruction>(Cmp)->getParent();
1699 IRBuilder<> IRBIf(Term);
1700 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
1701 LocalStackBase = IRBIf.CreateCall2(
1702 AsanStackMallocFunc[StackMallocIdx],
1703 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1704 BasicBlock *SetBlock = cast<Instruction>(LocalStackBase)->getParent();
1705 IRB.SetInsertPoint(InsBefore);
1706 IRB.SetCurrentDebugLocation(EntryDebugLocation);
1707 PHINode *Phi = IRB.CreatePHI(IntptrTy, 2);
1708 Phi->addIncoming(OrigStackBase, CmpBlock);
1709 Phi->addIncoming(LocalStackBase, SetBlock);
1710 LocalStackBase = Phi;
1713 // Insert poison calls for lifetime intrinsics for alloca.
1714 bool HavePoisonedAllocas = false;
1715 for (const auto &APC : AllocaPoisonCallVec) {
1716 assert(APC.InsBefore);
1718 IRBuilder<> IRB(APC.InsBefore);
1719 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
1720 HavePoisonedAllocas |= APC.DoPoison;
1723 // Replace Alloca instructions with base+offset.
1724 for (const auto &Desc : SVD) {
1725 AllocaInst *AI = Desc.AI;
1726 Value *NewAllocaPtr = IRB.CreateIntToPtr(
1727 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
1729 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
1730 AI->replaceAllUsesWith(NewAllocaPtr);
1733 // The left-most redzone has enough space for at least 4 pointers.
1734 // Write the Magic value to redzone[0].
1735 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1736 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1738 // Write the frame description constant to redzone[1].
1739 Value *BasePlus1 = IRB.CreateIntToPtr(
1740 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
1742 GlobalVariable *StackDescriptionGlobal =
1743 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
1744 /*AllowMerging*/true);
1745 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1747 IRB.CreateStore(Description, BasePlus1);
1748 // Write the PC to redzone[2].
1749 Value *BasePlus2 = IRB.CreateIntToPtr(
1750 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
1751 2 * ASan.LongSize/8)),
1753 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
1755 // Poison the stack redzones at the entry.
1756 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1757 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
1759 // (Un)poison the stack before all ret instructions.
1760 for (auto Ret : RetVec) {
1761 IRBuilder<> IRBRet(Ret);
1762 // Mark the current frame as retired.
1763 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1765 if (DoStackMalloc) {
1766 assert(StackMallocIdx >= 0);
1767 // if LocalStackBase != OrigStackBase:
1768 // // In use-after-return mode, poison the whole stack frame.
1769 // if StackMallocIdx <= 4
1770 // // For small sizes inline the whole thing:
1771 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
1772 // **SavedFlagPtr(LocalStackBase) = 0
1774 // __asan_stack_free_N(LocalStackBase, OrigStackBase)
1776 // <This is not a fake stack; unpoison the redzones>
1777 Value *Cmp = IRBRet.CreateICmpNE(LocalStackBase, OrigStackBase);
1778 TerminatorInst *ThenTerm, *ElseTerm;
1779 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1781 IRBuilder<> IRBPoison(ThenTerm);
1782 if (StackMallocIdx <= 4) {
1783 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1784 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1785 ClassSize >> Mapping.Scale);
1786 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
1788 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1789 Value *SavedFlagPtr = IRBPoison.CreateLoad(
1790 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1791 IRBPoison.CreateStore(
1792 Constant::getNullValue(IRBPoison.getInt8Ty()),
1793 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1795 // For larger frames call __asan_stack_free_*.
1796 IRBPoison.CreateCall3(AsanStackFreeFunc[StackMallocIdx], LocalStackBase,
1797 ConstantInt::get(IntptrTy, LocalStackSize),
1801 IRBuilder<> IRBElse(ElseTerm);
1802 poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
1803 } else if (HavePoisonedAllocas) {
1804 // If we poisoned some allocas in llvm.lifetime analysis,
1805 // unpoison whole stack frame now.
1806 assert(LocalStackBase == OrigStackBase);
1807 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
1809 poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
1813 // We are done. Remove the old unused alloca instructions.
1814 for (auto AI : AllocaVec)
1815 AI->eraseFromParent();
1818 void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
1819 IRBuilder<> &IRB, bool DoPoison) {
1820 // For now just insert the call to ASan runtime.
1821 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1822 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1823 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1824 : AsanUnpoisonStackMemoryFunc,
1828 // Handling llvm.lifetime intrinsics for a given %alloca:
1829 // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1830 // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1831 // invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1832 // could be poisoned by previous llvm.lifetime.end instruction, as the
1833 // variable may go in and out of scope several times, e.g. in loops).
1834 // (3) if we poisoned at least one %alloca in a function,
1835 // unpoison the whole stack frame at function exit.
1837 AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1838 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1839 // We're intested only in allocas we can handle.
1840 return isInterestingAlloca(*AI) ? AI : nullptr;
1841 // See if we've already calculated (or started to calculate) alloca for a
1843 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1844 if (I != AllocaForValue.end())
1846 // Store 0 while we're calculating alloca for value V to avoid
1847 // infinite recursion if the value references itself.
1848 AllocaForValue[V] = nullptr;
1849 AllocaInst *Res = nullptr;
1850 if (CastInst *CI = dyn_cast<CastInst>(V))
1851 Res = findAllocaForValue(CI->getOperand(0));
1852 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1853 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1854 Value *IncValue = PN->getIncomingValue(i);
1855 // Allow self-referencing phi-nodes.
1856 if (IncValue == PN) continue;
1857 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1858 // AI for incoming values should exist and should all be equal.
1859 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
1865 AllocaForValue[V] = Res;