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/SetVector.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/Analysis/MemoryBuiltins.h"
29 #include "llvm/Analysis/TargetLibraryInfo.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/IR/CallSite.h"
32 #include "llvm/IR/DIBuilder.h"
33 #include "llvm/IR/DataLayout.h"
34 #include "llvm/IR/Dominators.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/IR/IRBuilder.h"
37 #include "llvm/IR/InlineAsm.h"
38 #include "llvm/IR/InstVisitor.h"
39 #include "llvm/IR/IntrinsicInst.h"
40 #include "llvm/IR/LLVMContext.h"
41 #include "llvm/IR/MDBuilder.h"
42 #include "llvm/IR/Module.h"
43 #include "llvm/IR/Type.h"
44 #include "llvm/MC/MCSectionMachO.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/DataTypes.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/Endian.h"
49 #include "llvm/Support/SwapByteOrder.h"
50 #include "llvm/Support/raw_ostream.h"
51 #include "llvm/Transforms/Scalar.h"
52 #include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
53 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
54 #include "llvm/Transforms/Utils/Cloning.h"
55 #include "llvm/Transforms/Utils/Local.h"
56 #include "llvm/Transforms/Utils/ModuleUtils.h"
57 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
60 #include <system_error>
64 #define DEBUG_TYPE "asan"
66 // VMA size definition for architecture that support multiple sizes.
67 // AArch64 has 3 VMA sizes: 39, 42 and 48.
68 #ifndef SANITIZER_AARCH64_VMA
69 # define SANITIZER_AARCH64_VMA 39
71 # if SANITIZER_AARCH64_VMA != 39 && SANITIZER_AARCH64_VMA != 42
72 # error "invalid SANITIZER_AARCH64_VMA size"
76 static const uint64_t kDefaultShadowScale = 3;
77 static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
78 static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
79 static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
80 static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
81 static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;
82 static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
83 static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
84 static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
85 #if SANITIZER_AARCH64_VMA == 39
86 static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
87 #elif SANITIZER_AARCH64_VMA == 42
88 static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 39;
90 static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
91 static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
92 static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
94 static const size_t kMinStackMallocSize = 1 << 6; // 64B
95 static const size_t kMaxStackMallocSize = 1 << 16; // 64K
96 static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
97 static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
99 static const char *const kAsanModuleCtorName = "asan.module_ctor";
100 static const char *const kAsanModuleDtorName = "asan.module_dtor";
101 static const uint64_t kAsanCtorAndDtorPriority = 1;
102 static const char *const kAsanReportErrorTemplate = "__asan_report_";
103 static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
104 static const char *const kAsanUnregisterGlobalsName =
105 "__asan_unregister_globals";
106 static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
107 static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
108 static const char *const kAsanInitName = "__asan_init";
109 static const char *const kAsanVersionCheckName =
110 "__asan_version_mismatch_check_v6";
111 static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
112 static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
113 static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
114 static const int kMaxAsanStackMallocSizeClass = 10;
115 static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
116 static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
117 static const char *const kAsanGenPrefix = "__asan_gen_";
118 static const char *const kSanCovGenPrefix = "__sancov_gen_";
119 static const char *const kAsanPoisonStackMemoryName =
120 "__asan_poison_stack_memory";
121 static const char *const kAsanUnpoisonStackMemoryName =
122 "__asan_unpoison_stack_memory";
124 static const char *const kAsanOptionDetectUAR =
125 "__asan_option_detect_stack_use_after_return";
127 static const char *const kAsanAllocaPoison = "__asan_alloca_poison";
128 static const char *const kAsanAllocasUnpoison = "__asan_allocas_unpoison";
130 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
131 static const size_t kNumberOfAccessSizes = 5;
133 static const unsigned kAllocaRzSize = 32;
135 // Command-line flags.
136 static cl::opt<bool> ClEnableKasan(
137 "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
138 cl::Hidden, cl::init(false));
140 // This flag may need to be replaced with -f[no-]asan-reads.
141 static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
142 cl::desc("instrument read instructions"),
143 cl::Hidden, cl::init(true));
144 static cl::opt<bool> ClInstrumentWrites(
145 "asan-instrument-writes", cl::desc("instrument write instructions"),
146 cl::Hidden, cl::init(true));
147 static cl::opt<bool> ClInstrumentAtomics(
148 "asan-instrument-atomics",
149 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
151 static cl::opt<bool> ClAlwaysSlowPath(
152 "asan-always-slow-path",
153 cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
155 // This flag limits the number of instructions to be instrumented
156 // in any given BB. Normally, this should be set to unlimited (INT_MAX),
157 // but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
159 static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
160 "asan-max-ins-per-bb", cl::init(10000),
161 cl::desc("maximal number of instructions to instrument in any given BB"),
163 // This flag may need to be replaced with -f[no]asan-stack.
164 static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
165 cl::Hidden, cl::init(true));
166 static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
167 cl::desc("Check return-after-free"),
168 cl::Hidden, cl::init(true));
169 // This flag may need to be replaced with -f[no]asan-globals.
170 static cl::opt<bool> ClGlobals("asan-globals",
171 cl::desc("Handle global objects"), cl::Hidden,
173 static cl::opt<bool> ClInitializers("asan-initialization-order",
174 cl::desc("Handle C++ initializer order"),
175 cl::Hidden, cl::init(true));
176 static cl::opt<bool> ClInvalidPointerPairs(
177 "asan-detect-invalid-pointer-pair",
178 cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
180 static cl::opt<unsigned> ClRealignStack(
181 "asan-realign-stack",
182 cl::desc("Realign stack to the value of this flag (power of two)"),
183 cl::Hidden, cl::init(32));
184 static cl::opt<int> ClInstrumentationWithCallsThreshold(
185 "asan-instrumentation-with-call-threshold",
187 "If the function being instrumented contains more than "
188 "this number of memory accesses, use callbacks instead of "
189 "inline checks (-1 means never use callbacks)."),
190 cl::Hidden, cl::init(7000));
191 static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
192 "asan-memory-access-callback-prefix",
193 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
194 cl::init("__asan_"));
195 static cl::opt<bool> ClInstrumentAllocas("asan-instrument-allocas",
196 cl::desc("instrument dynamic allocas"),
197 cl::Hidden, cl::init(false));
198 static cl::opt<bool> ClSkipPromotableAllocas(
199 "asan-skip-promotable-allocas",
200 cl::desc("Do not instrument promotable allocas"), cl::Hidden,
203 // These flags allow to change the shadow mapping.
204 // The shadow mapping looks like
205 // Shadow = (Mem >> scale) + (1 << offset_log)
206 static cl::opt<int> ClMappingScale("asan-mapping-scale",
207 cl::desc("scale of asan shadow mapping"),
208 cl::Hidden, cl::init(0));
210 // Optimization flags. Not user visible, used mostly for testing
211 // and benchmarking the tool.
212 static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
213 cl::Hidden, cl::init(true));
214 static cl::opt<bool> ClOptSameTemp(
215 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
216 cl::Hidden, cl::init(true));
217 static cl::opt<bool> ClOptGlobals("asan-opt-globals",
218 cl::desc("Don't instrument scalar globals"),
219 cl::Hidden, cl::init(true));
220 static cl::opt<bool> ClOptStack(
221 "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
222 cl::Hidden, cl::init(false));
224 static cl::opt<bool> ClCheckLifetime(
225 "asan-check-lifetime",
226 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"), cl::Hidden,
229 static cl::opt<bool> ClDynamicAllocaStack(
230 "asan-stack-dynamic-alloca",
231 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
234 static cl::opt<uint32_t> ClForceExperiment(
235 "asan-force-experiment",
236 cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
240 static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
242 static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
243 cl::Hidden, cl::init(0));
244 static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
245 cl::desc("Debug func"));
246 static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
247 cl::Hidden, cl::init(-1));
248 static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
249 cl::Hidden, cl::init(-1));
251 STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
252 STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
253 STATISTIC(NumOptimizedAccessesToGlobalVar,
254 "Number of optimized accesses to global vars");
255 STATISTIC(NumOptimizedAccessesToStackVar,
256 "Number of optimized accesses to stack vars");
259 /// Frontend-provided metadata for source location.
260 struct LocationMetadata {
265 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
267 bool empty() const { return Filename.empty(); }
269 void parse(MDNode *MDN) {
270 assert(MDN->getNumOperands() == 3);
271 MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
272 Filename = DIFilename->getString();
274 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
276 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
280 /// Frontend-provided metadata for global variables.
281 class GlobalsMetadata {
284 Entry() : SourceLoc(), Name(), IsDynInit(false), IsBlacklisted(false) {}
285 LocationMetadata SourceLoc;
291 GlobalsMetadata() : inited_(false) {}
293 void init(Module &M) {
296 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
297 if (!Globals) return;
298 for (auto MDN : Globals->operands()) {
299 // Metadata node contains the global and the fields of "Entry".
300 assert(MDN->getNumOperands() == 5);
301 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
302 // The optimizer may optimize away a global entirely.
304 // We can already have an entry for GV if it was merged with another
306 Entry &E = Entries[GV];
307 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
308 E.SourceLoc.parse(Loc);
309 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
310 E.Name = Name->getString();
311 ConstantInt *IsDynInit =
312 mdconst::extract<ConstantInt>(MDN->getOperand(3));
313 E.IsDynInit |= IsDynInit->isOne();
314 ConstantInt *IsBlacklisted =
315 mdconst::extract<ConstantInt>(MDN->getOperand(4));
316 E.IsBlacklisted |= IsBlacklisted->isOne();
320 /// Returns metadata entry for a given global.
321 Entry get(GlobalVariable *G) const {
322 auto Pos = Entries.find(G);
323 return (Pos != Entries.end()) ? Pos->second : Entry();
328 DenseMap<GlobalVariable *, Entry> Entries;
331 /// This struct defines the shadow mapping using the rule:
332 /// shadow = (mem >> Scale) ADD-or-OR Offset.
333 struct ShadowMapping {
339 static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
341 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
342 bool IsIOS = TargetTriple.isiOS();
343 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
344 bool IsLinux = TargetTriple.isOSLinux();
345 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
346 TargetTriple.getArch() == llvm::Triple::ppc64le;
347 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
348 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
349 TargetTriple.getArch() == llvm::Triple::mipsel;
350 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
351 TargetTriple.getArch() == llvm::Triple::mips64el;
352 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
353 bool IsWindows = TargetTriple.isOSWindows();
355 ShadowMapping Mapping;
357 if (LongSize == 32) {
358 // Android is always PIE, which means that the beginning of the address
359 // space is always available.
363 Mapping.Offset = kMIPS32_ShadowOffset32;
365 Mapping.Offset = kFreeBSD_ShadowOffset32;
367 Mapping.Offset = kIOSShadowOffset32;
369 Mapping.Offset = kWindowsShadowOffset32;
371 Mapping.Offset = kDefaultShadowOffset32;
372 } else { // LongSize == 64
374 Mapping.Offset = kPPC64_ShadowOffset64;
376 Mapping.Offset = kFreeBSD_ShadowOffset64;
377 else if (IsLinux && IsX86_64) {
379 Mapping.Offset = kLinuxKasan_ShadowOffset64;
381 Mapping.Offset = kSmallX86_64ShadowOffset;
383 Mapping.Offset = kMIPS64_ShadowOffset64;
385 Mapping.Offset = kAArch64_ShadowOffset64;
387 Mapping.Offset = kDefaultShadowOffset64;
390 Mapping.Scale = kDefaultShadowScale;
391 if (ClMappingScale) {
392 Mapping.Scale = ClMappingScale;
395 // OR-ing shadow offset if more efficient (at least on x86) if the offset
396 // is a power of two, but on ppc64 we have to use add since the shadow
397 // offset is not necessary 1/8-th of the address space.
398 Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
403 static size_t RedzoneSizeForScale(int MappingScale) {
404 // Redzone used for stack and globals is at least 32 bytes.
405 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
406 return std::max(32U, 1U << MappingScale);
409 /// AddressSanitizer: instrument the code in module to find memory bugs.
410 struct AddressSanitizer : public FunctionPass {
411 explicit AddressSanitizer(bool CompileKernel = false)
412 : FunctionPass(ID), CompileKernel(CompileKernel || ClEnableKasan) {
413 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
415 const char *getPassName() const override {
416 return "AddressSanitizerFunctionPass";
418 void getAnalysisUsage(AnalysisUsage &AU) const override {
419 AU.addRequired<DominatorTreeWrapperPass>();
420 AU.addRequired<TargetLibraryInfoWrapperPass>();
422 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
423 Type *Ty = AI->getAllocatedType();
424 uint64_t SizeInBytes =
425 AI->getModule()->getDataLayout().getTypeAllocSize(Ty);
428 /// Check if we want (and can) handle this alloca.
429 bool isInterestingAlloca(AllocaInst &AI);
431 // Check if we have dynamic alloca.
432 bool isDynamicAlloca(AllocaInst &AI) const {
433 return AI.isArrayAllocation() || !AI.isStaticAlloca();
436 /// If it is an interesting memory access, return the PointerOperand
437 /// and set IsWrite/Alignment. Otherwise return nullptr.
438 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
439 uint64_t *TypeSize, unsigned *Alignment);
440 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
441 bool UseCalls, const DataLayout &DL);
442 void instrumentPointerComparisonOrSubtraction(Instruction *I);
443 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
444 Value *Addr, uint32_t TypeSize, bool IsWrite,
445 Value *SizeArgument, bool UseCalls, uint32_t Exp);
446 void instrumentUnusualSizeOrAlignment(Instruction *I, Value *Addr,
447 uint32_t TypeSize, bool IsWrite,
448 Value *SizeArgument, bool UseCalls,
450 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
451 Value *ShadowValue, uint32_t TypeSize);
452 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
453 bool IsWrite, size_t AccessSizeIndex,
454 Value *SizeArgument, uint32_t Exp);
455 void instrumentMemIntrinsic(MemIntrinsic *MI);
456 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
457 bool runOnFunction(Function &F) override;
458 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
459 void markEscapedLocalAllocas(Function &F);
460 bool doInitialization(Module &M) override;
461 static char ID; // Pass identification, replacement for typeid
463 DominatorTree &getDominatorTree() const { return *DT; }
466 void initializeCallbacks(Module &M);
468 bool LooksLikeCodeInBug11395(Instruction *I);
469 bool GlobalIsLinkerInitialized(GlobalVariable *G);
470 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
471 uint64_t TypeSize) const;
473 /// Helper to cleanup per-function state.
474 struct FunctionStateRAII {
475 AddressSanitizer *Pass;
476 FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
477 assert(Pass->ProcessedAllocas.empty() &&
478 "last pass forgot to clear cache");
480 ~FunctionStateRAII() { Pass->ProcessedAllocas.clear(); }
488 ShadowMapping Mapping;
490 Function *AsanCtorFunction = nullptr;
491 Function *AsanInitFunction = nullptr;
492 Function *AsanHandleNoReturnFunc;
493 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
494 // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
495 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
496 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
497 // This array is indexed by AccessIsWrite and Experiment.
498 Function *AsanErrorCallbackSized[2][2];
499 Function *AsanMemoryAccessCallbackSized[2][2];
500 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
502 GlobalsMetadata GlobalsMD;
503 DenseMap<AllocaInst *, bool> ProcessedAllocas;
505 friend struct FunctionStackPoisoner;
508 class AddressSanitizerModule : public ModulePass {
510 explicit AddressSanitizerModule(bool CompileKernel = false)
511 : ModulePass(ID), CompileKernel(CompileKernel || ClEnableKasan) {}
512 bool runOnModule(Module &M) override;
513 static char ID; // Pass identification, replacement for typeid
514 const char *getPassName() const override { return "AddressSanitizerModule"; }
517 void initializeCallbacks(Module &M);
519 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
520 bool ShouldInstrumentGlobal(GlobalVariable *G);
521 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
522 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
523 size_t MinRedzoneSizeForGlobal() const {
524 return RedzoneSizeForScale(Mapping.Scale);
527 GlobalsMetadata GlobalsMD;
532 ShadowMapping Mapping;
533 Function *AsanPoisonGlobals;
534 Function *AsanUnpoisonGlobals;
535 Function *AsanRegisterGlobals;
536 Function *AsanUnregisterGlobals;
539 // Stack poisoning does not play well with exception handling.
540 // When an exception is thrown, we essentially bypass the code
541 // that unpoisones the stack. This is why the run-time library has
542 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
543 // stack in the interceptor. This however does not work inside the
544 // actual function which catches the exception. Most likely because the
545 // compiler hoists the load of the shadow value somewhere too high.
546 // This causes asan to report a non-existing bug on 453.povray.
547 // It sounds like an LLVM bug.
548 struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
550 AddressSanitizer &ASan;
555 ShadowMapping Mapping;
557 SmallVector<AllocaInst *, 16> AllocaVec;
558 SmallSetVector<AllocaInst *, 16> NonInstrumentedStaticAllocaVec;
559 SmallVector<Instruction *, 8> RetVec;
560 unsigned StackAlignment;
562 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
563 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
564 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
565 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
567 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
568 struct AllocaPoisonCall {
569 IntrinsicInst *InsBefore;
574 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
576 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
577 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
578 AllocaInst *DynamicAllocaLayout = nullptr;
579 IntrinsicInst *LocalEscapeCall = nullptr;
581 // Maps Value to an AllocaInst from which the Value is originated.
582 typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
583 AllocaForValueMapTy AllocaForValue;
585 bool HasNonEmptyInlineAsm = false;
586 bool HasReturnsTwiceCall = false;
587 std::unique_ptr<CallInst> EmptyInlineAsm;
589 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
592 DIB(*F.getParent(), /*AllowUnresolved*/ false),
594 IntptrTy(ASan.IntptrTy),
595 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
596 Mapping(ASan.Mapping),
597 StackAlignment(1 << Mapping.Scale),
598 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
600 bool runOnFunction() {
601 if (!ClStack) return false;
602 // Collect alloca, ret, lifetime instructions etc.
603 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
605 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
607 initializeCallbacks(*F.getParent());
617 // Finds all Alloca instructions and puts
618 // poisoned red zones around all of them.
619 // Then unpoison everything back before the function returns.
622 void createDynamicAllocasInitStorage();
624 // ----------------------- Visitors.
625 /// \brief Collect all Ret instructions.
626 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
628 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
630 IRBuilder<> IRB(InstBefore);
631 IRB.CreateCall(AsanAllocasUnpoisonFunc,
632 {IRB.CreateLoad(DynamicAllocaLayout),
633 IRB.CreatePtrToInt(SavedStack, IntptrTy)});
636 // Unpoison dynamic allocas redzones.
637 void unpoisonDynamicAllocas() {
638 for (auto &Ret : RetVec)
639 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
641 for (auto &StackRestoreInst : StackRestoreVec)
642 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
643 StackRestoreInst->getOperand(0));
646 // Deploy and poison redzones around dynamic alloca call. To do this, we
647 // should replace this call with another one with changed parameters and
648 // replace all its uses with new address, so
649 // addr = alloca type, old_size, align
651 // new_size = (old_size + additional_size) * sizeof(type)
652 // tmp = alloca i8, new_size, max(align, 32)
653 // addr = tmp + 32 (first 32 bytes are for the left redzone).
654 // Additional_size is added to make new memory allocation contain not only
655 // requested memory, but also left, partial and right redzones.
656 void handleDynamicAllocaCall(AllocaInst *AI);
658 /// \brief Collect Alloca instructions we want (and can) handle.
659 void visitAllocaInst(AllocaInst &AI) {
660 if (!ASan.isInterestingAlloca(AI)) {
661 if (AI.isStaticAlloca()) NonInstrumentedStaticAllocaVec.insert(&AI);
665 StackAlignment = std::max(StackAlignment, AI.getAlignment());
666 if (ASan.isDynamicAlloca(AI))
667 DynamicAllocaVec.push_back(&AI);
669 AllocaVec.push_back(&AI);
672 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
674 void visitIntrinsicInst(IntrinsicInst &II) {
675 Intrinsic::ID ID = II.getIntrinsicID();
676 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
677 if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
678 if (!ClCheckLifetime) return;
679 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
681 // Found lifetime intrinsic, add ASan instrumentation if necessary.
682 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
683 // If size argument is undefined, don't do anything.
684 if (Size->isMinusOne()) return;
685 // Check that size doesn't saturate uint64_t and can
686 // be stored in IntptrTy.
687 const uint64_t SizeValue = Size->getValue().getLimitedValue();
688 if (SizeValue == ~0ULL ||
689 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
691 // Find alloca instruction that corresponds to llvm.lifetime argument.
692 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
694 bool DoPoison = (ID == Intrinsic::lifetime_end);
695 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
696 AllocaPoisonCallVec.push_back(APC);
699 void visitCallSite(CallSite CS) {
700 Instruction *I = CS.getInstruction();
701 if (CallInst *CI = dyn_cast<CallInst>(I)) {
702 HasNonEmptyInlineAsm |=
703 CI->isInlineAsm() && !CI->isIdenticalTo(EmptyInlineAsm.get());
704 HasReturnsTwiceCall |= CI->canReturnTwice();
708 // ---------------------- Helpers.
709 void initializeCallbacks(Module &M);
711 bool doesDominateAllExits(const Instruction *I) const {
712 for (auto Ret : RetVec) {
713 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
718 /// Finds alloca where the value comes from.
719 AllocaInst *findAllocaForValue(Value *V);
720 void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
721 Value *ShadowBase, bool DoPoison);
722 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
724 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
726 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
728 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
729 Instruction *ThenTerm, Value *ValueIfFalse);
734 char AddressSanitizer::ID = 0;
735 INITIALIZE_PASS_BEGIN(
736 AddressSanitizer, "asan",
737 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
739 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
741 AddressSanitizer, "asan",
742 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
744 FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel) {
745 return new AddressSanitizer(CompileKernel);
748 char AddressSanitizerModule::ID = 0;
750 AddressSanitizerModule, "asan-module",
751 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
754 ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel) {
755 return new AddressSanitizerModule(CompileKernel);
758 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
759 size_t Res = countTrailingZeros(TypeSize / 8);
760 assert(Res < kNumberOfAccessSizes);
764 // \brief Create a constant for Str so that we can pass it to the run-time lib.
765 static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
767 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
768 // We use private linkage for module-local strings. If they can be merged
769 // with another one, we set the unnamed_addr attribute.
771 new GlobalVariable(M, StrConst->getType(), true,
772 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
773 if (AllowMerging) GV->setUnnamedAddr(true);
774 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
778 /// \brief Create a global describing a source location.
779 static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
780 LocationMetadata MD) {
781 Constant *LocData[] = {
782 createPrivateGlobalForString(M, MD.Filename, true),
783 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
784 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
786 auto LocStruct = ConstantStruct::getAnon(LocData);
787 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
788 GlobalValue::PrivateLinkage, LocStruct,
790 GV->setUnnamedAddr(true);
794 static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
795 return G->getName().find(kAsanGenPrefix) == 0 ||
796 G->getName().find(kSanCovGenPrefix) == 0;
799 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
801 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
802 if (Mapping.Offset == 0) return Shadow;
803 // (Shadow >> scale) | offset
804 if (Mapping.OrShadowOffset)
805 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
807 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
810 // Instrument memset/memmove/memcpy
811 void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
813 if (isa<MemTransferInst>(MI)) {
815 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
816 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
817 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
818 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
819 } else if (isa<MemSetInst>(MI)) {
822 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
823 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
824 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
826 MI->eraseFromParent();
829 /// Check if we want (and can) handle this alloca.
830 bool AddressSanitizer::isInterestingAlloca(AllocaInst &AI) {
831 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
833 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
834 return PreviouslySeenAllocaInfo->getSecond();
837 (AI.getAllocatedType()->isSized() &&
838 // alloca() may be called with 0 size, ignore it.
839 getAllocaSizeInBytes(&AI) > 0 &&
840 // We are only interested in allocas not promotable to registers.
841 // Promotable allocas are common under -O0.
842 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI) ||
843 isDynamicAlloca(AI)));
845 ProcessedAllocas[&AI] = IsInteresting;
846 return IsInteresting;
849 /// If I is an interesting memory access, return the PointerOperand
850 /// and set IsWrite/Alignment. Otherwise return nullptr.
851 Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
854 unsigned *Alignment) {
855 // Skip memory accesses inserted by another instrumentation.
856 if (I->getMetadata("nosanitize")) return nullptr;
858 Value *PtrOperand = nullptr;
859 const DataLayout &DL = I->getModule()->getDataLayout();
860 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
861 if (!ClInstrumentReads) return nullptr;
863 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
864 *Alignment = LI->getAlignment();
865 PtrOperand = LI->getPointerOperand();
866 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
867 if (!ClInstrumentWrites) return nullptr;
869 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
870 *Alignment = SI->getAlignment();
871 PtrOperand = SI->getPointerOperand();
872 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
873 if (!ClInstrumentAtomics) return nullptr;
875 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
877 PtrOperand = RMW->getPointerOperand();
878 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
879 if (!ClInstrumentAtomics) return nullptr;
881 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
883 PtrOperand = XCHG->getPointerOperand();
886 // Treat memory accesses to promotable allocas as non-interesting since they
887 // will not cause memory violations. This greatly speeds up the instrumented
888 // executable at -O0.
889 if (ClSkipPromotableAllocas)
890 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
891 return isInterestingAlloca(*AI) ? AI : nullptr;
896 static bool isPointerOperand(Value *V) {
897 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
900 // This is a rough heuristic; it may cause both false positives and
901 // false negatives. The proper implementation requires cooperation with
903 static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
904 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
905 if (!Cmp->isRelational()) return false;
906 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
907 if (BO->getOpcode() != Instruction::Sub) return false;
911 if (!isPointerOperand(I->getOperand(0)) ||
912 !isPointerOperand(I->getOperand(1)))
917 bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
918 // If a global variable does not have dynamic initialization we don't
919 // have to instrument it. However, if a global does not have initializer
920 // at all, we assume it has dynamic initializer (in other TU).
921 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
924 void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
927 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
928 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
929 for (int i = 0; i < 2; i++) {
930 if (Param[i]->getType()->isPointerTy())
931 Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
933 IRB.CreateCall(F, Param);
936 void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
937 Instruction *I, bool UseCalls,
938 const DataLayout &DL) {
939 bool IsWrite = false;
940 unsigned Alignment = 0;
941 uint64_t TypeSize = 0;
942 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment);
945 // Optimization experiments.
946 // The experiments can be used to evaluate potential optimizations that remove
947 // instrumentation (assess false negatives). Instead of completely removing
948 // some instrumentation, you set Exp to a non-zero value (mask of optimization
949 // experiments that want to remove instrumentation of this instruction).
950 // If Exp is non-zero, this pass will emit special calls into runtime
951 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
952 // make runtime terminate the program in a special way (with a different
953 // exit status). Then you run the new compiler on a buggy corpus, collect
954 // the special terminations (ideally, you don't see them at all -- no false
955 // negatives) and make the decision on the optimization.
956 uint32_t Exp = ClForceExperiment;
958 if (ClOpt && ClOptGlobals) {
959 // If initialization order checking is disabled, a simple access to a
960 // dynamically initialized global is always valid.
961 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
962 if (G != NULL && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
963 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
964 NumOptimizedAccessesToGlobalVar++;
969 if (ClOpt && ClOptStack) {
970 // A direct inbounds access to a stack variable is always valid.
971 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
972 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
973 NumOptimizedAccessesToStackVar++;
979 NumInstrumentedWrites++;
981 NumInstrumentedReads++;
983 unsigned Granularity = 1 << Mapping.Scale;
984 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
985 // if the data is properly aligned.
986 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
988 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
989 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls,
991 instrumentUnusualSizeOrAlignment(I, Addr, TypeSize, IsWrite, nullptr,
995 Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
996 Value *Addr, bool IsWrite,
997 size_t AccessSizeIndex,
1000 IRBuilder<> IRB(InsertBefore);
1001 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1002 CallInst *Call = nullptr;
1005 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1006 {Addr, SizeArgument});
1008 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1009 {Addr, SizeArgument, ExpVal});
1013 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1015 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1019 // We don't do Call->setDoesNotReturn() because the BB already has
1020 // UnreachableInst at the end.
1021 // This EmptyAsm is required to avoid callback merge.
1022 IRB.CreateCall(EmptyAsm, {});
1026 Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
1028 uint32_t TypeSize) {
1029 size_t Granularity = 1 << Mapping.Scale;
1030 // Addr & (Granularity - 1)
1031 Value *LastAccessedByte =
1032 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
1033 // (Addr & (Granularity - 1)) + size - 1
1034 if (TypeSize / 8 > 1)
1035 LastAccessedByte = IRB.CreateAdd(
1036 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1037 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
1039 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
1040 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1041 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1044 void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
1045 Instruction *InsertBefore, Value *Addr,
1046 uint32_t TypeSize, bool IsWrite,
1047 Value *SizeArgument, bool UseCalls,
1049 IRBuilder<> IRB(InsertBefore);
1050 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1051 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1055 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1058 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1059 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
1064 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
1065 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1066 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1067 Value *CmpVal = Constant::getNullValue(ShadowTy);
1068 Value *ShadowValue =
1069 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
1071 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
1072 size_t Granularity = 1 << Mapping.Scale;
1073 TerminatorInst *CrashTerm = nullptr;
1075 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
1076 // We use branch weights for the slow path check, to indicate that the slow
1077 // path is rarely taken. This seems to be the case for SPEC benchmarks.
1078 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1079 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
1080 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
1081 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
1082 IRB.SetInsertPoint(CheckTerm);
1083 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
1084 BasicBlock *CrashBlock =
1085 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
1086 CrashTerm = new UnreachableInst(*C, CrashBlock);
1087 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1088 ReplaceInstWithInst(CheckTerm, NewTerm);
1090 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
1093 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
1094 AccessSizeIndex, SizeArgument, Exp);
1095 Crash->setDebugLoc(OrigIns->getDebugLoc());
1098 // Instrument unusual size or unusual alignment.
1099 // We can not do it with a single check, so we do 1-byte check for the first
1100 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1101 // to report the actual access size.
1102 void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1103 Instruction *I, Value *Addr, uint32_t TypeSize, bool IsWrite,
1104 Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1106 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1107 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1110 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1113 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1114 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
1116 Value *LastByte = IRB.CreateIntToPtr(
1117 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1119 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false, Exp);
1120 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false, Exp);
1124 void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1125 GlobalValue *ModuleName) {
1126 // Set up the arguments to our poison/unpoison functions.
1127 IRBuilder<> IRB(GlobalInit.begin()->getFirstInsertionPt());
1129 // Add a call to poison all external globals before the given function starts.
1130 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1131 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
1133 // Add calls to unpoison all globals before each return instruction.
1134 for (auto &BB : GlobalInit.getBasicBlockList())
1135 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
1136 CallInst::Create(AsanUnpoisonGlobals, "", RI);
1139 void AddressSanitizerModule::createInitializerPoisonCalls(
1140 Module &M, GlobalValue *ModuleName) {
1141 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1143 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1144 for (Use &OP : CA->operands()) {
1145 if (isa<ConstantAggregateZero>(OP)) continue;
1146 ConstantStruct *CS = cast<ConstantStruct>(OP);
1148 // Must have a function or null ptr.
1149 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
1150 if (F->getName() == kAsanModuleCtorName) continue;
1151 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1152 // Don't instrument CTORs that will run before asan.module_ctor.
1153 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1154 poisonOneInitializer(*F, ModuleName);
1159 bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
1160 Type *Ty = cast<PointerType>(G->getType())->getElementType();
1161 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
1163 if (GlobalsMD.get(G).IsBlacklisted) return false;
1164 if (!Ty->isSized()) return false;
1165 if (!G->hasInitializer()) return false;
1166 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
1167 // Touch only those globals that will not be defined in other modules.
1168 // Don't handle ODR linkage types and COMDATs since other modules may be built
1170 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1171 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1172 G->getLinkage() != GlobalVariable::InternalLinkage)
1174 if (G->hasComdat()) return false;
1175 // Two problems with thread-locals:
1176 // - The address of the main thread's copy can't be computed at link-time.
1177 // - Need to poison all copies, not just the main thread's one.
1178 if (G->isThreadLocal()) return false;
1179 // For now, just ignore this Global if the alignment is large.
1180 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
1182 if (G->hasSection()) {
1183 StringRef Section(G->getSection());
1185 // Globals from llvm.metadata aren't emitted, do not instrument them.
1186 if (Section == "llvm.metadata") return false;
1187 // Do not instrument globals from special LLVM sections.
1188 if (Section.find("__llvm") != StringRef::npos) return false;
1190 // Callbacks put into the CRT initializer/terminator sections
1191 // should not be instrumented.
1192 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1193 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1194 if (Section.startswith(".CRT")) {
1195 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1199 if (TargetTriple.isOSBinFormatMachO()) {
1200 StringRef ParsedSegment, ParsedSection;
1201 unsigned TAA = 0, StubSize = 0;
1203 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1204 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
1205 if (!ErrorCode.empty()) {
1206 assert(false && "Invalid section specifier.");
1210 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1211 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1213 if (ParsedSegment == "__OBJC" ||
1214 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1215 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1218 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1219 // Constant CFString instances are compiled in the following way:
1220 // -- the string buffer is emitted into
1221 // __TEXT,__cstring,cstring_literals
1222 // -- the constant NSConstantString structure referencing that buffer
1223 // is placed into __DATA,__cfstring
1224 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1225 // Moreover, it causes the linker to crash on OS X 10.7
1226 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1227 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1230 // The linker merges the contents of cstring_literals and removes the
1232 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1233 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1242 void AddressSanitizerModule::initializeCallbacks(Module &M) {
1243 IRBuilder<> IRB(*C);
1244 // Declare our poisoning and unpoisoning functions.
1245 AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1246 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
1247 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
1248 AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1249 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
1250 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1251 // Declare functions that register/unregister globals.
1252 AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1253 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1254 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
1255 AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
1256 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1257 IntptrTy, IntptrTy, nullptr));
1258 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1261 // This function replaces all global variables with new variables that have
1262 // trailing redzones. It also creates a function that poisons
1263 // redzones and inserts this function into llvm.global_ctors.
1264 bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
1267 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1269 for (auto &G : M.globals()) {
1270 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
1273 size_t n = GlobalsToChange.size();
1274 if (n == 0) return false;
1276 // A global is described by a structure
1279 // size_t size_with_redzone;
1280 // const char *name;
1281 // const char *module_name;
1282 // size_t has_dynamic_init;
1283 // void *source_location;
1284 // We initialize an array of such structures and pass it to a run-time call.
1285 StructType *GlobalStructTy =
1286 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
1287 IntptrTy, IntptrTy, nullptr);
1288 SmallVector<Constant *, 16> Initializers(n);
1290 bool HasDynamicallyInitializedGlobals = false;
1292 // We shouldn't merge same module names, as this string serves as unique
1293 // module ID in runtime.
1294 GlobalVariable *ModuleName = createPrivateGlobalForString(
1295 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
1297 auto &DL = M.getDataLayout();
1298 for (size_t i = 0; i < n; i++) {
1299 static const uint64_t kMaxGlobalRedzone = 1 << 18;
1300 GlobalVariable *G = GlobalsToChange[i];
1302 auto MD = GlobalsMD.get(G);
1303 // Create string holding the global name (use global name from metadata
1304 // if it's available, otherwise just write the name of global variable).
1305 GlobalVariable *Name = createPrivateGlobalForString(
1306 M, MD.Name.empty() ? G->getName() : MD.Name,
1307 /*AllowMerging*/ true);
1309 PointerType *PtrTy = cast<PointerType>(G->getType());
1310 Type *Ty = PtrTy->getElementType();
1311 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
1312 uint64_t MinRZ = MinRedzoneSizeForGlobal();
1313 // MinRZ <= RZ <= kMaxGlobalRedzone
1314 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
1315 uint64_t RZ = std::max(
1316 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
1317 uint64_t RightRedzoneSize = RZ;
1318 // Round up to MinRZ
1319 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
1320 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
1321 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1323 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
1324 Constant *NewInitializer =
1325 ConstantStruct::get(NewTy, G->getInitializer(),
1326 Constant::getNullValue(RightRedZoneTy), nullptr);
1328 // Create a new global variable with enough space for a redzone.
1329 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1330 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1331 Linkage = GlobalValue::InternalLinkage;
1332 GlobalVariable *NewGlobal =
1333 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1334 "", G, G->getThreadLocalMode());
1335 NewGlobal->copyAttributesFrom(G);
1336 NewGlobal->setAlignment(MinRZ);
1339 Indices2[0] = IRB.getInt32(0);
1340 Indices2[1] = IRB.getInt32(0);
1342 G->replaceAllUsesWith(
1343 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
1344 NewGlobal->takeName(G);
1345 G->eraseFromParent();
1347 Constant *SourceLoc;
1348 if (!MD.SourceLoc.empty()) {
1349 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1350 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1352 SourceLoc = ConstantInt::get(IntptrTy, 0);
1355 Initializers[i] = ConstantStruct::get(
1356 GlobalStructTy, ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
1357 ConstantInt::get(IntptrTy, SizeInBytes),
1358 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1359 ConstantExpr::getPointerCast(Name, IntptrTy),
1360 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
1361 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc, nullptr);
1363 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
1365 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
1368 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1369 GlobalVariable *AllGlobals = new GlobalVariable(
1370 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1371 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1373 // Create calls for poisoning before initializers run and unpoisoning after.
1374 if (HasDynamicallyInitializedGlobals)
1375 createInitializerPoisonCalls(M, ModuleName);
1376 IRB.CreateCall(AsanRegisterGlobals,
1377 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1378 ConstantInt::get(IntptrTy, n)});
1380 // We also need to unregister globals at the end, e.g. when a shared library
1382 Function *AsanDtorFunction =
1383 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1384 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1385 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1386 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
1387 IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1388 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1389 ConstantInt::get(IntptrTy, n)});
1390 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
1396 bool AddressSanitizerModule::runOnModule(Module &M) {
1397 C = &(M.getContext());
1398 int LongSize = M.getDataLayout().getPointerSizeInBits();
1399 IntptrTy = Type::getIntNTy(*C, LongSize);
1400 TargetTriple = Triple(M.getTargetTriple());
1401 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
1402 initializeCallbacks(M);
1404 bool Changed = false;
1406 // TODO(glider): temporarily disabled globals instrumentation for KASan.
1407 if (ClGlobals && !CompileKernel) {
1408 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1410 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1411 Changed |= InstrumentGlobals(IRB, M);
1417 void AddressSanitizer::initializeCallbacks(Module &M) {
1418 IRBuilder<> IRB(*C);
1419 // Create __asan_report* callbacks.
1420 // IsWrite, TypeSize and Exp are encoded in the function name.
1421 for (int Exp = 0; Exp < 2; Exp++) {
1422 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1423 const std::string TypeStr = AccessIsWrite ? "store" : "load";
1424 const std::string ExpStr = Exp ? "exp_" : "";
1425 const std::string SuffixStr = CompileKernel ? "N" : "_n";
1426 const std::string EndingStr = CompileKernel ? "_noabort" : "";
1427 Type *ExpType = Exp ? Type::getInt32Ty(*C) : nullptr;
1428 // TODO(glider): for KASan builds add _noabort to error reporting
1429 // functions and make them actually noabort (remove the UnreachableInst).
1430 AsanErrorCallbackSized[AccessIsWrite][Exp] =
1431 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1432 kAsanReportErrorTemplate + ExpStr + TypeStr + SuffixStr,
1433 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1434 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
1435 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1436 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
1437 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1438 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1439 AccessSizeIndex++) {
1440 const std::string Suffix = TypeStr + itostr(1 << AccessSizeIndex);
1441 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
1442 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1443 kAsanReportErrorTemplate + ExpStr + Suffix,
1444 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
1445 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
1446 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1447 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
1448 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
1453 const std::string MemIntrinCallbackPrefix =
1454 CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
1455 AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1456 MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
1457 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
1458 AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1459 MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
1460 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
1461 AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1462 MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
1463 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
1465 AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
1466 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
1468 AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1469 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1470 AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1471 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1472 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1473 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1474 StringRef(""), StringRef(""),
1475 /*hasSideEffects=*/true);
1479 bool AddressSanitizer::doInitialization(Module &M) {
1480 // Initialize the private fields. No one has accessed them before.
1484 C = &(M.getContext());
1485 LongSize = M.getDataLayout().getPointerSizeInBits();
1486 IntptrTy = Type::getIntNTy(*C, LongSize);
1487 TargetTriple = Triple(M.getTargetTriple());
1489 if (!CompileKernel) {
1490 std::tie(AsanCtorFunction, AsanInitFunction) =
1491 createSanitizerCtorAndInitFunctions(
1492 M, kAsanModuleCtorName, kAsanInitName,
1493 /*InitArgTypes=*/{}, /*InitArgs=*/{}, kAsanVersionCheckName);
1494 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
1496 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
1500 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1501 // For each NSObject descendant having a +load method, this method is invoked
1502 // by the ObjC runtime before any of the static constructors is called.
1503 // Therefore we need to instrument such methods with a call to __asan_init
1504 // at the beginning in order to initialize our runtime before any access to
1505 // the shadow memory.
1506 // We cannot just ignore these methods, because they may call other
1507 // instrumented functions.
1508 if (F.getName().find(" load]") != std::string::npos) {
1509 IRBuilder<> IRB(F.begin()->begin());
1510 IRB.CreateCall(AsanInitFunction, {});
1516 void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
1517 // Find the one possible call to llvm.localescape and pre-mark allocas passed
1518 // to it as uninteresting. This assumes we haven't started processing allocas
1519 // yet. This check is done up front because iterating the use list in
1520 // isInterestingAlloca would be algorithmically slower.
1521 assert(ProcessedAllocas.empty() && "must process localescape before allocas");
1523 // Try to get the declaration of llvm.localescape. If it's not in the module,
1524 // we can exit early.
1525 if (!F.getParent()->getFunction("llvm.localescape")) return;
1527 // Look for a call to llvm.localescape call in the entry block. It can't be in
1529 for (Instruction &I : F.getEntryBlock()) {
1530 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
1531 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
1532 // We found a call. Mark all the allocas passed in as uninteresting.
1533 for (Value *Arg : II->arg_operands()) {
1534 AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
1535 assert(AI && AI->isStaticAlloca() &&
1536 "non-static alloca arg to localescape");
1537 ProcessedAllocas[AI] = false;
1544 bool AddressSanitizer::runOnFunction(Function &F) {
1545 if (&F == AsanCtorFunction) return false;
1546 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
1547 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
1548 initializeCallbacks(*F.getParent());
1550 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1552 // If needed, insert __asan_init before checking for SanitizeAddress attr.
1553 maybeInsertAsanInitAtFunctionEntry(F);
1555 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return false;
1557 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName()) return false;
1559 FunctionStateRAII CleanupObj(this);
1561 // We can't instrument allocas used with llvm.localescape. Only static allocas
1562 // can be passed to that intrinsic.
1563 markEscapedLocalAllocas(F);
1565 // We want to instrument every address only once per basic block (unless there
1566 // are calls between uses).
1567 SmallSet<Value *, 16> TempsToInstrument;
1568 SmallVector<Instruction *, 16> ToInstrument;
1569 SmallVector<Instruction *, 8> NoReturnCalls;
1570 SmallVector<BasicBlock *, 16> AllBlocks;
1571 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
1577 // Fill the set of memory operations to instrument.
1578 for (auto &BB : F) {
1579 AllBlocks.push_back(&BB);
1580 TempsToInstrument.clear();
1581 int NumInsnsPerBB = 0;
1582 for (auto &Inst : BB) {
1583 if (LooksLikeCodeInBug11395(&Inst)) return false;
1584 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
1586 if (ClOpt && ClOptSameTemp) {
1587 if (!TempsToInstrument.insert(Addr).second)
1588 continue; // We've seen this temp in the current BB.
1590 } else if (ClInvalidPointerPairs &&
1591 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1592 PointerComparisonsOrSubtracts.push_back(&Inst);
1594 } else if (isa<MemIntrinsic>(Inst)) {
1597 if (isa<AllocaInst>(Inst)) NumAllocas++;
1600 // A call inside BB.
1601 TempsToInstrument.clear();
1602 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
1606 ToInstrument.push_back(&Inst);
1608 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
1614 (ClInstrumentationWithCallsThreshold >= 0 &&
1615 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
1616 const TargetLibraryInfo *TLI =
1617 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1618 const DataLayout &DL = F.getParent()->getDataLayout();
1619 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(),
1620 /*RoundToAlign=*/true);
1623 int NumInstrumented = 0;
1624 for (auto Inst : ToInstrument) {
1625 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1626 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
1627 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
1628 instrumentMop(ObjSizeVis, Inst, UseCalls,
1629 F.getParent()->getDataLayout());
1631 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
1636 FunctionStackPoisoner FSP(F, *this);
1637 bool ChangedStack = FSP.runOnFunction();
1639 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1640 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1641 for (auto CI : NoReturnCalls) {
1642 IRBuilder<> IRB(CI);
1643 IRB.CreateCall(AsanHandleNoReturnFunc, {});
1646 for (auto Inst : PointerComparisonsOrSubtracts) {
1647 instrumentPointerComparisonOrSubtraction(Inst);
1651 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
1653 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1658 // Workaround for bug 11395: we don't want to instrument stack in functions
1659 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1660 // FIXME: remove once the bug 11395 is fixed.
1661 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1662 if (LongSize != 32) return false;
1663 CallInst *CI = dyn_cast<CallInst>(I);
1664 if (!CI || !CI->isInlineAsm()) return false;
1665 if (CI->getNumArgOperands() <= 5) return false;
1666 // We have inline assembly with quite a few arguments.
1670 void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1671 IRBuilder<> IRB(*C);
1672 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1673 std::string Suffix = itostr(i);
1674 AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
1675 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1676 IntptrTy, nullptr));
1677 AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
1678 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
1679 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1681 AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
1682 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
1683 IntptrTy, IntptrTy, nullptr));
1684 AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
1685 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
1686 IntptrTy, IntptrTy, nullptr));
1687 AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1688 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1689 AsanAllocasUnpoisonFunc =
1690 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1691 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1694 void FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
1695 IRBuilder<> &IRB, Value *ShadowBase,
1697 size_t n = ShadowBytes.size();
1699 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1700 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1701 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1702 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1703 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1704 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1706 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
1707 if (F.getParent()->getDataLayout().isLittleEndian())
1708 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1710 Val = (Val << 8) | ShadowBytes[i + j];
1713 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1714 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1715 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1716 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
1721 // Fake stack allocator (asan_fake_stack.h) has 11 size classes
1722 // for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1723 static int StackMallocSizeClass(uint64_t LocalStackSize) {
1724 assert(LocalStackSize <= kMaxStackMallocSize);
1725 uint64_t MaxSize = kMinStackMallocSize;
1726 for (int i = 0;; i++, MaxSize *= 2)
1727 if (LocalStackSize <= MaxSize) return i;
1728 llvm_unreachable("impossible LocalStackSize");
1731 // Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1732 // We can not use MemSet intrinsic because it may end up calling the actual
1733 // memset. Size is a multiple of 8.
1734 // Currently this generates 8-byte stores on x86_64; it may be better to
1735 // generate wider stores.
1736 void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1737 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1738 assert(!(Size % 8));
1740 // kAsanStackAfterReturnMagic is 0xf5.
1741 const uint64_t kAsanStackAfterReturnMagic64 = 0xf5f5f5f5f5f5f5f5ULL;
1743 for (int i = 0; i < Size; i += 8) {
1744 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1746 ConstantInt::get(IRB.getInt64Ty(), kAsanStackAfterReturnMagic64),
1747 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1751 PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
1753 Instruction *ThenTerm,
1754 Value *ValueIfFalse) {
1755 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
1756 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
1757 PHI->addIncoming(ValueIfFalse, CondBlock);
1758 BasicBlock *ThenBlock = ThenTerm->getParent();
1759 PHI->addIncoming(ValueIfTrue, ThenBlock);
1763 Value *FunctionStackPoisoner::createAllocaForLayout(
1764 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
1767 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
1768 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
1771 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
1772 nullptr, "MyAlloca");
1773 assert(Alloca->isStaticAlloca());
1775 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1776 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1777 Alloca->setAlignment(FrameAlignment);
1778 return IRB.CreatePointerCast(Alloca, IntptrTy);
1781 void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
1782 BasicBlock &FirstBB = *F.begin();
1783 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
1784 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
1785 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
1786 DynamicAllocaLayout->setAlignment(32);
1789 void FunctionStackPoisoner::poisonStack() {
1790 assert(AllocaVec.size() > 0 || DynamicAllocaVec.size() > 0);
1792 if (ClInstrumentAllocas && DynamicAllocaVec.size() > 0) {
1793 // Handle dynamic allocas.
1794 createDynamicAllocasInitStorage();
1795 for (auto &AI : DynamicAllocaVec) handleDynamicAllocaCall(AI);
1797 unpoisonDynamicAllocas();
1800 if (AllocaVec.size() == 0) return;
1802 int StackMallocIdx = -1;
1803 DebugLoc EntryDebugLocation;
1804 if (auto SP = getDISubprogram(&F))
1805 EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
1807 Instruction *InsBefore = AllocaVec[0];
1808 IRBuilder<> IRB(InsBefore);
1809 IRB.SetCurrentDebugLocation(EntryDebugLocation);
1811 // Make sure non-instrumented allocas stay in the entry block. Otherwise,
1812 // debug info is broken, because only entry-block allocas are treated as
1813 // regular stack slots.
1814 auto InsBeforeB = InsBefore->getParent();
1815 assert(InsBeforeB == &F.getEntryBlock());
1816 for (BasicBlock::iterator I = InsBefore; I != InsBeforeB->end(); ++I)
1817 if (auto *AI = dyn_cast_or_null<AllocaInst>(I))
1818 if (NonInstrumentedStaticAllocaVec.count(AI) > 0)
1819 AI->moveBefore(InsBefore);
1821 // If we have a call to llvm.localescape, keep it in the entry block.
1822 if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
1824 SmallVector<ASanStackVariableDescription, 16> SVD;
1825 SVD.reserve(AllocaVec.size());
1826 for (AllocaInst *AI : AllocaVec) {
1827 ASanStackVariableDescription D = {AI->getName().data(),
1828 ASan.getAllocaSizeInBytes(AI),
1829 AI->getAlignment(), AI, 0};
1832 // Minimal header size (left redzone) is 4 pointers,
1833 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1834 size_t MinHeaderSize = ASan.LongSize / 2;
1835 ASanStackFrameLayout L;
1836 ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1837 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1838 uint64_t LocalStackSize = L.FrameSize;
1839 bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
1840 LocalStackSize <= kMaxStackMallocSize;
1841 bool DoDynamicAlloca = ClDynamicAllocaStack;
1842 // Don't do dynamic alloca or stack malloc if:
1843 // 1) There is inline asm: too often it makes assumptions on which registers
1845 // 2) There is a returns_twice call (typically setjmp), which is
1846 // optimization-hostile, and doesn't play well with introduced indirect
1847 // register-relative calculation of local variable addresses.
1848 DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
1849 DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
1851 Value *StaticAlloca =
1852 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
1855 Value *LocalStackBase;
1857 if (DoStackMalloc) {
1858 // void *FakeStack = __asan_option_detect_stack_use_after_return
1859 // ? __asan_stack_malloc_N(LocalStackSize)
1861 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
1862 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1863 kAsanOptionDetectUAR, IRB.getInt32Ty());
1864 Value *UARIsEnabled =
1865 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1866 Constant::getNullValue(IRB.getInt32Ty()));
1868 SplitBlockAndInsertIfThen(UARIsEnabled, InsBefore, false);
1869 IRBuilder<> IRBIf(Term);
1870 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
1871 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1872 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
1873 Value *FakeStackValue =
1874 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
1875 ConstantInt::get(IntptrTy, LocalStackSize));
1876 IRB.SetInsertPoint(InsBefore);
1877 IRB.SetCurrentDebugLocation(EntryDebugLocation);
1878 FakeStack = createPHI(IRB, UARIsEnabled, FakeStackValue, Term,
1879 ConstantInt::get(IntptrTy, 0));
1881 Value *NoFakeStack =
1882 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
1883 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
1884 IRBIf.SetInsertPoint(Term);
1885 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
1886 Value *AllocaValue =
1887 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
1888 IRB.SetInsertPoint(InsBefore);
1889 IRB.SetCurrentDebugLocation(EntryDebugLocation);
1890 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
1892 // void *FakeStack = nullptr;
1893 // void *LocalStackBase = alloca(LocalStackSize);
1894 FakeStack = ConstantInt::get(IntptrTy, 0);
1896 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
1899 // Insert poison calls for lifetime intrinsics for alloca.
1900 bool HavePoisonedAllocas = false;
1901 for (const auto &APC : AllocaPoisonCallVec) {
1902 assert(APC.InsBefore);
1904 IRBuilder<> IRB(APC.InsBefore);
1905 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
1906 HavePoisonedAllocas |= APC.DoPoison;
1909 // Replace Alloca instructions with base+offset.
1910 for (const auto &Desc : SVD) {
1911 AllocaInst *AI = Desc.AI;
1912 Value *NewAllocaPtr = IRB.CreateIntToPtr(
1913 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
1915 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true);
1916 AI->replaceAllUsesWith(NewAllocaPtr);
1919 // The left-most redzone has enough space for at least 4 pointers.
1920 // Write the Magic value to redzone[0].
1921 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1922 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1924 // Write the frame description constant to redzone[1].
1925 Value *BasePlus1 = IRB.CreateIntToPtr(
1926 IRB.CreateAdd(LocalStackBase,
1927 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
1929 GlobalVariable *StackDescriptionGlobal =
1930 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
1931 /*AllowMerging*/ true);
1932 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
1933 IRB.CreateStore(Description, BasePlus1);
1934 // Write the PC to redzone[2].
1935 Value *BasePlus2 = IRB.CreateIntToPtr(
1936 IRB.CreateAdd(LocalStackBase,
1937 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
1939 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
1941 // Poison the stack redzones at the entry.
1942 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1943 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
1945 // (Un)poison the stack before all ret instructions.
1946 for (auto Ret : RetVec) {
1947 IRBuilder<> IRBRet(Ret);
1948 // Mark the current frame as retired.
1949 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1951 if (DoStackMalloc) {
1952 assert(StackMallocIdx >= 0);
1953 // if FakeStack != 0 // LocalStackBase == FakeStack
1954 // // In use-after-return mode, poison the whole stack frame.
1955 // if StackMallocIdx <= 4
1956 // // For small sizes inline the whole thing:
1957 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
1958 // **SavedFlagPtr(FakeStack) = 0
1960 // __asan_stack_free_N(FakeStack, LocalStackSize)
1962 // <This is not a fake stack; unpoison the redzones>
1964 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
1965 TerminatorInst *ThenTerm, *ElseTerm;
1966 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1968 IRBuilder<> IRBPoison(ThenTerm);
1969 if (StackMallocIdx <= 4) {
1970 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1971 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1972 ClassSize >> Mapping.Scale);
1973 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
1975 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1976 Value *SavedFlagPtr = IRBPoison.CreateLoad(
1977 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1978 IRBPoison.CreateStore(
1979 Constant::getNullValue(IRBPoison.getInt8Ty()),
1980 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1982 // For larger frames call __asan_stack_free_*.
1983 IRBPoison.CreateCall(
1984 AsanStackFreeFunc[StackMallocIdx],
1985 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
1988 IRBuilder<> IRBElse(ElseTerm);
1989 poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
1990 } else if (HavePoisonedAllocas) {
1991 // If we poisoned some allocas in llvm.lifetime analysis,
1992 // unpoison whole stack frame now.
1993 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
1995 poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
1999 // We are done. Remove the old unused alloca instructions.
2000 for (auto AI : AllocaVec) AI->eraseFromParent();
2003 void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
2004 IRBuilder<> &IRB, bool DoPoison) {
2005 // For now just insert the call to ASan runtime.
2006 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
2007 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
2009 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
2010 {AddrArg, SizeArg});
2013 // Handling llvm.lifetime intrinsics for a given %alloca:
2014 // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
2015 // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
2016 // invalid accesses) and unpoison it for llvm.lifetime.start (the memory
2017 // could be poisoned by previous llvm.lifetime.end instruction, as the
2018 // variable may go in and out of scope several times, e.g. in loops).
2019 // (3) if we poisoned at least one %alloca in a function,
2020 // unpoison the whole stack frame at function exit.
2022 AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
2023 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
2024 // We're intested only in allocas we can handle.
2025 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
2026 // See if we've already calculated (or started to calculate) alloca for a
2028 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
2029 if (I != AllocaForValue.end()) return I->second;
2030 // Store 0 while we're calculating alloca for value V to avoid
2031 // infinite recursion if the value references itself.
2032 AllocaForValue[V] = nullptr;
2033 AllocaInst *Res = nullptr;
2034 if (CastInst *CI = dyn_cast<CastInst>(V))
2035 Res = findAllocaForValue(CI->getOperand(0));
2036 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
2037 for (Value *IncValue : PN->incoming_values()) {
2038 // Allow self-referencing phi-nodes.
2039 if (IncValue == PN) continue;
2040 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
2041 // AI for incoming values should exist and should all be equal.
2042 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
2047 if (Res) AllocaForValue[V] = Res;
2051 void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
2052 IRBuilder<> IRB(AI);
2054 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
2055 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
2057 Value *Zero = Constant::getNullValue(IntptrTy);
2058 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
2059 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
2061 // Since we need to extend alloca with additional memory to locate
2062 // redzones, and OldSize is number of allocated blocks with
2063 // ElementSize size, get allocated memory size in bytes by
2064 // OldSize * ElementSize.
2065 const unsigned ElementSize =
2066 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
2068 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
2069 ConstantInt::get(IntptrTy, ElementSize));
2071 // PartialSize = OldSize % 32
2072 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
2074 // Misalign = kAllocaRzSize - PartialSize;
2075 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
2077 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
2078 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
2079 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
2081 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
2082 // Align is added to locate left redzone, PartialPadding for possible
2083 // partial redzone and kAllocaRzSize for right redzone respectively.
2084 Value *AdditionalChunkSize = IRB.CreateAdd(
2085 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
2087 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
2089 // Insert new alloca with new NewSize and Align params.
2090 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
2091 NewAlloca->setAlignment(Align);
2093 // NewAddress = Address + Align
2094 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
2095 ConstantInt::get(IntptrTy, Align));
2097 // Insert __asan_alloca_poison call for new created alloca.
2098 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
2100 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
2101 // for unpoisoning stuff.
2102 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
2104 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2106 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
2107 AI->replaceAllUsesWith(NewAddressPtr);
2109 // We are done. Erase old alloca from parent.
2110 AI->eraseFromParent();
2113 // isSafeAccess returns true if Addr is always inbounds with respect to its
2114 // base object. For example, it is a field access or an array access with
2115 // constant inbounds index.
2116 bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
2117 Value *Addr, uint64_t TypeSize) const {
2118 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
2119 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
2120 uint64_t Size = SizeOffset.first.getZExtValue();
2121 int64_t Offset = SizeOffset.second.getSExtValue();
2122 // Three checks are required to ensure safety:
2123 // . Offset >= 0 (since the offset is given from the base ptr)
2124 // . Size >= Offset (unsigned)
2125 // . Size - Offset >= NeededSize (unsigned)
2126 return Offset >= 0 && Size >= uint64_t(Offset) &&
2127 Size - uint64_t(Offset) >= TypeSize / 8;