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;
340 if (LongSize == 32) {
344 Mapping.Offset = kMIPS32_ShadowOffset32;
346 Mapping.Offset = kFreeBSD_ShadowOffset32;
348 Mapping.Offset = kIOSShadowOffset32;
350 Mapping.Offset = kWindowsShadowOffset32;
352 Mapping.Offset = kDefaultShadowOffset32;
353 } else { // LongSize == 64
355 Mapping.Offset = kPPC64_ShadowOffset64;
357 Mapping.Offset = kFreeBSD_ShadowOffset64;
358 else if (IsLinux && IsX86_64) {
360 Mapping.Offset = kLinuxKasan_ShadowOffset64;
362 Mapping.Offset = kSmallX86_64ShadowOffset;
364 Mapping.Offset = kMIPS64_ShadowOffset64;
366 Mapping.Offset = kAArch64_ShadowOffset64;
368 Mapping.Offset = kDefaultShadowOffset64;
371 Mapping.Scale = kDefaultShadowScale;
372 if (ClMappingScale) {
373 Mapping.Scale = ClMappingScale;
376 // OR-ing shadow offset if more efficient (at least on x86) if the offset
377 // is a power of two, but on ppc64 we have to use add since the shadow
378 // offset is not necessary 1/8-th of the address space.
379 Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
384 static size_t RedzoneSizeForScale(int MappingScale) {
385 // Redzone used for stack and globals is at least 32 bytes.
386 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
387 return std::max(32U, 1U << MappingScale);
390 /// AddressSanitizer: instrument the code in module to find memory bugs.
391 struct AddressSanitizer : public FunctionPass {
392 explicit AddressSanitizer(bool CompileKernel = false)
393 : FunctionPass(ID), CompileKernel(CompileKernel || ClEnableKasan) {
394 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
396 const char *getPassName() const override {
397 return "AddressSanitizerFunctionPass";
399 void getAnalysisUsage(AnalysisUsage &AU) const override {
400 AU.addRequired<DominatorTreeWrapperPass>();
401 AU.addRequired<TargetLibraryInfoWrapperPass>();
403 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
404 Type *Ty = AI->getAllocatedType();
405 uint64_t SizeInBytes =
406 AI->getModule()->getDataLayout().getTypeAllocSize(Ty);
409 /// Check if we want (and can) handle this alloca.
410 bool isInterestingAlloca(AllocaInst &AI);
412 // Check if we have dynamic alloca.
413 bool isDynamicAlloca(AllocaInst &AI) const {
414 return AI.isArrayAllocation() || !AI.isStaticAlloca();
417 /// If it is an interesting memory access, return the PointerOperand
418 /// and set IsWrite/Alignment. Otherwise return nullptr.
419 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
420 uint64_t *TypeSize, unsigned *Alignment);
421 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
422 bool UseCalls, const DataLayout &DL);
423 void instrumentPointerComparisonOrSubtraction(Instruction *I);
424 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
425 Value *Addr, uint32_t TypeSize, bool IsWrite,
426 Value *SizeArgument, bool UseCalls, uint32_t Exp);
427 void instrumentUnusualSizeOrAlignment(Instruction *I, Value *Addr,
428 uint32_t TypeSize, bool IsWrite,
429 Value *SizeArgument, bool UseCalls,
431 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
432 Value *ShadowValue, uint32_t TypeSize);
433 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
434 bool IsWrite, size_t AccessSizeIndex,
435 Value *SizeArgument, uint32_t Exp);
436 void instrumentMemIntrinsic(MemIntrinsic *MI);
437 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
438 bool runOnFunction(Function &F) override;
439 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
440 bool doInitialization(Module &M) override;
441 static char ID; // Pass identification, replacement for typeid
443 DominatorTree &getDominatorTree() const { return *DT; }
446 void initializeCallbacks(Module &M);
448 bool LooksLikeCodeInBug11395(Instruction *I);
449 bool GlobalIsLinkerInitialized(GlobalVariable *G);
450 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
451 uint64_t TypeSize) const;
458 ShadowMapping Mapping;
460 Function *AsanCtorFunction = nullptr;
461 Function *AsanInitFunction = nullptr;
462 Function *AsanHandleNoReturnFunc;
463 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
464 // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
465 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
466 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
467 // This array is indexed by AccessIsWrite and Experiment.
468 Function *AsanErrorCallbackSized[2][2];
469 Function *AsanMemoryAccessCallbackSized[2][2];
470 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
472 GlobalsMetadata GlobalsMD;
473 DenseMap<AllocaInst *, bool> ProcessedAllocas;
475 friend struct FunctionStackPoisoner;
478 class AddressSanitizerModule : public ModulePass {
480 explicit AddressSanitizerModule(bool CompileKernel = false)
481 : ModulePass(ID), CompileKernel(CompileKernel || ClEnableKasan) {}
482 bool runOnModule(Module &M) override;
483 static char ID; // Pass identification, replacement for typeid
484 const char *getPassName() const override { return "AddressSanitizerModule"; }
487 void initializeCallbacks(Module &M);
489 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
490 bool ShouldInstrumentGlobal(GlobalVariable *G);
491 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
492 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
493 size_t MinRedzoneSizeForGlobal() const {
494 return RedzoneSizeForScale(Mapping.Scale);
497 GlobalsMetadata GlobalsMD;
502 ShadowMapping Mapping;
503 Function *AsanPoisonGlobals;
504 Function *AsanUnpoisonGlobals;
505 Function *AsanRegisterGlobals;
506 Function *AsanUnregisterGlobals;
509 // Stack poisoning does not play well with exception handling.
510 // When an exception is thrown, we essentially bypass the code
511 // that unpoisones the stack. This is why the run-time library has
512 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
513 // stack in the interceptor. This however does not work inside the
514 // actual function which catches the exception. Most likely because the
515 // compiler hoists the load of the shadow value somewhere too high.
516 // This causes asan to report a non-existing bug on 453.povray.
517 // It sounds like an LLVM bug.
518 struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
520 AddressSanitizer &ASan;
525 ShadowMapping Mapping;
527 SmallVector<AllocaInst *, 16> AllocaVec;
528 SmallVector<Instruction *, 8> RetVec;
529 unsigned StackAlignment;
531 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
532 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
533 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
534 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
536 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
537 struct AllocaPoisonCall {
538 IntrinsicInst *InsBefore;
543 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
545 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
546 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
547 AllocaInst *DynamicAllocaLayout = nullptr;
549 // Maps Value to an AllocaInst from which the Value is originated.
550 typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
551 AllocaForValueMapTy AllocaForValue;
553 bool HasNonEmptyInlineAsm;
554 std::unique_ptr<CallInst> EmptyInlineAsm;
556 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
559 DIB(*F.getParent(), /*AllowUnresolved*/ false),
561 IntptrTy(ASan.IntptrTy),
562 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
563 Mapping(ASan.Mapping),
564 StackAlignment(1 << Mapping.Scale),
565 HasNonEmptyInlineAsm(false),
566 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
568 bool runOnFunction() {
569 if (!ClStack) return false;
570 // Collect alloca, ret, lifetime instructions etc.
571 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
573 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
575 initializeCallbacks(*F.getParent());
585 // Finds all Alloca instructions and puts
586 // poisoned red zones around all of them.
587 // Then unpoison everything back before the function returns.
590 void createDynamicAllocasInitStorage();
592 // ----------------------- Visitors.
593 /// \brief Collect all Ret instructions.
594 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
596 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
598 IRBuilder<> IRB(InstBefore);
599 IRB.CreateCall(AsanAllocasUnpoisonFunc,
600 {IRB.CreateLoad(DynamicAllocaLayout),
601 IRB.CreatePtrToInt(SavedStack, IntptrTy)});
604 // Unpoison dynamic allocas redzones.
605 void unpoisonDynamicAllocas() {
606 for (auto &Ret : RetVec)
607 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
609 for (auto &StackRestoreInst : StackRestoreVec)
610 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
611 StackRestoreInst->getOperand(0));
614 // Deploy and poison redzones around dynamic alloca call. To do this, we
615 // should replace this call with another one with changed parameters and
616 // replace all its uses with new address, so
617 // addr = alloca type, old_size, align
619 // new_size = (old_size + additional_size) * sizeof(type)
620 // tmp = alloca i8, new_size, max(align, 32)
621 // addr = tmp + 32 (first 32 bytes are for the left redzone).
622 // Additional_size is added to make new memory allocation contain not only
623 // requested memory, but also left, partial and right redzones.
624 void handleDynamicAllocaCall(AllocaInst *AI);
626 /// \brief Collect Alloca instructions we want (and can) handle.
627 void visitAllocaInst(AllocaInst &AI) {
628 if (!ASan.isInterestingAlloca(AI)) return;
630 StackAlignment = std::max(StackAlignment, AI.getAlignment());
631 if (ASan.isDynamicAlloca(AI))
632 DynamicAllocaVec.push_back(&AI);
634 AllocaVec.push_back(&AI);
637 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
639 void visitIntrinsicInst(IntrinsicInst &II) {
640 Intrinsic::ID ID = II.getIntrinsicID();
641 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
642 if (!ClCheckLifetime) return;
643 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
645 // Found lifetime intrinsic, add ASan instrumentation if necessary.
646 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
647 // If size argument is undefined, don't do anything.
648 if (Size->isMinusOne()) return;
649 // Check that size doesn't saturate uint64_t and can
650 // be stored in IntptrTy.
651 const uint64_t SizeValue = Size->getValue().getLimitedValue();
652 if (SizeValue == ~0ULL ||
653 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
655 // Find alloca instruction that corresponds to llvm.lifetime argument.
656 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
658 bool DoPoison = (ID == Intrinsic::lifetime_end);
659 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
660 AllocaPoisonCallVec.push_back(APC);
663 void visitCallInst(CallInst &CI) {
664 HasNonEmptyInlineAsm |=
665 CI.isInlineAsm() && !CI.isIdenticalTo(EmptyInlineAsm.get());
668 // ---------------------- Helpers.
669 void initializeCallbacks(Module &M);
671 bool doesDominateAllExits(const Instruction *I) const {
672 for (auto Ret : RetVec) {
673 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
678 /// Finds alloca where the value comes from.
679 AllocaInst *findAllocaForValue(Value *V);
680 void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
681 Value *ShadowBase, bool DoPoison);
682 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
684 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
686 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
688 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
689 Instruction *ThenTerm, Value *ValueIfFalse);
694 char AddressSanitizer::ID = 0;
695 INITIALIZE_PASS_BEGIN(
696 AddressSanitizer, "asan",
697 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
699 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
701 AddressSanitizer, "asan",
702 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
704 FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel) {
705 return new AddressSanitizer(CompileKernel);
708 char AddressSanitizerModule::ID = 0;
710 AddressSanitizerModule, "asan-module",
711 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
714 ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel) {
715 return new AddressSanitizerModule(CompileKernel);
718 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
719 size_t Res = countTrailingZeros(TypeSize / 8);
720 assert(Res < kNumberOfAccessSizes);
724 // \brief Create a constant for Str so that we can pass it to the run-time lib.
725 static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
727 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
728 // We use private linkage for module-local strings. If they can be merged
729 // with another one, we set the unnamed_addr attribute.
731 new GlobalVariable(M, StrConst->getType(), true,
732 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
733 if (AllowMerging) GV->setUnnamedAddr(true);
734 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
738 /// \brief Create a global describing a source location.
739 static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
740 LocationMetadata MD) {
741 Constant *LocData[] = {
742 createPrivateGlobalForString(M, MD.Filename, true),
743 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
744 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
746 auto LocStruct = ConstantStruct::getAnon(LocData);
747 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
748 GlobalValue::PrivateLinkage, LocStruct,
750 GV->setUnnamedAddr(true);
754 static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
755 return G->getName().find(kAsanGenPrefix) == 0 ||
756 G->getName().find(kSanCovGenPrefix) == 0;
759 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
761 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
762 if (Mapping.Offset == 0) return Shadow;
763 // (Shadow >> scale) | offset
764 if (Mapping.OrShadowOffset)
765 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
767 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
770 // Instrument memset/memmove/memcpy
771 void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
773 if (isa<MemTransferInst>(MI)) {
775 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
776 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
777 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
778 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
779 } else if (isa<MemSetInst>(MI)) {
782 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
783 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
784 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
786 MI->eraseFromParent();
789 /// Check if we want (and can) handle this alloca.
790 bool AddressSanitizer::isInterestingAlloca(AllocaInst &AI) {
791 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
793 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
794 return PreviouslySeenAllocaInfo->getSecond();
797 (AI.getAllocatedType()->isSized() &&
798 // alloca() may be called with 0 size, ignore it.
799 getAllocaSizeInBytes(&AI) > 0 &&
800 // We are only interested in allocas not promotable to registers.
801 // Promotable allocas are common under -O0.
802 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI) ||
803 isDynamicAlloca(AI)));
805 ProcessedAllocas[&AI] = IsInteresting;
806 return IsInteresting;
809 /// If I is an interesting memory access, return the PointerOperand
810 /// and set IsWrite/Alignment. Otherwise return nullptr.
811 Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
814 unsigned *Alignment) {
815 // Skip memory accesses inserted by another instrumentation.
816 if (I->getMetadata("nosanitize")) return nullptr;
818 Value *PtrOperand = nullptr;
819 const DataLayout &DL = I->getModule()->getDataLayout();
820 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
821 if (!ClInstrumentReads) return nullptr;
823 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
824 *Alignment = LI->getAlignment();
825 PtrOperand = LI->getPointerOperand();
826 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
827 if (!ClInstrumentWrites) return nullptr;
829 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
830 *Alignment = SI->getAlignment();
831 PtrOperand = SI->getPointerOperand();
832 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
833 if (!ClInstrumentAtomics) return nullptr;
835 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
837 PtrOperand = RMW->getPointerOperand();
838 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
839 if (!ClInstrumentAtomics) return nullptr;
841 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
843 PtrOperand = XCHG->getPointerOperand();
846 // Treat memory accesses to promotable allocas as non-interesting since they
847 // will not cause memory violations. This greatly speeds up the instrumented
848 // executable at -O0.
849 if (ClSkipPromotableAllocas)
850 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
851 return isInterestingAlloca(*AI) ? AI : nullptr;
856 static bool isPointerOperand(Value *V) {
857 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
860 // This is a rough heuristic; it may cause both false positives and
861 // false negatives. The proper implementation requires cooperation with
863 static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
864 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
865 if (!Cmp->isRelational()) return false;
866 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
867 if (BO->getOpcode() != Instruction::Sub) return false;
871 if (!isPointerOperand(I->getOperand(0)) ||
872 !isPointerOperand(I->getOperand(1)))
877 bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
878 // If a global variable does not have dynamic initialization we don't
879 // have to instrument it. However, if a global does not have initializer
880 // at all, we assume it has dynamic initializer (in other TU).
881 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
884 void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
887 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
888 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
889 for (int i = 0; i < 2; i++) {
890 if (Param[i]->getType()->isPointerTy())
891 Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
893 IRB.CreateCall(F, Param);
896 void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
897 Instruction *I, bool UseCalls,
898 const DataLayout &DL) {
899 bool IsWrite = false;
900 unsigned Alignment = 0;
901 uint64_t TypeSize = 0;
902 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment);
905 // Optimization experiments.
906 // The experiments can be used to evaluate potential optimizations that remove
907 // instrumentation (assess false negatives). Instead of completely removing
908 // some instrumentation, you set Exp to a non-zero value (mask of optimization
909 // experiments that want to remove instrumentation of this instruction).
910 // If Exp is non-zero, this pass will emit special calls into runtime
911 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
912 // make runtime terminate the program in a special way (with a different
913 // exit status). Then you run the new compiler on a buggy corpus, collect
914 // the special terminations (ideally, you don't see them at all -- no false
915 // negatives) and make the decision on the optimization.
916 uint32_t Exp = ClForceExperiment;
918 if (ClOpt && ClOptGlobals) {
919 // If initialization order checking is disabled, a simple access to a
920 // dynamically initialized global is always valid.
921 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
922 if (G != NULL && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
923 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
924 NumOptimizedAccessesToGlobalVar++;
929 if (ClOpt && ClOptStack) {
930 // A direct inbounds access to a stack variable is always valid.
931 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
932 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
933 NumOptimizedAccessesToStackVar++;
939 NumInstrumentedWrites++;
941 NumInstrumentedReads++;
943 unsigned Granularity = 1 << Mapping.Scale;
944 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
945 // if the data is properly aligned.
946 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
948 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
949 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls,
951 instrumentUnusualSizeOrAlignment(I, Addr, TypeSize, IsWrite, nullptr,
955 Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
956 Value *Addr, bool IsWrite,
957 size_t AccessSizeIndex,
960 IRBuilder<> IRB(InsertBefore);
961 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
962 CallInst *Call = nullptr;
965 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
966 {Addr, SizeArgument});
968 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
969 {Addr, SizeArgument, ExpVal});
973 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
975 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
979 // We don't do Call->setDoesNotReturn() because the BB already has
980 // UnreachableInst at the end.
981 // This EmptyAsm is required to avoid callback merge.
982 IRB.CreateCall(EmptyAsm, {});
986 Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
989 size_t Granularity = 1 << Mapping.Scale;
990 // Addr & (Granularity - 1)
991 Value *LastAccessedByte =
992 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
993 // (Addr & (Granularity - 1)) + size - 1
994 if (TypeSize / 8 > 1)
995 LastAccessedByte = IRB.CreateAdd(
996 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
997 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
999 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
1000 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1001 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1004 void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
1005 Instruction *InsertBefore, Value *Addr,
1006 uint32_t TypeSize, bool IsWrite,
1007 Value *SizeArgument, bool UseCalls,
1009 IRBuilder<> IRB(InsertBefore);
1010 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1011 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1015 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1018 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1019 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
1024 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
1025 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1026 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1027 Value *CmpVal = Constant::getNullValue(ShadowTy);
1028 Value *ShadowValue =
1029 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
1031 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
1032 size_t Granularity = 1 << Mapping.Scale;
1033 TerminatorInst *CrashTerm = nullptr;
1035 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
1036 // We use branch weights for the slow path check, to indicate that the slow
1037 // path is rarely taken. This seems to be the case for SPEC benchmarks.
1038 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1039 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
1040 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
1041 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
1042 IRB.SetInsertPoint(CheckTerm);
1043 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
1044 BasicBlock *CrashBlock =
1045 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
1046 CrashTerm = new UnreachableInst(*C, CrashBlock);
1047 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1048 ReplaceInstWithInst(CheckTerm, NewTerm);
1050 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
1053 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
1054 AccessSizeIndex, SizeArgument, Exp);
1055 Crash->setDebugLoc(OrigIns->getDebugLoc());
1058 // Instrument unusual size or unusual alignment.
1059 // We can not do it with a single check, so we do 1-byte check for the first
1060 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1061 // to report the actual access size.
1062 void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1063 Instruction *I, Value *Addr, uint32_t TypeSize, bool IsWrite,
1064 Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1066 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1067 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1070 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1073 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1074 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
1076 Value *LastByte = IRB.CreateIntToPtr(
1077 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1079 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false, Exp);
1080 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false, Exp);
1084 void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1085 GlobalValue *ModuleName) {
1086 // Set up the arguments to our poison/unpoison functions.
1087 IRBuilder<> IRB(GlobalInit.begin()->getFirstInsertionPt());
1089 // Add a call to poison all external globals before the given function starts.
1090 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1091 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
1093 // Add calls to unpoison all globals before each return instruction.
1094 for (auto &BB : GlobalInit.getBasicBlockList())
1095 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
1096 CallInst::Create(AsanUnpoisonGlobals, "", RI);
1099 void AddressSanitizerModule::createInitializerPoisonCalls(
1100 Module &M, GlobalValue *ModuleName) {
1101 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1103 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1104 for (Use &OP : CA->operands()) {
1105 if (isa<ConstantAggregateZero>(OP)) continue;
1106 ConstantStruct *CS = cast<ConstantStruct>(OP);
1108 // Must have a function or null ptr.
1109 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
1110 if (F->getName() == kAsanModuleCtorName) continue;
1111 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1112 // Don't instrument CTORs that will run before asan.module_ctor.
1113 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1114 poisonOneInitializer(*F, ModuleName);
1119 bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
1120 Type *Ty = cast<PointerType>(G->getType())->getElementType();
1121 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
1123 if (GlobalsMD.get(G).IsBlacklisted) return false;
1124 if (!Ty->isSized()) return false;
1125 if (!G->hasInitializer()) return false;
1126 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
1127 // Touch only those globals that will not be defined in other modules.
1128 // Don't handle ODR linkage types and COMDATs since other modules may be built
1130 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1131 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1132 G->getLinkage() != GlobalVariable::InternalLinkage)
1134 if (G->hasComdat()) return false;
1135 // Two problems with thread-locals:
1136 // - The address of the main thread's copy can't be computed at link-time.
1137 // - Need to poison all copies, not just the main thread's one.
1138 if (G->isThreadLocal()) return false;
1139 // For now, just ignore this Global if the alignment is large.
1140 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
1142 if (G->hasSection()) {
1143 StringRef Section(G->getSection());
1145 // Globals from llvm.metadata aren't emitted, do not instrument them.
1146 if (Section == "llvm.metadata") return false;
1147 // Do not instrument globals from special LLVM sections.
1148 if (Section.find("__llvm") != StringRef::npos) return false;
1150 // Callbacks put into the CRT initializer/terminator sections
1151 // should not be instrumented.
1152 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1153 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1154 if (Section.startswith(".CRT")) {
1155 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1159 if (TargetTriple.isOSBinFormatMachO()) {
1160 StringRef ParsedSegment, ParsedSection;
1161 unsigned TAA = 0, StubSize = 0;
1163 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1164 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
1165 if (!ErrorCode.empty()) {
1166 assert(false && "Invalid section specifier.");
1170 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1171 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1173 if (ParsedSegment == "__OBJC" ||
1174 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1175 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1178 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1179 // Constant CFString instances are compiled in the following way:
1180 // -- the string buffer is emitted into
1181 // __TEXT,__cstring,cstring_literals
1182 // -- the constant NSConstantString structure referencing that buffer
1183 // is placed into __DATA,__cfstring
1184 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1185 // Moreover, it causes the linker to crash on OS X 10.7
1186 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1187 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1190 // The linker merges the contents of cstring_literals and removes the
1192 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1193 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1202 void AddressSanitizerModule::initializeCallbacks(Module &M) {
1203 IRBuilder<> IRB(*C);
1204 // Declare our poisoning and unpoisoning functions.
1205 AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1206 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
1207 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
1208 AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1209 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
1210 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1211 // Declare functions that register/unregister globals.
1212 AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1213 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1214 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
1215 AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
1216 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1217 IntptrTy, IntptrTy, nullptr));
1218 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1221 // This function replaces all global variables with new variables that have
1222 // trailing redzones. It also creates a function that poisons
1223 // redzones and inserts this function into llvm.global_ctors.
1224 bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
1227 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1229 for (auto &G : M.globals()) {
1230 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
1233 size_t n = GlobalsToChange.size();
1234 if (n == 0) return false;
1236 // A global is described by a structure
1239 // size_t size_with_redzone;
1240 // const char *name;
1241 // const char *module_name;
1242 // size_t has_dynamic_init;
1243 // void *source_location;
1244 // We initialize an array of such structures and pass it to a run-time call.
1245 StructType *GlobalStructTy =
1246 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
1247 IntptrTy, IntptrTy, nullptr);
1248 SmallVector<Constant *, 16> Initializers(n);
1250 bool HasDynamicallyInitializedGlobals = false;
1252 // We shouldn't merge same module names, as this string serves as unique
1253 // module ID in runtime.
1254 GlobalVariable *ModuleName = createPrivateGlobalForString(
1255 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
1257 auto &DL = M.getDataLayout();
1258 for (size_t i = 0; i < n; i++) {
1259 static const uint64_t kMaxGlobalRedzone = 1 << 18;
1260 GlobalVariable *G = GlobalsToChange[i];
1262 auto MD = GlobalsMD.get(G);
1263 // Create string holding the global name (use global name from metadata
1264 // if it's available, otherwise just write the name of global variable).
1265 GlobalVariable *Name = createPrivateGlobalForString(
1266 M, MD.Name.empty() ? G->getName() : MD.Name,
1267 /*AllowMerging*/ true);
1269 PointerType *PtrTy = cast<PointerType>(G->getType());
1270 Type *Ty = PtrTy->getElementType();
1271 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
1272 uint64_t MinRZ = MinRedzoneSizeForGlobal();
1273 // MinRZ <= RZ <= kMaxGlobalRedzone
1274 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
1275 uint64_t RZ = std::max(
1276 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
1277 uint64_t RightRedzoneSize = RZ;
1278 // Round up to MinRZ
1279 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
1280 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
1281 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1283 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
1284 Constant *NewInitializer =
1285 ConstantStruct::get(NewTy, G->getInitializer(),
1286 Constant::getNullValue(RightRedZoneTy), nullptr);
1288 // Create a new global variable with enough space for a redzone.
1289 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1290 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1291 Linkage = GlobalValue::InternalLinkage;
1292 GlobalVariable *NewGlobal =
1293 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1294 "", G, G->getThreadLocalMode());
1295 NewGlobal->copyAttributesFrom(G);
1296 NewGlobal->setAlignment(MinRZ);
1299 Indices2[0] = IRB.getInt32(0);
1300 Indices2[1] = IRB.getInt32(0);
1302 G->replaceAllUsesWith(
1303 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
1304 NewGlobal->takeName(G);
1305 G->eraseFromParent();
1307 Constant *SourceLoc;
1308 if (!MD.SourceLoc.empty()) {
1309 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1310 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1312 SourceLoc = ConstantInt::get(IntptrTy, 0);
1315 Initializers[i] = ConstantStruct::get(
1316 GlobalStructTy, ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
1317 ConstantInt::get(IntptrTy, SizeInBytes),
1318 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1319 ConstantExpr::getPointerCast(Name, IntptrTy),
1320 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
1321 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc, nullptr);
1323 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
1325 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
1328 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1329 GlobalVariable *AllGlobals = new GlobalVariable(
1330 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1331 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1333 // Create calls for poisoning before initializers run and unpoisoning after.
1334 if (HasDynamicallyInitializedGlobals)
1335 createInitializerPoisonCalls(M, ModuleName);
1336 IRB.CreateCall(AsanRegisterGlobals,
1337 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1338 ConstantInt::get(IntptrTy, n)});
1340 // We also need to unregister globals at the end, e.g. when a shared library
1342 Function *AsanDtorFunction =
1343 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1344 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1345 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1346 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
1347 IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1348 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1349 ConstantInt::get(IntptrTy, n)});
1350 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
1356 bool AddressSanitizerModule::runOnModule(Module &M) {
1357 C = &(M.getContext());
1358 int LongSize = M.getDataLayout().getPointerSizeInBits();
1359 IntptrTy = Type::getIntNTy(*C, LongSize);
1360 TargetTriple = Triple(M.getTargetTriple());
1361 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
1362 initializeCallbacks(M);
1364 bool Changed = false;
1366 // TODO(glider): temporarily disabled globals instrumentation for KASan.
1367 if (ClGlobals && !CompileKernel) {
1368 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1370 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1371 Changed |= InstrumentGlobals(IRB, M);
1377 void AddressSanitizer::initializeCallbacks(Module &M) {
1378 IRBuilder<> IRB(*C);
1379 // Create __asan_report* callbacks.
1380 // IsWrite, TypeSize and Exp are encoded in the function name.
1381 for (int Exp = 0; Exp < 2; Exp++) {
1382 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1383 const std::string TypeStr = AccessIsWrite ? "store" : "load";
1384 const std::string ExpStr = Exp ? "exp_" : "";
1385 const std::string SuffixStr = CompileKernel ? "N" : "_n";
1386 const std::string EndingStr = CompileKernel ? "_noabort" : "";
1387 const Type *ExpType = Exp ? Type::getInt32Ty(*C) : nullptr;
1388 // TODO(glider): for KASan builds add _noabort to error reporting
1389 // functions and make them actually noabort (remove the UnreachableInst).
1390 AsanErrorCallbackSized[AccessIsWrite][Exp] =
1391 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1392 kAsanReportErrorTemplate + ExpStr + TypeStr + SuffixStr,
1393 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1394 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
1395 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1396 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
1397 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1398 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1399 AccessSizeIndex++) {
1400 const std::string Suffix = TypeStr + itostr(1 << AccessSizeIndex);
1401 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
1402 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1403 kAsanReportErrorTemplate + ExpStr + Suffix,
1404 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
1405 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
1406 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1407 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
1408 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
1413 const std::string MemIntrinCallbackPrefix =
1414 CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
1415 AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1416 MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
1417 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
1418 AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1419 MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
1420 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
1421 AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1422 MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
1423 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
1425 AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
1426 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
1428 AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1429 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1430 AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1431 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1432 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1433 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1434 StringRef(""), StringRef(""),
1435 /*hasSideEffects=*/true);
1439 bool AddressSanitizer::doInitialization(Module &M) {
1440 // Initialize the private fields. No one has accessed them before.
1444 C = &(M.getContext());
1445 LongSize = M.getDataLayout().getPointerSizeInBits();
1446 IntptrTy = Type::getIntNTy(*C, LongSize);
1447 TargetTriple = Triple(M.getTargetTriple());
1449 if (!CompileKernel) {
1450 std::tie(AsanCtorFunction, AsanInitFunction) =
1451 createSanitizerCtorAndInitFunctions(M, kAsanModuleCtorName, kAsanInitName,
1452 /*InitArgTypes=*/{},
1454 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
1456 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
1460 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1461 // For each NSObject descendant having a +load method, this method is invoked
1462 // by the ObjC runtime before any of the static constructors is called.
1463 // Therefore we need to instrument such methods with a call to __asan_init
1464 // at the beginning in order to initialize our runtime before any access to
1465 // the shadow memory.
1466 // We cannot just ignore these methods, because they may call other
1467 // instrumented functions.
1468 if (F.getName().find(" load]") != std::string::npos) {
1469 IRBuilder<> IRB(F.begin()->begin());
1470 IRB.CreateCall(AsanInitFunction, {});
1476 bool AddressSanitizer::runOnFunction(Function &F) {
1477 if (&F == AsanCtorFunction) return false;
1478 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
1479 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
1480 initializeCallbacks(*F.getParent());
1482 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1484 // If needed, insert __asan_init before checking for SanitizeAddress attr.
1485 maybeInsertAsanInitAtFunctionEntry(F);
1487 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return false;
1489 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName()) return false;
1491 // We want to instrument every address only once per basic block (unless there
1492 // are calls between uses).
1493 SmallSet<Value *, 16> TempsToInstrument;
1494 SmallVector<Instruction *, 16> ToInstrument;
1495 SmallVector<Instruction *, 8> NoReturnCalls;
1496 SmallVector<BasicBlock *, 16> AllBlocks;
1497 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
1503 // Fill the set of memory operations to instrument.
1504 for (auto &BB : F) {
1505 AllBlocks.push_back(&BB);
1506 TempsToInstrument.clear();
1507 int NumInsnsPerBB = 0;
1508 for (auto &Inst : BB) {
1509 if (LooksLikeCodeInBug11395(&Inst)) return false;
1510 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
1512 if (ClOpt && ClOptSameTemp) {
1513 if (!TempsToInstrument.insert(Addr).second)
1514 continue; // We've seen this temp in the current BB.
1516 } else if (ClInvalidPointerPairs &&
1517 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1518 PointerComparisonsOrSubtracts.push_back(&Inst);
1520 } else if (isa<MemIntrinsic>(Inst)) {
1523 if (isa<AllocaInst>(Inst)) NumAllocas++;
1526 // A call inside BB.
1527 TempsToInstrument.clear();
1528 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
1532 ToInstrument.push_back(&Inst);
1534 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
1540 (ClInstrumentationWithCallsThreshold >= 0 &&
1541 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
1542 const TargetLibraryInfo *TLI =
1543 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1544 const DataLayout &DL = F.getParent()->getDataLayout();
1545 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(),
1546 /*RoundToAlign=*/true);
1549 int NumInstrumented = 0;
1550 for (auto Inst : ToInstrument) {
1551 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1552 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
1553 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
1554 instrumentMop(ObjSizeVis, Inst, UseCalls,
1555 F.getParent()->getDataLayout());
1557 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
1562 FunctionStackPoisoner FSP(F, *this);
1563 bool ChangedStack = FSP.runOnFunction();
1565 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1566 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1567 for (auto CI : NoReturnCalls) {
1568 IRBuilder<> IRB(CI);
1569 IRB.CreateCall(AsanHandleNoReturnFunc, {});
1572 for (auto Inst : PointerComparisonsOrSubtracts) {
1573 instrumentPointerComparisonOrSubtraction(Inst);
1577 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
1579 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1584 // Workaround for bug 11395: we don't want to instrument stack in functions
1585 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1586 // FIXME: remove once the bug 11395 is fixed.
1587 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1588 if (LongSize != 32) return false;
1589 CallInst *CI = dyn_cast<CallInst>(I);
1590 if (!CI || !CI->isInlineAsm()) return false;
1591 if (CI->getNumArgOperands() <= 5) return false;
1592 // We have inline assembly with quite a few arguments.
1596 void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1597 IRBuilder<> IRB(*C);
1598 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1599 std::string Suffix = itostr(i);
1600 AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
1601 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1602 IntptrTy, nullptr));
1603 AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
1604 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
1605 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1607 AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
1608 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
1609 IntptrTy, IntptrTy, nullptr));
1610 AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
1611 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
1612 IntptrTy, IntptrTy, nullptr));
1613 AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1614 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1615 AsanAllocasUnpoisonFunc =
1616 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1617 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1620 void FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
1621 IRBuilder<> &IRB, Value *ShadowBase,
1623 size_t n = ShadowBytes.size();
1625 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1626 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1627 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1628 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1629 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1630 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1632 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
1633 if (F.getParent()->getDataLayout().isLittleEndian())
1634 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1636 Val = (Val << 8) | ShadowBytes[i + j];
1639 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1640 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1641 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1642 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
1647 // Fake stack allocator (asan_fake_stack.h) has 11 size classes
1648 // for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1649 static int StackMallocSizeClass(uint64_t LocalStackSize) {
1650 assert(LocalStackSize <= kMaxStackMallocSize);
1651 uint64_t MaxSize = kMinStackMallocSize;
1652 for (int i = 0;; i++, MaxSize *= 2)
1653 if (LocalStackSize <= MaxSize) return i;
1654 llvm_unreachable("impossible LocalStackSize");
1657 // Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1658 // We can not use MemSet intrinsic because it may end up calling the actual
1659 // memset. Size is a multiple of 8.
1660 // Currently this generates 8-byte stores on x86_64; it may be better to
1661 // generate wider stores.
1662 void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1663 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1664 assert(!(Size % 8));
1666 // kAsanStackAfterReturnMagic is 0xf5.
1667 const uint64_t kAsanStackAfterReturnMagic64 = 0xf5f5f5f5f5f5f5f5ULL;
1669 for (int i = 0; i < Size; i += 8) {
1670 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1672 ConstantInt::get(IRB.getInt64Ty(), kAsanStackAfterReturnMagic64),
1673 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1677 static DebugLoc getFunctionEntryDebugLocation(Function &F) {
1678 for (const auto &Inst : F.getEntryBlock())
1679 if (!isa<AllocaInst>(Inst)) return Inst.getDebugLoc();
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 = getFunctionEntryDebugLocation(F);
1737 Instruction *InsBefore = AllocaVec[0];
1738 IRBuilder<> IRB(InsBefore);
1739 IRB.SetCurrentDebugLocation(EntryDebugLocation);
1741 SmallVector<ASanStackVariableDescription, 16> SVD;
1742 SVD.reserve(AllocaVec.size());
1743 for (AllocaInst *AI : AllocaVec) {
1744 ASanStackVariableDescription D = {AI->getName().data(),
1745 ASan.getAllocaSizeInBytes(AI),
1746 AI->getAlignment(), AI, 0};
1749 // Minimal header size (left redzone) is 4 pointers,
1750 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1751 size_t MinHeaderSize = ASan.LongSize / 2;
1752 ASanStackFrameLayout L;
1753 ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1754 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1755 uint64_t LocalStackSize = L.FrameSize;
1756 bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
1757 LocalStackSize <= kMaxStackMallocSize;
1758 // Don't do dynamic alloca or stack malloc in presence of inline asm:
1759 // too often it makes assumptions on which registers are available.
1760 bool DoDynamicAlloca = ClDynamicAllocaStack && !HasNonEmptyInlineAsm;
1761 DoStackMalloc &= !HasNonEmptyInlineAsm;
1763 Value *StaticAlloca =
1764 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
1767 Value *LocalStackBase;
1769 if (DoStackMalloc) {
1770 // void *FakeStack = __asan_option_detect_stack_use_after_return
1771 // ? __asan_stack_malloc_N(LocalStackSize)
1773 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
1774 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1775 kAsanOptionDetectUAR, IRB.getInt32Ty());
1776 Value *UARIsEnabled =
1777 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1778 Constant::getNullValue(IRB.getInt32Ty()));
1780 SplitBlockAndInsertIfThen(UARIsEnabled, InsBefore, false);
1781 IRBuilder<> IRBIf(Term);
1782 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
1783 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1784 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
1785 Value *FakeStackValue =
1786 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
1787 ConstantInt::get(IntptrTy, LocalStackSize));
1788 IRB.SetInsertPoint(InsBefore);
1789 IRB.SetCurrentDebugLocation(EntryDebugLocation);
1790 FakeStack = createPHI(IRB, UARIsEnabled, FakeStackValue, Term,
1791 ConstantInt::get(IntptrTy, 0));
1793 Value *NoFakeStack =
1794 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
1795 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
1796 IRBIf.SetInsertPoint(Term);
1797 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
1798 Value *AllocaValue =
1799 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
1800 IRB.SetInsertPoint(InsBefore);
1801 IRB.SetCurrentDebugLocation(EntryDebugLocation);
1802 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
1804 // void *FakeStack = nullptr;
1805 // void *LocalStackBase = alloca(LocalStackSize);
1806 FakeStack = ConstantInt::get(IntptrTy, 0);
1808 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
1811 // Insert poison calls for lifetime intrinsics for alloca.
1812 bool HavePoisonedAllocas = false;
1813 for (const auto &APC : AllocaPoisonCallVec) {
1814 assert(APC.InsBefore);
1816 IRBuilder<> IRB(APC.InsBefore);
1817 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
1818 HavePoisonedAllocas |= APC.DoPoison;
1821 // Replace Alloca instructions with base+offset.
1822 for (const auto &Desc : SVD) {
1823 AllocaInst *AI = Desc.AI;
1824 Value *NewAllocaPtr = IRB.CreateIntToPtr(
1825 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
1827 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true);
1828 AI->replaceAllUsesWith(NewAllocaPtr);
1831 // The left-most redzone has enough space for at least 4 pointers.
1832 // Write the Magic value to redzone[0].
1833 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1834 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1836 // Write the frame description constant to redzone[1].
1837 Value *BasePlus1 = IRB.CreateIntToPtr(
1838 IRB.CreateAdd(LocalStackBase,
1839 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
1841 GlobalVariable *StackDescriptionGlobal =
1842 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
1843 /*AllowMerging*/ true);
1844 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
1845 IRB.CreateStore(Description, BasePlus1);
1846 // Write the PC to redzone[2].
1847 Value *BasePlus2 = IRB.CreateIntToPtr(
1848 IRB.CreateAdd(LocalStackBase,
1849 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
1851 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
1853 // Poison the stack redzones at the entry.
1854 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1855 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
1857 // (Un)poison the stack before all ret instructions.
1858 for (auto Ret : RetVec) {
1859 IRBuilder<> IRBRet(Ret);
1860 // Mark the current frame as retired.
1861 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1863 if (DoStackMalloc) {
1864 assert(StackMallocIdx >= 0);
1865 // if FakeStack != 0 // LocalStackBase == FakeStack
1866 // // In use-after-return mode, poison the whole stack frame.
1867 // if StackMallocIdx <= 4
1868 // // For small sizes inline the whole thing:
1869 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
1870 // **SavedFlagPtr(FakeStack) = 0
1872 // __asan_stack_free_N(FakeStack, LocalStackSize)
1874 // <This is not a fake stack; unpoison the redzones>
1876 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
1877 TerminatorInst *ThenTerm, *ElseTerm;
1878 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1880 IRBuilder<> IRBPoison(ThenTerm);
1881 if (StackMallocIdx <= 4) {
1882 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1883 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1884 ClassSize >> Mapping.Scale);
1885 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
1887 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1888 Value *SavedFlagPtr = IRBPoison.CreateLoad(
1889 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1890 IRBPoison.CreateStore(
1891 Constant::getNullValue(IRBPoison.getInt8Ty()),
1892 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1894 // For larger frames call __asan_stack_free_*.
1895 IRBPoison.CreateCall(
1896 AsanStackFreeFunc[StackMallocIdx],
1897 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
1900 IRBuilder<> IRBElse(ElseTerm);
1901 poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
1902 } else if (HavePoisonedAllocas) {
1903 // If we poisoned some allocas in llvm.lifetime analysis,
1904 // unpoison whole stack frame now.
1905 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
1907 poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
1911 // We are done. Remove the old unused alloca instructions.
1912 for (auto AI : AllocaVec) AI->eraseFromParent();
1915 void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
1916 IRBuilder<> &IRB, bool DoPoison) {
1917 // For now just insert the call to ASan runtime.
1918 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1919 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1921 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
1922 {AddrArg, SizeArg});
1925 // Handling llvm.lifetime intrinsics for a given %alloca:
1926 // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1927 // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1928 // invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1929 // could be poisoned by previous llvm.lifetime.end instruction, as the
1930 // variable may go in and out of scope several times, e.g. in loops).
1931 // (3) if we poisoned at least one %alloca in a function,
1932 // unpoison the whole stack frame at function exit.
1934 AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1935 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1936 // We're intested only in allocas we can handle.
1937 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
1938 // See if we've already calculated (or started to calculate) alloca for a
1940 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1941 if (I != AllocaForValue.end()) return I->second;
1942 // Store 0 while we're calculating alloca for value V to avoid
1943 // infinite recursion if the value references itself.
1944 AllocaForValue[V] = nullptr;
1945 AllocaInst *Res = nullptr;
1946 if (CastInst *CI = dyn_cast<CastInst>(V))
1947 Res = findAllocaForValue(CI->getOperand(0));
1948 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1949 for (Value *IncValue : PN->incoming_values()) {
1950 // Allow self-referencing phi-nodes.
1951 if (IncValue == PN) continue;
1952 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1953 // AI for incoming values should exist and should all be equal.
1954 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
1959 if (Res) AllocaForValue[V] = Res;
1963 void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
1964 IRBuilder<> IRB(AI);
1966 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
1967 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
1969 Value *Zero = Constant::getNullValue(IntptrTy);
1970 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
1971 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
1973 // Since we need to extend alloca with additional memory to locate
1974 // redzones, and OldSize is number of allocated blocks with
1975 // ElementSize size, get allocated memory size in bytes by
1976 // OldSize * ElementSize.
1977 const unsigned ElementSize =
1978 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
1980 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
1981 ConstantInt::get(IntptrTy, ElementSize));
1983 // PartialSize = OldSize % 32
1984 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
1986 // Misalign = kAllocaRzSize - PartialSize;
1987 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
1989 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
1990 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
1991 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
1993 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
1994 // Align is added to locate left redzone, PartialPadding for possible
1995 // partial redzone and kAllocaRzSize for right redzone respectively.
1996 Value *AdditionalChunkSize = IRB.CreateAdd(
1997 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
1999 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
2001 // Insert new alloca with new NewSize and Align params.
2002 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
2003 NewAlloca->setAlignment(Align);
2005 // NewAddress = Address + Align
2006 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
2007 ConstantInt::get(IntptrTy, Align));
2009 // Insert __asan_alloca_poison call for new created alloca.
2010 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
2012 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
2013 // for unpoisoning stuff.
2014 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
2016 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2018 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
2019 AI->replaceAllUsesWith(NewAddressPtr);
2021 // We are done. Erase old alloca from parent.
2022 AI->eraseFromParent();
2025 // isSafeAccess returns true if Addr is always inbounds with respect to its
2026 // base object. For example, it is a field access or an array access with
2027 // constant inbounds index.
2028 bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
2029 Value *Addr, uint64_t TypeSize) const {
2030 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
2031 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
2032 uint64_t Size = SizeOffset.first.getZExtValue();
2033 int64_t Offset = SizeOffset.second.getSExtValue();
2034 // Three checks are required to ensure safety:
2035 // . Offset >= 0 (since the offset is given from the base ptr)
2036 // . Size >= Offset (unsigned)
2037 // . Size - Offset >= NeededSize (unsigned)
2038 return Offset >= 0 && Size >= uint64_t(Offset) &&
2039 Size - uint64_t(Offset) >= TypeSize / 8;