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/Dominators.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/IRBuilder.h"
33 #include "llvm/IR/InlineAsm.h"
34 #include "llvm/IR/InstVisitor.h"
35 #include "llvm/IR/IntrinsicInst.h"
36 #include "llvm/IR/LLVMContext.h"
37 #include "llvm/IR/MDBuilder.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/IR/Type.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/DataTypes.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/Endian.h"
44 #include "llvm/Support/SwapByteOrder.h"
45 #include "llvm/Transforms/Scalar.h"
46 #include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
47 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
48 #include "llvm/Transforms/Utils/Cloning.h"
49 #include "llvm/Transforms/Utils/Local.h"
50 #include "llvm/Transforms/Utils/ModuleUtils.h"
53 #include <system_error>
57 #define DEBUG_TYPE "asan"
59 static const uint64_t kDefaultShadowScale = 3;
60 static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
61 static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
62 static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
63 static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
64 static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
65 static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
66 static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 36;
67 static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
68 static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
70 static const size_t kMinStackMallocSize = 1 << 6; // 64B
71 static const size_t kMaxStackMallocSize = 1 << 16; // 64K
72 static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
73 static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
75 static const char *const kAsanModuleCtorName = "asan.module_ctor";
76 static const char *const kAsanModuleDtorName = "asan.module_dtor";
77 static const uint64_t kAsanCtorAndDtorPriority = 1;
78 static const char *const kAsanReportErrorTemplate = "__asan_report_";
79 static const char *const kAsanReportLoadN = "__asan_report_load_n";
80 static const char *const kAsanReportStoreN = "__asan_report_store_n";
81 static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
82 static const char *const kAsanUnregisterGlobalsName =
83 "__asan_unregister_globals";
84 static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
85 static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
86 static const char *const kAsanInitName = "__asan_init_v4";
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 kSanCovGenPrefix = "__sancov_gen_";
95 static const char *const kAsanPoisonStackMemoryName =
96 "__asan_poison_stack_memory";
97 static const char *const kAsanUnpoisonStackMemoryName =
98 "__asan_unpoison_stack_memory";
100 static const char *const kAsanOptionDetectUAR =
101 "__asan_option_detect_stack_use_after_return";
104 static const int kAsanStackAfterReturnMagic = 0xf5;
107 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
108 static const size_t kNumberOfAccessSizes = 5;
110 static const unsigned kAllocaRzSize = 32;
111 static const unsigned kAsanAllocaLeftMagic = 0xcacacacaU;
112 static const unsigned kAsanAllocaRightMagic = 0xcbcbcbcbU;
113 static const unsigned kAsanAllocaPartialVal1 = 0xcbcbcb00U;
114 static const unsigned kAsanAllocaPartialVal2 = 0x000000cbU;
116 // Command-line flags.
118 // This flag may need to be replaced with -f[no-]asan-reads.
119 static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
120 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
121 static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
122 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
123 static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
124 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
125 cl::Hidden, cl::init(true));
126 static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
127 cl::desc("use instrumentation with slow path for all accesses"),
128 cl::Hidden, cl::init(false));
129 // This flag limits the number of instructions to be instrumented
130 // in any given BB. Normally, this should be set to unlimited (INT_MAX),
131 // but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
133 static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
135 cl::desc("maximal number of instructions to instrument in any given BB"),
137 // This flag may need to be replaced with -f[no]asan-stack.
138 static cl::opt<bool> ClStack("asan-stack",
139 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
140 static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
141 cl::desc("Check return-after-free"), cl::Hidden, cl::init(true));
142 // This flag may need to be replaced with -f[no]asan-globals.
143 static cl::opt<bool> ClGlobals("asan-globals",
144 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
145 static cl::opt<bool> ClInitializers("asan-initialization-order",
146 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(true));
147 static cl::opt<bool> ClInvalidPointerPairs("asan-detect-invalid-pointer-pair",
148 cl::desc("Instrument <, <=, >, >=, - with pointer operands"),
149 cl::Hidden, cl::init(false));
150 static cl::opt<unsigned> ClRealignStack("asan-realign-stack",
151 cl::desc("Realign stack to the value of this flag (power of two)"),
152 cl::Hidden, cl::init(32));
153 static cl::opt<int> ClInstrumentationWithCallsThreshold(
154 "asan-instrumentation-with-call-threshold",
155 cl::desc("If the function being instrumented contains more than "
156 "this number of memory accesses, use callbacks instead of "
157 "inline checks (-1 means never use callbacks)."),
158 cl::Hidden, cl::init(7000));
159 static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
160 "asan-memory-access-callback-prefix",
161 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
162 cl::init("__asan_"));
163 static cl::opt<bool> ClInstrumentAllocas("asan-instrument-allocas",
164 cl::desc("instrument dynamic allocas"), cl::Hidden, cl::init(false));
166 // These flags allow to change the shadow mapping.
167 // The shadow mapping looks like
168 // Shadow = (Mem >> scale) + (1 << offset_log)
169 static cl::opt<int> ClMappingScale("asan-mapping-scale",
170 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
172 // Optimization flags. Not user visible, used mostly for testing
173 // and benchmarking the tool.
174 static cl::opt<bool> ClOpt("asan-opt",
175 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
176 static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
177 cl::desc("Instrument the same temp just once"), cl::Hidden,
179 static cl::opt<bool> ClOptGlobals("asan-opt-globals",
180 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
182 static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
183 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
184 cl::Hidden, cl::init(false));
187 static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
189 static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
190 cl::Hidden, cl::init(0));
191 static cl::opt<std::string> ClDebugFunc("asan-debug-func",
192 cl::Hidden, cl::desc("Debug func"));
193 static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
194 cl::Hidden, cl::init(-1));
195 static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
196 cl::Hidden, cl::init(-1));
198 STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
199 STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
200 STATISTIC(NumInstrumentedDynamicAllocas,
201 "Number of instrumented dynamic allocas");
202 STATISTIC(NumOptimizedAccessesToGlobalArray,
203 "Number of optimized accesses to global arrays");
204 STATISTIC(NumOptimizedAccessesToGlobalVar,
205 "Number of optimized accesses to global vars");
208 /// Frontend-provided metadata for source location.
209 struct LocationMetadata {
214 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
216 bool empty() const { return Filename.empty(); }
218 void parse(MDNode *MDN) {
219 assert(MDN->getNumOperands() == 3);
220 MDString *MDFilename = cast<MDString>(MDN->getOperand(0));
221 Filename = MDFilename->getString();
222 LineNo = cast<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
223 ColumnNo = cast<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
227 /// Frontend-provided metadata for global variables.
228 class GlobalsMetadata {
232 : SourceLoc(), Name(), IsDynInit(false),
233 IsBlacklisted(false) {}
234 LocationMetadata SourceLoc;
240 GlobalsMetadata() : inited_(false) {}
242 void init(Module& M) {
245 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
248 for (auto MDN : Globals->operands()) {
249 // Metadata node contains the global and the fields of "Entry".
250 assert(MDN->getNumOperands() == 5);
251 Value *V = MDN->getOperand(0);
252 // The optimizer may optimize away a global entirely.
255 GlobalVariable *GV = cast<GlobalVariable>(V);
256 // We can already have an entry for GV if it was merged with another
258 Entry &E = Entries[GV];
259 if (Value *Loc = MDN->getOperand(1))
260 E.SourceLoc.parse(cast<MDNode>(Loc));
261 if (Value *Name = MDN->getOperand(2)) {
262 MDString *MDName = cast<MDString>(Name);
263 E.Name = MDName->getString();
265 ConstantInt *IsDynInit = cast<ConstantInt>(MDN->getOperand(3));
266 E.IsDynInit |= IsDynInit->isOne();
267 ConstantInt *IsBlacklisted = cast<ConstantInt>(MDN->getOperand(4));
268 E.IsBlacklisted |= IsBlacklisted->isOne();
272 /// Returns metadata entry for a given global.
273 Entry get(GlobalVariable *G) const {
274 auto Pos = Entries.find(G);
275 return (Pos != Entries.end()) ? Pos->second : Entry();
280 DenseMap<GlobalVariable*, Entry> Entries;
283 /// This struct defines the shadow mapping using the rule:
284 /// shadow = (mem >> Scale) ADD-or-OR Offset.
285 struct ShadowMapping {
291 static ShadowMapping getShadowMapping(const Module &M, int LongSize) {
292 llvm::Triple TargetTriple(M.getTargetTriple());
293 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
294 bool IsIOS = TargetTriple.isiOS();
295 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
296 bool IsLinux = TargetTriple.isOSLinux();
297 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
298 TargetTriple.getArch() == llvm::Triple::ppc64le;
299 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
300 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
301 TargetTriple.getArch() == llvm::Triple::mipsel;
302 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
303 TargetTriple.getArch() == llvm::Triple::mips64el;
305 ShadowMapping Mapping;
307 if (LongSize == 32) {
311 Mapping.Offset = kMIPS32_ShadowOffset32;
313 Mapping.Offset = kFreeBSD_ShadowOffset32;
315 Mapping.Offset = kIOSShadowOffset32;
317 Mapping.Offset = kDefaultShadowOffset32;
318 } else { // LongSize == 64
320 Mapping.Offset = kPPC64_ShadowOffset64;
322 Mapping.Offset = kFreeBSD_ShadowOffset64;
323 else if (IsLinux && IsX86_64)
324 Mapping.Offset = kSmallX86_64ShadowOffset;
326 Mapping.Offset = kMIPS64_ShadowOffset64;
328 Mapping.Offset = kDefaultShadowOffset64;
331 Mapping.Scale = kDefaultShadowScale;
332 if (ClMappingScale) {
333 Mapping.Scale = ClMappingScale;
336 // OR-ing shadow offset if more efficient (at least on x86) if the offset
337 // is a power of two, but on ppc64 we have to use add since the shadow
338 // offset is not necessary 1/8-th of the address space.
339 Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
344 static size_t RedzoneSizeForScale(int MappingScale) {
345 // Redzone used for stack and globals is at least 32 bytes.
346 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
347 return std::max(32U, 1U << MappingScale);
350 /// AddressSanitizer: instrument the code in module to find memory bugs.
351 struct AddressSanitizer : public FunctionPass {
352 AddressSanitizer() : FunctionPass(ID) {
353 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
355 const char *getPassName() const override {
356 return "AddressSanitizerFunctionPass";
358 void getAnalysisUsage(AnalysisUsage &AU) const override {
359 AU.addRequired<DominatorTreeWrapperPass>();
361 void instrumentMop(Instruction *I, bool UseCalls);
362 void instrumentPointerComparisonOrSubtraction(Instruction *I);
363 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
364 Value *Addr, uint32_t TypeSize, bool IsWrite,
365 Value *SizeArgument, bool UseCalls);
366 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
367 Value *ShadowValue, uint32_t TypeSize);
368 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
369 bool IsWrite, size_t AccessSizeIndex,
370 Value *SizeArgument);
371 void instrumentMemIntrinsic(MemIntrinsic *MI);
372 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
373 bool runOnFunction(Function &F) override;
374 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
375 bool doInitialization(Module &M) override;
376 static char ID; // Pass identification, replacement for typeid
378 DominatorTree &getDominatorTree() const { return *DT; }
381 void initializeCallbacks(Module &M);
383 bool LooksLikeCodeInBug11395(Instruction *I);
384 bool GlobalIsLinkerInitialized(GlobalVariable *G);
387 const DataLayout *DL;
390 ShadowMapping Mapping;
392 Function *AsanCtorFunction;
393 Function *AsanInitFunction;
394 Function *AsanHandleNoReturnFunc;
395 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
396 // This array is indexed by AccessIsWrite and log2(AccessSize).
397 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
398 Function *AsanMemoryAccessCallback[2][kNumberOfAccessSizes];
399 // This array is indexed by AccessIsWrite.
400 Function *AsanErrorCallbackSized[2],
401 *AsanMemoryAccessCallbackSized[2];
402 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
404 GlobalsMetadata GlobalsMD;
406 friend struct FunctionStackPoisoner;
409 class AddressSanitizerModule : public ModulePass {
411 AddressSanitizerModule() : ModulePass(ID) {}
412 bool runOnModule(Module &M) override;
413 static char ID; // Pass identification, replacement for typeid
414 const char *getPassName() const override {
415 return "AddressSanitizerModule";
419 void initializeCallbacks(Module &M);
421 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
422 bool ShouldInstrumentGlobal(GlobalVariable *G);
423 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
424 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
425 size_t MinRedzoneSizeForGlobal() const {
426 return RedzoneSizeForScale(Mapping.Scale);
429 GlobalsMetadata GlobalsMD;
432 const DataLayout *DL;
433 ShadowMapping Mapping;
434 Function *AsanPoisonGlobals;
435 Function *AsanUnpoisonGlobals;
436 Function *AsanRegisterGlobals;
437 Function *AsanUnregisterGlobals;
440 // Stack poisoning does not play well with exception handling.
441 // When an exception is thrown, we essentially bypass the code
442 // that unpoisones the stack. This is why the run-time library has
443 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
444 // stack in the interceptor. This however does not work inside the
445 // actual function which catches the exception. Most likely because the
446 // compiler hoists the load of the shadow value somewhere too high.
447 // This causes asan to report a non-existing bug on 453.povray.
448 // It sounds like an LLVM bug.
449 struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
451 AddressSanitizer &ASan;
456 ShadowMapping Mapping;
458 SmallVector<AllocaInst*, 16> AllocaVec;
459 SmallVector<Instruction*, 8> RetVec;
460 unsigned StackAlignment;
462 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
463 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
464 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
466 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
467 struct AllocaPoisonCall {
468 IntrinsicInst *InsBefore;
473 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
475 // Stores left and right redzone shadow addresses for dynamic alloca
476 // and pointer to alloca instruction itself.
477 // LeftRzAddr is a shadow address for alloca left redzone.
478 // RightRzAddr is a shadow address for alloca right redzone.
479 struct DynamicAllocaCall {
484 explicit DynamicAllocaCall(AllocaInst *AI,
485 Value *LeftRzAddr = nullptr,
486 Value *RightRzAddr = nullptr)
487 : AI(AI), LeftRzAddr(LeftRzAddr), RightRzAddr(RightRzAddr), Poison(true)
490 SmallVector<DynamicAllocaCall, 1> DynamicAllocaVec;
492 // Maps Value to an AllocaInst from which the Value is originated.
493 typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
494 AllocaForValueMapTy AllocaForValue;
496 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
497 : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
498 IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
499 Mapping(ASan.Mapping),
500 StackAlignment(1 << Mapping.Scale) {}
502 bool runOnFunction() {
503 if (!ClStack) return false;
504 // Collect alloca, ret, lifetime instructions etc.
505 for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
508 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
510 initializeCallbacks(*F.getParent());
520 // Finds all Alloca instructions and puts
521 // poisoned red zones around all of them.
522 // Then unpoison everything back before the function returns.
525 // ----------------------- Visitors.
526 /// \brief Collect all Ret instructions.
527 void visitReturnInst(ReturnInst &RI) {
528 RetVec.push_back(&RI);
531 // Unpoison dynamic allocas redzones.
532 void unpoisonDynamicAlloca(DynamicAllocaCall &AllocaCall) {
533 if (!AllocaCall.Poison)
535 for (auto Ret : RetVec) {
536 IRBuilder<> IRBRet(Ret);
537 PointerType *Int32PtrTy = PointerType::getUnqual(IRBRet.getInt32Ty());
538 Value *Zero = Constant::getNullValue(IRBRet.getInt32Ty());
539 Value *PartialRzAddr = IRBRet.CreateSub(AllocaCall.RightRzAddr,
540 ConstantInt::get(IntptrTy, 4));
541 IRBRet.CreateStore(Zero, IRBRet.CreateIntToPtr(AllocaCall.LeftRzAddr,
543 IRBRet.CreateStore(Zero, IRBRet.CreateIntToPtr(PartialRzAddr,
545 IRBRet.CreateStore(Zero, IRBRet.CreateIntToPtr(AllocaCall.RightRzAddr,
550 // Right shift for BigEndian and left shift for LittleEndian.
551 Value *shiftAllocaMagic(Value *Val, IRBuilder<> &IRB, Value *Shift) {
552 return ASan.DL->isLittleEndian() ? IRB.CreateShl(Val, Shift)
553 : IRB.CreateLShr(Val, Shift);
556 // Compute PartialRzMagic for dynamic alloca call. Since we don't know the
557 // size of requested memory until runtime, we should compute it dynamically.
558 // If PartialSize is 0, PartialRzMagic would contain kAsanAllocaRightMagic,
559 // otherwise it would contain the value that we will use to poison the
560 // partial redzone for alloca call.
561 Value *computePartialRzMagic(Value *PartialSize, IRBuilder<> &IRB);
563 // Deploy and poison redzones around dynamic alloca call. To do this, we
564 // should replace this call with another one with changed parameters and
565 // replace all its uses with new address, so
566 // addr = alloca type, old_size, align
568 // new_size = (old_size + additional_size) * sizeof(type)
569 // tmp = alloca i8, new_size, max(align, 32)
570 // addr = tmp + 32 (first 32 bytes are for the left redzone).
571 // Additional_size is added to make new memory allocation contain not only
572 // requested memory, but also left, partial and right redzones.
573 // After that, we should poison redzones:
574 // (1) Left redzone with kAsanAllocaLeftMagic.
575 // (2) Partial redzone with the value, computed in runtime by
576 // computePartialRzMagic function.
577 // (3) Right redzone with kAsanAllocaRightMagic.
578 void handleDynamicAllocaCall(DynamicAllocaCall &AllocaCall);
580 /// \brief Collect Alloca instructions we want (and can) handle.
581 void visitAllocaInst(AllocaInst &AI) {
582 if (!isInterestingAlloca(AI)) return;
584 StackAlignment = std::max(StackAlignment, AI.getAlignment());
585 if (isDynamicAlloca(AI))
586 DynamicAllocaVec.push_back(DynamicAllocaCall(&AI));
588 AllocaVec.push_back(&AI);
591 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
593 void visitIntrinsicInst(IntrinsicInst &II) {
594 if (!ClCheckLifetime) return;
595 Intrinsic::ID ID = II.getIntrinsicID();
596 if (ID != Intrinsic::lifetime_start &&
597 ID != Intrinsic::lifetime_end)
599 // Found lifetime intrinsic, add ASan instrumentation if necessary.
600 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
601 // If size argument is undefined, don't do anything.
602 if (Size->isMinusOne()) return;
603 // Check that size doesn't saturate uint64_t and can
604 // be stored in IntptrTy.
605 const uint64_t SizeValue = Size->getValue().getLimitedValue();
606 if (SizeValue == ~0ULL ||
607 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
609 // Find alloca instruction that corresponds to llvm.lifetime argument.
610 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
612 bool DoPoison = (ID == Intrinsic::lifetime_end);
613 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
614 AllocaPoisonCallVec.push_back(APC);
617 // ---------------------- Helpers.
618 void initializeCallbacks(Module &M);
620 bool doesDominateAllExits(const Instruction *I) const {
621 for (auto Ret : RetVec) {
622 if (!ASan.getDominatorTree().dominates(I, Ret))
628 bool isDynamicAlloca(AllocaInst &AI) const {
629 return AI.isArrayAllocation() || !AI.isStaticAlloca();
632 // Check if we want (and can) handle this alloca.
633 bool isInterestingAlloca(AllocaInst &AI) const {
634 return (AI.getAllocatedType()->isSized() &&
635 // alloca() may be called with 0 size, ignore it.
636 getAllocaSizeInBytes(&AI) > 0);
639 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
640 Type *Ty = AI->getAllocatedType();
641 uint64_t SizeInBytes = ASan.DL->getTypeAllocSize(Ty);
644 /// Finds alloca where the value comes from.
645 AllocaInst *findAllocaForValue(Value *V);
646 void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
647 Value *ShadowBase, bool DoPoison);
648 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
650 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
656 char AddressSanitizer::ID = 0;
657 INITIALIZE_PASS_BEGIN(AddressSanitizer, "asan",
658 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
660 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
661 INITIALIZE_PASS_END(AddressSanitizer, "asan",
662 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
664 FunctionPass *llvm::createAddressSanitizerFunctionPass() {
665 return new AddressSanitizer();
668 char AddressSanitizerModule::ID = 0;
669 INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
670 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
671 "ModulePass", false, false)
672 ModulePass *llvm::createAddressSanitizerModulePass() {
673 return new AddressSanitizerModule();
676 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
677 size_t Res = countTrailingZeros(TypeSize / 8);
678 assert(Res < kNumberOfAccessSizes);
682 // \brief Create a constant for Str so that we can pass it to the run-time lib.
683 static GlobalVariable *createPrivateGlobalForString(
684 Module &M, StringRef Str, bool AllowMerging) {
685 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
686 // We use private linkage for module-local strings. If they can be merged
687 // with another one, we set the unnamed_addr attribute.
689 new GlobalVariable(M, StrConst->getType(), true,
690 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
692 GV->setUnnamedAddr(true);
693 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
697 /// \brief Create a global describing a source location.
698 static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
699 LocationMetadata MD) {
700 Constant *LocData[] = {
701 createPrivateGlobalForString(M, MD.Filename, true),
702 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
703 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
705 auto LocStruct = ConstantStruct::getAnon(LocData);
706 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
707 GlobalValue::PrivateLinkage, LocStruct,
709 GV->setUnnamedAddr(true);
713 static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
714 return G->getName().find(kAsanGenPrefix) == 0 ||
715 G->getName().find(kSanCovGenPrefix) == 0;
718 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
720 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
721 if (Mapping.Offset == 0)
723 // (Shadow >> scale) | offset
724 if (Mapping.OrShadowOffset)
725 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
727 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
730 // Instrument memset/memmove/memcpy
731 void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
733 if (isa<MemTransferInst>(MI)) {
735 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
736 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
737 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
738 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
739 } else if (isa<MemSetInst>(MI)) {
742 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
743 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
744 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
746 MI->eraseFromParent();
749 // If I is an interesting memory access, return the PointerOperand
750 // and set IsWrite/Alignment. Otherwise return nullptr.
751 static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
752 unsigned *Alignment) {
753 // Skip memory accesses inserted by another instrumentation.
754 if (I->getMetadata("nosanitize"))
756 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
757 if (!ClInstrumentReads) return nullptr;
759 *Alignment = LI->getAlignment();
760 return LI->getPointerOperand();
762 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
763 if (!ClInstrumentWrites) return nullptr;
765 *Alignment = SI->getAlignment();
766 return SI->getPointerOperand();
768 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
769 if (!ClInstrumentAtomics) return nullptr;
772 return RMW->getPointerOperand();
774 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
775 if (!ClInstrumentAtomics) return nullptr;
778 return XCHG->getPointerOperand();
783 static bool isPointerOperand(Value *V) {
784 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
787 // This is a rough heuristic; it may cause both false positives and
788 // false negatives. The proper implementation requires cooperation with
790 static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
791 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
792 if (!Cmp->isRelational())
794 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
795 if (BO->getOpcode() != Instruction::Sub)
800 if (!isPointerOperand(I->getOperand(0)) ||
801 !isPointerOperand(I->getOperand(1)))
806 bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
807 // If a global variable does not have dynamic initialization we don't
808 // have to instrument it. However, if a global does not have initializer
809 // at all, we assume it has dynamic initializer (in other TU).
810 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
814 AddressSanitizer::instrumentPointerComparisonOrSubtraction(Instruction *I) {
816 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
817 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
818 for (int i = 0; i < 2; i++) {
819 if (Param[i]->getType()->isPointerTy())
820 Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
822 IRB.CreateCall2(F, Param[0], Param[1]);
825 void AddressSanitizer::instrumentMop(Instruction *I, bool UseCalls) {
826 bool IsWrite = false;
827 unsigned Alignment = 0;
828 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &Alignment);
830 if (ClOpt && ClOptGlobals) {
831 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
832 // If initialization order checking is disabled, a simple access to a
833 // dynamically initialized global is always valid.
834 if (!ClInitializers || GlobalIsLinkerInitialized(G)) {
835 NumOptimizedAccessesToGlobalVar++;
839 ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr);
840 if (CE && CE->isGEPWithNoNotionalOverIndexing()) {
841 if (GlobalVariable *G = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
842 if (CE->getOperand(1)->isNullValue() && GlobalIsLinkerInitialized(G)) {
843 NumOptimizedAccessesToGlobalArray++;
850 Type *OrigPtrTy = Addr->getType();
851 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
853 assert(OrigTy->isSized());
854 uint32_t TypeSize = DL->getTypeStoreSizeInBits(OrigTy);
856 assert((TypeSize % 8) == 0);
859 NumInstrumentedWrites++;
861 NumInstrumentedReads++;
863 unsigned Granularity = 1 << Mapping.Scale;
864 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
865 // if the data is properly aligned.
866 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
868 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
869 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls);
870 // Instrument unusual size or unusual alignment.
871 // We can not do it with a single check, so we do 1-byte check for the first
872 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
873 // to report the actual access size.
875 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
876 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
878 IRB.CreateCall2(AsanMemoryAccessCallbackSized[IsWrite], AddrLong, Size);
880 Value *LastByte = IRB.CreateIntToPtr(
881 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
883 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false);
884 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false);
888 // Validate the result of Module::getOrInsertFunction called for an interface
889 // function of AddressSanitizer. If the instrumented module defines a function
890 // with the same name, their prototypes must match, otherwise
891 // getOrInsertFunction returns a bitcast.
892 static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
893 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
894 FuncOrBitcast->dump();
895 report_fatal_error("trying to redefine an AddressSanitizer "
896 "interface function");
899 Instruction *AddressSanitizer::generateCrashCode(
900 Instruction *InsertBefore, Value *Addr,
901 bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
902 IRBuilder<> IRB(InsertBefore);
903 CallInst *Call = SizeArgument
904 ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
905 : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
907 // We don't do Call->setDoesNotReturn() because the BB already has
908 // UnreachableInst at the end.
909 // This EmptyAsm is required to avoid callback merge.
910 IRB.CreateCall(EmptyAsm);
914 Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
917 size_t Granularity = 1 << Mapping.Scale;
918 // Addr & (Granularity - 1)
919 Value *LastAccessedByte = IRB.CreateAnd(
920 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
921 // (Addr & (Granularity - 1)) + size - 1
922 if (TypeSize / 8 > 1)
923 LastAccessedByte = IRB.CreateAdd(
924 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
925 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
926 LastAccessedByte = IRB.CreateIntCast(
927 LastAccessedByte, ShadowValue->getType(), false);
928 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
929 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
932 void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
933 Instruction *InsertBefore, Value *Addr,
934 uint32_t TypeSize, bool IsWrite,
935 Value *SizeArgument, bool UseCalls) {
936 IRBuilder<> IRB(InsertBefore);
937 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
938 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
941 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][AccessSizeIndex],
946 Type *ShadowTy = IntegerType::get(
947 *C, std::max(8U, TypeSize >> Mapping.Scale));
948 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
949 Value *ShadowPtr = memToShadow(AddrLong, IRB);
950 Value *CmpVal = Constant::getNullValue(ShadowTy);
951 Value *ShadowValue = IRB.CreateLoad(
952 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
954 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
955 size_t Granularity = 1 << Mapping.Scale;
956 TerminatorInst *CrashTerm = nullptr;
958 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
959 // We use branch weights for the slow path check, to indicate that the slow
960 // path is rarely taken. This seems to be the case for SPEC benchmarks.
961 TerminatorInst *CheckTerm =
962 SplitBlockAndInsertIfThen(Cmp, InsertBefore, false,
963 MDBuilder(*C).createBranchWeights(1, 100000));
964 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
965 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
966 IRB.SetInsertPoint(CheckTerm);
967 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
968 BasicBlock *CrashBlock =
969 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
970 CrashTerm = new UnreachableInst(*C, CrashBlock);
971 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
972 ReplaceInstWithInst(CheckTerm, NewTerm);
974 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
977 Instruction *Crash = generateCrashCode(
978 CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
979 Crash->setDebugLoc(OrigIns->getDebugLoc());
982 void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
983 GlobalValue *ModuleName) {
984 // Set up the arguments to our poison/unpoison functions.
985 IRBuilder<> IRB(GlobalInit.begin()->getFirstInsertionPt());
987 // Add a call to poison all external globals before the given function starts.
988 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
989 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
991 // Add calls to unpoison all globals before each return instruction.
992 for (auto &BB : GlobalInit.getBasicBlockList())
993 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
994 CallInst::Create(AsanUnpoisonGlobals, "", RI);
997 void AddressSanitizerModule::createInitializerPoisonCalls(
998 Module &M, GlobalValue *ModuleName) {
999 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1001 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1002 for (Use &OP : CA->operands()) {
1003 if (isa<ConstantAggregateZero>(OP))
1005 ConstantStruct *CS = cast<ConstantStruct>(OP);
1007 // Must have a function or null ptr.
1008 if (Function* F = dyn_cast<Function>(CS->getOperand(1))) {
1009 if (F->getName() == kAsanModuleCtorName) continue;
1010 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1011 // Don't instrument CTORs that will run before asan.module_ctor.
1012 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1013 poisonOneInitializer(*F, ModuleName);
1018 bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
1019 Type *Ty = cast<PointerType>(G->getType())->getElementType();
1020 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
1022 if (GlobalsMD.get(G).IsBlacklisted) return false;
1023 if (!Ty->isSized()) return false;
1024 if (!G->hasInitializer()) return false;
1025 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
1026 // Touch only those globals that will not be defined in other modules.
1027 // Don't handle ODR linkage types and COMDATs since other modules may be built
1029 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1030 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1031 G->getLinkage() != GlobalVariable::InternalLinkage)
1035 // Two problems with thread-locals:
1036 // - The address of the main thread's copy can't be computed at link-time.
1037 // - Need to poison all copies, not just the main thread's one.
1038 if (G->isThreadLocal())
1040 // For now, just ignore this Global if the alignment is large.
1041 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
1043 if (G->hasSection()) {
1044 StringRef Section(G->getSection());
1045 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1046 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1048 if (Section.startswith("__OBJC,") ||
1049 Section.startswith("__DATA, __objc_")) {
1050 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1053 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1054 // Constant CFString instances are compiled in the following way:
1055 // -- the string buffer is emitted into
1056 // __TEXT,__cstring,cstring_literals
1057 // -- the constant NSConstantString structure referencing that buffer
1058 // is placed into __DATA,__cfstring
1059 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1060 // Moreover, it causes the linker to crash on OS X 10.7
1061 if (Section.startswith("__DATA,__cfstring")) {
1062 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1065 // The linker merges the contents of cstring_literals and removes the
1067 if (Section.startswith("__TEXT,__cstring,cstring_literals")) {
1068 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1071 if (Section.startswith("__TEXT,__objc_methname,cstring_literals")) {
1072 DEBUG(dbgs() << "Ignoring objc_methname cstring global: " << *G << "\n");
1077 // Callbacks put into the CRT initializer/terminator sections
1078 // should not be instrumented.
1079 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1080 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1081 if (Section.startswith(".CRT")) {
1082 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1086 // Globals from llvm.metadata aren't emitted, do not instrument them.
1087 if (Section == "llvm.metadata") return false;
1093 void AddressSanitizerModule::initializeCallbacks(Module &M) {
1094 IRBuilder<> IRB(*C);
1095 // Declare our poisoning and unpoisoning functions.
1096 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1097 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
1098 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
1099 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1100 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
1101 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1102 // Declare functions that register/unregister globals.
1103 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1104 kAsanRegisterGlobalsName, IRB.getVoidTy(),
1105 IntptrTy, IntptrTy, nullptr));
1106 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
1107 AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1108 kAsanUnregisterGlobalsName,
1109 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1110 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1113 // This function replaces all global variables with new variables that have
1114 // trailing redzones. It also creates a function that poisons
1115 // redzones and inserts this function into llvm.global_ctors.
1116 bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
1119 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1121 for (auto &G : M.globals()) {
1122 if (ShouldInstrumentGlobal(&G))
1123 GlobalsToChange.push_back(&G);
1126 size_t n = GlobalsToChange.size();
1127 if (n == 0) return false;
1129 // A global is described by a structure
1132 // size_t size_with_redzone;
1133 // const char *name;
1134 // const char *module_name;
1135 // size_t has_dynamic_init;
1136 // void *source_location;
1137 // We initialize an array of such structures and pass it to a run-time call.
1138 StructType *GlobalStructTy =
1139 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
1140 IntptrTy, IntptrTy, nullptr);
1141 SmallVector<Constant *, 16> Initializers(n);
1143 bool HasDynamicallyInitializedGlobals = false;
1145 // We shouldn't merge same module names, as this string serves as unique
1146 // module ID in runtime.
1147 GlobalVariable *ModuleName = createPrivateGlobalForString(
1148 M, M.getModuleIdentifier(), /*AllowMerging*/false);
1150 for (size_t i = 0; i < n; i++) {
1151 static const uint64_t kMaxGlobalRedzone = 1 << 18;
1152 GlobalVariable *G = GlobalsToChange[i];
1154 auto MD = GlobalsMD.get(G);
1155 // Create string holding the global name (use global name from metadata
1156 // if it's available, otherwise just write the name of global variable).
1157 GlobalVariable *Name = createPrivateGlobalForString(
1158 M, MD.Name.empty() ? G->getName() : MD.Name,
1159 /*AllowMerging*/ true);
1161 PointerType *PtrTy = cast<PointerType>(G->getType());
1162 Type *Ty = PtrTy->getElementType();
1163 uint64_t SizeInBytes = DL->getTypeAllocSize(Ty);
1164 uint64_t MinRZ = MinRedzoneSizeForGlobal();
1165 // MinRZ <= RZ <= kMaxGlobalRedzone
1166 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
1167 uint64_t RZ = std::max(MinRZ,
1168 std::min(kMaxGlobalRedzone,
1169 (SizeInBytes / MinRZ / 4) * MinRZ));
1170 uint64_t RightRedzoneSize = RZ;
1171 // Round up to MinRZ
1172 if (SizeInBytes % MinRZ)
1173 RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
1174 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
1175 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1177 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
1178 Constant *NewInitializer = ConstantStruct::get(
1179 NewTy, G->getInitializer(),
1180 Constant::getNullValue(RightRedZoneTy), nullptr);
1182 // Create a new global variable with enough space for a redzone.
1183 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1184 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1185 Linkage = GlobalValue::InternalLinkage;
1186 GlobalVariable *NewGlobal = new GlobalVariable(
1187 M, NewTy, G->isConstant(), Linkage,
1188 NewInitializer, "", G, G->getThreadLocalMode());
1189 NewGlobal->copyAttributesFrom(G);
1190 NewGlobal->setAlignment(MinRZ);
1193 Indices2[0] = IRB.getInt32(0);
1194 Indices2[1] = IRB.getInt32(0);
1196 G->replaceAllUsesWith(
1197 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
1198 NewGlobal->takeName(G);
1199 G->eraseFromParent();
1201 Constant *SourceLoc;
1202 if (!MD.SourceLoc.empty()) {
1203 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1204 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1206 SourceLoc = ConstantInt::get(IntptrTy, 0);
1209 Initializers[i] = ConstantStruct::get(
1210 GlobalStructTy, ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
1211 ConstantInt::get(IntptrTy, SizeInBytes),
1212 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1213 ConstantExpr::getPointerCast(Name, IntptrTy),
1214 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
1215 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc, nullptr);
1217 if (ClInitializers && MD.IsDynInit)
1218 HasDynamicallyInitializedGlobals = true;
1220 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
1223 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1224 GlobalVariable *AllGlobals = new GlobalVariable(
1225 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1226 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1228 // Create calls for poisoning before initializers run and unpoisoning after.
1229 if (HasDynamicallyInitializedGlobals)
1230 createInitializerPoisonCalls(M, ModuleName);
1231 IRB.CreateCall2(AsanRegisterGlobals,
1232 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1233 ConstantInt::get(IntptrTy, n));
1235 // We also need to unregister globals at the end, e.g. when a shared library
1237 Function *AsanDtorFunction = Function::Create(
1238 FunctionType::get(Type::getVoidTy(*C), false),
1239 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1240 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1241 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
1242 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
1243 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1244 ConstantInt::get(IntptrTy, n));
1245 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
1251 bool AddressSanitizerModule::runOnModule(Module &M) {
1252 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1255 DL = &DLP->getDataLayout();
1256 C = &(M.getContext());
1257 int LongSize = DL->getPointerSizeInBits();
1258 IntptrTy = Type::getIntNTy(*C, LongSize);
1259 Mapping = getShadowMapping(M, LongSize);
1260 initializeCallbacks(M);
1262 bool Changed = false;
1264 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1266 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1269 Changed |= InstrumentGlobals(IRB, M);
1274 void AddressSanitizer::initializeCallbacks(Module &M) {
1275 IRBuilder<> IRB(*C);
1276 // Create __asan_report* callbacks.
1277 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1278 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1279 AccessSizeIndex++) {
1280 // IsWrite and TypeSize are encoded in the function name.
1281 std::string Suffix =
1282 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
1283 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
1284 checkInterfaceFunction(
1285 M.getOrInsertFunction(kAsanReportErrorTemplate + Suffix,
1286 IRB.getVoidTy(), IntptrTy, nullptr));
1287 AsanMemoryAccessCallback[AccessIsWrite][AccessSizeIndex] =
1288 checkInterfaceFunction(
1289 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + Suffix,
1290 IRB.getVoidTy(), IntptrTy, nullptr));
1293 AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
1294 kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1295 AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
1296 kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1298 AsanMemoryAccessCallbackSized[0] = checkInterfaceFunction(
1299 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "loadN",
1300 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1301 AsanMemoryAccessCallbackSized[1] = checkInterfaceFunction(
1302 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "storeN",
1303 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1305 AsanMemmove = checkInterfaceFunction(M.getOrInsertFunction(
1306 ClMemoryAccessCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
1307 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
1308 AsanMemcpy = checkInterfaceFunction(M.getOrInsertFunction(
1309 ClMemoryAccessCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
1310 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
1311 AsanMemset = checkInterfaceFunction(M.getOrInsertFunction(
1312 ClMemoryAccessCallbackPrefix + "memset", IRB.getInt8PtrTy(),
1313 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
1315 AsanHandleNoReturnFunc = checkInterfaceFunction(
1316 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
1318 AsanPtrCmpFunction = checkInterfaceFunction(M.getOrInsertFunction(
1319 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1320 AsanPtrSubFunction = checkInterfaceFunction(M.getOrInsertFunction(
1321 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1322 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1323 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1324 StringRef(""), StringRef(""),
1325 /*hasSideEffects=*/true);
1329 bool AddressSanitizer::doInitialization(Module &M) {
1330 // Initialize the private fields. No one has accessed them before.
1331 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1333 report_fatal_error("data layout missing");
1334 DL = &DLP->getDataLayout();
1338 C = &(M.getContext());
1339 LongSize = DL->getPointerSizeInBits();
1340 IntptrTy = Type::getIntNTy(*C, LongSize);
1342 AsanCtorFunction = Function::Create(
1343 FunctionType::get(Type::getVoidTy(*C), false),
1344 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1345 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1346 // call __asan_init in the module ctor.
1347 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1348 AsanInitFunction = checkInterfaceFunction(
1349 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), nullptr));
1350 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1351 IRB.CreateCall(AsanInitFunction);
1353 Mapping = getShadowMapping(M, LongSize);
1355 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
1359 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1360 // For each NSObject descendant having a +load method, this method is invoked
1361 // by the ObjC runtime before any of the static constructors is called.
1362 // Therefore we need to instrument such methods with a call to __asan_init
1363 // at the beginning in order to initialize our runtime before any access to
1364 // the shadow memory.
1365 // We cannot just ignore these methods, because they may call other
1366 // instrumented functions.
1367 if (F.getName().find(" load]") != std::string::npos) {
1368 IRBuilder<> IRB(F.begin()->begin());
1369 IRB.CreateCall(AsanInitFunction);
1375 bool AddressSanitizer::runOnFunction(Function &F) {
1376 if (&F == AsanCtorFunction) return false;
1377 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
1378 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
1379 initializeCallbacks(*F.getParent());
1381 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1383 // If needed, insert __asan_init before checking for SanitizeAddress attr.
1384 maybeInsertAsanInitAtFunctionEntry(F);
1386 if (!F.hasFnAttribute(Attribute::SanitizeAddress))
1389 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1392 // We want to instrument every address only once per basic block (unless there
1393 // are calls between uses).
1394 SmallSet<Value*, 16> TempsToInstrument;
1395 SmallVector<Instruction*, 16> ToInstrument;
1396 SmallVector<Instruction*, 8> NoReturnCalls;
1397 SmallVector<BasicBlock*, 16> AllBlocks;
1398 SmallVector<Instruction*, 16> PointerComparisonsOrSubtracts;
1403 // Fill the set of memory operations to instrument.
1404 for (auto &BB : F) {
1405 AllBlocks.push_back(&BB);
1406 TempsToInstrument.clear();
1407 int NumInsnsPerBB = 0;
1408 for (auto &Inst : BB) {
1409 if (LooksLikeCodeInBug11395(&Inst)) return false;
1411 isInterestingMemoryAccess(&Inst, &IsWrite, &Alignment)) {
1412 if (ClOpt && ClOptSameTemp) {
1413 if (!TempsToInstrument.insert(Addr).second)
1414 continue; // We've seen this temp in the current BB.
1416 } else if (ClInvalidPointerPairs &&
1417 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1418 PointerComparisonsOrSubtracts.push_back(&Inst);
1420 } else if (isa<MemIntrinsic>(Inst)) {
1423 if (isa<AllocaInst>(Inst))
1427 // A call inside BB.
1428 TempsToInstrument.clear();
1429 if (CS.doesNotReturn())
1430 NoReturnCalls.push_back(CS.getInstruction());
1434 ToInstrument.push_back(&Inst);
1436 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1441 bool UseCalls = false;
1442 if (ClInstrumentationWithCallsThreshold >= 0 &&
1443 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold)
1447 int NumInstrumented = 0;
1448 for (auto Inst : ToInstrument) {
1449 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1450 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
1451 if (isInterestingMemoryAccess(Inst, &IsWrite, &Alignment))
1452 instrumentMop(Inst, UseCalls);
1454 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
1459 FunctionStackPoisoner FSP(F, *this);
1460 bool ChangedStack = FSP.runOnFunction();
1462 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1463 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1464 for (auto CI : NoReturnCalls) {
1465 IRBuilder<> IRB(CI);
1466 IRB.CreateCall(AsanHandleNoReturnFunc);
1469 for (auto Inst : PointerComparisonsOrSubtracts) {
1470 instrumentPointerComparisonOrSubtraction(Inst);
1474 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
1476 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1481 // Workaround for bug 11395: we don't want to instrument stack in functions
1482 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1483 // FIXME: remove once the bug 11395 is fixed.
1484 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1485 if (LongSize != 32) return false;
1486 CallInst *CI = dyn_cast<CallInst>(I);
1487 if (!CI || !CI->isInlineAsm()) return false;
1488 if (CI->getNumArgOperands() <= 5) return false;
1489 // We have inline assembly with quite a few arguments.
1493 void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1494 IRBuilder<> IRB(*C);
1495 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1496 std::string Suffix = itostr(i);
1497 AsanStackMallocFunc[i] = checkInterfaceFunction(
1498 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1499 IntptrTy, IntptrTy, nullptr));
1500 AsanStackFreeFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
1501 kAsanStackFreeNameTemplate + Suffix, IRB.getVoidTy(), IntptrTy,
1502 IntptrTy, IntptrTy, nullptr));
1504 AsanPoisonStackMemoryFunc = checkInterfaceFunction(
1505 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
1506 IntptrTy, IntptrTy, nullptr));
1507 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(
1508 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
1509 IntptrTy, IntptrTy, nullptr));
1513 FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
1514 IRBuilder<> &IRB, Value *ShadowBase,
1516 size_t n = ShadowBytes.size();
1518 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1519 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1520 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1521 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1522 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1523 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1525 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
1526 if (ASan.DL->isLittleEndian())
1527 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1529 Val = (Val << 8) | ShadowBytes[i + j];
1532 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1533 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1534 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1535 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
1540 // Fake stack allocator (asan_fake_stack.h) has 11 size classes
1541 // for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1542 static int StackMallocSizeClass(uint64_t LocalStackSize) {
1543 assert(LocalStackSize <= kMaxStackMallocSize);
1544 uint64_t MaxSize = kMinStackMallocSize;
1545 for (int i = 0; ; i++, MaxSize *= 2)
1546 if (LocalStackSize <= MaxSize)
1548 llvm_unreachable("impossible LocalStackSize");
1551 // Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1552 // We can not use MemSet intrinsic because it may end up calling the actual
1553 // memset. Size is a multiple of 8.
1554 // Currently this generates 8-byte stores on x86_64; it may be better to
1555 // generate wider stores.
1556 void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1557 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1558 assert(!(Size % 8));
1559 assert(kAsanStackAfterReturnMagic == 0xf5);
1560 for (int i = 0; i < Size; i += 8) {
1561 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1562 IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
1563 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1567 static DebugLoc getFunctionEntryDebugLocation(Function &F) {
1568 for (const auto &Inst : F.getEntryBlock())
1569 if (!isa<AllocaInst>(Inst))
1570 return Inst.getDebugLoc();
1574 void FunctionStackPoisoner::poisonStack() {
1575 assert(AllocaVec.size() > 0 || DynamicAllocaVec.size() > 0);
1577 if (ClInstrumentAllocas)
1578 // Handle dynamic allocas.
1579 for (auto &AllocaCall : DynamicAllocaVec)
1580 handleDynamicAllocaCall(AllocaCall);
1582 if (AllocaVec.size() == 0) return;
1584 int StackMallocIdx = -1;
1585 DebugLoc EntryDebugLocation = getFunctionEntryDebugLocation(F);
1587 Instruction *InsBefore = AllocaVec[0];
1588 IRBuilder<> IRB(InsBefore);
1589 IRB.SetCurrentDebugLocation(EntryDebugLocation);
1591 SmallVector<ASanStackVariableDescription, 16> SVD;
1592 SVD.reserve(AllocaVec.size());
1593 for (AllocaInst *AI : AllocaVec) {
1594 ASanStackVariableDescription D = { AI->getName().data(),
1595 getAllocaSizeInBytes(AI),
1596 AI->getAlignment(), AI, 0};
1599 // Minimal header size (left redzone) is 4 pointers,
1600 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1601 size_t MinHeaderSize = ASan.LongSize / 2;
1602 ASanStackFrameLayout L;
1603 ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1604 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1605 uint64_t LocalStackSize = L.FrameSize;
1606 bool DoStackMalloc =
1607 ClUseAfterReturn && LocalStackSize <= kMaxStackMallocSize;
1609 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1610 AllocaInst *MyAlloca =
1611 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
1612 MyAlloca->setDebugLoc(EntryDebugLocation);
1613 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1614 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1615 MyAlloca->setAlignment(FrameAlignment);
1616 assert(MyAlloca->isStaticAlloca());
1617 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1618 Value *LocalStackBase = OrigStackBase;
1620 if (DoStackMalloc) {
1621 // LocalStackBase = OrigStackBase
1622 // if (__asan_option_detect_stack_use_after_return)
1623 // LocalStackBase = __asan_stack_malloc_N(LocalStackBase, OrigStackBase);
1624 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1625 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
1626 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1627 kAsanOptionDetectUAR, IRB.getInt32Ty());
1628 Value *Cmp = IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1629 Constant::getNullValue(IRB.getInt32Ty()));
1630 Instruction *Term = SplitBlockAndInsertIfThen(Cmp, InsBefore, false);
1631 BasicBlock *CmpBlock = cast<Instruction>(Cmp)->getParent();
1632 IRBuilder<> IRBIf(Term);
1633 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
1634 LocalStackBase = IRBIf.CreateCall2(
1635 AsanStackMallocFunc[StackMallocIdx],
1636 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1637 BasicBlock *SetBlock = cast<Instruction>(LocalStackBase)->getParent();
1638 IRB.SetInsertPoint(InsBefore);
1639 IRB.SetCurrentDebugLocation(EntryDebugLocation);
1640 PHINode *Phi = IRB.CreatePHI(IntptrTy, 2);
1641 Phi->addIncoming(OrigStackBase, CmpBlock);
1642 Phi->addIncoming(LocalStackBase, SetBlock);
1643 LocalStackBase = Phi;
1646 // Insert poison calls for lifetime intrinsics for alloca.
1647 bool HavePoisonedAllocas = false;
1648 for (const auto &APC : AllocaPoisonCallVec) {
1649 assert(APC.InsBefore);
1651 IRBuilder<> IRB(APC.InsBefore);
1652 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
1653 HavePoisonedAllocas |= APC.DoPoison;
1656 // Replace Alloca instructions with base+offset.
1657 for (const auto &Desc : SVD) {
1658 AllocaInst *AI = Desc.AI;
1659 Value *NewAllocaPtr = IRB.CreateIntToPtr(
1660 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
1662 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
1663 AI->replaceAllUsesWith(NewAllocaPtr);
1666 // The left-most redzone has enough space for at least 4 pointers.
1667 // Write the Magic value to redzone[0].
1668 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1669 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1671 // Write the frame description constant to redzone[1].
1672 Value *BasePlus1 = IRB.CreateIntToPtr(
1673 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
1675 GlobalVariable *StackDescriptionGlobal =
1676 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
1677 /*AllowMerging*/true);
1678 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1680 IRB.CreateStore(Description, BasePlus1);
1681 // Write the PC to redzone[2].
1682 Value *BasePlus2 = IRB.CreateIntToPtr(
1683 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
1684 2 * ASan.LongSize/8)),
1686 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
1688 // Poison the stack redzones at the entry.
1689 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1690 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
1692 // (Un)poison the stack before all ret instructions.
1693 for (auto Ret : RetVec) {
1694 IRBuilder<> IRBRet(Ret);
1695 // Mark the current frame as retired.
1696 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1698 if (DoStackMalloc) {
1699 assert(StackMallocIdx >= 0);
1700 // if LocalStackBase != OrigStackBase:
1701 // // In use-after-return mode, poison the whole stack frame.
1702 // if StackMallocIdx <= 4
1703 // // For small sizes inline the whole thing:
1704 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
1705 // **SavedFlagPtr(LocalStackBase) = 0
1707 // __asan_stack_free_N(LocalStackBase, OrigStackBase)
1709 // <This is not a fake stack; unpoison the redzones>
1710 Value *Cmp = IRBRet.CreateICmpNE(LocalStackBase, OrigStackBase);
1711 TerminatorInst *ThenTerm, *ElseTerm;
1712 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1714 IRBuilder<> IRBPoison(ThenTerm);
1715 if (StackMallocIdx <= 4) {
1716 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1717 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1718 ClassSize >> Mapping.Scale);
1719 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
1721 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1722 Value *SavedFlagPtr = IRBPoison.CreateLoad(
1723 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1724 IRBPoison.CreateStore(
1725 Constant::getNullValue(IRBPoison.getInt8Ty()),
1726 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1728 // For larger frames call __asan_stack_free_*.
1729 IRBPoison.CreateCall3(AsanStackFreeFunc[StackMallocIdx], LocalStackBase,
1730 ConstantInt::get(IntptrTy, LocalStackSize),
1734 IRBuilder<> IRBElse(ElseTerm);
1735 poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
1736 } else if (HavePoisonedAllocas) {
1737 // If we poisoned some allocas in llvm.lifetime analysis,
1738 // unpoison whole stack frame now.
1739 assert(LocalStackBase == OrigStackBase);
1740 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
1742 poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
1746 if (ClInstrumentAllocas)
1747 // Unpoison dynamic allocas.
1748 for (auto &AllocaCall : DynamicAllocaVec)
1749 unpoisonDynamicAlloca(AllocaCall);
1751 // We are done. Remove the old unused alloca instructions.
1752 for (auto AI : AllocaVec)
1753 AI->eraseFromParent();
1756 void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
1757 IRBuilder<> &IRB, bool DoPoison) {
1758 // For now just insert the call to ASan runtime.
1759 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1760 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1761 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1762 : AsanUnpoisonStackMemoryFunc,
1766 // Handling llvm.lifetime intrinsics for a given %alloca:
1767 // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1768 // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1769 // invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1770 // could be poisoned by previous llvm.lifetime.end instruction, as the
1771 // variable may go in and out of scope several times, e.g. in loops).
1772 // (3) if we poisoned at least one %alloca in a function,
1773 // unpoison the whole stack frame at function exit.
1775 AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1776 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1777 // We're intested only in allocas we can handle.
1778 return isInterestingAlloca(*AI) ? AI : nullptr;
1779 // See if we've already calculated (or started to calculate) alloca for a
1781 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1782 if (I != AllocaForValue.end())
1784 // Store 0 while we're calculating alloca for value V to avoid
1785 // infinite recursion if the value references itself.
1786 AllocaForValue[V] = nullptr;
1787 AllocaInst *Res = nullptr;
1788 if (CastInst *CI = dyn_cast<CastInst>(V))
1789 Res = findAllocaForValue(CI->getOperand(0));
1790 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1791 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1792 Value *IncValue = PN->getIncomingValue(i);
1793 // Allow self-referencing phi-nodes.
1794 if (IncValue == PN) continue;
1795 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1796 // AI for incoming values should exist and should all be equal.
1797 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
1803 AllocaForValue[V] = Res;
1807 // Compute PartialRzMagic for dynamic alloca call. PartialRzMagic is
1808 // constructed from two separate 32-bit numbers: PartialRzMagic = Val1 | Val2.
1809 // (1) Val1 is resposible for forming base value for PartialRzMagic, containing
1810 // only 00 for fully addressable and 0xcb for fully poisoned bytes for each
1811 // 8-byte chunk of user memory respectively.
1812 // (2) Val2 forms the value for marking first poisoned byte in shadow memory
1813 // with appropriate value (0x01 - 0x07 or 0xcb if Padding % 8 == 0).
1815 // Shift = Padding & ~7; // the number of bits we need to shift to access first
1816 // chunk in shadow memory, containing nonzero bytes.
1818 // Padding = 21 Padding = 16
1819 // Shadow: |00|00|05|cb| Shadow: |00|00|cb|cb|
1822 // Shift = 21 & ~7 = 16 Shift = 16 & ~7 = 16
1824 // Val1 = 0xcbcbcbcb << Shift;
1825 // PartialBits = Padding ? Padding & 7 : 0xcb;
1826 // Val2 = PartialBits << Shift;
1827 // Result = Val1 | Val2;
1828 Value *FunctionStackPoisoner::computePartialRzMagic(Value *PartialSize,
1830 PartialSize = IRB.CreateIntCast(PartialSize, IRB.getInt32Ty(), false);
1831 Value *Shift = IRB.CreateAnd(PartialSize, IRB.getInt32(~7));
1832 unsigned Val1Int = kAsanAllocaPartialVal1;
1833 unsigned Val2Int = kAsanAllocaPartialVal2;
1834 if (!ASan.DL->isLittleEndian()) {
1835 Val1Int = sys::getSwappedBytes(Val1Int);
1836 Val2Int = sys::getSwappedBytes(Val2Int);
1838 Value *Val1 = shiftAllocaMagic(IRB.getInt32(Val1Int), IRB, Shift);
1839 Value *PartialBits = IRB.CreateAnd(PartialSize, IRB.getInt32(7));
1840 // For BigEndian get 0x000000YZ -> 0xYZ000000.
1841 if (ASan.DL->isBigEndian())
1842 PartialBits = IRB.CreateShl(PartialBits, IRB.getInt32(24));
1843 Value *Val2 = IRB.getInt32(Val2Int);
1845 IRB.CreateICmpNE(PartialBits, Constant::getNullValue(IRB.getInt32Ty()));
1846 Val2 = IRB.CreateSelect(Cond, shiftAllocaMagic(PartialBits, IRB, Shift),
1847 shiftAllocaMagic(Val2, IRB, Shift));
1848 return IRB.CreateOr(Val1, Val2);
1851 void FunctionStackPoisoner::handleDynamicAllocaCall(
1852 DynamicAllocaCall &AllocaCall) {
1853 AllocaInst *AI = AllocaCall.AI;
1854 if (!doesDominateAllExits(AI)) {
1855 // We do not yet handle complex allocas
1856 AllocaCall.Poison = false;
1860 IRBuilder<> IRB(AI);
1862 PointerType *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
1863 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
1864 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
1866 Value *Zero = Constant::getNullValue(IntptrTy);
1867 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
1868 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
1869 Value *NotAllocaRzMask = ConstantInt::get(IntptrTy, ~AllocaRedzoneMask);
1871 // Since we need to extend alloca with additional memory to locate
1872 // redzones, and OldSize is number of allocated blocks with
1873 // ElementSize size, get allocated memory size in bytes by
1874 // OldSize * ElementSize.
1875 unsigned ElementSize = ASan.DL->getTypeAllocSize(AI->getAllocatedType());
1876 Value *OldSize = IRB.CreateMul(AI->getArraySize(),
1877 ConstantInt::get(IntptrTy, ElementSize));
1879 // PartialSize = OldSize % 32
1880 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
1882 // Misalign = kAllocaRzSize - PartialSize;
1883 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
1885 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
1886 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
1887 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
1889 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
1890 // Align is added to locate left redzone, PartialPadding for possible
1891 // partial redzone and kAllocaRzSize for right redzone respectively.
1892 Value *AdditionalChunkSize = IRB.CreateAdd(
1893 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
1895 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
1897 // Insert new alloca with new NewSize and Align params.
1898 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
1899 NewAlloca->setAlignment(Align);
1901 // NewAddress = Address + Align
1902 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
1903 ConstantInt::get(IntptrTy, Align));
1905 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
1907 // LeftRzAddress = NewAddress - kAllocaRzSize
1908 Value *LeftRzAddress = IRB.CreateSub(NewAddress, AllocaRzSize);
1910 // Poisoning left redzone.
1911 AllocaCall.LeftRzAddr = ASan.memToShadow(LeftRzAddress, IRB);
1912 IRB.CreateStore(ConstantInt::get(IRB.getInt32Ty(), kAsanAllocaLeftMagic),
1913 IRB.CreateIntToPtr(AllocaCall.LeftRzAddr, Int32PtrTy));
1915 // PartialRzAligned = PartialRzAddr & ~AllocaRzMask
1916 Value *PartialRzAddr = IRB.CreateAdd(NewAddress, OldSize);
1917 Value *PartialRzAligned = IRB.CreateAnd(PartialRzAddr, NotAllocaRzMask);
1919 // Poisoning partial redzone.
1920 Value *PartialRzMagic = computePartialRzMagic(PartialSize, IRB);
1921 Value *PartialRzShadowAddr = ASan.memToShadow(PartialRzAligned, IRB);
1922 IRB.CreateStore(PartialRzMagic,
1923 IRB.CreateIntToPtr(PartialRzShadowAddr, Int32PtrTy));
1926 // = (PartialRzAddr + AllocaRzMask) & ~AllocaRzMask
1927 Value *RightRzAddress = IRB.CreateAnd(
1928 IRB.CreateAdd(PartialRzAddr, AllocaRzMask), NotAllocaRzMask);
1930 // Poisoning right redzone.
1931 AllocaCall.RightRzAddr = ASan.memToShadow(RightRzAddress, IRB);
1932 IRB.CreateStore(ConstantInt::get(IRB.getInt32Ty(), kAsanAllocaRightMagic),
1933 IRB.CreateIntToPtr(AllocaCall.RightRzAddr, Int32PtrTy));
1935 // Replace all uses of AddessReturnedByAlloca with NewAddress.
1936 AI->replaceAllUsesWith(NewAddressPtr);
1938 // We are done. Erase old alloca and store left, partial and right redzones
1939 // shadow addresses for future unpoisoning.
1940 AI->eraseFromParent();
1941 NumInstrumentedDynamicAllocas++;