1 //===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is a part of AddressSanitizer, an address sanity checker.
11 // Details of the algorithm:
12 // http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm
14 //===----------------------------------------------------------------------===//
16 #include "llvm/Transforms/Instrumentation.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/DenseSet.h"
20 #include "llvm/ADT/DepthFirstIterator.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/Triple.h"
27 #include "llvm/IR/CallSite.h"
28 #include "llvm/IR/DIBuilder.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/IRBuilder.h"
32 #include "llvm/IR/InlineAsm.h"
33 #include "llvm/IR/InstVisitor.h"
34 #include "llvm/IR/IntrinsicInst.h"
35 #include "llvm/IR/LLVMContext.h"
36 #include "llvm/IR/MDBuilder.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/IR/Type.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/DataTypes.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/Endian.h"
43 #include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
44 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
45 #include "llvm/Transforms/Utils/Cloning.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Transforms/Utils/ModuleUtils.h"
50 #include <system_error>
54 #define DEBUG_TYPE "asan"
56 static const uint64_t kDefaultShadowScale = 3;
57 static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
58 static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
59 static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
60 static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
61 static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
62 static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa8000;
63 static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
64 static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
66 static const size_t kMinStackMallocSize = 1 << 6; // 64B
67 static const size_t kMaxStackMallocSize = 1 << 16; // 64K
68 static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
69 static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
71 static const char *const kAsanModuleCtorName = "asan.module_ctor";
72 static const char *const kAsanModuleDtorName = "asan.module_dtor";
73 static const int kAsanCtorAndDtorPriority = 1;
74 static const char *const kAsanReportErrorTemplate = "__asan_report_";
75 static const char *const kAsanReportLoadN = "__asan_report_load_n";
76 static const char *const kAsanReportStoreN = "__asan_report_store_n";
77 static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
78 static const char *const kAsanUnregisterGlobalsName =
79 "__asan_unregister_globals";
80 static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
81 static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
82 static const char *const kAsanInitName = "__asan_init_v4";
83 static const char *const kAsanCovModuleInitName = "__sanitizer_cov_module_init";
84 static const char *const kAsanCovName = "__sanitizer_cov";
85 static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
86 static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
87 static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
88 static const int kMaxAsanStackMallocSizeClass = 10;
89 static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
90 static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
91 static const char *const kAsanGenPrefix = "__asan_gen_";
92 static const char *const kAsanPoisonStackMemoryName =
93 "__asan_poison_stack_memory";
94 static const char *const kAsanUnpoisonStackMemoryName =
95 "__asan_unpoison_stack_memory";
97 static const char *const kAsanOptionDetectUAR =
98 "__asan_option_detect_stack_use_after_return";
101 static const int kAsanStackAfterReturnMagic = 0xf5;
104 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
105 static const size_t kNumberOfAccessSizes = 5;
107 // Command-line flags.
109 // This flag may need to be replaced with -f[no-]asan-reads.
110 static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
111 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
112 static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
113 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
114 static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
115 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
116 cl::Hidden, cl::init(true));
117 static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
118 cl::desc("use instrumentation with slow path for all accesses"),
119 cl::Hidden, cl::init(false));
120 // This flag limits the number of instructions to be instrumented
121 // in any given BB. Normally, this should be set to unlimited (INT_MAX),
122 // but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
124 static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
126 cl::desc("maximal number of instructions to instrument in any given BB"),
128 // This flag may need to be replaced with -f[no]asan-stack.
129 static cl::opt<bool> ClStack("asan-stack",
130 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
131 static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
132 cl::desc("Check return-after-free"), cl::Hidden, cl::init(true));
133 // This flag may need to be replaced with -f[no]asan-globals.
134 static cl::opt<bool> ClGlobals("asan-globals",
135 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
136 static cl::opt<int> ClCoverage("asan-coverage",
137 cl::desc("ASan coverage. 0: none, 1: entry block, 2: all blocks"),
138 cl::Hidden, cl::init(false));
139 static cl::opt<int> ClCoverageBlockThreshold("asan-coverage-block-threshold",
140 cl::desc("Add coverage instrumentation only to the entry block if there "
141 "are more than this number of blocks."),
142 cl::Hidden, cl::init(1500));
143 static cl::opt<bool> ClInitializers("asan-initialization-order",
144 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(true));
145 static cl::opt<bool> ClInvalidPointerPairs("asan-detect-invalid-pointer-pair",
146 cl::desc("Instrument <, <=, >, >=, - with pointer operands"),
147 cl::Hidden, cl::init(false));
148 static cl::opt<unsigned> ClRealignStack("asan-realign-stack",
149 cl::desc("Realign stack to the value of this flag (power of two)"),
150 cl::Hidden, cl::init(32));
151 static cl::opt<int> ClInstrumentationWithCallsThreshold(
152 "asan-instrumentation-with-call-threshold",
153 cl::desc("If the function being instrumented contains more than "
154 "this number of memory accesses, use callbacks instead of "
155 "inline checks (-1 means never use callbacks)."),
156 cl::Hidden, cl::init(7000));
157 static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
158 "asan-memory-access-callback-prefix",
159 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
160 cl::init("__asan_"));
162 // This is an experimental feature that will allow to choose between
163 // instrumented and non-instrumented code at link-time.
164 // If this option is on, just before instrumenting a function we create its
165 // clone; if the function is not changed by asan the clone is deleted.
166 // If we end up with a clone, we put the instrumented function into a section
167 // called "ASAN" and the uninstrumented function into a section called "NOASAN".
169 // This is still a prototype, we need to figure out a way to keep two copies of
170 // a function so that the linker can easily choose one of them.
171 static cl::opt<bool> ClKeepUninstrumented("asan-keep-uninstrumented-functions",
172 cl::desc("Keep uninstrumented copies of functions"),
173 cl::Hidden, cl::init(false));
175 // These flags allow to change the shadow mapping.
176 // The shadow mapping looks like
177 // Shadow = (Mem >> scale) + (1 << offset_log)
178 static cl::opt<int> ClMappingScale("asan-mapping-scale",
179 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
181 // Optimization flags. Not user visible, used mostly for testing
182 // and benchmarking the tool.
183 static cl::opt<bool> ClOpt("asan-opt",
184 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
185 static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
186 cl::desc("Instrument the same temp just once"), cl::Hidden,
188 static cl::opt<bool> ClOptGlobals("asan-opt-globals",
189 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
191 static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
192 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
193 cl::Hidden, cl::init(false));
196 static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
198 static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
199 cl::Hidden, cl::init(0));
200 static cl::opt<std::string> ClDebugFunc("asan-debug-func",
201 cl::Hidden, cl::desc("Debug func"));
202 static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
203 cl::Hidden, cl::init(-1));
204 static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
205 cl::Hidden, cl::init(-1));
207 STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
208 STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
209 STATISTIC(NumOptimizedAccessesToGlobalArray,
210 "Number of optimized accesses to global arrays");
211 STATISTIC(NumOptimizedAccessesToGlobalVar,
212 "Number of optimized accesses to global vars");
215 /// Frontend-provided metadata for global variables.
216 class GlobalsMetadata {
218 GlobalsMetadata() : inited_(false) {}
219 void init(Module& M) {
222 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
225 for (auto MDN : Globals->operands()) {
226 // Format of the metadata node for the global:
230 // i1 is_dynamically_initialized,
233 assert(MDN->getNumOperands() == 4);
234 Value *V = MDN->getOperand(0);
235 // The optimizer may optimize away a global entirely.
238 GlobalVariable *GV = cast<GlobalVariable>(V);
239 if (Value *Loc = MDN->getOperand(1)) {
240 GlobalVariable *GVLoc = cast<GlobalVariable>(Loc);
241 // We may already know the source location for GV, if it was merged
242 // with another global.
243 if (SourceLocation.insert(std::make_pair(GV, GVLoc)).second)
244 addSourceLocationGlobal(GVLoc);
246 ConstantInt *IsDynInit = cast<ConstantInt>(MDN->getOperand(2));
247 if (IsDynInit->isOne())
248 DynInitGlobals.insert(GV);
249 ConstantInt *IsBlacklisted = cast<ConstantInt>(MDN->getOperand(3));
250 if (IsBlacklisted->isOne())
251 BlacklistedGlobals.insert(GV);
255 GlobalVariable *getSourceLocation(GlobalVariable *G) const {
256 auto Pos = SourceLocation.find(G);
257 return (Pos != SourceLocation.end()) ? Pos->second : nullptr;
260 /// Check if the global is dynamically initialized.
261 bool isDynInit(GlobalVariable *G) const {
262 return DynInitGlobals.count(G);
265 /// Check if the global was blacklisted.
266 bool isBlacklisted(GlobalVariable *G) const {
267 return BlacklistedGlobals.count(G);
270 /// Check if the global was generated to describe source location of another
271 /// global (we don't want to instrument them).
272 bool isSourceLocationGlobal(GlobalVariable *G) const {
273 return LocationGlobals.count(G);
278 DenseMap<GlobalVariable*, GlobalVariable*> SourceLocation;
279 DenseSet<GlobalVariable*> DynInitGlobals;
280 DenseSet<GlobalVariable*> BlacklistedGlobals;
281 DenseSet<GlobalVariable*> LocationGlobals;
283 void addSourceLocationGlobal(GlobalVariable *SourceLocGV) {
284 // Source location global is a struct with layout:
288 // i32 column_number,
290 LocationGlobals.insert(SourceLocGV);
291 ConstantStruct *Contents =
292 cast<ConstantStruct>(SourceLocGV->getInitializer());
293 GlobalVariable *FilenameGV = cast<GlobalVariable>(Contents->getOperand(0));
294 LocationGlobals.insert(FilenameGV);
298 /// This struct defines the shadow mapping using the rule:
299 /// shadow = (mem >> Scale) ADD-or-OR Offset.
300 struct ShadowMapping {
306 static ShadowMapping getShadowMapping(const Module &M, int LongSize) {
307 llvm::Triple TargetTriple(M.getTargetTriple());
308 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
309 bool IsIOS = TargetTriple.getOS() == llvm::Triple::IOS;
310 bool IsFreeBSD = TargetTriple.getOS() == llvm::Triple::FreeBSD;
311 bool IsLinux = TargetTriple.getOS() == llvm::Triple::Linux;
312 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
313 TargetTriple.getArch() == llvm::Triple::ppc64le;
314 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
315 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
316 TargetTriple.getArch() == llvm::Triple::mipsel;
318 ShadowMapping Mapping;
320 if (LongSize == 32) {
324 Mapping.Offset = kMIPS32_ShadowOffset32;
326 Mapping.Offset = kFreeBSD_ShadowOffset32;
328 Mapping.Offset = kIOSShadowOffset32;
330 Mapping.Offset = kDefaultShadowOffset32;
331 } else { // LongSize == 64
333 Mapping.Offset = kPPC64_ShadowOffset64;
335 Mapping.Offset = kFreeBSD_ShadowOffset64;
336 else if (IsLinux && IsX86_64)
337 Mapping.Offset = kSmallX86_64ShadowOffset;
339 Mapping.Offset = kDefaultShadowOffset64;
342 Mapping.Scale = kDefaultShadowScale;
343 if (ClMappingScale) {
344 Mapping.Scale = ClMappingScale;
347 // OR-ing shadow offset if more efficient (at least on x86) if the offset
348 // is a power of two, but on ppc64 we have to use add since the shadow
349 // offset is not necessary 1/8-th of the address space.
350 Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
355 static size_t RedzoneSizeForScale(int MappingScale) {
356 // Redzone used for stack and globals is at least 32 bytes.
357 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
358 return std::max(32U, 1U << MappingScale);
361 /// AddressSanitizer: instrument the code in module to find memory bugs.
362 struct AddressSanitizer : public FunctionPass {
363 AddressSanitizer() : FunctionPass(ID) {}
364 const char *getPassName() const override {
365 return "AddressSanitizerFunctionPass";
367 void instrumentMop(Instruction *I, bool UseCalls);
368 void instrumentPointerComparisonOrSubtraction(Instruction *I);
369 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
370 Value *Addr, uint32_t TypeSize, bool IsWrite,
371 Value *SizeArgument, bool UseCalls);
372 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
373 Value *ShadowValue, uint32_t TypeSize);
374 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
375 bool IsWrite, size_t AccessSizeIndex,
376 Value *SizeArgument);
377 void instrumentMemIntrinsic(MemIntrinsic *MI);
378 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
379 bool runOnFunction(Function &F) override;
380 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
381 bool doInitialization(Module &M) override;
382 static char ID; // Pass identification, replacement for typeid
385 void initializeCallbacks(Module &M);
387 bool LooksLikeCodeInBug11395(Instruction *I);
388 bool GlobalIsLinkerInitialized(GlobalVariable *G);
389 bool InjectCoverage(Function &F, const ArrayRef<BasicBlock*> AllBlocks);
390 void InjectCoverageAtBlock(Function &F, BasicBlock &BB);
393 const DataLayout *DL;
396 ShadowMapping Mapping;
397 Function *AsanCtorFunction;
398 Function *AsanInitFunction;
399 Function *AsanHandleNoReturnFunc;
400 Function *AsanCovFunction;
401 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
402 // This array is indexed by AccessIsWrite and log2(AccessSize).
403 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
404 Function *AsanMemoryAccessCallback[2][kNumberOfAccessSizes];
405 // This array is indexed by AccessIsWrite.
406 Function *AsanErrorCallbackSized[2],
407 *AsanMemoryAccessCallbackSized[2];
408 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
410 GlobalsMetadata GlobalsMD;
412 friend struct FunctionStackPoisoner;
415 class AddressSanitizerModule : public ModulePass {
417 AddressSanitizerModule() : ModulePass(ID) {}
418 bool runOnModule(Module &M) override;
419 static char ID; // Pass identification, replacement for typeid
420 const char *getPassName() const override {
421 return "AddressSanitizerModule";
425 void initializeCallbacks(Module &M);
427 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
428 bool ShouldInstrumentGlobal(GlobalVariable *G);
429 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
430 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
431 size_t MinRedzoneSizeForGlobal() const {
432 return RedzoneSizeForScale(Mapping.Scale);
435 GlobalsMetadata GlobalsMD;
438 const DataLayout *DL;
439 ShadowMapping Mapping;
440 Function *AsanPoisonGlobals;
441 Function *AsanUnpoisonGlobals;
442 Function *AsanRegisterGlobals;
443 Function *AsanUnregisterGlobals;
444 Function *AsanCovModuleInit;
447 // Stack poisoning does not play well with exception handling.
448 // When an exception is thrown, we essentially bypass the code
449 // that unpoisones the stack. This is why the run-time library has
450 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
451 // stack in the interceptor. This however does not work inside the
452 // actual function which catches the exception. Most likely because the
453 // compiler hoists the load of the shadow value somewhere too high.
454 // This causes asan to report a non-existing bug on 453.povray.
455 // It sounds like an LLVM bug.
456 struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
458 AddressSanitizer &ASan;
463 ShadowMapping Mapping;
465 SmallVector<AllocaInst*, 16> AllocaVec;
466 SmallVector<Instruction*, 8> RetVec;
467 unsigned StackAlignment;
469 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
470 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
471 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
473 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
474 struct AllocaPoisonCall {
475 IntrinsicInst *InsBefore;
480 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
482 // Maps Value to an AllocaInst from which the Value is originated.
483 typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
484 AllocaForValueMapTy AllocaForValue;
486 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
487 : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
488 IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
489 Mapping(ASan.Mapping),
490 StackAlignment(1 << Mapping.Scale) {}
492 bool runOnFunction() {
493 if (!ClStack) return false;
494 // Collect alloca, ret, lifetime instructions etc.
495 for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
498 if (AllocaVec.empty()) return false;
500 initializeCallbacks(*F.getParent());
510 // Finds all static Alloca instructions and puts
511 // poisoned red zones around all of them.
512 // Then unpoison everything back before the function returns.
515 // ----------------------- Visitors.
516 /// \brief Collect all Ret instructions.
517 void visitReturnInst(ReturnInst &RI) {
518 RetVec.push_back(&RI);
521 /// \brief Collect Alloca instructions we want (and can) handle.
522 void visitAllocaInst(AllocaInst &AI) {
523 if (!isInterestingAlloca(AI)) return;
525 StackAlignment = std::max(StackAlignment, AI.getAlignment());
526 AllocaVec.push_back(&AI);
529 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
531 void visitIntrinsicInst(IntrinsicInst &II) {
532 if (!ClCheckLifetime) return;
533 Intrinsic::ID ID = II.getIntrinsicID();
534 if (ID != Intrinsic::lifetime_start &&
535 ID != Intrinsic::lifetime_end)
537 // Found lifetime intrinsic, add ASan instrumentation if necessary.
538 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
539 // If size argument is undefined, don't do anything.
540 if (Size->isMinusOne()) return;
541 // Check that size doesn't saturate uint64_t and can
542 // be stored in IntptrTy.
543 const uint64_t SizeValue = Size->getValue().getLimitedValue();
544 if (SizeValue == ~0ULL ||
545 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
547 // Find alloca instruction that corresponds to llvm.lifetime argument.
548 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
550 bool DoPoison = (ID == Intrinsic::lifetime_end);
551 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
552 AllocaPoisonCallVec.push_back(APC);
555 // ---------------------- Helpers.
556 void initializeCallbacks(Module &M);
558 // Check if we want (and can) handle this alloca.
559 bool isInterestingAlloca(AllocaInst &AI) const {
560 return (!AI.isArrayAllocation() && AI.isStaticAlloca() &&
561 AI.getAllocatedType()->isSized() &&
562 // alloca() may be called with 0 size, ignore it.
563 getAllocaSizeInBytes(&AI) > 0);
566 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
567 Type *Ty = AI->getAllocatedType();
568 uint64_t SizeInBytes = ASan.DL->getTypeAllocSize(Ty);
571 /// Finds alloca where the value comes from.
572 AllocaInst *findAllocaForValue(Value *V);
573 void poisonRedZones(const ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
574 Value *ShadowBase, bool DoPoison);
575 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
577 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
583 char AddressSanitizer::ID = 0;
584 INITIALIZE_PASS(AddressSanitizer, "asan",
585 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
587 FunctionPass *llvm::createAddressSanitizerFunctionPass() {
588 return new AddressSanitizer();
591 char AddressSanitizerModule::ID = 0;
592 INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
593 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
594 "ModulePass", false, false)
595 ModulePass *llvm::createAddressSanitizerModulePass() {
596 return new AddressSanitizerModule();
599 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
600 size_t Res = countTrailingZeros(TypeSize / 8);
601 assert(Res < kNumberOfAccessSizes);
605 // \brief Create a constant for Str so that we can pass it to the run-time lib.
606 static GlobalVariable *createPrivateGlobalForString(
607 Module &M, StringRef Str, bool AllowMerging) {
608 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
609 // We use private linkage for module-local strings. If they can be merged
610 // with another one, we set the unnamed_addr attribute.
612 new GlobalVariable(M, StrConst->getType(), true,
613 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
615 GV->setUnnamedAddr(true);
616 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
620 static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
621 return G->getName().find(kAsanGenPrefix) == 0;
624 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
626 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
627 if (Mapping.Offset == 0)
629 // (Shadow >> scale) | offset
630 if (Mapping.OrShadowOffset)
631 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
633 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
636 // Instrument memset/memmove/memcpy
637 void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
639 if (isa<MemTransferInst>(MI)) {
641 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
642 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
643 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
644 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
645 } else if (isa<MemSetInst>(MI)) {
648 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
649 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
650 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
652 MI->eraseFromParent();
655 // If I is an interesting memory access, return the PointerOperand
656 // and set IsWrite/Alignment. Otherwise return NULL.
657 static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
658 unsigned *Alignment) {
659 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
660 if (!ClInstrumentReads) return nullptr;
662 *Alignment = LI->getAlignment();
663 return LI->getPointerOperand();
665 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
666 if (!ClInstrumentWrites) return nullptr;
668 *Alignment = SI->getAlignment();
669 return SI->getPointerOperand();
671 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
672 if (!ClInstrumentAtomics) return nullptr;
675 return RMW->getPointerOperand();
677 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
678 if (!ClInstrumentAtomics) return nullptr;
681 return XCHG->getPointerOperand();
686 static bool isPointerOperand(Value *V) {
687 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
690 // This is a rough heuristic; it may cause both false positives and
691 // false negatives. The proper implementation requires cooperation with
693 static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
694 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
695 if (!Cmp->isRelational())
697 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
698 if (BO->getOpcode() != Instruction::Sub)
703 if (!isPointerOperand(I->getOperand(0)) ||
704 !isPointerOperand(I->getOperand(1)))
709 bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
710 // If a global variable does not have dynamic initialization we don't
711 // have to instrument it. However, if a global does not have initializer
712 // at all, we assume it has dynamic initializer (in other TU).
713 return G->hasInitializer() && !GlobalsMD.isDynInit(G);
717 AddressSanitizer::instrumentPointerComparisonOrSubtraction(Instruction *I) {
719 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
720 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
721 for (int i = 0; i < 2; i++) {
722 if (Param[i]->getType()->isPointerTy())
723 Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
725 IRB.CreateCall2(F, Param[0], Param[1]);
728 void AddressSanitizer::instrumentMop(Instruction *I, bool UseCalls) {
729 bool IsWrite = false;
730 unsigned Alignment = 0;
731 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &Alignment);
733 if (ClOpt && ClOptGlobals) {
734 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
735 // If initialization order checking is disabled, a simple access to a
736 // dynamically initialized global is always valid.
737 if (!ClInitializers || GlobalIsLinkerInitialized(G)) {
738 NumOptimizedAccessesToGlobalVar++;
742 ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr);
743 if (CE && CE->isGEPWithNoNotionalOverIndexing()) {
744 if (GlobalVariable *G = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
745 if (CE->getOperand(1)->isNullValue() && GlobalIsLinkerInitialized(G)) {
746 NumOptimizedAccessesToGlobalArray++;
753 Type *OrigPtrTy = Addr->getType();
754 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
756 assert(OrigTy->isSized());
757 uint32_t TypeSize = DL->getTypeStoreSizeInBits(OrigTy);
759 assert((TypeSize % 8) == 0);
762 NumInstrumentedWrites++;
764 NumInstrumentedReads++;
766 unsigned Granularity = 1 << Mapping.Scale;
767 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
768 // if the data is properly aligned.
769 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
771 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
772 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls);
773 // Instrument unusual size or unusual alignment.
774 // We can not do it with a single check, so we do 1-byte check for the first
775 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
776 // to report the actual access size.
778 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
779 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
781 IRB.CreateCall2(AsanMemoryAccessCallbackSized[IsWrite], AddrLong, Size);
783 Value *LastByte = IRB.CreateIntToPtr(
784 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
786 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false);
787 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false);
791 // Validate the result of Module::getOrInsertFunction called for an interface
792 // function of AddressSanitizer. If the instrumented module defines a function
793 // with the same name, their prototypes must match, otherwise
794 // getOrInsertFunction returns a bitcast.
795 static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
796 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
797 FuncOrBitcast->dump();
798 report_fatal_error("trying to redefine an AddressSanitizer "
799 "interface function");
802 Instruction *AddressSanitizer::generateCrashCode(
803 Instruction *InsertBefore, Value *Addr,
804 bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
805 IRBuilder<> IRB(InsertBefore);
806 CallInst *Call = SizeArgument
807 ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
808 : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
810 // We don't do Call->setDoesNotReturn() because the BB already has
811 // UnreachableInst at the end.
812 // This EmptyAsm is required to avoid callback merge.
813 IRB.CreateCall(EmptyAsm);
817 Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
820 size_t Granularity = 1 << Mapping.Scale;
821 // Addr & (Granularity - 1)
822 Value *LastAccessedByte = IRB.CreateAnd(
823 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
824 // (Addr & (Granularity - 1)) + size - 1
825 if (TypeSize / 8 > 1)
826 LastAccessedByte = IRB.CreateAdd(
827 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
828 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
829 LastAccessedByte = IRB.CreateIntCast(
830 LastAccessedByte, ShadowValue->getType(), false);
831 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
832 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
835 void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
836 Instruction *InsertBefore, Value *Addr,
837 uint32_t TypeSize, bool IsWrite,
838 Value *SizeArgument, bool UseCalls) {
839 IRBuilder<> IRB(InsertBefore);
840 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
841 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
844 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][AccessSizeIndex],
849 Type *ShadowTy = IntegerType::get(
850 *C, std::max(8U, TypeSize >> Mapping.Scale));
851 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
852 Value *ShadowPtr = memToShadow(AddrLong, IRB);
853 Value *CmpVal = Constant::getNullValue(ShadowTy);
854 Value *ShadowValue = IRB.CreateLoad(
855 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
857 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
858 size_t Granularity = 1 << Mapping.Scale;
859 TerminatorInst *CrashTerm = nullptr;
861 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
862 TerminatorInst *CheckTerm =
863 SplitBlockAndInsertIfThen(Cmp, InsertBefore, false);
864 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
865 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
866 IRB.SetInsertPoint(CheckTerm);
867 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
868 BasicBlock *CrashBlock =
869 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
870 CrashTerm = new UnreachableInst(*C, CrashBlock);
871 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
872 ReplaceInstWithInst(CheckTerm, NewTerm);
874 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
877 Instruction *Crash = generateCrashCode(
878 CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
879 Crash->setDebugLoc(OrigIns->getDebugLoc());
882 void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
883 GlobalValue *ModuleName) {
884 // Set up the arguments to our poison/unpoison functions.
885 IRBuilder<> IRB(GlobalInit.begin()->getFirstInsertionPt());
887 // Add a call to poison all external globals before the given function starts.
888 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
889 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
891 // Add calls to unpoison all globals before each return instruction.
892 for (auto &BB : GlobalInit.getBasicBlockList())
893 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
894 CallInst::Create(AsanUnpoisonGlobals, "", RI);
897 void AddressSanitizerModule::createInitializerPoisonCalls(
898 Module &M, GlobalValue *ModuleName) {
899 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
901 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
902 for (Use &OP : CA->operands()) {
903 if (isa<ConstantAggregateZero>(OP))
905 ConstantStruct *CS = cast<ConstantStruct>(OP);
907 // Must have a function or null ptr.
908 // (CS->getOperand(0) is the init priority.)
909 if (Function* F = dyn_cast<Function>(CS->getOperand(1))) {
910 if (F->getName() != kAsanModuleCtorName)
911 poisonOneInitializer(*F, ModuleName);
916 bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
917 Type *Ty = cast<PointerType>(G->getType())->getElementType();
918 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
920 if (GlobalsMD.isBlacklisted(G)) return false;
921 if (GlobalsMD.isSourceLocationGlobal(G)) return false;
922 if (!Ty->isSized()) return false;
923 if (!G->hasInitializer()) return false;
924 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
925 // Touch only those globals that will not be defined in other modules.
926 // Don't handle ODR type linkages since other modules may be built w/o asan.
927 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
928 G->getLinkage() != GlobalVariable::PrivateLinkage &&
929 G->getLinkage() != GlobalVariable::InternalLinkage)
931 // Two problems with thread-locals:
932 // - The address of the main thread's copy can't be computed at link-time.
933 // - Need to poison all copies, not just the main thread's one.
934 if (G->isThreadLocal())
936 // For now, just ignore this Global if the alignment is large.
937 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
939 // Ignore all the globals with the names starting with "\01L_OBJC_".
940 // Many of those are put into the .cstring section. The linker compresses
941 // that section by removing the spare \0s after the string terminator, so
942 // our redzones get broken.
943 if ((G->getName().find("\01L_OBJC_") == 0) ||
944 (G->getName().find("\01l_OBJC_") == 0)) {
945 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G << "\n");
949 if (G->hasSection()) {
950 StringRef Section(G->getSection());
951 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
952 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
954 if (Section.startswith("__OBJC,") ||
955 Section.startswith("__DATA, __objc_")) {
956 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
959 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
960 // Constant CFString instances are compiled in the following way:
961 // -- the string buffer is emitted into
962 // __TEXT,__cstring,cstring_literals
963 // -- the constant NSConstantString structure referencing that buffer
964 // is placed into __DATA,__cfstring
965 // Therefore there's no point in placing redzones into __DATA,__cfstring.
966 // Moreover, it causes the linker to crash on OS X 10.7
967 if (Section.startswith("__DATA,__cfstring")) {
968 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
971 // The linker merges the contents of cstring_literals and removes the
973 if (Section.startswith("__TEXT,__cstring,cstring_literals")) {
974 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
978 // Callbacks put into the CRT initializer/terminator sections
979 // should not be instrumented.
980 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
981 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
982 if (Section.startswith(".CRT")) {
983 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
987 // Globals from llvm.metadata aren't emitted, do not instrument them.
988 if (Section == "llvm.metadata") return false;
994 void AddressSanitizerModule::initializeCallbacks(Module &M) {
996 // Declare our poisoning and unpoisoning functions.
997 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
998 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, NULL));
999 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
1000 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1001 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
1002 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1003 // Declare functions that register/unregister globals.
1004 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1005 kAsanRegisterGlobalsName, IRB.getVoidTy(),
1006 IntptrTy, IntptrTy, NULL));
1007 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
1008 AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1009 kAsanUnregisterGlobalsName,
1010 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1011 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1012 AsanCovModuleInit = checkInterfaceFunction(M.getOrInsertFunction(
1013 kAsanCovModuleInitName,
1014 IRB.getVoidTy(), IntptrTy, NULL));
1015 AsanCovModuleInit->setLinkage(Function::ExternalLinkage);
1018 // This function replaces all global variables with new variables that have
1019 // trailing redzones. It also creates a function that poisons
1020 // redzones and inserts this function into llvm.global_ctors.
1021 bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
1024 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1026 for (auto &G : M.globals()) {
1027 if (ShouldInstrumentGlobal(&G))
1028 GlobalsToChange.push_back(&G);
1031 size_t n = GlobalsToChange.size();
1032 if (n == 0) return false;
1034 // A global is described by a structure
1037 // size_t size_with_redzone;
1038 // const char *name;
1039 // const char *module_name;
1040 // size_t has_dynamic_init;
1041 // void *source_location;
1042 // We initialize an array of such structures and pass it to a run-time call.
1043 StructType *GlobalStructTy =
1044 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
1045 IntptrTy, IntptrTy, NULL);
1046 SmallVector<Constant *, 16> Initializers(n);
1048 bool HasDynamicallyInitializedGlobals = false;
1050 // We shouldn't merge same module names, as this string serves as unique
1051 // module ID in runtime.
1052 GlobalVariable *ModuleName = createPrivateGlobalForString(
1053 M, M.getModuleIdentifier(), /*AllowMerging*/false);
1055 for (size_t i = 0; i < n; i++) {
1056 static const uint64_t kMaxGlobalRedzone = 1 << 18;
1057 GlobalVariable *G = GlobalsToChange[i];
1058 PointerType *PtrTy = cast<PointerType>(G->getType());
1059 Type *Ty = PtrTy->getElementType();
1060 uint64_t SizeInBytes = DL->getTypeAllocSize(Ty);
1061 uint64_t MinRZ = MinRedzoneSizeForGlobal();
1062 // MinRZ <= RZ <= kMaxGlobalRedzone
1063 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
1064 uint64_t RZ = std::max(MinRZ,
1065 std::min(kMaxGlobalRedzone,
1066 (SizeInBytes / MinRZ / 4) * MinRZ));
1067 uint64_t RightRedzoneSize = RZ;
1068 // Round up to MinRZ
1069 if (SizeInBytes % MinRZ)
1070 RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
1071 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
1072 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1074 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
1075 Constant *NewInitializer = ConstantStruct::get(
1076 NewTy, G->getInitializer(),
1077 Constant::getNullValue(RightRedZoneTy), NULL);
1079 GlobalVariable *Name =
1080 createPrivateGlobalForString(M, G->getName(), /*AllowMerging*/true);
1082 // Create a new global variable with enough space for a redzone.
1083 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1084 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1085 Linkage = GlobalValue::InternalLinkage;
1086 GlobalVariable *NewGlobal = new GlobalVariable(
1087 M, NewTy, G->isConstant(), Linkage,
1088 NewInitializer, "", G, G->getThreadLocalMode());
1089 NewGlobal->copyAttributesFrom(G);
1090 NewGlobal->setAlignment(MinRZ);
1093 Indices2[0] = IRB.getInt32(0);
1094 Indices2[1] = IRB.getInt32(0);
1096 G->replaceAllUsesWith(
1097 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
1098 NewGlobal->takeName(G);
1099 G->eraseFromParent();
1101 bool GlobalHasDynamicInitializer = GlobalsMD.isDynInit(G);
1102 GlobalVariable *SourceLoc = GlobalsMD.getSourceLocation(G);
1104 Initializers[i] = ConstantStruct::get(
1105 GlobalStructTy, ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
1106 ConstantInt::get(IntptrTy, SizeInBytes),
1107 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1108 ConstantExpr::getPointerCast(Name, IntptrTy),
1109 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
1110 ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
1111 SourceLoc ? ConstantExpr::getPointerCast(SourceLoc, IntptrTy)
1112 : ConstantInt::get(IntptrTy, 0),
1115 if (ClInitializers && GlobalHasDynamicInitializer)
1116 HasDynamicallyInitializedGlobals = true;
1118 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
1121 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1122 GlobalVariable *AllGlobals = new GlobalVariable(
1123 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1124 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1126 // Create calls for poisoning before initializers run and unpoisoning after.
1127 if (HasDynamicallyInitializedGlobals)
1128 createInitializerPoisonCalls(M, ModuleName);
1129 IRB.CreateCall2(AsanRegisterGlobals,
1130 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1131 ConstantInt::get(IntptrTy, n));
1133 // We also need to unregister globals at the end, e.g. when a shared library
1135 Function *AsanDtorFunction = Function::Create(
1136 FunctionType::get(Type::getVoidTy(*C), false),
1137 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1138 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1139 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
1140 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
1141 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1142 ConstantInt::get(IntptrTy, n));
1143 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
1149 bool AddressSanitizerModule::runOnModule(Module &M) {
1150 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1153 DL = &DLP->getDataLayout();
1154 C = &(M.getContext());
1155 int LongSize = DL->getPointerSizeInBits();
1156 IntptrTy = Type::getIntNTy(*C, LongSize);
1157 Mapping = getShadowMapping(M, LongSize);
1158 initializeCallbacks(M);
1160 bool Changed = false;
1162 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1164 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1166 if (ClCoverage > 0) {
1167 Function *CovFunc = M.getFunction(kAsanCovName);
1168 int nCov = CovFunc ? CovFunc->getNumUses() : 0;
1169 IRB.CreateCall(AsanCovModuleInit, ConstantInt::get(IntptrTy, nCov));
1174 Changed |= InstrumentGlobals(IRB, M);
1179 void AddressSanitizer::initializeCallbacks(Module &M) {
1180 IRBuilder<> IRB(*C);
1181 // Create __asan_report* callbacks.
1182 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1183 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1184 AccessSizeIndex++) {
1185 // IsWrite and TypeSize are encoded in the function name.
1186 std::string Suffix =
1187 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
1188 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
1189 checkInterfaceFunction(
1190 M.getOrInsertFunction(kAsanReportErrorTemplate + Suffix,
1191 IRB.getVoidTy(), IntptrTy, NULL));
1192 AsanMemoryAccessCallback[AccessIsWrite][AccessSizeIndex] =
1193 checkInterfaceFunction(
1194 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + Suffix,
1195 IRB.getVoidTy(), IntptrTy, NULL));
1198 AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
1199 kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1200 AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
1201 kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1203 AsanMemoryAccessCallbackSized[0] = checkInterfaceFunction(
1204 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "loadN",
1205 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1206 AsanMemoryAccessCallbackSized[1] = checkInterfaceFunction(
1207 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "storeN",
1208 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1210 AsanMemmove = checkInterfaceFunction(M.getOrInsertFunction(
1211 ClMemoryAccessCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
1212 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, NULL));
1213 AsanMemcpy = checkInterfaceFunction(M.getOrInsertFunction(
1214 ClMemoryAccessCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
1215 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, NULL));
1216 AsanMemset = checkInterfaceFunction(M.getOrInsertFunction(
1217 ClMemoryAccessCallbackPrefix + "memset", IRB.getInt8PtrTy(),
1218 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, NULL));
1220 AsanHandleNoReturnFunc = checkInterfaceFunction(
1221 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
1222 AsanCovFunction = checkInterfaceFunction(M.getOrInsertFunction(
1223 kAsanCovName, IRB.getVoidTy(), NULL));
1224 AsanPtrCmpFunction = checkInterfaceFunction(M.getOrInsertFunction(
1225 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1226 AsanPtrSubFunction = checkInterfaceFunction(M.getOrInsertFunction(
1227 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1228 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1229 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1230 StringRef(""), StringRef(""),
1231 /*hasSideEffects=*/true);
1235 bool AddressSanitizer::doInitialization(Module &M) {
1236 // Initialize the private fields. No one has accessed them before.
1237 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1239 report_fatal_error("data layout missing");
1240 DL = &DLP->getDataLayout();
1244 C = &(M.getContext());
1245 LongSize = DL->getPointerSizeInBits();
1246 IntptrTy = Type::getIntNTy(*C, LongSize);
1248 AsanCtorFunction = Function::Create(
1249 FunctionType::get(Type::getVoidTy(*C), false),
1250 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1251 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1252 // call __asan_init in the module ctor.
1253 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1254 AsanInitFunction = checkInterfaceFunction(
1255 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
1256 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1257 IRB.CreateCall(AsanInitFunction);
1259 Mapping = getShadowMapping(M, LongSize);
1261 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
1265 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1266 // For each NSObject descendant having a +load method, this method is invoked
1267 // by the ObjC runtime before any of the static constructors is called.
1268 // Therefore we need to instrument such methods with a call to __asan_init
1269 // at the beginning in order to initialize our runtime before any access to
1270 // the shadow memory.
1271 // We cannot just ignore these methods, because they may call other
1272 // instrumented functions.
1273 if (F.getName().find(" load]") != std::string::npos) {
1274 IRBuilder<> IRB(F.begin()->begin());
1275 IRB.CreateCall(AsanInitFunction);
1281 void AddressSanitizer::InjectCoverageAtBlock(Function &F, BasicBlock &BB) {
1282 BasicBlock::iterator IP = BB.getFirstInsertionPt(), BE = BB.end();
1283 // Skip static allocas at the top of the entry block so they don't become
1284 // dynamic when we split the block. If we used our optimized stack layout,
1285 // then there will only be one alloca and it will come first.
1286 for (; IP != BE; ++IP) {
1287 AllocaInst *AI = dyn_cast<AllocaInst>(IP);
1288 if (!AI || !AI->isStaticAlloca())
1292 DebugLoc EntryLoc = IP->getDebugLoc().getFnDebugLoc(*C);
1293 IRBuilder<> IRB(IP);
1294 IRB.SetCurrentDebugLocation(EntryLoc);
1295 Type *Int8Ty = IRB.getInt8Ty();
1296 GlobalVariable *Guard = new GlobalVariable(
1297 *F.getParent(), Int8Ty, false, GlobalValue::PrivateLinkage,
1298 Constant::getNullValue(Int8Ty), "__asan_gen_cov_" + F.getName());
1299 LoadInst *Load = IRB.CreateLoad(Guard);
1300 Load->setAtomic(Monotonic);
1301 Load->setAlignment(1);
1302 Value *Cmp = IRB.CreateICmpEQ(Constant::getNullValue(Int8Ty), Load);
1303 Instruction *Ins = SplitBlockAndInsertIfThen(
1304 Cmp, IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
1305 IRB.SetInsertPoint(Ins);
1306 IRB.SetCurrentDebugLocation(EntryLoc);
1307 // We pass &F to __sanitizer_cov. We could avoid this and rely on
1308 // GET_CALLER_PC, but having the PC of the first instruction is just nice.
1309 IRB.CreateCall(AsanCovFunction);
1310 StoreInst *Store = IRB.CreateStore(ConstantInt::get(Int8Ty, 1), Guard);
1311 Store->setAtomic(Monotonic);
1312 Store->setAlignment(1);
1315 // Poor man's coverage that works with ASan.
1316 // We create a Guard boolean variable with the same linkage
1317 // as the function and inject this code into the entry block (-asan-coverage=1)
1318 // or all blocks (-asan-coverage=2):
1320 // __sanitizer_cov(&F);
1323 // The accesses to Guard are atomic. The rest of the logic is
1324 // in __sanitizer_cov (it's fine to call it more than once).
1326 // This coverage implementation provides very limited data:
1327 // it only tells if a given function (block) was ever executed.
1328 // No counters, no per-edge data.
1329 // But for many use cases this is what we need and the added slowdown
1330 // is negligible. This simple implementation will probably be obsoleted
1331 // by the upcoming Clang-based coverage implementation.
1332 // By having it here and now we hope to
1333 // a) get the functionality to users earlier and
1334 // b) collect usage statistics to help improve Clang coverage design.
1335 bool AddressSanitizer::InjectCoverage(Function &F,
1336 const ArrayRef<BasicBlock *> AllBlocks) {
1337 if (!ClCoverage) return false;
1339 if (ClCoverage == 1 ||
1340 (unsigned)ClCoverageBlockThreshold < AllBlocks.size()) {
1341 InjectCoverageAtBlock(F, F.getEntryBlock());
1343 for (auto BB : AllBlocks)
1344 InjectCoverageAtBlock(F, *BB);
1349 bool AddressSanitizer::runOnFunction(Function &F) {
1350 if (&F == AsanCtorFunction) return false;
1351 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
1352 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
1353 initializeCallbacks(*F.getParent());
1355 // If needed, insert __asan_init before checking for SanitizeAddress attr.
1356 maybeInsertAsanInitAtFunctionEntry(F);
1358 if (!F.hasFnAttribute(Attribute::SanitizeAddress))
1361 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1364 // We want to instrument every address only once per basic block (unless there
1365 // are calls between uses).
1366 SmallSet<Value*, 16> TempsToInstrument;
1367 SmallVector<Instruction*, 16> ToInstrument;
1368 SmallVector<Instruction*, 8> NoReturnCalls;
1369 SmallVector<BasicBlock*, 16> AllBlocks;
1370 SmallVector<Instruction*, 16> PointerComparisonsOrSubtracts;
1375 // Fill the set of memory operations to instrument.
1376 for (auto &BB : F) {
1377 AllBlocks.push_back(&BB);
1378 TempsToInstrument.clear();
1379 int NumInsnsPerBB = 0;
1380 for (auto &Inst : BB) {
1381 if (LooksLikeCodeInBug11395(&Inst)) return false;
1383 isInterestingMemoryAccess(&Inst, &IsWrite, &Alignment)) {
1384 if (ClOpt && ClOptSameTemp) {
1385 if (!TempsToInstrument.insert(Addr))
1386 continue; // We've seen this temp in the current BB.
1388 } else if (ClInvalidPointerPairs &&
1389 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1390 PointerComparisonsOrSubtracts.push_back(&Inst);
1392 } else if (isa<MemIntrinsic>(Inst)) {
1395 if (isa<AllocaInst>(Inst))
1399 // A call inside BB.
1400 TempsToInstrument.clear();
1401 if (CS.doesNotReturn())
1402 NoReturnCalls.push_back(CS.getInstruction());
1406 ToInstrument.push_back(&Inst);
1408 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1413 Function *UninstrumentedDuplicate = nullptr;
1414 bool LikelyToInstrument =
1415 !NoReturnCalls.empty() || !ToInstrument.empty() || (NumAllocas > 0);
1416 if (ClKeepUninstrumented && LikelyToInstrument) {
1417 ValueToValueMapTy VMap;
1418 UninstrumentedDuplicate = CloneFunction(&F, VMap, false);
1419 UninstrumentedDuplicate->removeFnAttr(Attribute::SanitizeAddress);
1420 UninstrumentedDuplicate->setName("NOASAN_" + F.getName());
1421 F.getParent()->getFunctionList().push_back(UninstrumentedDuplicate);
1424 bool UseCalls = false;
1425 if (ClInstrumentationWithCallsThreshold >= 0 &&
1426 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold)
1430 int NumInstrumented = 0;
1431 for (auto Inst : ToInstrument) {
1432 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1433 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
1434 if (isInterestingMemoryAccess(Inst, &IsWrite, &Alignment))
1435 instrumentMop(Inst, UseCalls);
1437 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
1442 FunctionStackPoisoner FSP(F, *this);
1443 bool ChangedStack = FSP.runOnFunction();
1445 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1446 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1447 for (auto CI : NoReturnCalls) {
1448 IRBuilder<> IRB(CI);
1449 IRB.CreateCall(AsanHandleNoReturnFunc);
1452 for (auto Inst : PointerComparisonsOrSubtracts) {
1453 instrumentPointerComparisonOrSubtraction(Inst);
1457 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
1459 if (InjectCoverage(F, AllBlocks))
1462 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1464 if (ClKeepUninstrumented) {
1466 // No instrumentation is done, no need for the duplicate.
1467 if (UninstrumentedDuplicate)
1468 UninstrumentedDuplicate->eraseFromParent();
1470 // The function was instrumented. We must have the duplicate.
1471 assert(UninstrumentedDuplicate);
1472 UninstrumentedDuplicate->setSection("NOASAN");
1473 assert(!F.hasSection());
1474 F.setSection("ASAN");
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, NULL));
1500 AsanStackFreeFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
1501 kAsanStackFreeNameTemplate + Suffix, IRB.getVoidTy(), IntptrTy,
1502 IntptrTy, IntptrTy, NULL));
1504 AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1505 kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1506 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1507 kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1511 FunctionStackPoisoner::poisonRedZones(const ArrayRef<uint8_t> ShadowBytes,
1512 IRBuilder<> &IRB, Value *ShadowBase,
1514 size_t n = ShadowBytes.size();
1516 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1517 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1518 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1519 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1520 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1521 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1523 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
1524 if (ASan.DL->isLittleEndian())
1525 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1527 Val = (Val << 8) | ShadowBytes[i + j];
1530 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1531 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1532 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1533 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
1538 // Fake stack allocator (asan_fake_stack.h) has 11 size classes
1539 // for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1540 static int StackMallocSizeClass(uint64_t LocalStackSize) {
1541 assert(LocalStackSize <= kMaxStackMallocSize);
1542 uint64_t MaxSize = kMinStackMallocSize;
1543 for (int i = 0; ; i++, MaxSize *= 2)
1544 if (LocalStackSize <= MaxSize)
1546 llvm_unreachable("impossible LocalStackSize");
1549 // Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1550 // We can not use MemSet intrinsic because it may end up calling the actual
1551 // memset. Size is a multiple of 8.
1552 // Currently this generates 8-byte stores on x86_64; it may be better to
1553 // generate wider stores.
1554 void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1555 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1556 assert(!(Size % 8));
1557 assert(kAsanStackAfterReturnMagic == 0xf5);
1558 for (int i = 0; i < Size; i += 8) {
1559 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1560 IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
1561 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1565 static DebugLoc getFunctionEntryDebugLocation(Function &F) {
1566 for (const auto &Inst : F.getEntryBlock())
1567 if (!isa<AllocaInst>(Inst))
1568 return Inst.getDebugLoc();
1572 void FunctionStackPoisoner::poisonStack() {
1573 int StackMallocIdx = -1;
1574 DebugLoc EntryDebugLocation = getFunctionEntryDebugLocation(F);
1576 assert(AllocaVec.size() > 0);
1577 Instruction *InsBefore = AllocaVec[0];
1578 IRBuilder<> IRB(InsBefore);
1579 IRB.SetCurrentDebugLocation(EntryDebugLocation);
1581 SmallVector<ASanStackVariableDescription, 16> SVD;
1582 SVD.reserve(AllocaVec.size());
1583 for (AllocaInst *AI : AllocaVec) {
1584 ASanStackVariableDescription D = { AI->getName().data(),
1585 getAllocaSizeInBytes(AI),
1586 AI->getAlignment(), AI, 0};
1589 // Minimal header size (left redzone) is 4 pointers,
1590 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1591 size_t MinHeaderSize = ASan.LongSize / 2;
1592 ASanStackFrameLayout L;
1593 ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1594 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1595 uint64_t LocalStackSize = L.FrameSize;
1596 bool DoStackMalloc =
1597 ClUseAfterReturn && LocalStackSize <= kMaxStackMallocSize;
1599 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1600 AllocaInst *MyAlloca =
1601 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
1602 MyAlloca->setDebugLoc(EntryDebugLocation);
1603 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1604 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1605 MyAlloca->setAlignment(FrameAlignment);
1606 assert(MyAlloca->isStaticAlloca());
1607 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1608 Value *LocalStackBase = OrigStackBase;
1610 if (DoStackMalloc) {
1611 // LocalStackBase = OrigStackBase
1612 // if (__asan_option_detect_stack_use_after_return)
1613 // LocalStackBase = __asan_stack_malloc_N(LocalStackBase, OrigStackBase);
1614 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1615 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
1616 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1617 kAsanOptionDetectUAR, IRB.getInt32Ty());
1618 Value *Cmp = IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1619 Constant::getNullValue(IRB.getInt32Ty()));
1620 Instruction *Term = SplitBlockAndInsertIfThen(Cmp, InsBefore, false);
1621 BasicBlock *CmpBlock = cast<Instruction>(Cmp)->getParent();
1622 IRBuilder<> IRBIf(Term);
1623 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
1624 LocalStackBase = IRBIf.CreateCall2(
1625 AsanStackMallocFunc[StackMallocIdx],
1626 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1627 BasicBlock *SetBlock = cast<Instruction>(LocalStackBase)->getParent();
1628 IRB.SetInsertPoint(InsBefore);
1629 IRB.SetCurrentDebugLocation(EntryDebugLocation);
1630 PHINode *Phi = IRB.CreatePHI(IntptrTy, 2);
1631 Phi->addIncoming(OrigStackBase, CmpBlock);
1632 Phi->addIncoming(LocalStackBase, SetBlock);
1633 LocalStackBase = Phi;
1636 // Insert poison calls for lifetime intrinsics for alloca.
1637 bool HavePoisonedAllocas = false;
1638 for (const auto &APC : AllocaPoisonCallVec) {
1639 assert(APC.InsBefore);
1641 IRBuilder<> IRB(APC.InsBefore);
1642 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
1643 HavePoisonedAllocas |= APC.DoPoison;
1646 // Replace Alloca instructions with base+offset.
1647 for (const auto &Desc : SVD) {
1648 AllocaInst *AI = Desc.AI;
1649 Value *NewAllocaPtr = IRB.CreateIntToPtr(
1650 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
1652 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
1653 AI->replaceAllUsesWith(NewAllocaPtr);
1656 // The left-most redzone has enough space for at least 4 pointers.
1657 // Write the Magic value to redzone[0].
1658 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1659 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1661 // Write the frame description constant to redzone[1].
1662 Value *BasePlus1 = IRB.CreateIntToPtr(
1663 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
1665 GlobalVariable *StackDescriptionGlobal =
1666 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
1667 /*AllowMerging*/true);
1668 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1670 IRB.CreateStore(Description, BasePlus1);
1671 // Write the PC to redzone[2].
1672 Value *BasePlus2 = IRB.CreateIntToPtr(
1673 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
1674 2 * ASan.LongSize/8)),
1676 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
1678 // Poison the stack redzones at the entry.
1679 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1680 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
1682 // (Un)poison the stack before all ret instructions.
1683 for (auto Ret : RetVec) {
1684 IRBuilder<> IRBRet(Ret);
1685 // Mark the current frame as retired.
1686 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1688 if (DoStackMalloc) {
1689 assert(StackMallocIdx >= 0);
1690 // if LocalStackBase != OrigStackBase:
1691 // // In use-after-return mode, poison the whole stack frame.
1692 // if StackMallocIdx <= 4
1693 // // For small sizes inline the whole thing:
1694 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
1695 // **SavedFlagPtr(LocalStackBase) = 0
1697 // __asan_stack_free_N(LocalStackBase, OrigStackBase)
1699 // <This is not a fake stack; unpoison the redzones>
1700 Value *Cmp = IRBRet.CreateICmpNE(LocalStackBase, OrigStackBase);
1701 TerminatorInst *ThenTerm, *ElseTerm;
1702 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1704 IRBuilder<> IRBPoison(ThenTerm);
1705 if (StackMallocIdx <= 4) {
1706 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1707 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1708 ClassSize >> Mapping.Scale);
1709 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
1711 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1712 Value *SavedFlagPtr = IRBPoison.CreateLoad(
1713 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1714 IRBPoison.CreateStore(
1715 Constant::getNullValue(IRBPoison.getInt8Ty()),
1716 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1718 // For larger frames call __asan_stack_free_*.
1719 IRBPoison.CreateCall3(AsanStackFreeFunc[StackMallocIdx], LocalStackBase,
1720 ConstantInt::get(IntptrTy, LocalStackSize),
1724 IRBuilder<> IRBElse(ElseTerm);
1725 poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
1726 } else if (HavePoisonedAllocas) {
1727 // If we poisoned some allocas in llvm.lifetime analysis,
1728 // unpoison whole stack frame now.
1729 assert(LocalStackBase == OrigStackBase);
1730 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
1732 poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
1736 // We are done. Remove the old unused alloca instructions.
1737 for (auto AI : AllocaVec)
1738 AI->eraseFromParent();
1741 void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
1742 IRBuilder<> &IRB, bool DoPoison) {
1743 // For now just insert the call to ASan runtime.
1744 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1745 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1746 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1747 : AsanUnpoisonStackMemoryFunc,
1751 // Handling llvm.lifetime intrinsics for a given %alloca:
1752 // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1753 // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1754 // invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1755 // could be poisoned by previous llvm.lifetime.end instruction, as the
1756 // variable may go in and out of scope several times, e.g. in loops).
1757 // (3) if we poisoned at least one %alloca in a function,
1758 // unpoison the whole stack frame at function exit.
1760 AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1761 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1762 // We're intested only in allocas we can handle.
1763 return isInterestingAlloca(*AI) ? AI : nullptr;
1764 // See if we've already calculated (or started to calculate) alloca for a
1766 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1767 if (I != AllocaForValue.end())
1769 // Store 0 while we're calculating alloca for value V to avoid
1770 // infinite recursion if the value references itself.
1771 AllocaForValue[V] = nullptr;
1772 AllocaInst *Res = nullptr;
1773 if (CastInst *CI = dyn_cast<CastInst>(V))
1774 Res = findAllocaForValue(CI->getOperand(0));
1775 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1776 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1777 Value *IncValue = PN->getIncomingValue(i);
1778 // Allow self-referencing phi-nodes.
1779 if (IncValue == PN) continue;
1780 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1781 // AI for incoming values should exist and should all be equal.
1782 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
1788 AllocaForValue[V] = Res;