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 #define DEBUG_TYPE "asan"
18 #include "llvm/Transforms/Instrumentation.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DepthFirstIterator.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/IR/CallSite.h"
29 #include "llvm/IR/DIBuilder.h"
30 #include "llvm/IR/DataLayout.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/system_error.h"
45 #include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
46 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
47 #include "llvm/Transforms/Utils/Cloning.h"
48 #include "llvm/Transforms/Utils/Local.h"
49 #include "llvm/Transforms/Utils/ModuleUtils.h"
50 #include "llvm/Transforms/Utils/SpecialCaseList.h"
56 static const uint64_t kDefaultShadowScale = 3;
57 static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
58 static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
59 static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
60 static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
61 static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa8000;
62 static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
63 static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
65 static const size_t kMinStackMallocSize = 1 << 6; // 64B
66 static const size_t kMaxStackMallocSize = 1 << 16; // 64K
67 static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
68 static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
70 static const char *const kAsanModuleCtorName = "asan.module_ctor";
71 static const char *const kAsanModuleDtorName = "asan.module_dtor";
72 static const int kAsanCtorAndCtorPriority = 1;
73 static const char *const kAsanReportErrorTemplate = "__asan_report_";
74 static const char *const kAsanReportLoadN = "__asan_report_load_n";
75 static const char *const kAsanReportStoreN = "__asan_report_store_n";
76 static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
77 static const char *const kAsanUnregisterGlobalsName =
78 "__asan_unregister_globals";
79 static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
80 static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
81 static const char *const kAsanInitName = "__asan_init_v3";
82 static const char *const kAsanCovName = "__sanitizer_cov";
83 static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
84 static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
85 static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
86 static const int kMaxAsanStackMallocSizeClass = 10;
87 static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
88 static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
89 static const char *const kAsanGenPrefix = "__asan_gen_";
90 static const char *const kAsanPoisonStackMemoryName =
91 "__asan_poison_stack_memory";
92 static const char *const kAsanUnpoisonStackMemoryName =
93 "__asan_unpoison_stack_memory";
95 static const char *const kAsanOptionDetectUAR =
96 "__asan_option_detect_stack_use_after_return";
99 static const int kAsanStackAfterReturnMagic = 0xf5;
102 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
103 static const size_t kNumberOfAccessSizes = 5;
105 // Command-line flags.
107 // This flag may need to be replaced with -f[no-]asan-reads.
108 static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
109 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
110 static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
111 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
112 static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
113 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
114 cl::Hidden, cl::init(true));
115 static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
116 cl::desc("use instrumentation with slow path for all accesses"),
117 cl::Hidden, cl::init(false));
118 // This flag limits the number of instructions to be instrumented
119 // in any given BB. Normally, this should be set to unlimited (INT_MAX),
120 // but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
122 static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
124 cl::desc("maximal number of instructions to instrument in any given BB"),
126 // This flag may need to be replaced with -f[no]asan-stack.
127 static cl::opt<bool> ClStack("asan-stack",
128 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
129 // This flag may need to be replaced with -f[no]asan-use-after-return.
130 static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
131 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
132 // This flag may need to be replaced with -f[no]asan-globals.
133 static cl::opt<bool> ClGlobals("asan-globals",
134 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
135 static cl::opt<int> ClCoverage("asan-coverage",
136 cl::desc("ASan coverage. 0: none, 1: entry block, 2: all blocks"),
137 cl::Hidden, cl::init(false));
138 static cl::opt<bool> ClInitializers("asan-initialization-order",
139 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
140 static cl::opt<bool> ClMemIntrin("asan-memintrin",
141 cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
142 static cl::opt<bool> ClInvalidPointerPairs("asan-detect-invalid-pointer-pair",
143 cl::desc("Instrument <, <=, >, >=, - with pointer operands"),
144 cl::Hidden, cl::init(false));
145 static cl::opt<unsigned> ClRealignStack("asan-realign-stack",
146 cl::desc("Realign stack to the value of this flag (power of two)"),
147 cl::Hidden, cl::init(32));
148 static cl::opt<std::string> ClBlacklistFile("asan-blacklist",
149 cl::desc("File containing the list of objects to ignore "
150 "during instrumentation"), cl::Hidden);
152 // This is an experimental feature that will allow to choose between
153 // instrumented and non-instrumented code at link-time.
154 // If this option is on, just before instrumenting a function we create its
155 // clone; if the function is not changed by asan the clone is deleted.
156 // If we end up with a clone, we put the instrumented function into a section
157 // called "ASAN" and the uninstrumented function into a section called "NOASAN".
159 // This is still a prototype, we need to figure out a way to keep two copies of
160 // a function so that the linker can easily choose one of them.
161 static cl::opt<bool> ClKeepUninstrumented("asan-keep-uninstrumented-functions",
162 cl::desc("Keep uninstrumented copies of functions"),
163 cl::Hidden, cl::init(false));
165 // These flags allow to change the shadow mapping.
166 // The shadow mapping looks like
167 // Shadow = (Mem >> scale) + (1 << offset_log)
168 static cl::opt<int> ClMappingScale("asan-mapping-scale",
169 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
171 // Optimization flags. Not user visible, used mostly for testing
172 // and benchmarking the tool.
173 static cl::opt<bool> ClOpt("asan-opt",
174 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
175 static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
176 cl::desc("Instrument the same temp just once"), cl::Hidden,
178 static cl::opt<bool> ClOptGlobals("asan-opt-globals",
179 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
181 static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
182 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
183 cl::Hidden, cl::init(false));
186 static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
188 static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
189 cl::Hidden, cl::init(0));
190 static cl::opt<std::string> ClDebugFunc("asan-debug-func",
191 cl::Hidden, cl::desc("Debug func"));
192 static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
193 cl::Hidden, cl::init(-1));
194 static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
195 cl::Hidden, cl::init(-1));
197 STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
198 STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
199 STATISTIC(NumOptimizedAccessesToGlobalArray,
200 "Number of optimized accesses to global arrays");
201 STATISTIC(NumOptimizedAccessesToGlobalVar,
202 "Number of optimized accesses to global vars");
205 /// A set of dynamically initialized globals extracted from metadata.
206 class SetOfDynamicallyInitializedGlobals {
208 void Init(Module& M) {
209 // Clang generates metadata identifying all dynamically initialized globals.
210 NamedMDNode *DynamicGlobals =
211 M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
214 for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
215 MDNode *MDN = DynamicGlobals->getOperand(i);
216 assert(MDN->getNumOperands() == 1);
217 Value *VG = MDN->getOperand(0);
218 // The optimizer may optimize away a global entirely, in which case we
219 // cannot instrument access to it.
222 DynInitGlobals.insert(cast<GlobalVariable>(VG));
225 bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
227 SmallSet<GlobalValue*, 32> DynInitGlobals;
230 /// This struct defines the shadow mapping using the rule:
231 /// shadow = (mem >> Scale) ADD-or-OR Offset.
232 struct ShadowMapping {
238 static ShadowMapping getShadowMapping(const Module &M, int LongSize) {
239 llvm::Triple TargetTriple(M.getTargetTriple());
240 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
241 // bool IsMacOSX = TargetTriple.getOS() == llvm::Triple::MacOSX;
242 bool IsFreeBSD = TargetTriple.getOS() == llvm::Triple::FreeBSD;
243 bool IsLinux = TargetTriple.getOS() == llvm::Triple::Linux;
244 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
245 TargetTriple.getArch() == llvm::Triple::ppc64le;
246 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
247 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
248 TargetTriple.getArch() == llvm::Triple::mipsel;
250 ShadowMapping Mapping;
252 if (LongSize == 32) {
256 Mapping.Offset = kMIPS32_ShadowOffset32;
258 Mapping.Offset = kFreeBSD_ShadowOffset32;
260 Mapping.Offset = kDefaultShadowOffset32;
261 } else { // LongSize == 64
263 Mapping.Offset = kPPC64_ShadowOffset64;
265 Mapping.Offset = kFreeBSD_ShadowOffset64;
266 else if (IsLinux && IsX86_64)
267 Mapping.Offset = kSmallX86_64ShadowOffset;
269 Mapping.Offset = kDefaultShadowOffset64;
272 Mapping.Scale = kDefaultShadowScale;
273 if (ClMappingScale) {
274 Mapping.Scale = ClMappingScale;
277 // OR-ing shadow offset if more efficient (at least on x86) if the offset
278 // is a power of two, but on ppc64 we have to use add since the shadow
279 // offset is not necessary 1/8-th of the address space.
280 Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
285 static size_t RedzoneSizeForScale(int MappingScale) {
286 // Redzone used for stack and globals is at least 32 bytes.
287 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
288 return std::max(32U, 1U << MappingScale);
291 /// AddressSanitizer: instrument the code in module to find memory bugs.
292 struct AddressSanitizer : public FunctionPass {
293 AddressSanitizer(bool CheckInitOrder = true,
294 bool CheckUseAfterReturn = false,
295 bool CheckLifetime = false,
296 StringRef BlacklistFile = StringRef())
298 CheckInitOrder(CheckInitOrder || ClInitializers),
299 CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
300 CheckLifetime(CheckLifetime || ClCheckLifetime),
301 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
303 const char *getPassName() const override {
304 return "AddressSanitizerFunctionPass";
306 void instrumentMop(Instruction *I);
307 void instrumentPointerComparisonOrSubtraction(Instruction *I);
308 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
309 Value *Addr, uint32_t TypeSize, bool IsWrite,
310 Value *SizeArgument);
311 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
312 Value *ShadowValue, uint32_t TypeSize);
313 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
314 bool IsWrite, size_t AccessSizeIndex,
315 Value *SizeArgument);
316 bool instrumentMemIntrinsic(MemIntrinsic *MI);
317 void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
319 Instruction *InsertBefore, bool IsWrite);
320 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
321 bool runOnFunction(Function &F) override;
322 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
323 bool doInitialization(Module &M) override;
324 static char ID; // Pass identification, replacement for typeid
327 void initializeCallbacks(Module &M);
329 bool ShouldInstrumentGlobal(GlobalVariable *G);
330 bool LooksLikeCodeInBug11395(Instruction *I);
331 void FindDynamicInitializers(Module &M);
332 bool GlobalIsLinkerInitialized(GlobalVariable *G);
333 bool InjectCoverage(Function &F, const ArrayRef<BasicBlock*> AllBlocks);
334 void InjectCoverageAtBlock(Function &F, BasicBlock &BB);
337 bool CheckUseAfterReturn;
339 SmallString<64> BlacklistFile;
342 const DataLayout *DL;
345 ShadowMapping Mapping;
346 Function *AsanCtorFunction;
347 Function *AsanInitFunction;
348 Function *AsanHandleNoReturnFunc;
349 Function *AsanCovFunction;
350 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
351 std::unique_ptr<SpecialCaseList> BL;
352 // This array is indexed by AccessIsWrite and log2(AccessSize).
353 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
354 // This array is indexed by AccessIsWrite.
355 Function *AsanErrorCallbackSized[2];
357 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
359 friend struct FunctionStackPoisoner;
362 class AddressSanitizerModule : public ModulePass {
364 AddressSanitizerModule(bool CheckInitOrder = true,
365 StringRef BlacklistFile = StringRef())
367 CheckInitOrder(CheckInitOrder || ClInitializers),
368 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
370 bool runOnModule(Module &M) override;
371 static char ID; // Pass identification, replacement for typeid
372 const char *getPassName() const override {
373 return "AddressSanitizerModule";
377 void initializeCallbacks(Module &M);
379 bool ShouldInstrumentGlobal(GlobalVariable *G);
380 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
381 size_t MinRedzoneSizeForGlobal() const {
382 return RedzoneSizeForScale(Mapping.Scale);
386 SmallString<64> BlacklistFile;
388 std::unique_ptr<SpecialCaseList> BL;
389 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
392 const DataLayout *DL;
393 ShadowMapping Mapping;
394 Function *AsanPoisonGlobals;
395 Function *AsanUnpoisonGlobals;
396 Function *AsanRegisterGlobals;
397 Function *AsanUnregisterGlobals;
400 // Stack poisoning does not play well with exception handling.
401 // When an exception is thrown, we essentially bypass the code
402 // that unpoisones the stack. This is why the run-time library has
403 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
404 // stack in the interceptor. This however does not work inside the
405 // actual function which catches the exception. Most likely because the
406 // compiler hoists the load of the shadow value somewhere too high.
407 // This causes asan to report a non-existing bug on 453.povray.
408 // It sounds like an LLVM bug.
409 struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
411 AddressSanitizer &ASan;
416 ShadowMapping Mapping;
418 SmallVector<AllocaInst*, 16> AllocaVec;
419 SmallVector<Instruction*, 8> RetVec;
420 unsigned StackAlignment;
422 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
423 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
424 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
426 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
427 struct AllocaPoisonCall {
428 IntrinsicInst *InsBefore;
433 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
435 // Maps Value to an AllocaInst from which the Value is originated.
436 typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
437 AllocaForValueMapTy AllocaForValue;
439 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
440 : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
441 IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
442 Mapping(ASan.Mapping),
443 StackAlignment(1 << Mapping.Scale) {}
445 bool runOnFunction() {
446 if (!ClStack) return false;
447 // Collect alloca, ret, lifetime instructions etc.
448 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
449 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
450 BasicBlock *BB = *DI;
453 if (AllocaVec.empty()) return false;
455 initializeCallbacks(*F.getParent());
465 // Finds all static Alloca instructions and puts
466 // poisoned red zones around all of them.
467 // Then unpoison everything back before the function returns.
470 // ----------------------- Visitors.
471 /// \brief Collect all Ret instructions.
472 void visitReturnInst(ReturnInst &RI) {
473 RetVec.push_back(&RI);
476 /// \brief Collect Alloca instructions we want (and can) handle.
477 void visitAllocaInst(AllocaInst &AI) {
478 if (!isInterestingAlloca(AI)) return;
480 StackAlignment = std::max(StackAlignment, AI.getAlignment());
481 AllocaVec.push_back(&AI);
484 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
486 void visitIntrinsicInst(IntrinsicInst &II) {
487 if (!ASan.CheckLifetime) return;
488 Intrinsic::ID ID = II.getIntrinsicID();
489 if (ID != Intrinsic::lifetime_start &&
490 ID != Intrinsic::lifetime_end)
492 // Found lifetime intrinsic, add ASan instrumentation if necessary.
493 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
494 // If size argument is undefined, don't do anything.
495 if (Size->isMinusOne()) return;
496 // Check that size doesn't saturate uint64_t and can
497 // be stored in IntptrTy.
498 const uint64_t SizeValue = Size->getValue().getLimitedValue();
499 if (SizeValue == ~0ULL ||
500 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
502 // Find alloca instruction that corresponds to llvm.lifetime argument.
503 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
505 bool DoPoison = (ID == Intrinsic::lifetime_end);
506 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
507 AllocaPoisonCallVec.push_back(APC);
510 // ---------------------- Helpers.
511 void initializeCallbacks(Module &M);
513 // Check if we want (and can) handle this alloca.
514 bool isInterestingAlloca(AllocaInst &AI) const {
515 return (!AI.isArrayAllocation() && AI.isStaticAlloca() &&
516 AI.getAllocatedType()->isSized() &&
517 // alloca() may be called with 0 size, ignore it.
518 getAllocaSizeInBytes(&AI) > 0);
521 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
522 Type *Ty = AI->getAllocatedType();
523 uint64_t SizeInBytes = ASan.DL->getTypeAllocSize(Ty);
526 /// Finds alloca where the value comes from.
527 AllocaInst *findAllocaForValue(Value *V);
528 void poisonRedZones(const ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
529 Value *ShadowBase, bool DoPoison);
530 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
532 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
538 char AddressSanitizer::ID = 0;
539 INITIALIZE_PASS(AddressSanitizer, "asan",
540 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
542 FunctionPass *llvm::createAddressSanitizerFunctionPass(
543 bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime,
544 StringRef BlacklistFile) {
545 return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
546 CheckLifetime, BlacklistFile);
549 char AddressSanitizerModule::ID = 0;
550 INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
551 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
552 "ModulePass", false, false)
553 ModulePass *llvm::createAddressSanitizerModulePass(
554 bool CheckInitOrder, StringRef BlacklistFile) {
555 return new AddressSanitizerModule(CheckInitOrder, BlacklistFile);
558 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
559 size_t Res = countTrailingZeros(TypeSize / 8);
560 assert(Res < kNumberOfAccessSizes);
564 // \brief Create a constant for Str so that we can pass it to the run-time lib.
565 static GlobalVariable *createPrivateGlobalForString(
566 Module &M, StringRef Str, bool AllowMerging) {
567 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
568 // We use private linkage for module-local strings. If they can be merged
569 // with another one, we set the unnamed_addr attribute.
571 new GlobalVariable(M, StrConst->getType(), true,
572 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
574 GV->setUnnamedAddr(true);
575 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
579 static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
580 return G->getName().find(kAsanGenPrefix) == 0;
583 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
585 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
586 if (Mapping.Offset == 0)
588 // (Shadow >> scale) | offset
589 if (Mapping.OrShadowOffset)
590 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
592 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
595 void AddressSanitizer::instrumentMemIntrinsicParam(
596 Instruction *OrigIns,
597 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
598 IRBuilder<> IRB(InsertBefore);
599 if (Size->getType() != IntptrTy)
600 Size = IRB.CreateIntCast(Size, IntptrTy, false);
601 // Check the first byte.
602 instrumentAddress(OrigIns, InsertBefore, Addr, 8, IsWrite, Size);
603 // Check the last byte.
604 IRB.SetInsertPoint(InsertBefore);
605 Value *SizeMinusOne = IRB.CreateSub(Size, ConstantInt::get(IntptrTy, 1));
606 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
607 Value *AddrLast = IRB.CreateAdd(AddrLong, SizeMinusOne);
608 instrumentAddress(OrigIns, InsertBefore, AddrLast, 8, IsWrite, Size);
611 // Instrument memset/memmove/memcpy
612 bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
613 Value *Dst = MI->getDest();
614 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
615 Value *Src = MemTran ? MemTran->getSource() : 0;
616 Value *Length = MI->getLength();
618 Constant *ConstLength = dyn_cast<Constant>(Length);
619 Instruction *InsertBefore = MI;
621 if (ConstLength->isNullValue()) return false;
623 // The size is not a constant so it could be zero -- check at run-time.
624 IRBuilder<> IRB(InsertBefore);
626 Value *Cmp = IRB.CreateICmpNE(Length,
627 Constant::getNullValue(Length->getType()));
628 InsertBefore = SplitBlockAndInsertIfThen(Cmp, InsertBefore, false);
631 instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
633 instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
637 // If I is an interesting memory access, return the PointerOperand
638 // and set IsWrite. Otherwise return NULL.
639 static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
640 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
641 if (!ClInstrumentReads) return NULL;
643 return LI->getPointerOperand();
645 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
646 if (!ClInstrumentWrites) return NULL;
648 return SI->getPointerOperand();
650 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
651 if (!ClInstrumentAtomics) return NULL;
653 return RMW->getPointerOperand();
655 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
656 if (!ClInstrumentAtomics) return NULL;
658 return XCHG->getPointerOperand();
663 static bool isPointerOperand(Value *V) {
664 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
667 // This is a rough heuristic; it may cause both false positives and
668 // false negatives. The proper implementation requires cooperation with
670 static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
671 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
672 if (!Cmp->isRelational())
674 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
675 if (BO->getOpcode() != Instruction::Sub)
680 if (!isPointerOperand(I->getOperand(0)) ||
681 !isPointerOperand(I->getOperand(1)))
686 bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
687 // If a global variable does not have dynamic initialization we don't
688 // have to instrument it. However, if a global does not have initializer
689 // at all, we assume it has dynamic initializer (in other TU).
690 return G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G);
694 AddressSanitizer::instrumentPointerComparisonOrSubtraction(Instruction *I) {
696 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
697 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
698 for (int i = 0; i < 2; i++) {
699 if (Param[i]->getType()->isPointerTy())
700 Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
702 IRB.CreateCall2(F, Param[0], Param[1]);
705 void AddressSanitizer::instrumentMop(Instruction *I) {
706 bool IsWrite = false;
707 Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
709 if (ClOpt && ClOptGlobals) {
710 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
711 // If initialization order checking is disabled, a simple access to a
712 // dynamically initialized global is always valid.
713 if (!CheckInitOrder || GlobalIsLinkerInitialized(G)) {
714 NumOptimizedAccessesToGlobalVar++;
718 ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr);
719 if (CE && CE->isGEPWithNoNotionalOverIndexing()) {
720 if (GlobalVariable *G = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
721 if (CE->getOperand(1)->isNullValue() && GlobalIsLinkerInitialized(G)) {
722 NumOptimizedAccessesToGlobalArray++;
729 Type *OrigPtrTy = Addr->getType();
730 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
732 assert(OrigTy->isSized());
733 uint32_t TypeSize = DL->getTypeStoreSizeInBits(OrigTy);
735 assert((TypeSize % 8) == 0);
738 NumInstrumentedWrites++;
740 NumInstrumentedReads++;
742 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check.
743 if (TypeSize == 8 || TypeSize == 16 ||
744 TypeSize == 32 || TypeSize == 64 || TypeSize == 128)
745 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, 0);
746 // Instrument unusual size (but still multiple of 8).
747 // We can not do it with a single check, so we do 1-byte check for the first
748 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
749 // to report the actual access size.
751 Value *LastByte = IRB.CreateIntToPtr(
752 IRB.CreateAdd(IRB.CreatePointerCast(Addr, IntptrTy),
753 ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
755 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
756 instrumentAddress(I, I, Addr, 8, IsWrite, Size);
757 instrumentAddress(I, I, LastByte, 8, IsWrite, Size);
760 // Validate the result of Module::getOrInsertFunction called for an interface
761 // function of AddressSanitizer. If the instrumented module defines a function
762 // with the same name, their prototypes must match, otherwise
763 // getOrInsertFunction returns a bitcast.
764 static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
765 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
766 FuncOrBitcast->dump();
767 report_fatal_error("trying to redefine an AddressSanitizer "
768 "interface function");
771 Instruction *AddressSanitizer::generateCrashCode(
772 Instruction *InsertBefore, Value *Addr,
773 bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
774 IRBuilder<> IRB(InsertBefore);
775 CallInst *Call = SizeArgument
776 ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
777 : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
779 // We don't do Call->setDoesNotReturn() because the BB already has
780 // UnreachableInst at the end.
781 // This EmptyAsm is required to avoid callback merge.
782 IRB.CreateCall(EmptyAsm);
786 Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
789 size_t Granularity = 1 << Mapping.Scale;
790 // Addr & (Granularity - 1)
791 Value *LastAccessedByte = IRB.CreateAnd(
792 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
793 // (Addr & (Granularity - 1)) + size - 1
794 if (TypeSize / 8 > 1)
795 LastAccessedByte = IRB.CreateAdd(
796 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
797 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
798 LastAccessedByte = IRB.CreateIntCast(
799 LastAccessedByte, ShadowValue->getType(), false);
800 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
801 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
804 void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
805 Instruction *InsertBefore,
806 Value *Addr, uint32_t TypeSize,
807 bool IsWrite, Value *SizeArgument) {
808 IRBuilder<> IRB(InsertBefore);
809 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
811 Type *ShadowTy = IntegerType::get(
812 *C, std::max(8U, TypeSize >> Mapping.Scale));
813 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
814 Value *ShadowPtr = memToShadow(AddrLong, IRB);
815 Value *CmpVal = Constant::getNullValue(ShadowTy);
816 Value *ShadowValue = IRB.CreateLoad(
817 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
819 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
820 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
821 size_t Granularity = 1 << Mapping.Scale;
822 TerminatorInst *CrashTerm = 0;
824 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
825 TerminatorInst *CheckTerm =
826 SplitBlockAndInsertIfThen(Cmp, InsertBefore, false);
827 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
828 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
829 IRB.SetInsertPoint(CheckTerm);
830 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
831 BasicBlock *CrashBlock =
832 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
833 CrashTerm = new UnreachableInst(*C, CrashBlock);
834 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
835 ReplaceInstWithInst(CheckTerm, NewTerm);
837 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
840 Instruction *Crash = generateCrashCode(
841 CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
842 Crash->setDebugLoc(OrigIns->getDebugLoc());
845 void AddressSanitizerModule::createInitializerPoisonCalls(
846 Module &M, GlobalValue *ModuleName) {
847 // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
848 Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
849 // If that function is not present, this TU contains no globals, or they have
850 // all been optimized away
854 // Set up the arguments to our poison/unpoison functions.
855 IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
857 // Add a call to poison all external globals before the given function starts.
858 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
859 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
861 // Add calls to unpoison all globals before each return instruction.
862 for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
864 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
865 CallInst::Create(AsanUnpoisonGlobals, "", RI);
870 bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
871 Type *Ty = cast<PointerType>(G->getType())->getElementType();
872 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
874 if (BL->isIn(*G)) return false;
875 if (!Ty->isSized()) return false;
876 if (!G->hasInitializer()) return false;
877 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
878 // Touch only those globals that will not be defined in other modules.
879 // Don't handle ODR type linkages since other modules may be built w/o asan.
880 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
881 G->getLinkage() != GlobalVariable::PrivateLinkage &&
882 G->getLinkage() != GlobalVariable::InternalLinkage)
884 // Two problems with thread-locals:
885 // - The address of the main thread's copy can't be computed at link-time.
886 // - Need to poison all copies, not just the main thread's one.
887 if (G->isThreadLocal())
889 // For now, just ignore this Global if the alignment is large.
890 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
892 // Ignore all the globals with the names starting with "\01L_OBJC_".
893 // Many of those are put into the .cstring section. The linker compresses
894 // that section by removing the spare \0s after the string terminator, so
895 // our redzones get broken.
896 if ((G->getName().find("\01L_OBJC_") == 0) ||
897 (G->getName().find("\01l_OBJC_") == 0)) {
898 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
902 if (G->hasSection()) {
903 StringRef Section(G->getSection());
904 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
905 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
907 if ((Section.find("__OBJC,") == 0) ||
908 (Section.find("__DATA, __objc_") == 0)) {
909 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
912 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
913 // Constant CFString instances are compiled in the following way:
914 // -- the string buffer is emitted into
915 // __TEXT,__cstring,cstring_literals
916 // -- the constant NSConstantString structure referencing that buffer
917 // is placed into __DATA,__cfstring
918 // Therefore there's no point in placing redzones into __DATA,__cfstring.
919 // Moreover, it causes the linker to crash on OS X 10.7
920 if (Section.find("__DATA,__cfstring") == 0) {
921 DEBUG(dbgs() << "Ignoring CFString: " << *G);
929 void AddressSanitizerModule::initializeCallbacks(Module &M) {
931 // Declare our poisoning and unpoisoning functions.
932 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
933 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, NULL));
934 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
935 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
936 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
937 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
938 // Declare functions that register/unregister globals.
939 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
940 kAsanRegisterGlobalsName, IRB.getVoidTy(),
941 IntptrTy, IntptrTy, NULL));
942 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
943 AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
944 kAsanUnregisterGlobalsName,
945 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
946 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
949 // This function replaces all global variables with new variables that have
950 // trailing redzones. It also creates a function that poisons
951 // redzones and inserts this function into llvm.global_ctors.
952 bool AddressSanitizerModule::runOnModule(Module &M) {
953 if (!ClGlobals) return false;
955 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
958 DL = &DLP->getDataLayout();
960 BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
961 if (BL->isIn(M)) return false;
962 C = &(M.getContext());
963 int LongSize = DL->getPointerSizeInBits();
964 IntptrTy = Type::getIntNTy(*C, LongSize);
965 Mapping = getShadowMapping(M, LongSize);
966 initializeCallbacks(M);
967 DynamicallyInitializedGlobals.Init(M);
969 SmallVector<GlobalVariable *, 16> GlobalsToChange;
971 for (Module::GlobalListType::iterator G = M.global_begin(),
972 E = M.global_end(); G != E; ++G) {
973 if (ShouldInstrumentGlobal(G))
974 GlobalsToChange.push_back(G);
977 size_t n = GlobalsToChange.size();
978 if (n == 0) return false;
980 // A global is described by a structure
983 // size_t size_with_redzone;
985 // const char *module_name;
986 // size_t has_dynamic_init;
987 // We initialize an array of such structures and pass it to a run-time call.
988 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
990 IntptrTy, IntptrTy, NULL);
991 SmallVector<Constant *, 16> Initializers(n);
993 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
995 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
997 bool HasDynamicallyInitializedGlobals = false;
999 // We shouldn't merge same module names, as this string serves as unique
1000 // module ID in runtime.
1001 GlobalVariable *ModuleName = createPrivateGlobalForString(
1002 M, M.getModuleIdentifier(), /*AllowMerging*/false);
1004 for (size_t i = 0; i < n; i++) {
1005 static const uint64_t kMaxGlobalRedzone = 1 << 18;
1006 GlobalVariable *G = GlobalsToChange[i];
1007 PointerType *PtrTy = cast<PointerType>(G->getType());
1008 Type *Ty = PtrTy->getElementType();
1009 uint64_t SizeInBytes = DL->getTypeAllocSize(Ty);
1010 uint64_t MinRZ = MinRedzoneSizeForGlobal();
1011 // MinRZ <= RZ <= kMaxGlobalRedzone
1012 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
1013 uint64_t RZ = std::max(MinRZ,
1014 std::min(kMaxGlobalRedzone,
1015 (SizeInBytes / MinRZ / 4) * MinRZ));
1016 uint64_t RightRedzoneSize = RZ;
1017 // Round up to MinRZ
1018 if (SizeInBytes % MinRZ)
1019 RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
1020 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
1021 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1022 // Determine whether this global should be poisoned in initialization.
1023 bool GlobalHasDynamicInitializer =
1024 DynamicallyInitializedGlobals.Contains(G);
1025 // Don't check initialization order if this global is blacklisted.
1026 GlobalHasDynamicInitializer &= !BL->isIn(*G, "init");
1028 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
1029 Constant *NewInitializer = ConstantStruct::get(
1030 NewTy, G->getInitializer(),
1031 Constant::getNullValue(RightRedZoneTy), NULL);
1033 GlobalVariable *Name =
1034 createPrivateGlobalForString(M, G->getName(), /*AllowMerging*/true);
1036 // Create a new global variable with enough space for a redzone.
1037 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1038 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1039 Linkage = GlobalValue::InternalLinkage;
1040 GlobalVariable *NewGlobal = new GlobalVariable(
1041 M, NewTy, G->isConstant(), Linkage,
1042 NewInitializer, "", G, G->getThreadLocalMode());
1043 NewGlobal->copyAttributesFrom(G);
1044 NewGlobal->setAlignment(MinRZ);
1047 Indices2[0] = IRB.getInt32(0);
1048 Indices2[1] = IRB.getInt32(0);
1050 G->replaceAllUsesWith(
1051 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
1052 NewGlobal->takeName(G);
1053 G->eraseFromParent();
1055 Initializers[i] = ConstantStruct::get(
1057 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
1058 ConstantInt::get(IntptrTy, SizeInBytes),
1059 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1060 ConstantExpr::getPointerCast(Name, IntptrTy),
1061 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
1062 ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
1065 // Populate the first and last globals declared in this TU.
1066 if (CheckInitOrder && GlobalHasDynamicInitializer)
1067 HasDynamicallyInitializedGlobals = true;
1069 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
1072 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1073 GlobalVariable *AllGlobals = new GlobalVariable(
1074 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1075 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1077 // Create calls for poisoning before initializers run and unpoisoning after.
1078 if (CheckInitOrder && HasDynamicallyInitializedGlobals)
1079 createInitializerPoisonCalls(M, ModuleName);
1080 IRB.CreateCall2(AsanRegisterGlobals,
1081 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1082 ConstantInt::get(IntptrTy, n));
1084 // We also need to unregister globals at the end, e.g. when a shared library
1086 Function *AsanDtorFunction = Function::Create(
1087 FunctionType::get(Type::getVoidTy(*C), false),
1088 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1089 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1090 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
1091 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
1092 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1093 ConstantInt::get(IntptrTy, n));
1094 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
1100 void AddressSanitizer::initializeCallbacks(Module &M) {
1101 IRBuilder<> IRB(*C);
1102 // Create __asan_report* callbacks.
1103 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1104 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1105 AccessSizeIndex++) {
1106 // IsWrite and TypeSize are encoded in the function name.
1107 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
1108 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
1109 // If we are merging crash callbacks, they have two parameters.
1110 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
1111 checkInterfaceFunction(M.getOrInsertFunction(
1112 FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
1115 AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
1116 kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1117 AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
1118 kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1120 AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
1121 kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
1122 AsanCovFunction = checkInterfaceFunction(M.getOrInsertFunction(
1123 kAsanCovName, IRB.getVoidTy(), NULL));
1124 AsanPtrCmpFunction = checkInterfaceFunction(M.getOrInsertFunction(
1125 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1126 AsanPtrSubFunction = checkInterfaceFunction(M.getOrInsertFunction(
1127 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1128 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1129 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1130 StringRef(""), StringRef(""),
1131 /*hasSideEffects=*/true);
1135 bool AddressSanitizer::doInitialization(Module &M) {
1136 // Initialize the private fields. No one has accessed them before.
1137 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1140 DL = &DLP->getDataLayout();
1142 BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
1143 DynamicallyInitializedGlobals.Init(M);
1145 C = &(M.getContext());
1146 LongSize = DL->getPointerSizeInBits();
1147 IntptrTy = Type::getIntNTy(*C, LongSize);
1149 AsanCtorFunction = Function::Create(
1150 FunctionType::get(Type::getVoidTy(*C), false),
1151 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1152 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1153 // call __asan_init in the module ctor.
1154 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1155 AsanInitFunction = checkInterfaceFunction(
1156 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
1157 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1158 IRB.CreateCall(AsanInitFunction);
1160 Mapping = getShadowMapping(M, LongSize);
1162 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
1166 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1167 // For each NSObject descendant having a +load method, this method is invoked
1168 // by the ObjC runtime before any of the static constructors is called.
1169 // Therefore we need to instrument such methods with a call to __asan_init
1170 // at the beginning in order to initialize our runtime before any access to
1171 // the shadow memory.
1172 // We cannot just ignore these methods, because they may call other
1173 // instrumented functions.
1174 if (F.getName().find(" load]") != std::string::npos) {
1175 IRBuilder<> IRB(F.begin()->begin());
1176 IRB.CreateCall(AsanInitFunction);
1182 void AddressSanitizer::InjectCoverageAtBlock(Function &F, BasicBlock &BB) {
1183 BasicBlock::iterator IP = BB.getFirstInsertionPt(), BE = BB.end();
1184 // Skip static allocas at the top of the entry block so they don't become
1185 // dynamic when we split the block. If we used our optimized stack layout,
1186 // then there will only be one alloca and it will come first.
1187 for (; IP != BE; ++IP) {
1188 AllocaInst *AI = dyn_cast<AllocaInst>(IP);
1189 if (!AI || !AI->isStaticAlloca())
1193 IRBuilder<> IRB(IP);
1194 Type *Int8Ty = IRB.getInt8Ty();
1195 GlobalVariable *Guard = new GlobalVariable(
1196 *F.getParent(), Int8Ty, false, GlobalValue::PrivateLinkage,
1197 Constant::getNullValue(Int8Ty), "__asan_gen_cov_" + F.getName());
1198 LoadInst *Load = IRB.CreateLoad(Guard);
1199 Load->setAtomic(Monotonic);
1200 Load->setAlignment(1);
1201 Value *Cmp = IRB.CreateICmpEQ(Constant::getNullValue(Int8Ty), Load);
1202 Instruction *Ins = SplitBlockAndInsertIfThen(
1203 Cmp, IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
1204 IRB.SetInsertPoint(Ins);
1205 // We pass &F to __sanitizer_cov. We could avoid this and rely on
1206 // GET_CALLER_PC, but having the PC of the first instruction is just nice.
1207 Instruction *Call = IRB.CreateCall(AsanCovFunction);
1208 Call->setDebugLoc(IP->getDebugLoc());
1209 StoreInst *Store = IRB.CreateStore(ConstantInt::get(Int8Ty, 1), Guard);
1210 Store->setAtomic(Monotonic);
1211 Store->setAlignment(1);
1214 // Poor man's coverage that works with ASan.
1215 // We create a Guard boolean variable with the same linkage
1216 // as the function and inject this code into the entry block (-asan-coverage=1)
1217 // or all blocks (-asan-coverage=2):
1219 // __sanitizer_cov(&F);
1222 // The accesses to Guard are atomic. The rest of the logic is
1223 // in __sanitizer_cov (it's fine to call it more than once).
1225 // This coverage implementation provides very limited data:
1226 // it only tells if a given function (block) was ever executed.
1227 // No counters, no per-edge data.
1228 // But for many use cases this is what we need and the added slowdown
1229 // is negligible. This simple implementation will probably be obsoleted
1230 // by the upcoming Clang-based coverage implementation.
1231 // By having it here and now we hope to
1232 // a) get the functionality to users earlier and
1233 // b) collect usage statistics to help improve Clang coverage design.
1234 bool AddressSanitizer::InjectCoverage(Function &F,
1235 const ArrayRef<BasicBlock *> AllBlocks) {
1236 if (!ClCoverage) return false;
1238 if (ClCoverage == 1) {
1239 InjectCoverageAtBlock(F, F.getEntryBlock());
1241 for (size_t i = 0, n = AllBlocks.size(); i < n; i++)
1242 InjectCoverageAtBlock(F, *AllBlocks[i]);
1247 bool AddressSanitizer::runOnFunction(Function &F) {
1248 if (BL->isIn(F)) return false;
1249 if (&F == AsanCtorFunction) return false;
1250 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
1251 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
1252 initializeCallbacks(*F.getParent());
1254 // If needed, insert __asan_init before checking for SanitizeAddress attr.
1255 maybeInsertAsanInitAtFunctionEntry(F);
1257 if (!F.hasFnAttribute(Attribute::SanitizeAddress))
1260 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1263 // We want to instrument every address only once per basic block (unless there
1264 // are calls between uses).
1265 SmallSet<Value*, 16> TempsToInstrument;
1266 SmallVector<Instruction*, 16> ToInstrument;
1267 SmallVector<Instruction*, 8> NoReturnCalls;
1268 SmallVector<BasicBlock*, 16> AllBlocks;
1269 SmallVector<Instruction*, 16> PointerComparisonsOrSubtracts;
1273 // Fill the set of memory operations to instrument.
1274 for (Function::iterator FI = F.begin(), FE = F.end();
1276 AllBlocks.push_back(FI);
1277 TempsToInstrument.clear();
1278 int NumInsnsPerBB = 0;
1279 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1281 if (LooksLikeCodeInBug11395(BI)) return false;
1282 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
1283 if (ClOpt && ClOptSameTemp) {
1284 if (!TempsToInstrument.insert(Addr))
1285 continue; // We've seen this temp in the current BB.
1287 } else if (ClInvalidPointerPairs &&
1288 isInterestingPointerComparisonOrSubtraction(BI)) {
1289 PointerComparisonsOrSubtracts.push_back(BI);
1291 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
1294 if (isa<AllocaInst>(BI))
1298 // A call inside BB.
1299 TempsToInstrument.clear();
1300 if (CS.doesNotReturn())
1301 NoReturnCalls.push_back(CS.getInstruction());
1305 ToInstrument.push_back(BI);
1307 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1312 Function *UninstrumentedDuplicate = 0;
1313 bool LikelyToInstrument =
1314 !NoReturnCalls.empty() || !ToInstrument.empty() || (NumAllocas > 0);
1315 if (ClKeepUninstrumented && LikelyToInstrument) {
1316 ValueToValueMapTy VMap;
1317 UninstrumentedDuplicate = CloneFunction(&F, VMap, false);
1318 UninstrumentedDuplicate->removeFnAttr(Attribute::SanitizeAddress);
1319 UninstrumentedDuplicate->setName("NOASAN_" + F.getName());
1320 F.getParent()->getFunctionList().push_back(UninstrumentedDuplicate);
1324 int NumInstrumented = 0;
1325 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
1326 Instruction *Inst = ToInstrument[i];
1327 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1328 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
1329 if (isInterestingMemoryAccess(Inst, &IsWrite))
1330 instrumentMop(Inst);
1332 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
1337 FunctionStackPoisoner FSP(F, *this);
1338 bool ChangedStack = FSP.runOnFunction();
1340 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1341 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1342 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
1343 Instruction *CI = NoReturnCalls[i];
1344 IRBuilder<> IRB(CI);
1345 IRB.CreateCall(AsanHandleNoReturnFunc);
1348 for (size_t i = 0, n = PointerComparisonsOrSubtracts.size(); i != n; i++) {
1349 instrumentPointerComparisonOrSubtraction(PointerComparisonsOrSubtracts[i]);
1353 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
1355 if (InjectCoverage(F, AllBlocks))
1358 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1360 if (ClKeepUninstrumented) {
1362 // No instrumentation is done, no need for the duplicate.
1363 if (UninstrumentedDuplicate)
1364 UninstrumentedDuplicate->eraseFromParent();
1366 // The function was instrumented. We must have the duplicate.
1367 assert(UninstrumentedDuplicate);
1368 UninstrumentedDuplicate->setSection("NOASAN");
1369 assert(!F.hasSection());
1370 F.setSection("ASAN");
1377 // Workaround for bug 11395: we don't want to instrument stack in functions
1378 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1379 // FIXME: remove once the bug 11395 is fixed.
1380 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1381 if (LongSize != 32) return false;
1382 CallInst *CI = dyn_cast<CallInst>(I);
1383 if (!CI || !CI->isInlineAsm()) return false;
1384 if (CI->getNumArgOperands() <= 5) return false;
1385 // We have inline assembly with quite a few arguments.
1389 void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1390 IRBuilder<> IRB(*C);
1391 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1392 std::string Suffix = itostr(i);
1393 AsanStackMallocFunc[i] = checkInterfaceFunction(
1394 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1395 IntptrTy, IntptrTy, NULL));
1396 AsanStackFreeFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
1397 kAsanStackFreeNameTemplate + Suffix, IRB.getVoidTy(), IntptrTy,
1398 IntptrTy, IntptrTy, NULL));
1400 AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1401 kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1402 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1403 kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1407 FunctionStackPoisoner::poisonRedZones(const ArrayRef<uint8_t> ShadowBytes,
1408 IRBuilder<> &IRB, Value *ShadowBase,
1410 size_t n = ShadowBytes.size();
1412 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1413 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1414 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1415 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1416 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1417 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1419 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
1420 if (ASan.DL->isLittleEndian())
1421 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1423 Val = (Val << 8) | ShadowBytes[i + j];
1426 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1427 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1428 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1429 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
1434 // Fake stack allocator (asan_fake_stack.h) has 11 size classes
1435 // for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1436 static int StackMallocSizeClass(uint64_t LocalStackSize) {
1437 assert(LocalStackSize <= kMaxStackMallocSize);
1438 uint64_t MaxSize = kMinStackMallocSize;
1439 for (int i = 0; ; i++, MaxSize *= 2)
1440 if (LocalStackSize <= MaxSize)
1442 llvm_unreachable("impossible LocalStackSize");
1445 // Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1446 // We can not use MemSet intrinsic because it may end up calling the actual
1447 // memset. Size is a multiple of 8.
1448 // Currently this generates 8-byte stores on x86_64; it may be better to
1449 // generate wider stores.
1450 void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1451 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1452 assert(!(Size % 8));
1453 assert(kAsanStackAfterReturnMagic == 0xf5);
1454 for (int i = 0; i < Size; i += 8) {
1455 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1456 IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
1457 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1461 void FunctionStackPoisoner::poisonStack() {
1462 int StackMallocIdx = -1;
1464 assert(AllocaVec.size() > 0);
1465 Instruction *InsBefore = AllocaVec[0];
1466 IRBuilder<> IRB(InsBefore);
1468 SmallVector<ASanStackVariableDescription, 16> SVD;
1469 SVD.reserve(AllocaVec.size());
1470 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1471 AllocaInst *AI = AllocaVec[i];
1472 ASanStackVariableDescription D = { AI->getName().data(),
1473 getAllocaSizeInBytes(AI),
1474 AI->getAlignment(), AI, 0};
1477 // Minimal header size (left redzone) is 4 pointers,
1478 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1479 size_t MinHeaderSize = ASan.LongSize / 2;
1480 ASanStackFrameLayout L;
1481 ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1482 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1483 uint64_t LocalStackSize = L.FrameSize;
1484 bool DoStackMalloc =
1485 ASan.CheckUseAfterReturn && LocalStackSize <= kMaxStackMallocSize;
1487 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1488 AllocaInst *MyAlloca =
1489 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
1490 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1491 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1492 MyAlloca->setAlignment(FrameAlignment);
1493 assert(MyAlloca->isStaticAlloca());
1494 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1495 Value *LocalStackBase = OrigStackBase;
1497 if (DoStackMalloc) {
1498 // LocalStackBase = OrigStackBase
1499 // if (__asan_option_detect_stack_use_after_return)
1500 // LocalStackBase = __asan_stack_malloc_N(LocalStackBase, OrigStackBase);
1501 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1502 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
1503 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1504 kAsanOptionDetectUAR, IRB.getInt32Ty());
1505 Value *Cmp = IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1506 Constant::getNullValue(IRB.getInt32Ty()));
1507 Instruction *Term = SplitBlockAndInsertIfThen(Cmp, InsBefore, false);
1508 BasicBlock *CmpBlock = cast<Instruction>(Cmp)->getParent();
1509 IRBuilder<> IRBIf(Term);
1510 LocalStackBase = IRBIf.CreateCall2(
1511 AsanStackMallocFunc[StackMallocIdx],
1512 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1513 BasicBlock *SetBlock = cast<Instruction>(LocalStackBase)->getParent();
1514 IRB.SetInsertPoint(InsBefore);
1515 PHINode *Phi = IRB.CreatePHI(IntptrTy, 2);
1516 Phi->addIncoming(OrigStackBase, CmpBlock);
1517 Phi->addIncoming(LocalStackBase, SetBlock);
1518 LocalStackBase = Phi;
1521 // Insert poison calls for lifetime intrinsics for alloca.
1522 bool HavePoisonedAllocas = false;
1523 for (size_t i = 0, n = AllocaPoisonCallVec.size(); i < n; i++) {
1524 const AllocaPoisonCall &APC = AllocaPoisonCallVec[i];
1525 assert(APC.InsBefore);
1527 IRBuilder<> IRB(APC.InsBefore);
1528 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
1529 HavePoisonedAllocas |= APC.DoPoison;
1532 // Replace Alloca instructions with base+offset.
1533 for (size_t i = 0, n = SVD.size(); i < n; i++) {
1534 AllocaInst *AI = SVD[i].AI;
1535 Value *NewAllocaPtr = IRB.CreateIntToPtr(
1536 IRB.CreateAdd(LocalStackBase,
1537 ConstantInt::get(IntptrTy, SVD[i].Offset)),
1539 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
1540 AI->replaceAllUsesWith(NewAllocaPtr);
1543 // The left-most redzone has enough space for at least 4 pointers.
1544 // Write the Magic value to redzone[0].
1545 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1546 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1548 // Write the frame description constant to redzone[1].
1549 Value *BasePlus1 = IRB.CreateIntToPtr(
1550 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
1552 GlobalVariable *StackDescriptionGlobal =
1553 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
1554 /*AllowMerging*/true);
1555 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1557 IRB.CreateStore(Description, BasePlus1);
1558 // Write the PC to redzone[2].
1559 Value *BasePlus2 = IRB.CreateIntToPtr(
1560 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
1561 2 * ASan.LongSize/8)),
1563 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
1565 // Poison the stack redzones at the entry.
1566 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1567 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
1569 // (Un)poison the stack before all ret instructions.
1570 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1571 Instruction *Ret = RetVec[i];
1572 IRBuilder<> IRBRet(Ret);
1573 // Mark the current frame as retired.
1574 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1576 if (DoStackMalloc) {
1577 assert(StackMallocIdx >= 0);
1578 // if LocalStackBase != OrigStackBase:
1579 // // In use-after-return mode, poison the whole stack frame.
1580 // if StackMallocIdx <= 4
1581 // // For small sizes inline the whole thing:
1582 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
1583 // **SavedFlagPtr(LocalStackBase) = 0
1585 // __asan_stack_free_N(LocalStackBase, OrigStackBase)
1587 // <This is not a fake stack; unpoison the redzones>
1588 Value *Cmp = IRBRet.CreateICmpNE(LocalStackBase, OrigStackBase);
1589 TerminatorInst *ThenTerm, *ElseTerm;
1590 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1592 IRBuilder<> IRBPoison(ThenTerm);
1593 if (StackMallocIdx <= 4) {
1594 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1595 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1596 ClassSize >> Mapping.Scale);
1597 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
1599 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1600 Value *SavedFlagPtr = IRBPoison.CreateLoad(
1601 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1602 IRBPoison.CreateStore(
1603 Constant::getNullValue(IRBPoison.getInt8Ty()),
1604 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1606 // For larger frames call __asan_stack_free_*.
1607 IRBPoison.CreateCall3(AsanStackFreeFunc[StackMallocIdx], LocalStackBase,
1608 ConstantInt::get(IntptrTy, LocalStackSize),
1612 IRBuilder<> IRBElse(ElseTerm);
1613 poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
1614 } else if (HavePoisonedAllocas) {
1615 // If we poisoned some allocas in llvm.lifetime analysis,
1616 // unpoison whole stack frame now.
1617 assert(LocalStackBase == OrigStackBase);
1618 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
1620 poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
1624 // We are done. Remove the old unused alloca instructions.
1625 for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1626 AllocaVec[i]->eraseFromParent();
1629 void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
1630 IRBuilder<> &IRB, bool DoPoison) {
1631 // For now just insert the call to ASan runtime.
1632 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1633 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1634 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1635 : AsanUnpoisonStackMemoryFunc,
1639 // Handling llvm.lifetime intrinsics for a given %alloca:
1640 // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1641 // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1642 // invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1643 // could be poisoned by previous llvm.lifetime.end instruction, as the
1644 // variable may go in and out of scope several times, e.g. in loops).
1645 // (3) if we poisoned at least one %alloca in a function,
1646 // unpoison the whole stack frame at function exit.
1648 AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1649 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1650 // We're intested only in allocas we can handle.
1651 return isInterestingAlloca(*AI) ? AI : 0;
1652 // See if we've already calculated (or started to calculate) alloca for a
1654 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1655 if (I != AllocaForValue.end())
1657 // Store 0 while we're calculating alloca for value V to avoid
1658 // infinite recursion if the value references itself.
1659 AllocaForValue[V] = 0;
1660 AllocaInst *Res = 0;
1661 if (CastInst *CI = dyn_cast<CastInst>(V))
1662 Res = findAllocaForValue(CI->getOperand(0));
1663 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1664 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1665 Value *IncValue = PN->getIncomingValue(i);
1666 // Allow self-referencing phi-nodes.
1667 if (IncValue == PN) continue;
1668 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1669 // AI for incoming values should exist and should all be equal.
1670 if (IncValueAI == 0 || (Res != 0 && IncValueAI != Res))
1676 AllocaForValue[V] = Res;