1 //===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is a part of AddressSanitizer, an address sanity checker.
11 // Details of the algorithm:
12 // http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm
14 //===----------------------------------------------------------------------===//
16 #include "llvm/Transforms/Instrumentation.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/DenseSet.h"
20 #include "llvm/ADT/DepthFirstIterator.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/Triple.h"
27 #include "llvm/Analysis/MemoryBuiltins.h"
28 #include "llvm/Analysis/TargetLibraryInfo.h"
29 #include "llvm/Analysis/ValueTracking.h"
30 #include "llvm/IR/CallSite.h"
31 #include "llvm/IR/DIBuilder.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/Dominators.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/IRBuilder.h"
36 #include "llvm/IR/InlineAsm.h"
37 #include "llvm/IR/InstVisitor.h"
38 #include "llvm/IR/IntrinsicInst.h"
39 #include "llvm/IR/LLVMContext.h"
40 #include "llvm/IR/MDBuilder.h"
41 #include "llvm/IR/Module.h"
42 #include "llvm/IR/Type.h"
43 #include "llvm/MC/MCSectionMachO.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/DataTypes.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/Endian.h"
48 #include "llvm/Support/SwapByteOrder.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/Transforms/Scalar.h"
51 #include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
52 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
53 #include "llvm/Transforms/Utils/Cloning.h"
54 #include "llvm/Transforms/Utils/Local.h"
55 #include "llvm/Transforms/Utils/ModuleUtils.h"
56 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
59 #include <system_error>
63 #define DEBUG_TYPE "asan"
65 static const uint64_t kDefaultShadowScale = 3;
66 static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
67 static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
68 static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
69 static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
70 static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;
71 static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
72 static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
73 static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
74 static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
75 static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
76 static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
77 static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
79 static const size_t kMinStackMallocSize = 1 << 6; // 64B
80 static const size_t kMaxStackMallocSize = 1 << 16; // 64K
81 static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
82 static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
84 static const char *const kAsanModuleCtorName = "asan.module_ctor";
85 static const char *const kAsanModuleDtorName = "asan.module_dtor";
86 static const uint64_t kAsanCtorAndDtorPriority = 1;
87 static const char *const kAsanReportErrorTemplate = "__asan_report_";
88 static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
89 static const char *const kAsanUnregisterGlobalsName =
90 "__asan_unregister_globals";
91 static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
92 static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
93 static const char *const kAsanInitName = "__asan_init_v5";
94 static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
95 static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
96 static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
97 static const int kMaxAsanStackMallocSizeClass = 10;
98 static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
99 static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
100 static const char *const kAsanGenPrefix = "__asan_gen_";
101 static const char *const kSanCovGenPrefix = "__sancov_gen_";
102 static const char *const kAsanPoisonStackMemoryName =
103 "__asan_poison_stack_memory";
104 static const char *const kAsanUnpoisonStackMemoryName =
105 "__asan_unpoison_stack_memory";
107 static const char *const kAsanOptionDetectUAR =
108 "__asan_option_detect_stack_use_after_return";
110 static const char *const kAsanAllocaPoison = "__asan_alloca_poison";
111 static const char *const kAsanAllocasUnpoison = "__asan_allocas_unpoison";
113 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
114 static const size_t kNumberOfAccessSizes = 5;
116 static const unsigned kAllocaRzSize = 32;
118 // Command-line flags.
119 static cl::opt<bool> ClEnableKasan(
120 "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
121 cl::Hidden, cl::init(false));
123 // This flag may need to be replaced with -f[no-]asan-reads.
124 static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
125 cl::desc("instrument read instructions"),
126 cl::Hidden, cl::init(true));
127 static cl::opt<bool> ClInstrumentWrites(
128 "asan-instrument-writes", cl::desc("instrument write instructions"),
129 cl::Hidden, cl::init(true));
130 static cl::opt<bool> ClInstrumentAtomics(
131 "asan-instrument-atomics",
132 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
134 static cl::opt<bool> ClAlwaysSlowPath(
135 "asan-always-slow-path",
136 cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
138 // This flag limits the number of instructions to be instrumented
139 // in any given BB. Normally, this should be set to unlimited (INT_MAX),
140 // but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
142 static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
143 "asan-max-ins-per-bb", cl::init(10000),
144 cl::desc("maximal number of instructions to instrument in any given BB"),
146 // This flag may need to be replaced with -f[no]asan-stack.
147 static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
148 cl::Hidden, cl::init(true));
149 static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
150 cl::desc("Check return-after-free"),
151 cl::Hidden, cl::init(true));
152 // This flag may need to be replaced with -f[no]asan-globals.
153 static cl::opt<bool> ClGlobals("asan-globals",
154 cl::desc("Handle global objects"), cl::Hidden,
156 static cl::opt<bool> ClInitializers("asan-initialization-order",
157 cl::desc("Handle C++ initializer order"),
158 cl::Hidden, cl::init(true));
159 static cl::opt<bool> ClInvalidPointerPairs(
160 "asan-detect-invalid-pointer-pair",
161 cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
163 static cl::opt<unsigned> ClRealignStack(
164 "asan-realign-stack",
165 cl::desc("Realign stack to the value of this flag (power of two)"),
166 cl::Hidden, cl::init(32));
167 static cl::opt<int> ClInstrumentationWithCallsThreshold(
168 "asan-instrumentation-with-call-threshold",
170 "If the function being instrumented contains more than "
171 "this number of memory accesses, use callbacks instead of "
172 "inline checks (-1 means never use callbacks)."),
173 cl::Hidden, cl::init(7000));
174 static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
175 "asan-memory-access-callback-prefix",
176 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
177 cl::init("__asan_"));
178 static cl::opt<bool> ClInstrumentAllocas("asan-instrument-allocas",
179 cl::desc("instrument dynamic allocas"),
180 cl::Hidden, cl::init(false));
181 static cl::opt<bool> ClSkipPromotableAllocas(
182 "asan-skip-promotable-allocas",
183 cl::desc("Do not instrument promotable allocas"), cl::Hidden,
186 // These flags allow to change the shadow mapping.
187 // The shadow mapping looks like
188 // Shadow = (Mem >> scale) + (1 << offset_log)
189 static cl::opt<int> ClMappingScale("asan-mapping-scale",
190 cl::desc("scale of asan shadow mapping"),
191 cl::Hidden, cl::init(0));
193 // Optimization flags. Not user visible, used mostly for testing
194 // and benchmarking the tool.
195 static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
196 cl::Hidden, cl::init(true));
197 static cl::opt<bool> ClOptSameTemp(
198 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
199 cl::Hidden, cl::init(true));
200 static cl::opt<bool> ClOptGlobals("asan-opt-globals",
201 cl::desc("Don't instrument scalar globals"),
202 cl::Hidden, cl::init(true));
203 static cl::opt<bool> ClOptStack(
204 "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
205 cl::Hidden, cl::init(false));
207 static cl::opt<bool> ClCheckLifetime(
208 "asan-check-lifetime",
209 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"), cl::Hidden,
212 static cl::opt<bool> ClDynamicAllocaStack(
213 "asan-stack-dynamic-alloca",
214 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
217 static cl::opt<uint32_t> ClForceExperiment(
218 "asan-force-experiment",
219 cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
223 static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
225 static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
226 cl::Hidden, cl::init(0));
227 static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
228 cl::desc("Debug func"));
229 static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
230 cl::Hidden, cl::init(-1));
231 static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
232 cl::Hidden, cl::init(-1));
234 STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
235 STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
236 STATISTIC(NumOptimizedAccessesToGlobalVar,
237 "Number of optimized accesses to global vars");
238 STATISTIC(NumOptimizedAccessesToStackVar,
239 "Number of optimized accesses to stack vars");
242 /// Frontend-provided metadata for source location.
243 struct LocationMetadata {
248 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
250 bool empty() const { return Filename.empty(); }
252 void parse(MDNode *MDN) {
253 assert(MDN->getNumOperands() == 3);
254 MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
255 Filename = DIFilename->getString();
257 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
259 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
263 /// Frontend-provided metadata for global variables.
264 class GlobalsMetadata {
267 Entry() : SourceLoc(), Name(), IsDynInit(false), IsBlacklisted(false) {}
268 LocationMetadata SourceLoc;
274 GlobalsMetadata() : inited_(false) {}
276 void init(Module &M) {
279 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
280 if (!Globals) return;
281 for (auto MDN : Globals->operands()) {
282 // Metadata node contains the global and the fields of "Entry".
283 assert(MDN->getNumOperands() == 5);
284 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
285 // The optimizer may optimize away a global entirely.
287 // We can already have an entry for GV if it was merged with another
289 Entry &E = Entries[GV];
290 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
291 E.SourceLoc.parse(Loc);
292 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
293 E.Name = Name->getString();
294 ConstantInt *IsDynInit =
295 mdconst::extract<ConstantInt>(MDN->getOperand(3));
296 E.IsDynInit |= IsDynInit->isOne();
297 ConstantInt *IsBlacklisted =
298 mdconst::extract<ConstantInt>(MDN->getOperand(4));
299 E.IsBlacklisted |= IsBlacklisted->isOne();
303 /// Returns metadata entry for a given global.
304 Entry get(GlobalVariable *G) const {
305 auto Pos = Entries.find(G);
306 return (Pos != Entries.end()) ? Pos->second : Entry();
311 DenseMap<GlobalVariable *, Entry> Entries;
314 /// This struct defines the shadow mapping using the rule:
315 /// shadow = (mem >> Scale) ADD-or-OR Offset.
316 struct ShadowMapping {
322 static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
324 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
325 bool IsIOS = TargetTriple.isiOS();
326 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
327 bool IsLinux = TargetTriple.isOSLinux();
328 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
329 TargetTriple.getArch() == llvm::Triple::ppc64le;
330 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
331 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
332 TargetTriple.getArch() == llvm::Triple::mipsel;
333 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
334 TargetTriple.getArch() == llvm::Triple::mips64el;
335 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
336 bool IsWindows = TargetTriple.isOSWindows();
338 ShadowMapping Mapping;
341 // Android is always PIE, which means that the beginning of the address
342 // space is always available.
344 } else if (LongSize == 32) {
346 Mapping.Offset = kMIPS32_ShadowOffset32;
348 Mapping.Offset = kFreeBSD_ShadowOffset32;
350 Mapping.Offset = kIOSShadowOffset32;
352 Mapping.Offset = kWindowsShadowOffset32;
354 Mapping.Offset = kDefaultShadowOffset32;
355 } else { // LongSize == 64
357 Mapping.Offset = kPPC64_ShadowOffset64;
359 Mapping.Offset = kFreeBSD_ShadowOffset64;
360 else if (IsLinux && IsX86_64) {
362 Mapping.Offset = kLinuxKasan_ShadowOffset64;
364 Mapping.Offset = kSmallX86_64ShadowOffset;
366 Mapping.Offset = kMIPS64_ShadowOffset64;
368 Mapping.Offset = kAArch64_ShadowOffset64;
370 Mapping.Offset = kDefaultShadowOffset64;
373 Mapping.Scale = kDefaultShadowScale;
374 if (ClMappingScale) {
375 Mapping.Scale = ClMappingScale;
378 // OR-ing shadow offset if more efficient (at least on x86) if the offset
379 // is a power of two, but on ppc64 we have to use add since the shadow
380 // offset is not necessary 1/8-th of the address space.
381 Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
386 static size_t RedzoneSizeForScale(int MappingScale) {
387 // Redzone used for stack and globals is at least 32 bytes.
388 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
389 return std::max(32U, 1U << MappingScale);
392 /// AddressSanitizer: instrument the code in module to find memory bugs.
393 struct AddressSanitizer : public FunctionPass {
394 explicit AddressSanitizer(bool CompileKernel = false)
395 : FunctionPass(ID), CompileKernel(CompileKernel || ClEnableKasan) {
396 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
398 const char *getPassName() const override {
399 return "AddressSanitizerFunctionPass";
401 void getAnalysisUsage(AnalysisUsage &AU) const override {
402 AU.addRequired<DominatorTreeWrapperPass>();
403 AU.addRequired<TargetLibraryInfoWrapperPass>();
405 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
406 Type *Ty = AI->getAllocatedType();
407 uint64_t SizeInBytes =
408 AI->getModule()->getDataLayout().getTypeAllocSize(Ty);
411 /// Check if we want (and can) handle this alloca.
412 bool isInterestingAlloca(AllocaInst &AI);
414 // Check if we have dynamic alloca.
415 bool isDynamicAlloca(AllocaInst &AI) const {
416 return AI.isArrayAllocation() || !AI.isStaticAlloca();
419 /// If it is an interesting memory access, return the PointerOperand
420 /// and set IsWrite/Alignment. Otherwise return nullptr.
421 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
422 uint64_t *TypeSize, unsigned *Alignment);
423 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
424 bool UseCalls, const DataLayout &DL);
425 void instrumentPointerComparisonOrSubtraction(Instruction *I);
426 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
427 Value *Addr, uint32_t TypeSize, bool IsWrite,
428 Value *SizeArgument, bool UseCalls, uint32_t Exp);
429 void instrumentUnusualSizeOrAlignment(Instruction *I, Value *Addr,
430 uint32_t TypeSize, bool IsWrite,
431 Value *SizeArgument, bool UseCalls,
433 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
434 Value *ShadowValue, uint32_t TypeSize);
435 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
436 bool IsWrite, size_t AccessSizeIndex,
437 Value *SizeArgument, uint32_t Exp);
438 void instrumentMemIntrinsic(MemIntrinsic *MI);
439 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
440 bool runOnFunction(Function &F) override;
441 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
442 bool doInitialization(Module &M) override;
443 static char ID; // Pass identification, replacement for typeid
445 DominatorTree &getDominatorTree() const { return *DT; }
448 void initializeCallbacks(Module &M);
450 bool LooksLikeCodeInBug11395(Instruction *I);
451 bool GlobalIsLinkerInitialized(GlobalVariable *G);
452 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
453 uint64_t TypeSize) const;
460 ShadowMapping Mapping;
462 Function *AsanCtorFunction = nullptr;
463 Function *AsanInitFunction = nullptr;
464 Function *AsanHandleNoReturnFunc;
465 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
466 // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
467 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
468 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
469 // This array is indexed by AccessIsWrite and Experiment.
470 Function *AsanErrorCallbackSized[2][2];
471 Function *AsanMemoryAccessCallbackSized[2][2];
472 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
474 GlobalsMetadata GlobalsMD;
475 DenseMap<AllocaInst *, bool> ProcessedAllocas;
477 friend struct FunctionStackPoisoner;
480 class AddressSanitizerModule : public ModulePass {
482 explicit AddressSanitizerModule(bool CompileKernel = false)
483 : ModulePass(ID), CompileKernel(CompileKernel || ClEnableKasan) {}
484 bool runOnModule(Module &M) override;
485 static char ID; // Pass identification, replacement for typeid
486 const char *getPassName() const override { return "AddressSanitizerModule"; }
489 void initializeCallbacks(Module &M);
491 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
492 bool ShouldInstrumentGlobal(GlobalVariable *G);
493 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
494 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
495 size_t MinRedzoneSizeForGlobal() const {
496 return RedzoneSizeForScale(Mapping.Scale);
499 GlobalsMetadata GlobalsMD;
504 ShadowMapping Mapping;
505 Function *AsanPoisonGlobals;
506 Function *AsanUnpoisonGlobals;
507 Function *AsanRegisterGlobals;
508 Function *AsanUnregisterGlobals;
511 // Stack poisoning does not play well with exception handling.
512 // When an exception is thrown, we essentially bypass the code
513 // that unpoisones the stack. This is why the run-time library has
514 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
515 // stack in the interceptor. This however does not work inside the
516 // actual function which catches the exception. Most likely because the
517 // compiler hoists the load of the shadow value somewhere too high.
518 // This causes asan to report a non-existing bug on 453.povray.
519 // It sounds like an LLVM bug.
520 struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
522 AddressSanitizer &ASan;
527 ShadowMapping Mapping;
529 SmallVector<AllocaInst *, 16> AllocaVec;
530 SmallVector<AllocaInst *, 16> NonInstrumentedStaticAllocaVec;
531 SmallVector<Instruction *, 8> RetVec;
532 unsigned StackAlignment;
534 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
535 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
536 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
537 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
539 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
540 struct AllocaPoisonCall {
541 IntrinsicInst *InsBefore;
546 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
548 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
549 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
550 AllocaInst *DynamicAllocaLayout = nullptr;
552 // Maps Value to an AllocaInst from which the Value is originated.
553 typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
554 AllocaForValueMapTy AllocaForValue;
556 bool HasNonEmptyInlineAsm;
557 std::unique_ptr<CallInst> EmptyInlineAsm;
559 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
562 DIB(*F.getParent(), /*AllowUnresolved*/ false),
564 IntptrTy(ASan.IntptrTy),
565 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
566 Mapping(ASan.Mapping),
567 StackAlignment(1 << Mapping.Scale),
568 HasNonEmptyInlineAsm(false),
569 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
571 bool runOnFunction() {
572 if (!ClStack) return false;
573 // Collect alloca, ret, lifetime instructions etc.
574 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
576 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
578 initializeCallbacks(*F.getParent());
588 // Finds all Alloca instructions and puts
589 // poisoned red zones around all of them.
590 // Then unpoison everything back before the function returns.
593 void createDynamicAllocasInitStorage();
595 // ----------------------- Visitors.
596 /// \brief Collect all Ret instructions.
597 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
599 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
601 IRBuilder<> IRB(InstBefore);
602 IRB.CreateCall(AsanAllocasUnpoisonFunc,
603 {IRB.CreateLoad(DynamicAllocaLayout),
604 IRB.CreatePtrToInt(SavedStack, IntptrTy)});
607 // Unpoison dynamic allocas redzones.
608 void unpoisonDynamicAllocas() {
609 for (auto &Ret : RetVec)
610 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
612 for (auto &StackRestoreInst : StackRestoreVec)
613 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
614 StackRestoreInst->getOperand(0));
617 // Deploy and poison redzones around dynamic alloca call. To do this, we
618 // should replace this call with another one with changed parameters and
619 // replace all its uses with new address, so
620 // addr = alloca type, old_size, align
622 // new_size = (old_size + additional_size) * sizeof(type)
623 // tmp = alloca i8, new_size, max(align, 32)
624 // addr = tmp + 32 (first 32 bytes are for the left redzone).
625 // Additional_size is added to make new memory allocation contain not only
626 // requested memory, but also left, partial and right redzones.
627 void handleDynamicAllocaCall(AllocaInst *AI);
629 /// \brief Collect Alloca instructions we want (and can) handle.
630 void visitAllocaInst(AllocaInst &AI) {
631 if (!ASan.isInterestingAlloca(AI)) {
632 if (AI.isStaticAlloca()) NonInstrumentedStaticAllocaVec.push_back(&AI);
636 StackAlignment = std::max(StackAlignment, AI.getAlignment());
637 if (ASan.isDynamicAlloca(AI))
638 DynamicAllocaVec.push_back(&AI);
640 AllocaVec.push_back(&AI);
643 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
645 void visitIntrinsicInst(IntrinsicInst &II) {
646 Intrinsic::ID ID = II.getIntrinsicID();
647 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
648 if (!ClCheckLifetime) return;
649 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
651 // Found lifetime intrinsic, add ASan instrumentation if necessary.
652 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
653 // If size argument is undefined, don't do anything.
654 if (Size->isMinusOne()) return;
655 // Check that size doesn't saturate uint64_t and can
656 // be stored in IntptrTy.
657 const uint64_t SizeValue = Size->getValue().getLimitedValue();
658 if (SizeValue == ~0ULL ||
659 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
661 // Find alloca instruction that corresponds to llvm.lifetime argument.
662 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
664 bool DoPoison = (ID == Intrinsic::lifetime_end);
665 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
666 AllocaPoisonCallVec.push_back(APC);
669 void visitCallInst(CallInst &CI) {
670 HasNonEmptyInlineAsm |=
671 CI.isInlineAsm() && !CI.isIdenticalTo(EmptyInlineAsm.get());
674 // ---------------------- Helpers.
675 void initializeCallbacks(Module &M);
677 bool doesDominateAllExits(const Instruction *I) const {
678 for (auto Ret : RetVec) {
679 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
684 /// Finds alloca where the value comes from.
685 AllocaInst *findAllocaForValue(Value *V);
686 void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
687 Value *ShadowBase, bool DoPoison);
688 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
690 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
692 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
694 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
695 Instruction *ThenTerm, Value *ValueIfFalse);
700 char AddressSanitizer::ID = 0;
701 INITIALIZE_PASS_BEGIN(
702 AddressSanitizer, "asan",
703 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
705 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
707 AddressSanitizer, "asan",
708 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
710 FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel) {
711 return new AddressSanitizer(CompileKernel);
714 char AddressSanitizerModule::ID = 0;
716 AddressSanitizerModule, "asan-module",
717 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
720 ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel) {
721 return new AddressSanitizerModule(CompileKernel);
724 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
725 size_t Res = countTrailingZeros(TypeSize / 8);
726 assert(Res < kNumberOfAccessSizes);
730 // \brief Create a constant for Str so that we can pass it to the run-time lib.
731 static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
733 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
734 // We use private linkage for module-local strings. If they can be merged
735 // with another one, we set the unnamed_addr attribute.
737 new GlobalVariable(M, StrConst->getType(), true,
738 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
739 if (AllowMerging) GV->setUnnamedAddr(true);
740 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
744 /// \brief Create a global describing a source location.
745 static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
746 LocationMetadata MD) {
747 Constant *LocData[] = {
748 createPrivateGlobalForString(M, MD.Filename, true),
749 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
750 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
752 auto LocStruct = ConstantStruct::getAnon(LocData);
753 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
754 GlobalValue::PrivateLinkage, LocStruct,
756 GV->setUnnamedAddr(true);
760 static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
761 return G->getName().find(kAsanGenPrefix) == 0 ||
762 G->getName().find(kSanCovGenPrefix) == 0;
765 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
767 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
768 if (Mapping.Offset == 0) return Shadow;
769 // (Shadow >> scale) | offset
770 if (Mapping.OrShadowOffset)
771 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
773 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
776 // Instrument memset/memmove/memcpy
777 void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
779 if (isa<MemTransferInst>(MI)) {
781 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
782 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
783 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
784 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
785 } else if (isa<MemSetInst>(MI)) {
788 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
789 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
790 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
792 MI->eraseFromParent();
795 /// Check if we want (and can) handle this alloca.
796 bool AddressSanitizer::isInterestingAlloca(AllocaInst &AI) {
797 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
799 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
800 return PreviouslySeenAllocaInfo->getSecond();
803 (AI.getAllocatedType()->isSized() &&
804 // alloca() may be called with 0 size, ignore it.
805 getAllocaSizeInBytes(&AI) > 0 &&
806 // We are only interested in allocas not promotable to registers.
807 // Promotable allocas are common under -O0.
808 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI) ||
809 isDynamicAlloca(AI)));
811 ProcessedAllocas[&AI] = IsInteresting;
812 return IsInteresting;
815 /// If I is an interesting memory access, return the PointerOperand
816 /// and set IsWrite/Alignment. Otherwise return nullptr.
817 Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
820 unsigned *Alignment) {
821 // Skip memory accesses inserted by another instrumentation.
822 if (I->getMetadata("nosanitize")) return nullptr;
824 Value *PtrOperand = nullptr;
825 const DataLayout &DL = I->getModule()->getDataLayout();
826 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
827 if (!ClInstrumentReads) return nullptr;
829 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
830 *Alignment = LI->getAlignment();
831 PtrOperand = LI->getPointerOperand();
832 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
833 if (!ClInstrumentWrites) return nullptr;
835 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
836 *Alignment = SI->getAlignment();
837 PtrOperand = SI->getPointerOperand();
838 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
839 if (!ClInstrumentAtomics) return nullptr;
841 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
843 PtrOperand = RMW->getPointerOperand();
844 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
845 if (!ClInstrumentAtomics) return nullptr;
847 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
849 PtrOperand = XCHG->getPointerOperand();
852 // Treat memory accesses to promotable allocas as non-interesting since they
853 // will not cause memory violations. This greatly speeds up the instrumented
854 // executable at -O0.
855 if (ClSkipPromotableAllocas)
856 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
857 return isInterestingAlloca(*AI) ? AI : nullptr;
862 static bool isPointerOperand(Value *V) {
863 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
866 // This is a rough heuristic; it may cause both false positives and
867 // false negatives. The proper implementation requires cooperation with
869 static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
870 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
871 if (!Cmp->isRelational()) return false;
872 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
873 if (BO->getOpcode() != Instruction::Sub) return false;
877 if (!isPointerOperand(I->getOperand(0)) ||
878 !isPointerOperand(I->getOperand(1)))
883 bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
884 // If a global variable does not have dynamic initialization we don't
885 // have to instrument it. However, if a global does not have initializer
886 // at all, we assume it has dynamic initializer (in other TU).
887 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
890 void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
893 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
894 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
895 for (int i = 0; i < 2; i++) {
896 if (Param[i]->getType()->isPointerTy())
897 Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
899 IRB.CreateCall(F, Param);
902 void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
903 Instruction *I, bool UseCalls,
904 const DataLayout &DL) {
905 bool IsWrite = false;
906 unsigned Alignment = 0;
907 uint64_t TypeSize = 0;
908 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment);
911 // Optimization experiments.
912 // The experiments can be used to evaluate potential optimizations that remove
913 // instrumentation (assess false negatives). Instead of completely removing
914 // some instrumentation, you set Exp to a non-zero value (mask of optimization
915 // experiments that want to remove instrumentation of this instruction).
916 // If Exp is non-zero, this pass will emit special calls into runtime
917 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
918 // make runtime terminate the program in a special way (with a different
919 // exit status). Then you run the new compiler on a buggy corpus, collect
920 // the special terminations (ideally, you don't see them at all -- no false
921 // negatives) and make the decision on the optimization.
922 uint32_t Exp = ClForceExperiment;
924 if (ClOpt && ClOptGlobals) {
925 // If initialization order checking is disabled, a simple access to a
926 // dynamically initialized global is always valid.
927 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
928 if (G != NULL && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
929 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
930 NumOptimizedAccessesToGlobalVar++;
935 if (ClOpt && ClOptStack) {
936 // A direct inbounds access to a stack variable is always valid.
937 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
938 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
939 NumOptimizedAccessesToStackVar++;
945 NumInstrumentedWrites++;
947 NumInstrumentedReads++;
949 unsigned Granularity = 1 << Mapping.Scale;
950 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
951 // if the data is properly aligned.
952 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
954 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
955 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls,
957 instrumentUnusualSizeOrAlignment(I, Addr, TypeSize, IsWrite, nullptr,
961 Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
962 Value *Addr, bool IsWrite,
963 size_t AccessSizeIndex,
966 IRBuilder<> IRB(InsertBefore);
967 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
968 CallInst *Call = nullptr;
971 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
972 {Addr, SizeArgument});
974 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
975 {Addr, SizeArgument, ExpVal});
979 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
981 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
985 // We don't do Call->setDoesNotReturn() because the BB already has
986 // UnreachableInst at the end.
987 // This EmptyAsm is required to avoid callback merge.
988 IRB.CreateCall(EmptyAsm, {});
992 Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
995 size_t Granularity = 1 << Mapping.Scale;
996 // Addr & (Granularity - 1)
997 Value *LastAccessedByte =
998 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
999 // (Addr & (Granularity - 1)) + size - 1
1000 if (TypeSize / 8 > 1)
1001 LastAccessedByte = IRB.CreateAdd(
1002 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1003 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
1005 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
1006 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1007 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1010 void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
1011 Instruction *InsertBefore, Value *Addr,
1012 uint32_t TypeSize, bool IsWrite,
1013 Value *SizeArgument, bool UseCalls,
1015 IRBuilder<> IRB(InsertBefore);
1016 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1017 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1021 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1024 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1025 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
1030 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
1031 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1032 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1033 Value *CmpVal = Constant::getNullValue(ShadowTy);
1034 Value *ShadowValue =
1035 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
1037 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
1038 size_t Granularity = 1 << Mapping.Scale;
1039 TerminatorInst *CrashTerm = nullptr;
1041 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
1042 // We use branch weights for the slow path check, to indicate that the slow
1043 // path is rarely taken. This seems to be the case for SPEC benchmarks.
1044 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1045 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
1046 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
1047 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
1048 IRB.SetInsertPoint(CheckTerm);
1049 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
1050 BasicBlock *CrashBlock =
1051 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
1052 CrashTerm = new UnreachableInst(*C, CrashBlock);
1053 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1054 ReplaceInstWithInst(CheckTerm, NewTerm);
1056 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
1059 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
1060 AccessSizeIndex, SizeArgument, Exp);
1061 Crash->setDebugLoc(OrigIns->getDebugLoc());
1064 // Instrument unusual size or unusual alignment.
1065 // We can not do it with a single check, so we do 1-byte check for the first
1066 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1067 // to report the actual access size.
1068 void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1069 Instruction *I, Value *Addr, uint32_t TypeSize, bool IsWrite,
1070 Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1072 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1073 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1076 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1079 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1080 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
1082 Value *LastByte = IRB.CreateIntToPtr(
1083 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1085 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false, Exp);
1086 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false, Exp);
1090 void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1091 GlobalValue *ModuleName) {
1092 // Set up the arguments to our poison/unpoison functions.
1093 IRBuilder<> IRB(GlobalInit.begin()->getFirstInsertionPt());
1095 // Add a call to poison all external globals before the given function starts.
1096 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1097 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
1099 // Add calls to unpoison all globals before each return instruction.
1100 for (auto &BB : GlobalInit.getBasicBlockList())
1101 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
1102 CallInst::Create(AsanUnpoisonGlobals, "", RI);
1105 void AddressSanitizerModule::createInitializerPoisonCalls(
1106 Module &M, GlobalValue *ModuleName) {
1107 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1109 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1110 for (Use &OP : CA->operands()) {
1111 if (isa<ConstantAggregateZero>(OP)) continue;
1112 ConstantStruct *CS = cast<ConstantStruct>(OP);
1114 // Must have a function or null ptr.
1115 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
1116 if (F->getName() == kAsanModuleCtorName) continue;
1117 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1118 // Don't instrument CTORs that will run before asan.module_ctor.
1119 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1120 poisonOneInitializer(*F, ModuleName);
1125 bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
1126 Type *Ty = cast<PointerType>(G->getType())->getElementType();
1127 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
1129 if (GlobalsMD.get(G).IsBlacklisted) return false;
1130 if (!Ty->isSized()) return false;
1131 if (!G->hasInitializer()) return false;
1132 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
1133 // Touch only those globals that will not be defined in other modules.
1134 // Don't handle ODR linkage types and COMDATs since other modules may be built
1136 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1137 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1138 G->getLinkage() != GlobalVariable::InternalLinkage)
1140 if (G->hasComdat()) return false;
1141 // Two problems with thread-locals:
1142 // - The address of the main thread's copy can't be computed at link-time.
1143 // - Need to poison all copies, not just the main thread's one.
1144 if (G->isThreadLocal()) return false;
1145 // For now, just ignore this Global if the alignment is large.
1146 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
1148 if (G->hasSection()) {
1149 StringRef Section(G->getSection());
1151 // Globals from llvm.metadata aren't emitted, do not instrument them.
1152 if (Section == "llvm.metadata") return false;
1153 // Do not instrument globals from special LLVM sections.
1154 if (Section.find("__llvm") != StringRef::npos) return false;
1156 // Callbacks put into the CRT initializer/terminator sections
1157 // should not be instrumented.
1158 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1159 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1160 if (Section.startswith(".CRT")) {
1161 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1165 if (TargetTriple.isOSBinFormatMachO()) {
1166 StringRef ParsedSegment, ParsedSection;
1167 unsigned TAA = 0, StubSize = 0;
1169 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1170 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
1171 if (!ErrorCode.empty()) {
1172 assert(false && "Invalid section specifier.");
1176 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1177 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1179 if (ParsedSegment == "__OBJC" ||
1180 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1181 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1184 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1185 // Constant CFString instances are compiled in the following way:
1186 // -- the string buffer is emitted into
1187 // __TEXT,__cstring,cstring_literals
1188 // -- the constant NSConstantString structure referencing that buffer
1189 // is placed into __DATA,__cfstring
1190 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1191 // Moreover, it causes the linker to crash on OS X 10.7
1192 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1193 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1196 // The linker merges the contents of cstring_literals and removes the
1198 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1199 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1208 void AddressSanitizerModule::initializeCallbacks(Module &M) {
1209 IRBuilder<> IRB(*C);
1210 // Declare our poisoning and unpoisoning functions.
1211 AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1212 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
1213 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
1214 AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1215 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
1216 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1217 // Declare functions that register/unregister globals.
1218 AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1219 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1220 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
1221 AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
1222 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1223 IntptrTy, IntptrTy, nullptr));
1224 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1227 // This function replaces all global variables with new variables that have
1228 // trailing redzones. It also creates a function that poisons
1229 // redzones and inserts this function into llvm.global_ctors.
1230 bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
1233 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1235 for (auto &G : M.globals()) {
1236 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
1239 size_t n = GlobalsToChange.size();
1240 if (n == 0) return false;
1242 // A global is described by a structure
1245 // size_t size_with_redzone;
1246 // const char *name;
1247 // const char *module_name;
1248 // size_t has_dynamic_init;
1249 // void *source_location;
1250 // We initialize an array of such structures and pass it to a run-time call.
1251 StructType *GlobalStructTy =
1252 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
1253 IntptrTy, IntptrTy, nullptr);
1254 SmallVector<Constant *, 16> Initializers(n);
1256 bool HasDynamicallyInitializedGlobals = false;
1258 // We shouldn't merge same module names, as this string serves as unique
1259 // module ID in runtime.
1260 GlobalVariable *ModuleName = createPrivateGlobalForString(
1261 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
1263 auto &DL = M.getDataLayout();
1264 for (size_t i = 0; i < n; i++) {
1265 static const uint64_t kMaxGlobalRedzone = 1 << 18;
1266 GlobalVariable *G = GlobalsToChange[i];
1268 auto MD = GlobalsMD.get(G);
1269 // Create string holding the global name (use global name from metadata
1270 // if it's available, otherwise just write the name of global variable).
1271 GlobalVariable *Name = createPrivateGlobalForString(
1272 M, MD.Name.empty() ? G->getName() : MD.Name,
1273 /*AllowMerging*/ true);
1275 PointerType *PtrTy = cast<PointerType>(G->getType());
1276 Type *Ty = PtrTy->getElementType();
1277 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
1278 uint64_t MinRZ = MinRedzoneSizeForGlobal();
1279 // MinRZ <= RZ <= kMaxGlobalRedzone
1280 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
1281 uint64_t RZ = std::max(
1282 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
1283 uint64_t RightRedzoneSize = RZ;
1284 // Round up to MinRZ
1285 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
1286 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
1287 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1289 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
1290 Constant *NewInitializer =
1291 ConstantStruct::get(NewTy, G->getInitializer(),
1292 Constant::getNullValue(RightRedZoneTy), nullptr);
1294 // Create a new global variable with enough space for a redzone.
1295 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1296 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1297 Linkage = GlobalValue::InternalLinkage;
1298 GlobalVariable *NewGlobal =
1299 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1300 "", G, G->getThreadLocalMode());
1301 NewGlobal->copyAttributesFrom(G);
1302 NewGlobal->setAlignment(MinRZ);
1305 Indices2[0] = IRB.getInt32(0);
1306 Indices2[1] = IRB.getInt32(0);
1308 G->replaceAllUsesWith(
1309 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
1310 NewGlobal->takeName(G);
1311 G->eraseFromParent();
1313 Constant *SourceLoc;
1314 if (!MD.SourceLoc.empty()) {
1315 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1316 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1318 SourceLoc = ConstantInt::get(IntptrTy, 0);
1321 Initializers[i] = ConstantStruct::get(
1322 GlobalStructTy, ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
1323 ConstantInt::get(IntptrTy, SizeInBytes),
1324 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1325 ConstantExpr::getPointerCast(Name, IntptrTy),
1326 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
1327 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc, nullptr);
1329 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
1331 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
1334 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1335 GlobalVariable *AllGlobals = new GlobalVariable(
1336 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1337 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1339 // Create calls for poisoning before initializers run and unpoisoning after.
1340 if (HasDynamicallyInitializedGlobals)
1341 createInitializerPoisonCalls(M, ModuleName);
1342 IRB.CreateCall(AsanRegisterGlobals,
1343 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1344 ConstantInt::get(IntptrTy, n)});
1346 // We also need to unregister globals at the end, e.g. when a shared library
1348 Function *AsanDtorFunction =
1349 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1350 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1351 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1352 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
1353 IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1354 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1355 ConstantInt::get(IntptrTy, n)});
1356 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
1362 bool AddressSanitizerModule::runOnModule(Module &M) {
1363 C = &(M.getContext());
1364 int LongSize = M.getDataLayout().getPointerSizeInBits();
1365 IntptrTy = Type::getIntNTy(*C, LongSize);
1366 TargetTriple = Triple(M.getTargetTriple());
1367 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
1368 initializeCallbacks(M);
1370 bool Changed = false;
1372 // TODO(glider): temporarily disabled globals instrumentation for KASan.
1373 if (ClGlobals && !CompileKernel) {
1374 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1376 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1377 Changed |= InstrumentGlobals(IRB, M);
1383 void AddressSanitizer::initializeCallbacks(Module &M) {
1384 IRBuilder<> IRB(*C);
1385 // Create __asan_report* callbacks.
1386 // IsWrite, TypeSize and Exp are encoded in the function name.
1387 for (int Exp = 0; Exp < 2; Exp++) {
1388 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1389 const std::string TypeStr = AccessIsWrite ? "store" : "load";
1390 const std::string ExpStr = Exp ? "exp_" : "";
1391 const std::string SuffixStr = CompileKernel ? "N" : "_n";
1392 const std::string EndingStr = CompileKernel ? "_noabort" : "";
1393 const Type *ExpType = Exp ? Type::getInt32Ty(*C) : nullptr;
1394 // TODO(glider): for KASan builds add _noabort to error reporting
1395 // functions and make them actually noabort (remove the UnreachableInst).
1396 AsanErrorCallbackSized[AccessIsWrite][Exp] =
1397 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1398 kAsanReportErrorTemplate + ExpStr + TypeStr + SuffixStr,
1399 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1400 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
1401 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1402 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
1403 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1404 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1405 AccessSizeIndex++) {
1406 const std::string Suffix = TypeStr + itostr(1 << AccessSizeIndex);
1407 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
1408 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1409 kAsanReportErrorTemplate + ExpStr + Suffix,
1410 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
1411 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
1412 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1413 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
1414 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
1419 const std::string MemIntrinCallbackPrefix =
1420 CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
1421 AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1422 MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
1423 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
1424 AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1425 MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
1426 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
1427 AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1428 MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
1429 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
1431 AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
1432 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
1434 AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1435 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1436 AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1437 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1438 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1439 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1440 StringRef(""), StringRef(""),
1441 /*hasSideEffects=*/true);
1445 bool AddressSanitizer::doInitialization(Module &M) {
1446 // Initialize the private fields. No one has accessed them before.
1450 C = &(M.getContext());
1451 LongSize = M.getDataLayout().getPointerSizeInBits();
1452 IntptrTy = Type::getIntNTy(*C, LongSize);
1453 TargetTriple = Triple(M.getTargetTriple());
1455 if (!CompileKernel) {
1456 std::tie(AsanCtorFunction, AsanInitFunction) =
1457 createSanitizerCtorAndInitFunctions(M, kAsanModuleCtorName, kAsanInitName,
1458 /*InitArgTypes=*/{},
1460 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
1462 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
1466 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1467 // For each NSObject descendant having a +load method, this method is invoked
1468 // by the ObjC runtime before any of the static constructors is called.
1469 // Therefore we need to instrument such methods with a call to __asan_init
1470 // at the beginning in order to initialize our runtime before any access to
1471 // the shadow memory.
1472 // We cannot just ignore these methods, because they may call other
1473 // instrumented functions.
1474 if (F.getName().find(" load]") != std::string::npos) {
1475 IRBuilder<> IRB(F.begin()->begin());
1476 IRB.CreateCall(AsanInitFunction, {});
1482 bool AddressSanitizer::runOnFunction(Function &F) {
1483 if (&F == AsanCtorFunction) return false;
1484 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
1485 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
1486 initializeCallbacks(*F.getParent());
1488 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1490 // If needed, insert __asan_init before checking for SanitizeAddress attr.
1491 maybeInsertAsanInitAtFunctionEntry(F);
1493 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return false;
1495 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName()) return false;
1497 // We want to instrument every address only once per basic block (unless there
1498 // are calls between uses).
1499 SmallSet<Value *, 16> TempsToInstrument;
1500 SmallVector<Instruction *, 16> ToInstrument;
1501 SmallVector<Instruction *, 8> NoReturnCalls;
1502 SmallVector<BasicBlock *, 16> AllBlocks;
1503 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
1509 // Fill the set of memory operations to instrument.
1510 for (auto &BB : F) {
1511 AllBlocks.push_back(&BB);
1512 TempsToInstrument.clear();
1513 int NumInsnsPerBB = 0;
1514 for (auto &Inst : BB) {
1515 if (LooksLikeCodeInBug11395(&Inst)) return false;
1516 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
1518 if (ClOpt && ClOptSameTemp) {
1519 if (!TempsToInstrument.insert(Addr).second)
1520 continue; // We've seen this temp in the current BB.
1522 } else if (ClInvalidPointerPairs &&
1523 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1524 PointerComparisonsOrSubtracts.push_back(&Inst);
1526 } else if (isa<MemIntrinsic>(Inst)) {
1529 if (isa<AllocaInst>(Inst)) NumAllocas++;
1532 // A call inside BB.
1533 TempsToInstrument.clear();
1534 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
1538 ToInstrument.push_back(&Inst);
1540 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
1546 (ClInstrumentationWithCallsThreshold >= 0 &&
1547 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
1548 const TargetLibraryInfo *TLI =
1549 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1550 const DataLayout &DL = F.getParent()->getDataLayout();
1551 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(),
1552 /*RoundToAlign=*/true);
1555 int NumInstrumented = 0;
1556 for (auto Inst : ToInstrument) {
1557 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1558 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
1559 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
1560 instrumentMop(ObjSizeVis, Inst, UseCalls,
1561 F.getParent()->getDataLayout());
1563 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
1568 FunctionStackPoisoner FSP(F, *this);
1569 bool ChangedStack = FSP.runOnFunction();
1571 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1572 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1573 for (auto CI : NoReturnCalls) {
1574 IRBuilder<> IRB(CI);
1575 IRB.CreateCall(AsanHandleNoReturnFunc, {});
1578 for (auto Inst : PointerComparisonsOrSubtracts) {
1579 instrumentPointerComparisonOrSubtraction(Inst);
1583 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
1585 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1590 // Workaround for bug 11395: we don't want to instrument stack in functions
1591 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1592 // FIXME: remove once the bug 11395 is fixed.
1593 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1594 if (LongSize != 32) return false;
1595 CallInst *CI = dyn_cast<CallInst>(I);
1596 if (!CI || !CI->isInlineAsm()) return false;
1597 if (CI->getNumArgOperands() <= 5) return false;
1598 // We have inline assembly with quite a few arguments.
1602 void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1603 IRBuilder<> IRB(*C);
1604 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1605 std::string Suffix = itostr(i);
1606 AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
1607 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1608 IntptrTy, nullptr));
1609 AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
1610 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
1611 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1613 AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
1614 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
1615 IntptrTy, IntptrTy, nullptr));
1616 AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
1617 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
1618 IntptrTy, IntptrTy, nullptr));
1619 AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1620 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1621 AsanAllocasUnpoisonFunc =
1622 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1623 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1626 void FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
1627 IRBuilder<> &IRB, Value *ShadowBase,
1629 size_t n = ShadowBytes.size();
1631 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1632 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1633 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1634 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1635 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1636 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1638 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
1639 if (F.getParent()->getDataLayout().isLittleEndian())
1640 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1642 Val = (Val << 8) | ShadowBytes[i + j];
1645 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1646 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1647 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1648 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
1653 // Fake stack allocator (asan_fake_stack.h) has 11 size classes
1654 // for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1655 static int StackMallocSizeClass(uint64_t LocalStackSize) {
1656 assert(LocalStackSize <= kMaxStackMallocSize);
1657 uint64_t MaxSize = kMinStackMallocSize;
1658 for (int i = 0;; i++, MaxSize *= 2)
1659 if (LocalStackSize <= MaxSize) return i;
1660 llvm_unreachable("impossible LocalStackSize");
1663 // Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1664 // We can not use MemSet intrinsic because it may end up calling the actual
1665 // memset. Size is a multiple of 8.
1666 // Currently this generates 8-byte stores on x86_64; it may be better to
1667 // generate wider stores.
1668 void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1669 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1670 assert(!(Size % 8));
1672 // kAsanStackAfterReturnMagic is 0xf5.
1673 const uint64_t kAsanStackAfterReturnMagic64 = 0xf5f5f5f5f5f5f5f5ULL;
1675 for (int i = 0; i < Size; i += 8) {
1676 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1678 ConstantInt::get(IRB.getInt64Ty(), kAsanStackAfterReturnMagic64),
1679 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1683 PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
1685 Instruction *ThenTerm,
1686 Value *ValueIfFalse) {
1687 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
1688 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
1689 PHI->addIncoming(ValueIfFalse, CondBlock);
1690 BasicBlock *ThenBlock = ThenTerm->getParent();
1691 PHI->addIncoming(ValueIfTrue, ThenBlock);
1695 Value *FunctionStackPoisoner::createAllocaForLayout(
1696 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
1699 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
1700 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
1703 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
1704 nullptr, "MyAlloca");
1705 assert(Alloca->isStaticAlloca());
1707 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1708 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1709 Alloca->setAlignment(FrameAlignment);
1710 return IRB.CreatePointerCast(Alloca, IntptrTy);
1713 void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
1714 BasicBlock &FirstBB = *F.begin();
1715 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
1716 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
1717 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
1718 DynamicAllocaLayout->setAlignment(32);
1721 void FunctionStackPoisoner::poisonStack() {
1722 assert(AllocaVec.size() > 0 || DynamicAllocaVec.size() > 0);
1724 if (ClInstrumentAllocas && DynamicAllocaVec.size() > 0) {
1725 // Handle dynamic allocas.
1726 createDynamicAllocasInitStorage();
1727 for (auto &AI : DynamicAllocaVec) handleDynamicAllocaCall(AI);
1729 unpoisonDynamicAllocas();
1732 if (AllocaVec.size() == 0) return;
1734 int StackMallocIdx = -1;
1735 DebugLoc EntryDebugLocation;
1736 if (auto SP = getDISubprogram(&F))
1737 EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
1739 Instruction *InsBefore = AllocaVec[0];
1740 IRBuilder<> IRB(InsBefore);
1741 IRB.SetCurrentDebugLocation(EntryDebugLocation);
1743 // Make sure non-instrumented allocas stay in the first basic block.
1744 // Otherwise, debug info is broken, because only first-basic-block allocas are
1745 // treated as regular stack slots.
1746 for (auto *AI : NonInstrumentedStaticAllocaVec) AI->moveBefore(InsBefore);
1748 SmallVector<ASanStackVariableDescription, 16> SVD;
1749 SVD.reserve(AllocaVec.size());
1750 for (AllocaInst *AI : AllocaVec) {
1751 ASanStackVariableDescription D = {AI->getName().data(),
1752 ASan.getAllocaSizeInBytes(AI),
1753 AI->getAlignment(), AI, 0};
1756 // Minimal header size (left redzone) is 4 pointers,
1757 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1758 size_t MinHeaderSize = ASan.LongSize / 2;
1759 ASanStackFrameLayout L;
1760 ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1761 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1762 uint64_t LocalStackSize = L.FrameSize;
1763 bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
1764 LocalStackSize <= kMaxStackMallocSize;
1765 // Don't do dynamic alloca or stack malloc in presence of inline asm:
1766 // too often it makes assumptions on which registers are available.
1767 bool DoDynamicAlloca = ClDynamicAllocaStack && !HasNonEmptyInlineAsm;
1768 DoStackMalloc &= !HasNonEmptyInlineAsm;
1770 Value *StaticAlloca =
1771 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
1774 Value *LocalStackBase;
1776 if (DoStackMalloc) {
1777 // void *FakeStack = __asan_option_detect_stack_use_after_return
1778 // ? __asan_stack_malloc_N(LocalStackSize)
1780 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
1781 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1782 kAsanOptionDetectUAR, IRB.getInt32Ty());
1783 Value *UARIsEnabled =
1784 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1785 Constant::getNullValue(IRB.getInt32Ty()));
1787 SplitBlockAndInsertIfThen(UARIsEnabled, InsBefore, false);
1788 IRBuilder<> IRBIf(Term);
1789 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
1790 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1791 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
1792 Value *FakeStackValue =
1793 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
1794 ConstantInt::get(IntptrTy, LocalStackSize));
1795 IRB.SetInsertPoint(InsBefore);
1796 IRB.SetCurrentDebugLocation(EntryDebugLocation);
1797 FakeStack = createPHI(IRB, UARIsEnabled, FakeStackValue, Term,
1798 ConstantInt::get(IntptrTy, 0));
1800 Value *NoFakeStack =
1801 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
1802 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
1803 IRBIf.SetInsertPoint(Term);
1804 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
1805 Value *AllocaValue =
1806 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
1807 IRB.SetInsertPoint(InsBefore);
1808 IRB.SetCurrentDebugLocation(EntryDebugLocation);
1809 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
1811 // void *FakeStack = nullptr;
1812 // void *LocalStackBase = alloca(LocalStackSize);
1813 FakeStack = ConstantInt::get(IntptrTy, 0);
1815 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
1818 // Insert poison calls for lifetime intrinsics for alloca.
1819 bool HavePoisonedAllocas = false;
1820 for (const auto &APC : AllocaPoisonCallVec) {
1821 assert(APC.InsBefore);
1823 IRBuilder<> IRB(APC.InsBefore);
1824 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
1825 HavePoisonedAllocas |= APC.DoPoison;
1828 // Replace Alloca instructions with base+offset.
1829 for (const auto &Desc : SVD) {
1830 AllocaInst *AI = Desc.AI;
1831 Value *NewAllocaPtr = IRB.CreateIntToPtr(
1832 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
1834 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true);
1835 AI->replaceAllUsesWith(NewAllocaPtr);
1838 // The left-most redzone has enough space for at least 4 pointers.
1839 // Write the Magic value to redzone[0].
1840 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1841 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1843 // Write the frame description constant to redzone[1].
1844 Value *BasePlus1 = IRB.CreateIntToPtr(
1845 IRB.CreateAdd(LocalStackBase,
1846 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
1848 GlobalVariable *StackDescriptionGlobal =
1849 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
1850 /*AllowMerging*/ true);
1851 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
1852 IRB.CreateStore(Description, BasePlus1);
1853 // Write the PC to redzone[2].
1854 Value *BasePlus2 = IRB.CreateIntToPtr(
1855 IRB.CreateAdd(LocalStackBase,
1856 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
1858 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
1860 // Poison the stack redzones at the entry.
1861 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1862 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
1864 // (Un)poison the stack before all ret instructions.
1865 for (auto Ret : RetVec) {
1866 IRBuilder<> IRBRet(Ret);
1867 // Mark the current frame as retired.
1868 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1870 if (DoStackMalloc) {
1871 assert(StackMallocIdx >= 0);
1872 // if FakeStack != 0 // LocalStackBase == FakeStack
1873 // // In use-after-return mode, poison the whole stack frame.
1874 // if StackMallocIdx <= 4
1875 // // For small sizes inline the whole thing:
1876 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
1877 // **SavedFlagPtr(FakeStack) = 0
1879 // __asan_stack_free_N(FakeStack, LocalStackSize)
1881 // <This is not a fake stack; unpoison the redzones>
1883 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
1884 TerminatorInst *ThenTerm, *ElseTerm;
1885 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1887 IRBuilder<> IRBPoison(ThenTerm);
1888 if (StackMallocIdx <= 4) {
1889 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1890 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1891 ClassSize >> Mapping.Scale);
1892 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
1894 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1895 Value *SavedFlagPtr = IRBPoison.CreateLoad(
1896 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1897 IRBPoison.CreateStore(
1898 Constant::getNullValue(IRBPoison.getInt8Ty()),
1899 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1901 // For larger frames call __asan_stack_free_*.
1902 IRBPoison.CreateCall(
1903 AsanStackFreeFunc[StackMallocIdx],
1904 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
1907 IRBuilder<> IRBElse(ElseTerm);
1908 poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
1909 } else if (HavePoisonedAllocas) {
1910 // If we poisoned some allocas in llvm.lifetime analysis,
1911 // unpoison whole stack frame now.
1912 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
1914 poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
1918 // We are done. Remove the old unused alloca instructions.
1919 for (auto AI : AllocaVec) AI->eraseFromParent();
1922 void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
1923 IRBuilder<> &IRB, bool DoPoison) {
1924 // For now just insert the call to ASan runtime.
1925 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1926 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1928 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
1929 {AddrArg, SizeArg});
1932 // Handling llvm.lifetime intrinsics for a given %alloca:
1933 // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1934 // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1935 // invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1936 // could be poisoned by previous llvm.lifetime.end instruction, as the
1937 // variable may go in and out of scope several times, e.g. in loops).
1938 // (3) if we poisoned at least one %alloca in a function,
1939 // unpoison the whole stack frame at function exit.
1941 AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1942 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1943 // We're intested only in allocas we can handle.
1944 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
1945 // See if we've already calculated (or started to calculate) alloca for a
1947 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1948 if (I != AllocaForValue.end()) return I->second;
1949 // Store 0 while we're calculating alloca for value V to avoid
1950 // infinite recursion if the value references itself.
1951 AllocaForValue[V] = nullptr;
1952 AllocaInst *Res = nullptr;
1953 if (CastInst *CI = dyn_cast<CastInst>(V))
1954 Res = findAllocaForValue(CI->getOperand(0));
1955 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1956 for (Value *IncValue : PN->incoming_values()) {
1957 // Allow self-referencing phi-nodes.
1958 if (IncValue == PN) continue;
1959 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1960 // AI for incoming values should exist and should all be equal.
1961 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
1966 if (Res) AllocaForValue[V] = Res;
1970 void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
1971 IRBuilder<> IRB(AI);
1973 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
1974 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
1976 Value *Zero = Constant::getNullValue(IntptrTy);
1977 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
1978 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
1980 // Since we need to extend alloca with additional memory to locate
1981 // redzones, and OldSize is number of allocated blocks with
1982 // ElementSize size, get allocated memory size in bytes by
1983 // OldSize * ElementSize.
1984 const unsigned ElementSize =
1985 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
1987 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
1988 ConstantInt::get(IntptrTy, ElementSize));
1990 // PartialSize = OldSize % 32
1991 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
1993 // Misalign = kAllocaRzSize - PartialSize;
1994 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
1996 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
1997 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
1998 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
2000 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
2001 // Align is added to locate left redzone, PartialPadding for possible
2002 // partial redzone and kAllocaRzSize for right redzone respectively.
2003 Value *AdditionalChunkSize = IRB.CreateAdd(
2004 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
2006 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
2008 // Insert new alloca with new NewSize and Align params.
2009 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
2010 NewAlloca->setAlignment(Align);
2012 // NewAddress = Address + Align
2013 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
2014 ConstantInt::get(IntptrTy, Align));
2016 // Insert __asan_alloca_poison call for new created alloca.
2017 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
2019 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
2020 // for unpoisoning stuff.
2021 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
2023 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2025 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
2026 AI->replaceAllUsesWith(NewAddressPtr);
2028 // We are done. Erase old alloca from parent.
2029 AI->eraseFromParent();
2032 // isSafeAccess returns true if Addr is always inbounds with respect to its
2033 // base object. For example, it is a field access or an array access with
2034 // constant inbounds index.
2035 bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
2036 Value *Addr, uint64_t TypeSize) const {
2037 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
2038 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
2039 uint64_t Size = SizeOffset.first.getZExtValue();
2040 int64_t Offset = SizeOffset.second.getSExtValue();
2041 // Three checks are required to ensure safety:
2042 // . Offset >= 0 (since the offset is given from the base ptr)
2043 // . Size >= Offset (unsigned)
2044 // . Size - Offset >= NeededSize (unsigned)
2045 return Offset >= 0 && Size >= uint64_t(Offset) &&
2046 Size - uint64_t(Offset) >= TypeSize / 8;