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);
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(-1));
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 /// A set of dynamically initialized globals extracted from metadata.
216 class SetOfDynamicallyInitializedGlobals {
218 void Init(Module& M) {
219 // Clang generates metadata identifying all dynamically initialized globals.
220 NamedMDNode *DynamicGlobals =
221 M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
224 for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
225 MDNode *MDN = DynamicGlobals->getOperand(i);
226 assert(MDN->getNumOperands() == 1);
227 Value *VG = MDN->getOperand(0);
228 // The optimizer may optimize away a global entirely, in which case we
229 // cannot instrument access to it.
232 DynInitGlobals.insert(cast<GlobalVariable>(VG));
235 bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
237 SmallSet<GlobalValue*, 32> DynInitGlobals;
240 /// This struct defines the shadow mapping using the rule:
241 /// shadow = (mem >> Scale) ADD-or-OR Offset.
242 struct ShadowMapping {
248 static ShadowMapping getShadowMapping(const Module &M, int LongSize) {
249 llvm::Triple TargetTriple(M.getTargetTriple());
250 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
251 // bool IsMacOSX = TargetTriple.getOS() == llvm::Triple::MacOSX;
252 bool IsFreeBSD = TargetTriple.getOS() == llvm::Triple::FreeBSD;
253 bool IsLinux = TargetTriple.getOS() == llvm::Triple::Linux;
254 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
255 TargetTriple.getArch() == llvm::Triple::ppc64le;
256 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
257 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
258 TargetTriple.getArch() == llvm::Triple::mipsel;
260 ShadowMapping Mapping;
262 if (LongSize == 32) {
266 Mapping.Offset = kMIPS32_ShadowOffset32;
268 Mapping.Offset = kFreeBSD_ShadowOffset32;
270 Mapping.Offset = kDefaultShadowOffset32;
271 } else { // LongSize == 64
273 Mapping.Offset = kPPC64_ShadowOffset64;
275 Mapping.Offset = kFreeBSD_ShadowOffset64;
276 else if (IsLinux && IsX86_64)
277 Mapping.Offset = kSmallX86_64ShadowOffset;
279 Mapping.Offset = kDefaultShadowOffset64;
282 Mapping.Scale = kDefaultShadowScale;
283 if (ClMappingScale) {
284 Mapping.Scale = ClMappingScale;
287 // OR-ing shadow offset if more efficient (at least on x86) if the offset
288 // is a power of two, but on ppc64 we have to use add since the shadow
289 // offset is not necessary 1/8-th of the address space.
290 Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
295 static size_t RedzoneSizeForScale(int MappingScale) {
296 // Redzone used for stack and globals is at least 32 bytes.
297 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
298 return std::max(32U, 1U << MappingScale);
301 /// AddressSanitizer: instrument the code in module to find memory bugs.
302 struct AddressSanitizer : public FunctionPass {
303 AddressSanitizer(bool CheckInitOrder = true,
304 bool CheckUseAfterReturn = false,
305 bool CheckLifetime = false,
306 StringRef BlacklistFile = StringRef())
308 CheckInitOrder(CheckInitOrder || ClInitializers),
309 CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
310 CheckLifetime(CheckLifetime || ClCheckLifetime),
311 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
313 const char *getPassName() const override {
314 return "AddressSanitizerFunctionPass";
316 void instrumentMop(Instruction *I, bool UseCalls);
317 void instrumentPointerComparisonOrSubtraction(Instruction *I);
318 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
319 Value *Addr, uint32_t TypeSize, bool IsWrite,
320 Value *SizeArgument, bool UseCalls);
321 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
322 Value *ShadowValue, uint32_t TypeSize);
323 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
324 bool IsWrite, size_t AccessSizeIndex,
325 Value *SizeArgument);
326 bool instrumentMemIntrinsic(MemIntrinsic *MI, bool UseCalls);
327 void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
328 Value *Size, Instruction *InsertBefore,
329 bool IsWrite, bool UseCalls);
330 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
331 bool runOnFunction(Function &F) override;
332 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
333 bool doInitialization(Module &M) override;
334 static char ID; // Pass identification, replacement for typeid
337 void initializeCallbacks(Module &M);
339 bool LooksLikeCodeInBug11395(Instruction *I);
340 bool GlobalIsLinkerInitialized(GlobalVariable *G);
341 bool InjectCoverage(Function &F, const ArrayRef<BasicBlock*> AllBlocks);
342 void InjectCoverageAtBlock(Function &F, BasicBlock &BB);
345 bool CheckUseAfterReturn;
347 SmallString<64> BlacklistFile;
350 const DataLayout *DL;
353 ShadowMapping Mapping;
354 Function *AsanCtorFunction;
355 Function *AsanInitFunction;
356 Function *AsanHandleNoReturnFunc;
357 Function *AsanCovFunction;
358 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
359 std::unique_ptr<SpecialCaseList> BL;
360 // This array is indexed by AccessIsWrite and log2(AccessSize).
361 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
362 Function *AsanMemoryAccessCallback[2][kNumberOfAccessSizes];
363 // This array is indexed by AccessIsWrite.
364 Function *AsanErrorCallbackSized[2];
366 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
368 friend struct FunctionStackPoisoner;
371 class AddressSanitizerModule : public ModulePass {
373 AddressSanitizerModule(bool CheckInitOrder = true,
374 StringRef BlacklistFile = StringRef())
376 CheckInitOrder(CheckInitOrder || ClInitializers),
377 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
379 bool runOnModule(Module &M) override;
380 static char ID; // Pass identification, replacement for typeid
381 const char *getPassName() const override {
382 return "AddressSanitizerModule";
386 void initializeCallbacks(Module &M);
388 bool ShouldInstrumentGlobal(GlobalVariable *G);
389 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
390 size_t MinRedzoneSizeForGlobal() const {
391 return RedzoneSizeForScale(Mapping.Scale);
395 SmallString<64> BlacklistFile;
397 std::unique_ptr<SpecialCaseList> BL;
398 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
401 const DataLayout *DL;
402 ShadowMapping Mapping;
403 Function *AsanPoisonGlobals;
404 Function *AsanUnpoisonGlobals;
405 Function *AsanRegisterGlobals;
406 Function *AsanUnregisterGlobals;
409 // Stack poisoning does not play well with exception handling.
410 // When an exception is thrown, we essentially bypass the code
411 // that unpoisones the stack. This is why the run-time library has
412 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
413 // stack in the interceptor. This however does not work inside the
414 // actual function which catches the exception. Most likely because the
415 // compiler hoists the load of the shadow value somewhere too high.
416 // This causes asan to report a non-existing bug on 453.povray.
417 // It sounds like an LLVM bug.
418 struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
420 AddressSanitizer &ASan;
425 ShadowMapping Mapping;
427 SmallVector<AllocaInst*, 16> AllocaVec;
428 SmallVector<Instruction*, 8> RetVec;
429 unsigned StackAlignment;
431 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
432 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
433 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
435 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
436 struct AllocaPoisonCall {
437 IntrinsicInst *InsBefore;
442 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
444 // Maps Value to an AllocaInst from which the Value is originated.
445 typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
446 AllocaForValueMapTy AllocaForValue;
448 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
449 : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
450 IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
451 Mapping(ASan.Mapping),
452 StackAlignment(1 << Mapping.Scale) {}
454 bool runOnFunction() {
455 if (!ClStack) return false;
456 // Collect alloca, ret, lifetime instructions etc.
457 for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
460 if (AllocaVec.empty()) return false;
462 initializeCallbacks(*F.getParent());
472 // Finds all static Alloca instructions and puts
473 // poisoned red zones around all of them.
474 // Then unpoison everything back before the function returns.
477 // ----------------------- Visitors.
478 /// \brief Collect all Ret instructions.
479 void visitReturnInst(ReturnInst &RI) {
480 RetVec.push_back(&RI);
483 /// \brief Collect Alloca instructions we want (and can) handle.
484 void visitAllocaInst(AllocaInst &AI) {
485 if (!isInterestingAlloca(AI)) return;
487 StackAlignment = std::max(StackAlignment, AI.getAlignment());
488 AllocaVec.push_back(&AI);
491 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
493 void visitIntrinsicInst(IntrinsicInst &II) {
494 if (!ASan.CheckLifetime) return;
495 Intrinsic::ID ID = II.getIntrinsicID();
496 if (ID != Intrinsic::lifetime_start &&
497 ID != Intrinsic::lifetime_end)
499 // Found lifetime intrinsic, add ASan instrumentation if necessary.
500 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
501 // If size argument is undefined, don't do anything.
502 if (Size->isMinusOne()) return;
503 // Check that size doesn't saturate uint64_t and can
504 // be stored in IntptrTy.
505 const uint64_t SizeValue = Size->getValue().getLimitedValue();
506 if (SizeValue == ~0ULL ||
507 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
509 // Find alloca instruction that corresponds to llvm.lifetime argument.
510 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
512 bool DoPoison = (ID == Intrinsic::lifetime_end);
513 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
514 AllocaPoisonCallVec.push_back(APC);
517 // ---------------------- Helpers.
518 void initializeCallbacks(Module &M);
520 // Check if we want (and can) handle this alloca.
521 bool isInterestingAlloca(AllocaInst &AI) const {
522 return (!AI.isArrayAllocation() && AI.isStaticAlloca() &&
523 AI.getAllocatedType()->isSized() &&
524 // alloca() may be called with 0 size, ignore it.
525 getAllocaSizeInBytes(&AI) > 0);
528 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
529 Type *Ty = AI->getAllocatedType();
530 uint64_t SizeInBytes = ASan.DL->getTypeAllocSize(Ty);
533 /// Finds alloca where the value comes from.
534 AllocaInst *findAllocaForValue(Value *V);
535 void poisonRedZones(const ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
536 Value *ShadowBase, bool DoPoison);
537 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
539 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
545 char AddressSanitizer::ID = 0;
546 INITIALIZE_PASS(AddressSanitizer, "asan",
547 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
549 FunctionPass *llvm::createAddressSanitizerFunctionPass(
550 bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime,
551 StringRef BlacklistFile) {
552 return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
553 CheckLifetime, BlacklistFile);
556 char AddressSanitizerModule::ID = 0;
557 INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
558 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
559 "ModulePass", false, false)
560 ModulePass *llvm::createAddressSanitizerModulePass(
561 bool CheckInitOrder, StringRef BlacklistFile) {
562 return new AddressSanitizerModule(CheckInitOrder, BlacklistFile);
565 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
566 size_t Res = countTrailingZeros(TypeSize / 8);
567 assert(Res < kNumberOfAccessSizes);
571 // \brief Create a constant for Str so that we can pass it to the run-time lib.
572 static GlobalVariable *createPrivateGlobalForString(
573 Module &M, StringRef Str, bool AllowMerging) {
574 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
575 // We use private linkage for module-local strings. If they can be merged
576 // with another one, we set the unnamed_addr attribute.
578 new GlobalVariable(M, StrConst->getType(), true,
579 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
581 GV->setUnnamedAddr(true);
582 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
586 static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
587 return G->getName().find(kAsanGenPrefix) == 0;
590 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
592 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
593 if (Mapping.Offset == 0)
595 // (Shadow >> scale) | offset
596 if (Mapping.OrShadowOffset)
597 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
599 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
602 void AddressSanitizer::instrumentMemIntrinsicParam(Instruction *OrigIns,
603 Value *Addr, Value *Size,
604 Instruction *InsertBefore,
607 IRBuilder<> IRB(InsertBefore);
608 if (Size->getType() != IntptrTy)
609 Size = IRB.CreateIntCast(Size, IntptrTy, false);
610 // Check the first byte.
611 instrumentAddress(OrigIns, InsertBefore, Addr, 8, IsWrite, Size, UseCalls);
612 // Check the last byte.
613 IRB.SetInsertPoint(InsertBefore);
614 Value *SizeMinusOne = IRB.CreateSub(Size, ConstantInt::get(IntptrTy, 1));
615 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
616 Value *AddrLast = IRB.CreateAdd(AddrLong, SizeMinusOne);
617 instrumentAddress(OrigIns, InsertBefore, AddrLast, 8, IsWrite, Size,
621 // Instrument memset/memmove/memcpy
622 bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI, bool UseCalls) {
623 Value *Dst = MI->getDest();
624 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
625 Value *Src = MemTran ? MemTran->getSource() : 0;
626 Value *Length = MI->getLength();
628 Constant *ConstLength = dyn_cast<Constant>(Length);
629 Instruction *InsertBefore = MI;
631 if (ConstLength->isNullValue()) return false;
633 // The size is not a constant so it could be zero -- check at run-time.
634 IRBuilder<> IRB(InsertBefore);
636 Value *Cmp = IRB.CreateICmpNE(Length,
637 Constant::getNullValue(Length->getType()));
638 InsertBefore = SplitBlockAndInsertIfThen(Cmp, InsertBefore, false);
641 instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true, UseCalls);
643 instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false, UseCalls);
647 // If I is an interesting memory access, return the PointerOperand
648 // and set IsWrite. Otherwise return NULL.
649 static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
650 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
651 if (!ClInstrumentReads) return NULL;
653 return LI->getPointerOperand();
655 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
656 if (!ClInstrumentWrites) return NULL;
658 return SI->getPointerOperand();
660 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
661 if (!ClInstrumentAtomics) return NULL;
663 return RMW->getPointerOperand();
665 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
666 if (!ClInstrumentAtomics) return NULL;
668 return XCHG->getPointerOperand();
673 static bool isPointerOperand(Value *V) {
674 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
677 // This is a rough heuristic; it may cause both false positives and
678 // false negatives. The proper implementation requires cooperation with
680 static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
681 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
682 if (!Cmp->isRelational())
684 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
685 if (BO->getOpcode() != Instruction::Sub)
690 if (!isPointerOperand(I->getOperand(0)) ||
691 !isPointerOperand(I->getOperand(1)))
696 bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
697 // If a global variable does not have dynamic initialization we don't
698 // have to instrument it. However, if a global does not have initializer
699 // at all, we assume it has dynamic initializer (in other TU).
700 return G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G);
704 AddressSanitizer::instrumentPointerComparisonOrSubtraction(Instruction *I) {
706 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
707 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
708 for (int i = 0; i < 2; i++) {
709 if (Param[i]->getType()->isPointerTy())
710 Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
712 IRB.CreateCall2(F, Param[0], Param[1]);
715 void AddressSanitizer::instrumentMop(Instruction *I, bool UseCalls) {
716 bool IsWrite = false;
717 Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
719 if (ClOpt && ClOptGlobals) {
720 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
721 // If initialization order checking is disabled, a simple access to a
722 // dynamically initialized global is always valid.
723 if (!CheckInitOrder || GlobalIsLinkerInitialized(G)) {
724 NumOptimizedAccessesToGlobalVar++;
728 ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr);
729 if (CE && CE->isGEPWithNoNotionalOverIndexing()) {
730 if (GlobalVariable *G = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
731 if (CE->getOperand(1)->isNullValue() && GlobalIsLinkerInitialized(G)) {
732 NumOptimizedAccessesToGlobalArray++;
739 Type *OrigPtrTy = Addr->getType();
740 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
742 assert(OrigTy->isSized());
743 uint32_t TypeSize = DL->getTypeStoreSizeInBits(OrigTy);
745 assert((TypeSize % 8) == 0);
748 NumInstrumentedWrites++;
750 NumInstrumentedReads++;
752 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check.
753 if (TypeSize == 8 || TypeSize == 16 ||
754 TypeSize == 32 || TypeSize == 64 || TypeSize == 128)
755 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, 0, UseCalls);
756 // Instrument unusual size (but still multiple of 8).
757 // We can not do it with a single check, so we do 1-byte check for the first
758 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
759 // to report the actual access size.
761 Value *LastByte = IRB.CreateIntToPtr(
762 IRB.CreateAdd(IRB.CreatePointerCast(Addr, IntptrTy),
763 ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
765 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
766 instrumentAddress(I, I, Addr, 8, IsWrite, Size, UseCalls);
767 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, UseCalls);
770 // Validate the result of Module::getOrInsertFunction called for an interface
771 // function of AddressSanitizer. If the instrumented module defines a function
772 // with the same name, their prototypes must match, otherwise
773 // getOrInsertFunction returns a bitcast.
774 static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
775 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
776 FuncOrBitcast->dump();
777 report_fatal_error("trying to redefine an AddressSanitizer "
778 "interface function");
781 Instruction *AddressSanitizer::generateCrashCode(
782 Instruction *InsertBefore, Value *Addr,
783 bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
784 IRBuilder<> IRB(InsertBefore);
785 CallInst *Call = SizeArgument
786 ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
787 : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
789 // We don't do Call->setDoesNotReturn() because the BB already has
790 // UnreachableInst at the end.
791 // This EmptyAsm is required to avoid callback merge.
792 IRB.CreateCall(EmptyAsm);
796 Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
799 size_t Granularity = 1 << Mapping.Scale;
800 // Addr & (Granularity - 1)
801 Value *LastAccessedByte = IRB.CreateAnd(
802 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
803 // (Addr & (Granularity - 1)) + size - 1
804 if (TypeSize / 8 > 1)
805 LastAccessedByte = IRB.CreateAdd(
806 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
807 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
808 LastAccessedByte = IRB.CreateIntCast(
809 LastAccessedByte, ShadowValue->getType(), false);
810 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
811 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
814 void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
815 Instruction *InsertBefore, Value *Addr,
816 uint32_t TypeSize, bool IsWrite,
817 Value *SizeArgument, bool UseCalls) {
818 IRBuilder<> IRB(InsertBefore);
819 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
820 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
823 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][AccessSizeIndex],
828 Type *ShadowTy = IntegerType::get(
829 *C, std::max(8U, TypeSize >> Mapping.Scale));
830 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
831 Value *ShadowPtr = memToShadow(AddrLong, IRB);
832 Value *CmpVal = Constant::getNullValue(ShadowTy);
833 Value *ShadowValue = IRB.CreateLoad(
834 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
836 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
837 size_t Granularity = 1 << Mapping.Scale;
838 TerminatorInst *CrashTerm = 0;
840 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
841 TerminatorInst *CheckTerm =
842 SplitBlockAndInsertIfThen(Cmp, InsertBefore, false);
843 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
844 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
845 IRB.SetInsertPoint(CheckTerm);
846 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
847 BasicBlock *CrashBlock =
848 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
849 CrashTerm = new UnreachableInst(*C, CrashBlock);
850 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
851 ReplaceInstWithInst(CheckTerm, NewTerm);
853 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
856 Instruction *Crash = generateCrashCode(
857 CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
858 Crash->setDebugLoc(OrigIns->getDebugLoc());
861 void AddressSanitizerModule::createInitializerPoisonCalls(
862 Module &M, GlobalValue *ModuleName) {
863 // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
864 Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
865 // If that function is not present, this TU contains no globals, or they have
866 // all been optimized away
870 // Set up the arguments to our poison/unpoison functions.
871 IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
873 // Add a call to poison all external globals before the given function starts.
874 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
875 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
877 // Add calls to unpoison all globals before each return instruction.
878 for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
880 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
881 CallInst::Create(AsanUnpoisonGlobals, "", RI);
886 bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
887 Type *Ty = cast<PointerType>(G->getType())->getElementType();
888 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
890 if (BL->isIn(*G)) return false;
891 if (!Ty->isSized()) return false;
892 if (!G->hasInitializer()) return false;
893 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
894 // Touch only those globals that will not be defined in other modules.
895 // Don't handle ODR type linkages since other modules may be built w/o asan.
896 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
897 G->getLinkage() != GlobalVariable::PrivateLinkage &&
898 G->getLinkage() != GlobalVariable::InternalLinkage)
900 // Two problems with thread-locals:
901 // - The address of the main thread's copy can't be computed at link-time.
902 // - Need to poison all copies, not just the main thread's one.
903 if (G->isThreadLocal())
905 // For now, just ignore this Global if the alignment is large.
906 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
908 // Ignore all the globals with the names starting with "\01L_OBJC_".
909 // Many of those are put into the .cstring section. The linker compresses
910 // that section by removing the spare \0s after the string terminator, so
911 // our redzones get broken.
912 if ((G->getName().find("\01L_OBJC_") == 0) ||
913 (G->getName().find("\01l_OBJC_") == 0)) {
914 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G << "\n");
918 if (G->hasSection()) {
919 StringRef Section(G->getSection());
920 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
921 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
923 if ((Section.find("__OBJC,") == 0) ||
924 (Section.find("__DATA, __objc_") == 0)) {
925 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
928 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
929 // Constant CFString instances are compiled in the following way:
930 // -- the string buffer is emitted into
931 // __TEXT,__cstring,cstring_literals
932 // -- the constant NSConstantString structure referencing that buffer
933 // is placed into __DATA,__cfstring
934 // Therefore there's no point in placing redzones into __DATA,__cfstring.
935 // Moreover, it causes the linker to crash on OS X 10.7
936 if (Section.find("__DATA,__cfstring") == 0) {
937 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
940 // The linker merges the contents of cstring_literals and removes the
942 if (Section.find("__TEXT,__cstring,cstring_literals") == 0) {
943 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
946 // Globals from llvm.metadata aren't emitted, do not instrument them.
947 if (Section == "llvm.metadata") return false;
953 void AddressSanitizerModule::initializeCallbacks(Module &M) {
955 // Declare our poisoning and unpoisoning functions.
956 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
957 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, NULL));
958 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
959 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
960 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
961 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
962 // Declare functions that register/unregister globals.
963 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
964 kAsanRegisterGlobalsName, IRB.getVoidTy(),
965 IntptrTy, IntptrTy, NULL));
966 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
967 AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
968 kAsanUnregisterGlobalsName,
969 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
970 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
973 // This function replaces all global variables with new variables that have
974 // trailing redzones. It also creates a function that poisons
975 // redzones and inserts this function into llvm.global_ctors.
976 bool AddressSanitizerModule::runOnModule(Module &M) {
977 if (!ClGlobals) return false;
979 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
982 DL = &DLP->getDataLayout();
984 BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
985 if (BL->isIn(M)) return false;
986 C = &(M.getContext());
987 int LongSize = DL->getPointerSizeInBits();
988 IntptrTy = Type::getIntNTy(*C, LongSize);
989 Mapping = getShadowMapping(M, LongSize);
990 initializeCallbacks(M);
991 DynamicallyInitializedGlobals.Init(M);
993 SmallVector<GlobalVariable *, 16> GlobalsToChange;
995 for (Module::GlobalListType::iterator G = M.global_begin(),
996 E = M.global_end(); G != E; ++G) {
997 if (ShouldInstrumentGlobal(G))
998 GlobalsToChange.push_back(G);
1001 size_t n = GlobalsToChange.size();
1002 if (n == 0) return false;
1004 // A global is described by a structure
1007 // size_t size_with_redzone;
1008 // const char *name;
1009 // const char *module_name;
1010 // size_t has_dynamic_init;
1011 // We initialize an array of such structures and pass it to a run-time call.
1012 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
1014 IntptrTy, IntptrTy, NULL);
1015 SmallVector<Constant *, 16> Initializers(n);
1017 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1019 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1021 bool HasDynamicallyInitializedGlobals = false;
1023 // We shouldn't merge same module names, as this string serves as unique
1024 // module ID in runtime.
1025 GlobalVariable *ModuleName = createPrivateGlobalForString(
1026 M, M.getModuleIdentifier(), /*AllowMerging*/false);
1028 for (size_t i = 0; i < n; i++) {
1029 static const uint64_t kMaxGlobalRedzone = 1 << 18;
1030 GlobalVariable *G = GlobalsToChange[i];
1031 PointerType *PtrTy = cast<PointerType>(G->getType());
1032 Type *Ty = PtrTy->getElementType();
1033 uint64_t SizeInBytes = DL->getTypeAllocSize(Ty);
1034 uint64_t MinRZ = MinRedzoneSizeForGlobal();
1035 // MinRZ <= RZ <= kMaxGlobalRedzone
1036 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
1037 uint64_t RZ = std::max(MinRZ,
1038 std::min(kMaxGlobalRedzone,
1039 (SizeInBytes / MinRZ / 4) * MinRZ));
1040 uint64_t RightRedzoneSize = RZ;
1041 // Round up to MinRZ
1042 if (SizeInBytes % MinRZ)
1043 RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
1044 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
1045 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1046 // Determine whether this global should be poisoned in initialization.
1047 bool GlobalHasDynamicInitializer =
1048 DynamicallyInitializedGlobals.Contains(G);
1049 // Don't check initialization order if this global is blacklisted.
1050 GlobalHasDynamicInitializer &= !BL->isIn(*G, "init");
1052 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
1053 Constant *NewInitializer = ConstantStruct::get(
1054 NewTy, G->getInitializer(),
1055 Constant::getNullValue(RightRedZoneTy), NULL);
1057 GlobalVariable *Name =
1058 createPrivateGlobalForString(M, G->getName(), /*AllowMerging*/true);
1060 // Create a new global variable with enough space for a redzone.
1061 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1062 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1063 Linkage = GlobalValue::InternalLinkage;
1064 GlobalVariable *NewGlobal = new GlobalVariable(
1065 M, NewTy, G->isConstant(), Linkage,
1066 NewInitializer, "", G, G->getThreadLocalMode());
1067 NewGlobal->copyAttributesFrom(G);
1068 NewGlobal->setAlignment(MinRZ);
1071 Indices2[0] = IRB.getInt32(0);
1072 Indices2[1] = IRB.getInt32(0);
1074 G->replaceAllUsesWith(
1075 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
1076 NewGlobal->takeName(G);
1077 G->eraseFromParent();
1079 Initializers[i] = ConstantStruct::get(
1081 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
1082 ConstantInt::get(IntptrTy, SizeInBytes),
1083 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1084 ConstantExpr::getPointerCast(Name, IntptrTy),
1085 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
1086 ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
1089 // Populate the first and last globals declared in this TU.
1090 if (CheckInitOrder && GlobalHasDynamicInitializer)
1091 HasDynamicallyInitializedGlobals = true;
1093 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
1096 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1097 GlobalVariable *AllGlobals = new GlobalVariable(
1098 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1099 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1101 // Create calls for poisoning before initializers run and unpoisoning after.
1102 if (CheckInitOrder && HasDynamicallyInitializedGlobals)
1103 createInitializerPoisonCalls(M, ModuleName);
1104 IRB.CreateCall2(AsanRegisterGlobals,
1105 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1106 ConstantInt::get(IntptrTy, n));
1108 // We also need to unregister globals at the end, e.g. when a shared library
1110 Function *AsanDtorFunction = Function::Create(
1111 FunctionType::get(Type::getVoidTy(*C), false),
1112 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1113 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1114 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
1115 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
1116 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1117 ConstantInt::get(IntptrTy, n));
1118 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
1124 void AddressSanitizer::initializeCallbacks(Module &M) {
1125 IRBuilder<> IRB(*C);
1126 // Create __asan_report* callbacks.
1127 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1128 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1129 AccessSizeIndex++) {
1130 // IsWrite and TypeSize are encoded in the function name.
1131 std::string Suffix =
1132 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
1133 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
1134 checkInterfaceFunction(
1135 M.getOrInsertFunction(kAsanReportErrorTemplate + Suffix,
1136 IRB.getVoidTy(), IntptrTy, NULL));
1137 AsanMemoryAccessCallback[AccessIsWrite][AccessSizeIndex] =
1138 checkInterfaceFunction(
1139 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + Suffix,
1140 IRB.getVoidTy(), IntptrTy, NULL));
1143 AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
1144 kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1145 AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
1146 kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1148 AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
1149 kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
1150 AsanCovFunction = checkInterfaceFunction(M.getOrInsertFunction(
1151 kAsanCovName, IRB.getVoidTy(), NULL));
1152 AsanPtrCmpFunction = checkInterfaceFunction(M.getOrInsertFunction(
1153 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1154 AsanPtrSubFunction = checkInterfaceFunction(M.getOrInsertFunction(
1155 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1156 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1157 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1158 StringRef(""), StringRef(""),
1159 /*hasSideEffects=*/true);
1163 bool AddressSanitizer::doInitialization(Module &M) {
1164 // Initialize the private fields. No one has accessed them before.
1165 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1168 DL = &DLP->getDataLayout();
1170 BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
1171 DynamicallyInitializedGlobals.Init(M);
1173 C = &(M.getContext());
1174 LongSize = DL->getPointerSizeInBits();
1175 IntptrTy = Type::getIntNTy(*C, LongSize);
1177 AsanCtorFunction = Function::Create(
1178 FunctionType::get(Type::getVoidTy(*C), false),
1179 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1180 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1181 // call __asan_init in the module ctor.
1182 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1183 AsanInitFunction = checkInterfaceFunction(
1184 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
1185 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1186 IRB.CreateCall(AsanInitFunction);
1188 Mapping = getShadowMapping(M, LongSize);
1190 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
1194 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1195 // For each NSObject descendant having a +load method, this method is invoked
1196 // by the ObjC runtime before any of the static constructors is called.
1197 // Therefore we need to instrument such methods with a call to __asan_init
1198 // at the beginning in order to initialize our runtime before any access to
1199 // the shadow memory.
1200 // We cannot just ignore these methods, because they may call other
1201 // instrumented functions.
1202 if (F.getName().find(" load]") != std::string::npos) {
1203 IRBuilder<> IRB(F.begin()->begin());
1204 IRB.CreateCall(AsanInitFunction);
1210 void AddressSanitizer::InjectCoverageAtBlock(Function &F, BasicBlock &BB) {
1211 BasicBlock::iterator IP = BB.getFirstInsertionPt(), BE = BB.end();
1212 // Skip static allocas at the top of the entry block so they don't become
1213 // dynamic when we split the block. If we used our optimized stack layout,
1214 // then there will only be one alloca and it will come first.
1215 for (; IP != BE; ++IP) {
1216 AllocaInst *AI = dyn_cast<AllocaInst>(IP);
1217 if (!AI || !AI->isStaticAlloca())
1221 IRBuilder<> IRB(IP);
1222 Type *Int8Ty = IRB.getInt8Ty();
1223 GlobalVariable *Guard = new GlobalVariable(
1224 *F.getParent(), Int8Ty, false, GlobalValue::PrivateLinkage,
1225 Constant::getNullValue(Int8Ty), "__asan_gen_cov_" + F.getName());
1226 LoadInst *Load = IRB.CreateLoad(Guard);
1227 Load->setAtomic(Monotonic);
1228 Load->setAlignment(1);
1229 Value *Cmp = IRB.CreateICmpEQ(Constant::getNullValue(Int8Ty), Load);
1230 Instruction *Ins = SplitBlockAndInsertIfThen(
1231 Cmp, IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
1232 IRB.SetInsertPoint(Ins);
1233 // We pass &F to __sanitizer_cov. We could avoid this and rely on
1234 // GET_CALLER_PC, but having the PC of the first instruction is just nice.
1235 Instruction *Call = IRB.CreateCall(AsanCovFunction);
1236 Call->setDebugLoc(IP->getDebugLoc());
1237 StoreInst *Store = IRB.CreateStore(ConstantInt::get(Int8Ty, 1), Guard);
1238 Store->setAtomic(Monotonic);
1239 Store->setAlignment(1);
1242 // Poor man's coverage that works with ASan.
1243 // We create a Guard boolean variable with the same linkage
1244 // as the function and inject this code into the entry block (-asan-coverage=1)
1245 // or all blocks (-asan-coverage=2):
1247 // __sanitizer_cov(&F);
1250 // The accesses to Guard are atomic. The rest of the logic is
1251 // in __sanitizer_cov (it's fine to call it more than once).
1253 // This coverage implementation provides very limited data:
1254 // it only tells if a given function (block) was ever executed.
1255 // No counters, no per-edge data.
1256 // But for many use cases this is what we need and the added slowdown
1257 // is negligible. This simple implementation will probably be obsoleted
1258 // by the upcoming Clang-based coverage implementation.
1259 // By having it here and now we hope to
1260 // a) get the functionality to users earlier and
1261 // b) collect usage statistics to help improve Clang coverage design.
1262 bool AddressSanitizer::InjectCoverage(Function &F,
1263 const ArrayRef<BasicBlock *> AllBlocks) {
1264 if (!ClCoverage) return false;
1266 if (ClCoverage == 1) {
1267 InjectCoverageAtBlock(F, F.getEntryBlock());
1269 for (size_t i = 0, n = AllBlocks.size(); i < n; i++)
1270 InjectCoverageAtBlock(F, *AllBlocks[i]);
1275 bool AddressSanitizer::runOnFunction(Function &F) {
1276 if (BL->isIn(F)) return false;
1277 if (&F == AsanCtorFunction) return false;
1278 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
1279 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
1280 initializeCallbacks(*F.getParent());
1282 // If needed, insert __asan_init before checking for SanitizeAddress attr.
1283 maybeInsertAsanInitAtFunctionEntry(F);
1285 if (!F.hasFnAttribute(Attribute::SanitizeAddress))
1288 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1291 // We want to instrument every address only once per basic block (unless there
1292 // are calls between uses).
1293 SmallSet<Value*, 16> TempsToInstrument;
1294 SmallVector<Instruction*, 16> ToInstrument;
1295 SmallVector<Instruction*, 8> NoReturnCalls;
1296 SmallVector<BasicBlock*, 16> AllBlocks;
1297 SmallVector<Instruction*, 16> PointerComparisonsOrSubtracts;
1301 // Fill the set of memory operations to instrument.
1302 for (Function::iterator FI = F.begin(), FE = F.end();
1304 AllBlocks.push_back(FI);
1305 TempsToInstrument.clear();
1306 int NumInsnsPerBB = 0;
1307 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1309 if (LooksLikeCodeInBug11395(BI)) return false;
1310 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
1311 if (ClOpt && ClOptSameTemp) {
1312 if (!TempsToInstrument.insert(Addr))
1313 continue; // We've seen this temp in the current BB.
1315 } else if (ClInvalidPointerPairs &&
1316 isInterestingPointerComparisonOrSubtraction(BI)) {
1317 PointerComparisonsOrSubtracts.push_back(BI);
1319 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
1322 if (isa<AllocaInst>(BI))
1326 // A call inside BB.
1327 TempsToInstrument.clear();
1328 if (CS.doesNotReturn())
1329 NoReturnCalls.push_back(CS.getInstruction());
1333 ToInstrument.push_back(BI);
1335 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1340 Function *UninstrumentedDuplicate = 0;
1341 bool LikelyToInstrument =
1342 !NoReturnCalls.empty() || !ToInstrument.empty() || (NumAllocas > 0);
1343 if (ClKeepUninstrumented && LikelyToInstrument) {
1344 ValueToValueMapTy VMap;
1345 UninstrumentedDuplicate = CloneFunction(&F, VMap, false);
1346 UninstrumentedDuplicate->removeFnAttr(Attribute::SanitizeAddress);
1347 UninstrumentedDuplicate->setName("NOASAN_" + F.getName());
1348 F.getParent()->getFunctionList().push_back(UninstrumentedDuplicate);
1351 bool UseCalls = false;
1352 if (ClInstrumentationWithCallsThreshold >= 0 &&
1353 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold)
1357 int NumInstrumented = 0;
1358 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
1359 Instruction *Inst = ToInstrument[i];
1360 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1361 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
1362 if (isInterestingMemoryAccess(Inst, &IsWrite))
1363 instrumentMop(Inst, UseCalls);
1365 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst), UseCalls);
1370 FunctionStackPoisoner FSP(F, *this);
1371 bool ChangedStack = FSP.runOnFunction();
1373 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1374 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1375 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
1376 Instruction *CI = NoReturnCalls[i];
1377 IRBuilder<> IRB(CI);
1378 IRB.CreateCall(AsanHandleNoReturnFunc);
1381 for (size_t i = 0, n = PointerComparisonsOrSubtracts.size(); i != n; i++) {
1382 instrumentPointerComparisonOrSubtraction(PointerComparisonsOrSubtracts[i]);
1386 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
1388 if (InjectCoverage(F, AllBlocks))
1391 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1393 if (ClKeepUninstrumented) {
1395 // No instrumentation is done, no need for the duplicate.
1396 if (UninstrumentedDuplicate)
1397 UninstrumentedDuplicate->eraseFromParent();
1399 // The function was instrumented. We must have the duplicate.
1400 assert(UninstrumentedDuplicate);
1401 UninstrumentedDuplicate->setSection("NOASAN");
1402 assert(!F.hasSection());
1403 F.setSection("ASAN");
1410 // Workaround for bug 11395: we don't want to instrument stack in functions
1411 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1412 // FIXME: remove once the bug 11395 is fixed.
1413 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1414 if (LongSize != 32) return false;
1415 CallInst *CI = dyn_cast<CallInst>(I);
1416 if (!CI || !CI->isInlineAsm()) return false;
1417 if (CI->getNumArgOperands() <= 5) return false;
1418 // We have inline assembly with quite a few arguments.
1422 void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1423 IRBuilder<> IRB(*C);
1424 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1425 std::string Suffix = itostr(i);
1426 AsanStackMallocFunc[i] = checkInterfaceFunction(
1427 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1428 IntptrTy, IntptrTy, NULL));
1429 AsanStackFreeFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
1430 kAsanStackFreeNameTemplate + Suffix, IRB.getVoidTy(), IntptrTy,
1431 IntptrTy, IntptrTy, NULL));
1433 AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1434 kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1435 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1436 kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1440 FunctionStackPoisoner::poisonRedZones(const ArrayRef<uint8_t> ShadowBytes,
1441 IRBuilder<> &IRB, Value *ShadowBase,
1443 size_t n = ShadowBytes.size();
1445 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1446 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1447 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1448 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1449 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1450 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1452 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
1453 if (ASan.DL->isLittleEndian())
1454 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1456 Val = (Val << 8) | ShadowBytes[i + j];
1459 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1460 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1461 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1462 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
1467 // Fake stack allocator (asan_fake_stack.h) has 11 size classes
1468 // for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1469 static int StackMallocSizeClass(uint64_t LocalStackSize) {
1470 assert(LocalStackSize <= kMaxStackMallocSize);
1471 uint64_t MaxSize = kMinStackMallocSize;
1472 for (int i = 0; ; i++, MaxSize *= 2)
1473 if (LocalStackSize <= MaxSize)
1475 llvm_unreachable("impossible LocalStackSize");
1478 // Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1479 // We can not use MemSet intrinsic because it may end up calling the actual
1480 // memset. Size is a multiple of 8.
1481 // Currently this generates 8-byte stores on x86_64; it may be better to
1482 // generate wider stores.
1483 void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1484 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1485 assert(!(Size % 8));
1486 assert(kAsanStackAfterReturnMagic == 0xf5);
1487 for (int i = 0; i < Size; i += 8) {
1488 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1489 IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
1490 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1494 void FunctionStackPoisoner::poisonStack() {
1495 int StackMallocIdx = -1;
1497 assert(AllocaVec.size() > 0);
1498 Instruction *InsBefore = AllocaVec[0];
1499 IRBuilder<> IRB(InsBefore);
1501 SmallVector<ASanStackVariableDescription, 16> SVD;
1502 SVD.reserve(AllocaVec.size());
1503 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1504 AllocaInst *AI = AllocaVec[i];
1505 ASanStackVariableDescription D = { AI->getName().data(),
1506 getAllocaSizeInBytes(AI),
1507 AI->getAlignment(), AI, 0};
1510 // Minimal header size (left redzone) is 4 pointers,
1511 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1512 size_t MinHeaderSize = ASan.LongSize / 2;
1513 ASanStackFrameLayout L;
1514 ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1515 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1516 uint64_t LocalStackSize = L.FrameSize;
1517 bool DoStackMalloc =
1518 ASan.CheckUseAfterReturn && LocalStackSize <= kMaxStackMallocSize;
1520 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1521 AllocaInst *MyAlloca =
1522 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
1523 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1524 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1525 MyAlloca->setAlignment(FrameAlignment);
1526 assert(MyAlloca->isStaticAlloca());
1527 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1528 Value *LocalStackBase = OrigStackBase;
1530 if (DoStackMalloc) {
1531 // LocalStackBase = OrigStackBase
1532 // if (__asan_option_detect_stack_use_after_return)
1533 // LocalStackBase = __asan_stack_malloc_N(LocalStackBase, OrigStackBase);
1534 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1535 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
1536 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1537 kAsanOptionDetectUAR, IRB.getInt32Ty());
1538 Value *Cmp = IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1539 Constant::getNullValue(IRB.getInt32Ty()));
1540 Instruction *Term = SplitBlockAndInsertIfThen(Cmp, InsBefore, false);
1541 BasicBlock *CmpBlock = cast<Instruction>(Cmp)->getParent();
1542 IRBuilder<> IRBIf(Term);
1543 LocalStackBase = IRBIf.CreateCall2(
1544 AsanStackMallocFunc[StackMallocIdx],
1545 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1546 BasicBlock *SetBlock = cast<Instruction>(LocalStackBase)->getParent();
1547 IRB.SetInsertPoint(InsBefore);
1548 PHINode *Phi = IRB.CreatePHI(IntptrTy, 2);
1549 Phi->addIncoming(OrigStackBase, CmpBlock);
1550 Phi->addIncoming(LocalStackBase, SetBlock);
1551 LocalStackBase = Phi;
1554 // Insert poison calls for lifetime intrinsics for alloca.
1555 bool HavePoisonedAllocas = false;
1556 for (size_t i = 0, n = AllocaPoisonCallVec.size(); i < n; i++) {
1557 const AllocaPoisonCall &APC = AllocaPoisonCallVec[i];
1558 assert(APC.InsBefore);
1560 IRBuilder<> IRB(APC.InsBefore);
1561 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
1562 HavePoisonedAllocas |= APC.DoPoison;
1565 // Replace Alloca instructions with base+offset.
1566 for (size_t i = 0, n = SVD.size(); i < n; i++) {
1567 AllocaInst *AI = SVD[i].AI;
1568 Value *NewAllocaPtr = IRB.CreateIntToPtr(
1569 IRB.CreateAdd(LocalStackBase,
1570 ConstantInt::get(IntptrTy, SVD[i].Offset)),
1572 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
1573 AI->replaceAllUsesWith(NewAllocaPtr);
1576 // The left-most redzone has enough space for at least 4 pointers.
1577 // Write the Magic value to redzone[0].
1578 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1579 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1581 // Write the frame description constant to redzone[1].
1582 Value *BasePlus1 = IRB.CreateIntToPtr(
1583 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
1585 GlobalVariable *StackDescriptionGlobal =
1586 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
1587 /*AllowMerging*/true);
1588 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1590 IRB.CreateStore(Description, BasePlus1);
1591 // Write the PC to redzone[2].
1592 Value *BasePlus2 = IRB.CreateIntToPtr(
1593 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
1594 2 * ASan.LongSize/8)),
1596 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
1598 // Poison the stack redzones at the entry.
1599 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1600 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
1602 // (Un)poison the stack before all ret instructions.
1603 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1604 Instruction *Ret = RetVec[i];
1605 IRBuilder<> IRBRet(Ret);
1606 // Mark the current frame as retired.
1607 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1609 if (DoStackMalloc) {
1610 assert(StackMallocIdx >= 0);
1611 // if LocalStackBase != OrigStackBase:
1612 // // In use-after-return mode, poison the whole stack frame.
1613 // if StackMallocIdx <= 4
1614 // // For small sizes inline the whole thing:
1615 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
1616 // **SavedFlagPtr(LocalStackBase) = 0
1618 // __asan_stack_free_N(LocalStackBase, OrigStackBase)
1620 // <This is not a fake stack; unpoison the redzones>
1621 Value *Cmp = IRBRet.CreateICmpNE(LocalStackBase, OrigStackBase);
1622 TerminatorInst *ThenTerm, *ElseTerm;
1623 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1625 IRBuilder<> IRBPoison(ThenTerm);
1626 if (StackMallocIdx <= 4) {
1627 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1628 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1629 ClassSize >> Mapping.Scale);
1630 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
1632 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1633 Value *SavedFlagPtr = IRBPoison.CreateLoad(
1634 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1635 IRBPoison.CreateStore(
1636 Constant::getNullValue(IRBPoison.getInt8Ty()),
1637 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1639 // For larger frames call __asan_stack_free_*.
1640 IRBPoison.CreateCall3(AsanStackFreeFunc[StackMallocIdx], LocalStackBase,
1641 ConstantInt::get(IntptrTy, LocalStackSize),
1645 IRBuilder<> IRBElse(ElseTerm);
1646 poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
1647 } else if (HavePoisonedAllocas) {
1648 // If we poisoned some allocas in llvm.lifetime analysis,
1649 // unpoison whole stack frame now.
1650 assert(LocalStackBase == OrigStackBase);
1651 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
1653 poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
1657 // We are done. Remove the old unused alloca instructions.
1658 for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1659 AllocaVec[i]->eraseFromParent();
1662 void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
1663 IRBuilder<> &IRB, bool DoPoison) {
1664 // For now just insert the call to ASan runtime.
1665 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1666 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1667 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1668 : AsanUnpoisonStackMemoryFunc,
1672 // Handling llvm.lifetime intrinsics for a given %alloca:
1673 // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1674 // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1675 // invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1676 // could be poisoned by previous llvm.lifetime.end instruction, as the
1677 // variable may go in and out of scope several times, e.g. in loops).
1678 // (3) if we poisoned at least one %alloca in a function,
1679 // unpoison the whole stack frame at function exit.
1681 AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1682 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1683 // We're intested only in allocas we can handle.
1684 return isInterestingAlloca(*AI) ? AI : 0;
1685 // See if we've already calculated (or started to calculate) alloca for a
1687 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1688 if (I != AllocaForValue.end())
1690 // Store 0 while we're calculating alloca for value V to avoid
1691 // infinite recursion if the value references itself.
1692 AllocaForValue[V] = 0;
1693 AllocaInst *Res = 0;
1694 if (CastInst *CI = dyn_cast<CastInst>(V))
1695 Res = findAllocaForValue(CI->getOperand(0));
1696 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1697 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1698 Value *IncValue = PN->getIncomingValue(i);
1699 // Allow self-referencing phi-nodes.
1700 if (IncValue == PN) continue;
1701 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1702 // AI for incoming values should exist and should all be equal.
1703 if (IncValueAI == 0 || (Res != 0 && IncValueAI != Res))
1709 AllocaForValue[V] = Res;