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/Transforms/Scalar.h"
50 #include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
51 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
52 #include "llvm/Transforms/Utils/Cloning.h"
53 #include "llvm/Transforms/Utils/Local.h"
54 #include "llvm/Transforms/Utils/ModuleUtils.h"
55 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
58 #include <system_error>
62 #define DEBUG_TYPE "asan"
64 static const uint64_t kDefaultShadowScale = 3;
65 static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
66 static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
67 static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
68 static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
69 static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
70 static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
71 static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
72 static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
73 static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
74 static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
75 static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
77 static const size_t kMinStackMallocSize = 1 << 6; // 64B
78 static const size_t kMaxStackMallocSize = 1 << 16; // 64K
79 static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
80 static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
82 static const char *const kAsanModuleCtorName = "asan.module_ctor";
83 static const char *const kAsanModuleDtorName = "asan.module_dtor";
84 static const uint64_t kAsanCtorAndDtorPriority = 1;
85 static const char *const kAsanReportErrorTemplate = "__asan_report_";
86 static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
87 static const char *const kAsanUnregisterGlobalsName =
88 "__asan_unregister_globals";
89 static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
90 static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
91 static const char *const kAsanInitName = "__asan_init_v5";
92 static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
93 static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
94 static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
95 static const int kMaxAsanStackMallocSizeClass = 10;
96 static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
97 static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
98 static const char *const kAsanGenPrefix = "__asan_gen_";
99 static const char *const kSanCovGenPrefix = "__sancov_gen_";
100 static const char *const kAsanPoisonStackMemoryName =
101 "__asan_poison_stack_memory";
102 static const char *const kAsanUnpoisonStackMemoryName =
103 "__asan_unpoison_stack_memory";
105 static const char *const kAsanOptionDetectUAR =
106 "__asan_option_detect_stack_use_after_return";
109 static const int kAsanStackAfterReturnMagic = 0xf5;
112 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
113 static const size_t kNumberOfAccessSizes = 5;
115 static const unsigned kAllocaRzSize = 32;
116 static const unsigned kAsanAllocaLeftMagic = 0xcacacacaU;
117 static const unsigned kAsanAllocaRightMagic = 0xcbcbcbcbU;
118 static const unsigned kAsanAllocaPartialVal1 = 0xcbcbcb00U;
119 static const unsigned kAsanAllocaPartialVal2 = 0x000000cbU;
121 // Command-line flags.
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(NumInstrumentedDynamicAllocas,
237 "Number of instrumented dynamic allocas");
238 STATISTIC(NumOptimizedAccessesToGlobalVar,
239 "Number of optimized accesses to global vars");
240 STATISTIC(NumOptimizedAccessesToStackVar,
241 "Number of optimized accesses to stack vars");
244 /// Frontend-provided metadata for source location.
245 struct LocationMetadata {
250 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
252 bool empty() const { return Filename.empty(); }
254 void parse(MDNode *MDN) {
255 assert(MDN->getNumOperands() == 3);
256 MDString *MDFilename = cast<MDString>(MDN->getOperand(0));
257 Filename = MDFilename->getString();
259 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
261 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
265 /// Frontend-provided metadata for global variables.
266 class GlobalsMetadata {
269 Entry() : SourceLoc(), Name(), IsDynInit(false), IsBlacklisted(false) {}
270 LocationMetadata SourceLoc;
276 GlobalsMetadata() : inited_(false) {}
278 void init(Module &M) {
281 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
282 if (!Globals) return;
283 for (auto MDN : Globals->operands()) {
284 // Metadata node contains the global and the fields of "Entry".
285 assert(MDN->getNumOperands() == 5);
286 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
287 // The optimizer may optimize away a global entirely.
289 // We can already have an entry for GV if it was merged with another
291 Entry &E = Entries[GV];
292 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
293 E.SourceLoc.parse(Loc);
294 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
295 E.Name = Name->getString();
296 ConstantInt *IsDynInit =
297 mdconst::extract<ConstantInt>(MDN->getOperand(3));
298 E.IsDynInit |= IsDynInit->isOne();
299 ConstantInt *IsBlacklisted =
300 mdconst::extract<ConstantInt>(MDN->getOperand(4));
301 E.IsBlacklisted |= IsBlacklisted->isOne();
305 /// Returns metadata entry for a given global.
306 Entry get(GlobalVariable *G) const {
307 auto Pos = Entries.find(G);
308 return (Pos != Entries.end()) ? Pos->second : Entry();
313 DenseMap<GlobalVariable *, Entry> Entries;
316 /// This struct defines the shadow mapping using the rule:
317 /// shadow = (mem >> Scale) ADD-or-OR Offset.
318 struct ShadowMapping {
324 static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize) {
325 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
326 bool IsIOS = TargetTriple.isiOS();
327 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
328 bool IsLinux = TargetTriple.isOSLinux();
329 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
330 TargetTriple.getArch() == llvm::Triple::ppc64le;
331 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
332 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
333 TargetTriple.getArch() == llvm::Triple::mipsel;
334 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
335 TargetTriple.getArch() == llvm::Triple::mips64el;
336 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
337 bool IsWindows = TargetTriple.isOSWindows();
339 ShadowMapping Mapping;
341 if (LongSize == 32) {
345 Mapping.Offset = kMIPS32_ShadowOffset32;
347 Mapping.Offset = kFreeBSD_ShadowOffset32;
349 Mapping.Offset = kIOSShadowOffset32;
351 Mapping.Offset = kWindowsShadowOffset32;
353 Mapping.Offset = kDefaultShadowOffset32;
354 } else { // LongSize == 64
356 Mapping.Offset = kPPC64_ShadowOffset64;
358 Mapping.Offset = kFreeBSD_ShadowOffset64;
359 else if (IsLinux && IsX86_64)
360 Mapping.Offset = kSmallX86_64ShadowOffset;
362 Mapping.Offset = kMIPS64_ShadowOffset64;
364 Mapping.Offset = kAArch64_ShadowOffset64;
366 Mapping.Offset = kDefaultShadowOffset64;
369 Mapping.Scale = kDefaultShadowScale;
370 if (ClMappingScale) {
371 Mapping.Scale = ClMappingScale;
374 // OR-ing shadow offset if more efficient (at least on x86) if the offset
375 // is a power of two, but on ppc64 we have to use add since the shadow
376 // offset is not necessary 1/8-th of the address space.
377 Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
382 static size_t RedzoneSizeForScale(int MappingScale) {
383 // Redzone used for stack and globals is at least 32 bytes.
384 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
385 return std::max(32U, 1U << MappingScale);
388 /// AddressSanitizer: instrument the code in module to find memory bugs.
389 struct AddressSanitizer : public FunctionPass {
390 AddressSanitizer() : FunctionPass(ID) {
391 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
393 const char *getPassName() const override {
394 return "AddressSanitizerFunctionPass";
396 void getAnalysisUsage(AnalysisUsage &AU) const override {
397 AU.addRequired<DominatorTreeWrapperPass>();
398 AU.addRequired<TargetLibraryInfoWrapperPass>();
400 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
401 Type *Ty = AI->getAllocatedType();
402 uint64_t SizeInBytes =
403 AI->getModule()->getDataLayout().getTypeAllocSize(Ty);
406 /// Check if we want (and can) handle this alloca.
407 bool isInterestingAlloca(AllocaInst &AI) const;
408 /// If it is an interesting memory access, return the PointerOperand
409 /// and set IsWrite/Alignment. Otherwise return nullptr.
410 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
412 unsigned *Alignment) const;
413 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
414 bool UseCalls, const DataLayout &DL);
415 void instrumentPointerComparisonOrSubtraction(Instruction *I);
416 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
417 Value *Addr, uint32_t TypeSize, bool IsWrite,
418 Value *SizeArgument, bool UseCalls, uint32_t Exp);
419 void instrumentUnusualSizeOrAlignment(Instruction *I, Value *Addr,
420 uint32_t TypeSize, bool IsWrite,
421 Value *SizeArgument, bool UseCalls,
423 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
424 Value *ShadowValue, uint32_t TypeSize);
425 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
426 bool IsWrite, size_t AccessSizeIndex,
427 Value *SizeArgument, uint32_t Exp);
428 void instrumentMemIntrinsic(MemIntrinsic *MI);
429 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
430 bool runOnFunction(Function &F) override;
431 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
432 bool doInitialization(Module &M) override;
433 static char ID; // Pass identification, replacement for typeid
435 DominatorTree &getDominatorTree() const { return *DT; }
438 void initializeCallbacks(Module &M);
440 bool LooksLikeCodeInBug11395(Instruction *I);
441 bool GlobalIsLinkerInitialized(GlobalVariable *G);
442 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
443 uint64_t TypeSize) const;
449 ShadowMapping Mapping;
451 Function *AsanCtorFunction;
452 Function *AsanInitFunction;
453 Function *AsanHandleNoReturnFunc;
454 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
455 // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
456 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
457 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
458 // This array is indexed by AccessIsWrite and Experiment.
459 Function *AsanErrorCallbackSized[2][2];
460 Function *AsanMemoryAccessCallbackSized[2][2];
461 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
463 GlobalsMetadata GlobalsMD;
465 friend struct FunctionStackPoisoner;
468 class AddressSanitizerModule : public ModulePass {
470 AddressSanitizerModule() : ModulePass(ID) {}
471 bool runOnModule(Module &M) override;
472 static char ID; // Pass identification, replacement for typeid
473 const char *getPassName() const override { return "AddressSanitizerModule"; }
476 void initializeCallbacks(Module &M);
478 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
479 bool ShouldInstrumentGlobal(GlobalVariable *G);
480 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
481 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
482 size_t MinRedzoneSizeForGlobal() const {
483 return RedzoneSizeForScale(Mapping.Scale);
486 GlobalsMetadata GlobalsMD;
490 ShadowMapping Mapping;
491 Function *AsanPoisonGlobals;
492 Function *AsanUnpoisonGlobals;
493 Function *AsanRegisterGlobals;
494 Function *AsanUnregisterGlobals;
497 // Stack poisoning does not play well with exception handling.
498 // When an exception is thrown, we essentially bypass the code
499 // that unpoisones the stack. This is why the run-time library has
500 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
501 // stack in the interceptor. This however does not work inside the
502 // actual function which catches the exception. Most likely because the
503 // compiler hoists the load of the shadow value somewhere too high.
504 // This causes asan to report a non-existing bug on 453.povray.
505 // It sounds like an LLVM bug.
506 struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
508 AddressSanitizer &ASan;
513 ShadowMapping Mapping;
515 SmallVector<AllocaInst *, 16> AllocaVec;
516 SmallVector<Instruction *, 8> RetVec;
517 unsigned StackAlignment;
519 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
520 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
521 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
523 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
524 struct AllocaPoisonCall {
525 IntrinsicInst *InsBefore;
530 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
532 // Stores left and right redzone shadow addresses for dynamic alloca
533 // and pointer to alloca instruction itself.
534 // LeftRzAddr is a shadow address for alloca left redzone.
535 // RightRzAddr is a shadow address for alloca right redzone.
536 struct DynamicAllocaCall {
541 explicit DynamicAllocaCall(AllocaInst *AI, Value *LeftRzAddr = nullptr,
542 Value *RightRzAddr = nullptr)
544 LeftRzAddr(LeftRzAddr),
545 RightRzAddr(RightRzAddr),
548 SmallVector<DynamicAllocaCall, 1> DynamicAllocaVec;
550 // Maps Value to an AllocaInst from which the Value is originated.
551 typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
552 AllocaForValueMapTy AllocaForValue;
554 bool HasNonEmptyInlineAsm;
555 std::unique_ptr<CallInst> EmptyInlineAsm;
557 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
560 DIB(*F.getParent(), /*AllowUnresolved*/ false),
562 IntptrTy(ASan.IntptrTy),
563 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
564 Mapping(ASan.Mapping),
565 StackAlignment(1 << Mapping.Scale),
566 HasNonEmptyInlineAsm(false),
567 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
569 bool runOnFunction() {
570 if (!ClStack) return false;
571 // Collect alloca, ret, lifetime instructions etc.
572 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
574 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
576 initializeCallbacks(*F.getParent());
586 // Finds all Alloca instructions and puts
587 // poisoned red zones around all of them.
588 // Then unpoison everything back before the function returns.
591 // ----------------------- Visitors.
592 /// \brief Collect all Ret instructions.
593 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
595 // Unpoison dynamic allocas redzones.
596 void unpoisonDynamicAlloca(DynamicAllocaCall &AllocaCall) {
597 if (!AllocaCall.Poison) return;
598 for (auto Ret : RetVec) {
599 IRBuilder<> IRBRet(Ret);
600 PointerType *Int32PtrTy = PointerType::getUnqual(IRBRet.getInt32Ty());
601 Value *Zero = Constant::getNullValue(IRBRet.getInt32Ty());
602 Value *PartialRzAddr = IRBRet.CreateSub(AllocaCall.RightRzAddr,
603 ConstantInt::get(IntptrTy, 4));
605 Zero, IRBRet.CreateIntToPtr(AllocaCall.LeftRzAddr, Int32PtrTy));
606 IRBRet.CreateStore(Zero,
607 IRBRet.CreateIntToPtr(PartialRzAddr, Int32PtrTy));
609 Zero, IRBRet.CreateIntToPtr(AllocaCall.RightRzAddr, Int32PtrTy));
613 // Right shift for BigEndian and left shift for LittleEndian.
614 Value *shiftAllocaMagic(Value *Val, IRBuilder<> &IRB, Value *Shift) {
615 auto &DL = F.getParent()->getDataLayout();
616 return DL.isLittleEndian() ? IRB.CreateShl(Val, Shift)
617 : IRB.CreateLShr(Val, Shift);
620 // Compute PartialRzMagic for dynamic alloca call. Since we don't know the
621 // size of requested memory until runtime, we should compute it dynamically.
622 // If PartialSize is 0, PartialRzMagic would contain kAsanAllocaRightMagic,
623 // otherwise it would contain the value that we will use to poison the
624 // partial redzone for alloca call.
625 Value *computePartialRzMagic(Value *PartialSize, IRBuilder<> &IRB);
627 // Deploy and poison redzones around dynamic alloca call. To do this, we
628 // should replace this call with another one with changed parameters and
629 // replace all its uses with new address, so
630 // addr = alloca type, old_size, align
632 // new_size = (old_size + additional_size) * sizeof(type)
633 // tmp = alloca i8, new_size, max(align, 32)
634 // addr = tmp + 32 (first 32 bytes are for the left redzone).
635 // Additional_size is added to make new memory allocation contain not only
636 // requested memory, but also left, partial and right redzones.
637 // After that, we should poison redzones:
638 // (1) Left redzone with kAsanAllocaLeftMagic.
639 // (2) Partial redzone with the value, computed in runtime by
640 // computePartialRzMagic function.
641 // (3) Right redzone with kAsanAllocaRightMagic.
642 void handleDynamicAllocaCall(DynamicAllocaCall &AllocaCall);
644 /// \brief Collect Alloca instructions we want (and can) handle.
645 void visitAllocaInst(AllocaInst &AI) {
646 if (!ASan.isInterestingAlloca(AI)) return;
648 StackAlignment = std::max(StackAlignment, AI.getAlignment());
649 if (isDynamicAlloca(AI))
650 DynamicAllocaVec.push_back(DynamicAllocaCall(&AI));
652 AllocaVec.push_back(&AI);
655 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
657 void visitIntrinsicInst(IntrinsicInst &II) {
658 if (!ClCheckLifetime) return;
659 Intrinsic::ID ID = II.getIntrinsicID();
660 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
662 // Found lifetime intrinsic, add ASan instrumentation if necessary.
663 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
664 // If size argument is undefined, don't do anything.
665 if (Size->isMinusOne()) return;
666 // Check that size doesn't saturate uint64_t and can
667 // be stored in IntptrTy.
668 const uint64_t SizeValue = Size->getValue().getLimitedValue();
669 if (SizeValue == ~0ULL ||
670 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
672 // Find alloca instruction that corresponds to llvm.lifetime argument.
673 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
675 bool DoPoison = (ID == Intrinsic::lifetime_end);
676 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
677 AllocaPoisonCallVec.push_back(APC);
680 void visitCallInst(CallInst &CI) {
681 HasNonEmptyInlineAsm |=
682 CI.isInlineAsm() && !CI.isIdenticalTo(EmptyInlineAsm.get());
685 // ---------------------- Helpers.
686 void initializeCallbacks(Module &M);
688 bool doesDominateAllExits(const Instruction *I) const {
689 for (auto Ret : RetVec) {
690 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
695 bool isDynamicAlloca(AllocaInst &AI) const {
696 return AI.isArrayAllocation() || !AI.isStaticAlloca();
698 /// Finds alloca where the value comes from.
699 AllocaInst *findAllocaForValue(Value *V);
700 void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
701 Value *ShadowBase, bool DoPoison);
702 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
704 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
706 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
708 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
709 Instruction *ThenTerm, Value *ValueIfFalse);
714 char AddressSanitizer::ID = 0;
715 INITIALIZE_PASS_BEGIN(
716 AddressSanitizer, "asan",
717 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
719 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
721 AddressSanitizer, "asan",
722 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
724 FunctionPass *llvm::createAddressSanitizerFunctionPass() {
725 return new AddressSanitizer();
728 char AddressSanitizerModule::ID = 0;
730 AddressSanitizerModule, "asan-module",
731 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
734 ModulePass *llvm::createAddressSanitizerModulePass() {
735 return new AddressSanitizerModule();
738 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
739 size_t Res = countTrailingZeros(TypeSize / 8);
740 assert(Res < kNumberOfAccessSizes);
744 // \brief Create a constant for Str so that we can pass it to the run-time lib.
745 static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
747 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
748 // We use private linkage for module-local strings. If they can be merged
749 // with another one, we set the unnamed_addr attribute.
751 new GlobalVariable(M, StrConst->getType(), true,
752 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
753 if (AllowMerging) GV->setUnnamedAddr(true);
754 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
758 /// \brief Create a global describing a source location.
759 static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
760 LocationMetadata MD) {
761 Constant *LocData[] = {
762 createPrivateGlobalForString(M, MD.Filename, true),
763 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
764 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
766 auto LocStruct = ConstantStruct::getAnon(LocData);
767 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
768 GlobalValue::PrivateLinkage, LocStruct,
770 GV->setUnnamedAddr(true);
774 static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
775 return G->getName().find(kAsanGenPrefix) == 0 ||
776 G->getName().find(kSanCovGenPrefix) == 0;
779 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
781 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
782 if (Mapping.Offset == 0) return Shadow;
783 // (Shadow >> scale) | offset
784 if (Mapping.OrShadowOffset)
785 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
787 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
790 // Instrument memset/memmove/memcpy
791 void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
793 if (isa<MemTransferInst>(MI)) {
795 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
796 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
797 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
798 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
799 } else if (isa<MemSetInst>(MI)) {
802 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
803 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
804 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
806 MI->eraseFromParent();
809 /// Check if we want (and can) handle this alloca.
810 bool AddressSanitizer::isInterestingAlloca(AllocaInst &AI) const {
811 return (AI.getAllocatedType()->isSized() &&
812 // alloca() may be called with 0 size, ignore it.
813 getAllocaSizeInBytes(&AI) > 0 &&
814 // We are only interested in allocas not promotable to registers.
815 // Promotable allocas are common under -O0.
816 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)));
819 /// If I is an interesting memory access, return the PointerOperand
820 /// and set IsWrite/Alignment. Otherwise return nullptr.
821 Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
824 unsigned *Alignment) const {
825 // Skip memory accesses inserted by another instrumentation.
826 if (I->getMetadata("nosanitize")) return nullptr;
828 Value *PtrOperand = nullptr;
829 const DataLayout &DL = I->getModule()->getDataLayout();
830 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
831 if (!ClInstrumentReads) return nullptr;
833 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
834 *Alignment = LI->getAlignment();
835 PtrOperand = LI->getPointerOperand();
836 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
837 if (!ClInstrumentWrites) return nullptr;
839 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
840 *Alignment = SI->getAlignment();
841 PtrOperand = SI->getPointerOperand();
842 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
843 if (!ClInstrumentAtomics) return nullptr;
845 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
847 PtrOperand = RMW->getPointerOperand();
848 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
849 if (!ClInstrumentAtomics) return nullptr;
851 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
853 PtrOperand = XCHG->getPointerOperand();
856 // Treat memory accesses to promotable allocas as non-interesting since they
857 // will not cause memory violations. This greatly speeds up the instrumented
858 // executable at -O0.
859 if (ClSkipPromotableAllocas)
860 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
861 return isInterestingAlloca(*AI) ? AI : nullptr;
866 static bool isPointerOperand(Value *V) {
867 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
870 // This is a rough heuristic; it may cause both false positives and
871 // false negatives. The proper implementation requires cooperation with
873 static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
874 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
875 if (!Cmp->isRelational()) return false;
876 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
877 if (BO->getOpcode() != Instruction::Sub) return false;
881 if (!isPointerOperand(I->getOperand(0)) ||
882 !isPointerOperand(I->getOperand(1)))
887 bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
888 // If a global variable does not have dynamic initialization we don't
889 // have to instrument it. However, if a global does not have initializer
890 // at all, we assume it has dynamic initializer (in other TU).
891 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
894 void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
897 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
898 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
899 for (int i = 0; i < 2; i++) {
900 if (Param[i]->getType()->isPointerTy())
901 Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
903 IRB.CreateCall2(F, Param[0], Param[1]);
906 void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
907 Instruction *I, bool UseCalls,
908 const DataLayout &DL) {
909 bool IsWrite = false;
910 unsigned Alignment = 0;
911 uint64_t TypeSize = 0;
912 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment);
915 // Optimization experiments.
916 // The experiments can be used to evaluate potential optimizations that remove
917 // instrumentation (assess false negatives). Instead of completely removing
918 // some instrumentation, you set Exp to a non-zero value (mask of optimization
919 // experiments that want to remove instrumentation of this instruction).
920 // If Exp is non-zero, this pass will emit special calls into runtime
921 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
922 // make runtime terminate the program in a special way (with a different
923 // exit status). Then you run the new compiler on a buggy corpus, collect
924 // the special terminations (ideally, you don't see them at all -- no false
925 // negatives) and make the decision on the optimization.
926 uint32_t Exp = ClForceExperiment;
928 if (ClOpt && ClOptGlobals) {
929 // If initialization order checking is disabled, a simple access to a
930 // dynamically initialized global is always valid.
931 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
932 if (G != NULL && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
933 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
934 NumOptimizedAccessesToGlobalVar++;
939 if (ClOpt && ClOptStack) {
940 // A direct inbounds access to a stack variable is always valid.
941 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
942 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
943 NumOptimizedAccessesToStackVar++;
949 NumInstrumentedWrites++;
951 NumInstrumentedReads++;
953 unsigned Granularity = 1 << Mapping.Scale;
954 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
955 // if the data is properly aligned.
956 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
958 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
959 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls,
961 instrumentUnusualSizeOrAlignment(I, Addr, TypeSize, IsWrite, nullptr,
965 // Validate the result of Module::getOrInsertFunction called for an interface
966 // function of AddressSanitizer. If the instrumented module defines a function
967 // with the same name, their prototypes must match, otherwise
968 // getOrInsertFunction returns a bitcast.
969 static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
970 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
971 FuncOrBitcast->dump();
973 "trying to redefine an AddressSanitizer "
974 "interface function");
977 Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
978 Value *Addr, bool IsWrite,
979 size_t AccessSizeIndex,
982 IRBuilder<> IRB(InsertBefore);
983 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
984 CallInst *Call = nullptr;
987 Call = IRB.CreateCall2(AsanErrorCallbackSized[IsWrite][0], Addr,
990 Call = IRB.CreateCall3(AsanErrorCallbackSized[IsWrite][1], Addr,
991 SizeArgument, ExpVal);
995 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
997 Call = IRB.CreateCall2(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1001 // We don't do Call->setDoesNotReturn() because the BB already has
1002 // UnreachableInst at the end.
1003 // This EmptyAsm is required to avoid callback merge.
1004 IRB.CreateCall(EmptyAsm);
1008 Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
1010 uint32_t TypeSize) {
1011 size_t Granularity = 1 << Mapping.Scale;
1012 // Addr & (Granularity - 1)
1013 Value *LastAccessedByte =
1014 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
1015 // (Addr & (Granularity - 1)) + size - 1
1016 if (TypeSize / 8 > 1)
1017 LastAccessedByte = IRB.CreateAdd(
1018 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1019 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
1021 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
1022 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1023 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1026 void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
1027 Instruction *InsertBefore, Value *Addr,
1028 uint32_t TypeSize, bool IsWrite,
1029 Value *SizeArgument, bool UseCalls,
1031 IRBuilder<> IRB(InsertBefore);
1032 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1033 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1037 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1040 IRB.CreateCall2(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1041 AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp));
1046 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
1047 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1048 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1049 Value *CmpVal = Constant::getNullValue(ShadowTy);
1050 Value *ShadowValue =
1051 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
1053 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
1054 size_t Granularity = 1 << Mapping.Scale;
1055 TerminatorInst *CrashTerm = nullptr;
1057 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
1058 // We use branch weights for the slow path check, to indicate that the slow
1059 // path is rarely taken. This seems to be the case for SPEC benchmarks.
1060 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1061 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
1062 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
1063 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
1064 IRB.SetInsertPoint(CheckTerm);
1065 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
1066 BasicBlock *CrashBlock =
1067 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
1068 CrashTerm = new UnreachableInst(*C, CrashBlock);
1069 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1070 ReplaceInstWithInst(CheckTerm, NewTerm);
1072 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
1075 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
1076 AccessSizeIndex, SizeArgument, Exp);
1077 Crash->setDebugLoc(OrigIns->getDebugLoc());
1080 // Instrument unusual size or unusual alignment.
1081 // We can not do it with a single check, so we do 1-byte check for the first
1082 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1083 // to report the actual access size.
1084 void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1085 Instruction *I, Value *Addr, uint32_t TypeSize, bool IsWrite,
1086 Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1088 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1089 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1092 IRB.CreateCall2(AsanMemoryAccessCallbackSized[IsWrite][0], AddrLong,
1095 IRB.CreateCall3(AsanMemoryAccessCallbackSized[IsWrite][1], AddrLong, Size,
1096 ConstantInt::get(IRB.getInt32Ty(), Exp));
1098 Value *LastByte = IRB.CreateIntToPtr(
1099 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1101 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false, Exp);
1102 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false, Exp);
1106 void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1107 GlobalValue *ModuleName) {
1108 // Set up the arguments to our poison/unpoison functions.
1109 IRBuilder<> IRB(GlobalInit.begin()->getFirstInsertionPt());
1111 // Add a call to poison all external globals before the given function starts.
1112 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1113 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
1115 // Add calls to unpoison all globals before each return instruction.
1116 for (auto &BB : GlobalInit.getBasicBlockList())
1117 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
1118 CallInst::Create(AsanUnpoisonGlobals, "", RI);
1121 void AddressSanitizerModule::createInitializerPoisonCalls(
1122 Module &M, GlobalValue *ModuleName) {
1123 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1125 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1126 for (Use &OP : CA->operands()) {
1127 if (isa<ConstantAggregateZero>(OP)) continue;
1128 ConstantStruct *CS = cast<ConstantStruct>(OP);
1130 // Must have a function or null ptr.
1131 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
1132 if (F->getName() == kAsanModuleCtorName) continue;
1133 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1134 // Don't instrument CTORs that will run before asan.module_ctor.
1135 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1136 poisonOneInitializer(*F, ModuleName);
1141 bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
1142 Type *Ty = cast<PointerType>(G->getType())->getElementType();
1143 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
1145 if (GlobalsMD.get(G).IsBlacklisted) return false;
1146 if (!Ty->isSized()) return false;
1147 if (!G->hasInitializer()) return false;
1148 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
1149 // Touch only those globals that will not be defined in other modules.
1150 // Don't handle ODR linkage types and COMDATs since other modules may be built
1152 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1153 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1154 G->getLinkage() != GlobalVariable::InternalLinkage)
1156 if (G->hasComdat()) return false;
1157 // Two problems with thread-locals:
1158 // - The address of the main thread's copy can't be computed at link-time.
1159 // - Need to poison all copies, not just the main thread's one.
1160 if (G->isThreadLocal()) return false;
1161 // For now, just ignore this Global if the alignment is large.
1162 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
1164 if (G->hasSection()) {
1165 StringRef Section(G->getSection());
1167 if (TargetTriple.isOSBinFormatMachO()) {
1168 StringRef ParsedSegment, ParsedSection;
1169 unsigned TAA = 0, StubSize = 0;
1171 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1172 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
1173 if (!ErrorCode.empty()) {
1174 report_fatal_error("Invalid section specifier '" + ParsedSection +
1175 "': " + ErrorCode + ".");
1178 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1179 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1181 if (ParsedSegment == "__OBJC" ||
1182 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1183 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1186 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1187 // Constant CFString instances are compiled in the following way:
1188 // -- the string buffer is emitted into
1189 // __TEXT,__cstring,cstring_literals
1190 // -- the constant NSConstantString structure referencing that buffer
1191 // is placed into __DATA,__cfstring
1192 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1193 // Moreover, it causes the linker to crash on OS X 10.7
1194 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1195 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1198 // The linker merges the contents of cstring_literals and removes the
1200 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1201 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1206 // Callbacks put into the CRT initializer/terminator sections
1207 // should not be instrumented.
1208 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1209 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1210 if (Section.startswith(".CRT")) {
1211 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1215 // Globals from llvm.metadata aren't emitted, do not instrument them.
1216 if (Section == "llvm.metadata") return false;
1222 void AddressSanitizerModule::initializeCallbacks(Module &M) {
1223 IRBuilder<> IRB(*C);
1224 // Declare our poisoning and unpoisoning functions.
1225 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1226 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
1227 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
1228 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1229 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
1230 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1231 // Declare functions that register/unregister globals.
1232 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1233 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1234 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
1235 AsanUnregisterGlobals = checkInterfaceFunction(
1236 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1237 IntptrTy, IntptrTy, nullptr));
1238 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1241 // This function replaces all global variables with new variables that have
1242 // trailing redzones. It also creates a function that poisons
1243 // redzones and inserts this function into llvm.global_ctors.
1244 bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
1247 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1249 for (auto &G : M.globals()) {
1250 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
1253 size_t n = GlobalsToChange.size();
1254 if (n == 0) return false;
1256 // A global is described by a structure
1259 // size_t size_with_redzone;
1260 // const char *name;
1261 // const char *module_name;
1262 // size_t has_dynamic_init;
1263 // void *source_location;
1264 // We initialize an array of such structures and pass it to a run-time call.
1265 StructType *GlobalStructTy =
1266 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
1267 IntptrTy, IntptrTy, nullptr);
1268 SmallVector<Constant *, 16> Initializers(n);
1270 bool HasDynamicallyInitializedGlobals = false;
1272 // We shouldn't merge same module names, as this string serves as unique
1273 // module ID in runtime.
1274 GlobalVariable *ModuleName = createPrivateGlobalForString(
1275 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
1277 auto &DL = M.getDataLayout();
1278 for (size_t i = 0; i < n; i++) {
1279 static const uint64_t kMaxGlobalRedzone = 1 << 18;
1280 GlobalVariable *G = GlobalsToChange[i];
1282 auto MD = GlobalsMD.get(G);
1283 // Create string holding the global name (use global name from metadata
1284 // if it's available, otherwise just write the name of global variable).
1285 GlobalVariable *Name = createPrivateGlobalForString(
1286 M, MD.Name.empty() ? G->getName() : MD.Name,
1287 /*AllowMerging*/ true);
1289 PointerType *PtrTy = cast<PointerType>(G->getType());
1290 Type *Ty = PtrTy->getElementType();
1291 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
1292 uint64_t MinRZ = MinRedzoneSizeForGlobal();
1293 // MinRZ <= RZ <= kMaxGlobalRedzone
1294 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
1295 uint64_t RZ = std::max(
1296 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
1297 uint64_t RightRedzoneSize = RZ;
1298 // Round up to MinRZ
1299 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
1300 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
1301 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1303 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
1304 Constant *NewInitializer =
1305 ConstantStruct::get(NewTy, G->getInitializer(),
1306 Constant::getNullValue(RightRedZoneTy), nullptr);
1308 // Create a new global variable with enough space for a redzone.
1309 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1310 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1311 Linkage = GlobalValue::InternalLinkage;
1312 GlobalVariable *NewGlobal =
1313 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1314 "", G, G->getThreadLocalMode());
1315 NewGlobal->copyAttributesFrom(G);
1316 NewGlobal->setAlignment(MinRZ);
1319 Indices2[0] = IRB.getInt32(0);
1320 Indices2[1] = IRB.getInt32(0);
1322 G->replaceAllUsesWith(
1323 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
1324 NewGlobal->takeName(G);
1325 G->eraseFromParent();
1327 Constant *SourceLoc;
1328 if (!MD.SourceLoc.empty()) {
1329 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1330 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1332 SourceLoc = ConstantInt::get(IntptrTy, 0);
1335 Initializers[i] = ConstantStruct::get(
1336 GlobalStructTy, ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
1337 ConstantInt::get(IntptrTy, SizeInBytes),
1338 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1339 ConstantExpr::getPointerCast(Name, IntptrTy),
1340 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
1341 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc, nullptr);
1343 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
1345 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
1348 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1349 GlobalVariable *AllGlobals = new GlobalVariable(
1350 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1351 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1353 // Create calls for poisoning before initializers run and unpoisoning after.
1354 if (HasDynamicallyInitializedGlobals)
1355 createInitializerPoisonCalls(M, ModuleName);
1356 IRB.CreateCall2(AsanRegisterGlobals,
1357 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1358 ConstantInt::get(IntptrTy, n));
1360 // We also need to unregister globals at the end, e.g. when a shared library
1362 Function *AsanDtorFunction =
1363 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1364 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1365 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1366 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
1367 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
1368 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1369 ConstantInt::get(IntptrTy, n));
1370 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
1376 bool AddressSanitizerModule::runOnModule(Module &M) {
1377 C = &(M.getContext());
1378 int LongSize = M.getDataLayout().getPointerSizeInBits();
1379 IntptrTy = Type::getIntNTy(*C, LongSize);
1380 TargetTriple = Triple(M.getTargetTriple());
1381 Mapping = getShadowMapping(TargetTriple, LongSize);
1382 initializeCallbacks(M);
1384 bool Changed = false;
1386 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1388 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1390 if (ClGlobals) Changed |= InstrumentGlobals(IRB, M);
1395 void AddressSanitizer::initializeCallbacks(Module &M) {
1396 IRBuilder<> IRB(*C);
1397 // Create __asan_report* callbacks.
1398 // IsWrite, TypeSize and Exp are encoded in the function name.
1399 for (int Exp = 0; Exp < 2; Exp++) {
1400 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1401 const std::string TypeStr = AccessIsWrite ? "store" : "load";
1402 const std::string ExpStr = Exp ? "exp_" : "";
1403 const Type *ExpType = Exp ? Type::getInt32Ty(*C) : nullptr;
1404 AsanErrorCallbackSized[AccessIsWrite][Exp] =
1405 checkInterfaceFunction(M.getOrInsertFunction(
1406 kAsanReportErrorTemplate + ExpStr + TypeStr + "_n",
1407 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1408 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
1409 checkInterfaceFunction(M.getOrInsertFunction(
1410 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N",
1411 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1412 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1413 AccessSizeIndex++) {
1414 const std::string Suffix = TypeStr + itostr(1 << AccessSizeIndex);
1415 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
1416 checkInterfaceFunction(M.getOrInsertFunction(
1417 kAsanReportErrorTemplate + ExpStr + Suffix, IRB.getVoidTy(),
1418 IntptrTy, ExpType, nullptr));
1419 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
1420 checkInterfaceFunction(M.getOrInsertFunction(
1421 ClMemoryAccessCallbackPrefix + ExpStr + Suffix, IRB.getVoidTy(),
1422 IntptrTy, ExpType, nullptr));
1427 AsanMemmove = checkInterfaceFunction(M.getOrInsertFunction(
1428 ClMemoryAccessCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
1429 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
1430 AsanMemcpy = checkInterfaceFunction(M.getOrInsertFunction(
1431 ClMemoryAccessCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
1432 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
1433 AsanMemset = checkInterfaceFunction(M.getOrInsertFunction(
1434 ClMemoryAccessCallbackPrefix + "memset", IRB.getInt8PtrTy(),
1435 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
1437 AsanHandleNoReturnFunc = checkInterfaceFunction(
1438 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
1440 AsanPtrCmpFunction = checkInterfaceFunction(M.getOrInsertFunction(
1441 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1442 AsanPtrSubFunction = checkInterfaceFunction(M.getOrInsertFunction(
1443 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1444 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1445 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1446 StringRef(""), StringRef(""),
1447 /*hasSideEffects=*/true);
1451 bool AddressSanitizer::doInitialization(Module &M) {
1452 // Initialize the private fields. No one has accessed them before.
1456 C = &(M.getContext());
1457 LongSize = M.getDataLayout().getPointerSizeInBits();
1458 IntptrTy = Type::getIntNTy(*C, LongSize);
1459 TargetTriple = Triple(M.getTargetTriple());
1462 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1463 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1464 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1465 // call __asan_init in the module ctor.
1466 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1467 AsanInitFunction = checkInterfaceFunction(
1468 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), nullptr));
1469 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1470 IRB.CreateCall(AsanInitFunction);
1472 Mapping = getShadowMapping(TargetTriple, LongSize);
1474 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
1478 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1479 // For each NSObject descendant having a +load method, this method is invoked
1480 // by the ObjC runtime before any of the static constructors is called.
1481 // Therefore we need to instrument such methods with a call to __asan_init
1482 // at the beginning in order to initialize our runtime before any access to
1483 // the shadow memory.
1484 // We cannot just ignore these methods, because they may call other
1485 // instrumented functions.
1486 if (F.getName().find(" load]") != std::string::npos) {
1487 IRBuilder<> IRB(F.begin()->begin());
1488 IRB.CreateCall(AsanInitFunction);
1494 bool AddressSanitizer::runOnFunction(Function &F) {
1495 if (&F == AsanCtorFunction) return false;
1496 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
1497 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
1498 initializeCallbacks(*F.getParent());
1500 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1502 // If needed, insert __asan_init before checking for SanitizeAddress attr.
1503 maybeInsertAsanInitAtFunctionEntry(F);
1505 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return false;
1507 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName()) return false;
1509 // We want to instrument every address only once per basic block (unless there
1510 // are calls between uses).
1511 SmallSet<Value *, 16> TempsToInstrument;
1512 SmallVector<Instruction *, 16> ToInstrument;
1513 SmallVector<Instruction *, 8> NoReturnCalls;
1514 SmallVector<BasicBlock *, 16> AllBlocks;
1515 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
1521 // Fill the set of memory operations to instrument.
1522 for (auto &BB : F) {
1523 AllBlocks.push_back(&BB);
1524 TempsToInstrument.clear();
1525 int NumInsnsPerBB = 0;
1526 for (auto &Inst : BB) {
1527 if (LooksLikeCodeInBug11395(&Inst)) return false;
1528 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
1530 if (ClOpt && ClOptSameTemp) {
1531 if (!TempsToInstrument.insert(Addr).second)
1532 continue; // We've seen this temp in the current BB.
1534 } else if (ClInvalidPointerPairs &&
1535 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1536 PointerComparisonsOrSubtracts.push_back(&Inst);
1538 } else if (isa<MemIntrinsic>(Inst)) {
1541 if (isa<AllocaInst>(Inst)) NumAllocas++;
1544 // A call inside BB.
1545 TempsToInstrument.clear();
1546 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
1550 ToInstrument.push_back(&Inst);
1552 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
1556 bool UseCalls = false;
1557 if (ClInstrumentationWithCallsThreshold >= 0 &&
1558 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold)
1561 const TargetLibraryInfo *TLI =
1562 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1563 const DataLayout &DL = F.getParent()->getDataLayout();
1564 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(),
1565 /*RoundToAlign=*/true);
1568 int NumInstrumented = 0;
1569 for (auto Inst : ToInstrument) {
1570 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1571 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
1572 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
1573 instrumentMop(ObjSizeVis, Inst, UseCalls,
1574 F.getParent()->getDataLayout());
1576 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
1581 FunctionStackPoisoner FSP(F, *this);
1582 bool ChangedStack = FSP.runOnFunction();
1584 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1585 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1586 for (auto CI : NoReturnCalls) {
1587 IRBuilder<> IRB(CI);
1588 IRB.CreateCall(AsanHandleNoReturnFunc);
1591 for (auto Inst : PointerComparisonsOrSubtracts) {
1592 instrumentPointerComparisonOrSubtraction(Inst);
1596 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
1598 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1603 // Workaround for bug 11395: we don't want to instrument stack in functions
1604 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1605 // FIXME: remove once the bug 11395 is fixed.
1606 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1607 if (LongSize != 32) return false;
1608 CallInst *CI = dyn_cast<CallInst>(I);
1609 if (!CI || !CI->isInlineAsm()) return false;
1610 if (CI->getNumArgOperands() <= 5) return false;
1611 // We have inline assembly with quite a few arguments.
1615 void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1616 IRBuilder<> IRB(*C);
1617 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1618 std::string Suffix = itostr(i);
1619 AsanStackMallocFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
1620 kAsanStackMallocNameTemplate + Suffix, IntptrTy, IntptrTy, nullptr));
1621 AsanStackFreeFunc[i] = checkInterfaceFunction(
1622 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
1623 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1625 AsanPoisonStackMemoryFunc = checkInterfaceFunction(
1626 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
1627 IntptrTy, IntptrTy, nullptr));
1628 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(
1629 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
1630 IntptrTy, IntptrTy, nullptr));
1633 void FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
1634 IRBuilder<> &IRB, Value *ShadowBase,
1636 size_t n = ShadowBytes.size();
1638 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1639 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1640 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1641 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1642 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1643 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1645 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
1646 if (F.getParent()->getDataLayout().isLittleEndian())
1647 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1649 Val = (Val << 8) | ShadowBytes[i + j];
1652 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1653 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1654 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1655 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
1660 // Fake stack allocator (asan_fake_stack.h) has 11 size classes
1661 // for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1662 static int StackMallocSizeClass(uint64_t LocalStackSize) {
1663 assert(LocalStackSize <= kMaxStackMallocSize);
1664 uint64_t MaxSize = kMinStackMallocSize;
1665 for (int i = 0;; i++, MaxSize *= 2)
1666 if (LocalStackSize <= MaxSize) return i;
1667 llvm_unreachable("impossible LocalStackSize");
1670 // Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1671 // We can not use MemSet intrinsic because it may end up calling the actual
1672 // memset. Size is a multiple of 8.
1673 // Currently this generates 8-byte stores on x86_64; it may be better to
1674 // generate wider stores.
1675 void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1676 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1677 assert(!(Size % 8));
1680 static_assert(kAsanStackAfterReturnMagic == 0xf5, "");
1683 for (int i = 0; i < Size; i += 8) {
1684 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1685 IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
1686 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1690 static DebugLoc getFunctionEntryDebugLocation(Function &F) {
1691 for (const auto &Inst : F.getEntryBlock())
1692 if (!isa<AllocaInst>(Inst)) return Inst.getDebugLoc();
1696 PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
1698 Instruction *ThenTerm,
1699 Value *ValueIfFalse) {
1700 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
1701 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
1702 PHI->addIncoming(ValueIfFalse, CondBlock);
1703 BasicBlock *ThenBlock = ThenTerm->getParent();
1704 PHI->addIncoming(ValueIfTrue, ThenBlock);
1708 Value *FunctionStackPoisoner::createAllocaForLayout(
1709 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
1712 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
1713 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
1716 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
1717 nullptr, "MyAlloca");
1718 assert(Alloca->isStaticAlloca());
1720 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1721 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1722 Alloca->setAlignment(FrameAlignment);
1723 return IRB.CreatePointerCast(Alloca, IntptrTy);
1726 void FunctionStackPoisoner::poisonStack() {
1727 assert(AllocaVec.size() > 0 || DynamicAllocaVec.size() > 0);
1729 if (ClInstrumentAllocas) {
1730 // Handle dynamic allocas.
1731 for (auto &AllocaCall : DynamicAllocaVec) {
1732 handleDynamicAllocaCall(AllocaCall);
1733 unpoisonDynamicAlloca(AllocaCall);
1737 if (AllocaVec.size() == 0) return;
1739 int StackMallocIdx = -1;
1740 DebugLoc EntryDebugLocation = getFunctionEntryDebugLocation(F);
1742 Instruction *InsBefore = AllocaVec[0];
1743 IRBuilder<> IRB(InsBefore);
1744 IRB.SetCurrentDebugLocation(EntryDebugLocation);
1746 SmallVector<ASanStackVariableDescription, 16> SVD;
1747 SVD.reserve(AllocaVec.size());
1748 for (AllocaInst *AI : AllocaVec) {
1749 ASanStackVariableDescription D = {AI->getName().data(),
1750 ASan.getAllocaSizeInBytes(AI),
1751 AI->getAlignment(), AI, 0};
1754 // Minimal header size (left redzone) is 4 pointers,
1755 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1756 size_t MinHeaderSize = ASan.LongSize / 2;
1757 ASanStackFrameLayout L;
1758 ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1759 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1760 uint64_t LocalStackSize = L.FrameSize;
1761 bool DoStackMalloc =
1762 ClUseAfterReturn && LocalStackSize <= kMaxStackMallocSize;
1763 // Don't do dynamic alloca in presence of inline asm: too often it
1764 // makes assumptions on which registers are available.
1765 bool DoDynamicAlloca = ClDynamicAllocaStack && !HasNonEmptyInlineAsm;
1767 Value *StaticAlloca =
1768 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
1771 Value *LocalStackBase;
1773 if (DoStackMalloc) {
1774 // void *FakeStack = __asan_option_detect_stack_use_after_return
1775 // ? __asan_stack_malloc_N(LocalStackSize)
1777 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
1778 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1779 kAsanOptionDetectUAR, IRB.getInt32Ty());
1780 Value *UARIsEnabled =
1781 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1782 Constant::getNullValue(IRB.getInt32Ty()));
1784 SplitBlockAndInsertIfThen(UARIsEnabled, InsBefore, false);
1785 IRBuilder<> IRBIf(Term);
1786 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
1787 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1788 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
1789 Value *FakeStackValue =
1790 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
1791 ConstantInt::get(IntptrTy, LocalStackSize));
1792 IRB.SetInsertPoint(InsBefore);
1793 IRB.SetCurrentDebugLocation(EntryDebugLocation);
1794 FakeStack = createPHI(IRB, UARIsEnabled, FakeStackValue, Term,
1795 ConstantInt::get(IntptrTy, 0));
1797 Value *NoFakeStack =
1798 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
1799 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
1800 IRBIf.SetInsertPoint(Term);
1801 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
1802 Value *AllocaValue =
1803 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
1804 IRB.SetInsertPoint(InsBefore);
1805 IRB.SetCurrentDebugLocation(EntryDebugLocation);
1806 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
1808 // void *FakeStack = nullptr;
1809 // void *LocalStackBase = alloca(LocalStackSize);
1810 FakeStack = ConstantInt::get(IntptrTy, 0);
1812 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
1815 // Insert poison calls for lifetime intrinsics for alloca.
1816 bool HavePoisonedAllocas = false;
1817 for (const auto &APC : AllocaPoisonCallVec) {
1818 assert(APC.InsBefore);
1820 IRBuilder<> IRB(APC.InsBefore);
1821 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
1822 HavePoisonedAllocas |= APC.DoPoison;
1825 // Replace Alloca instructions with base+offset.
1826 for (const auto &Desc : SVD) {
1827 AllocaInst *AI = Desc.AI;
1828 Value *NewAllocaPtr = IRB.CreateIntToPtr(
1829 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
1831 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true);
1832 AI->replaceAllUsesWith(NewAllocaPtr);
1835 // The left-most redzone has enough space for at least 4 pointers.
1836 // Write the Magic value to redzone[0].
1837 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1838 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1840 // Write the frame description constant to redzone[1].
1841 Value *BasePlus1 = IRB.CreateIntToPtr(
1842 IRB.CreateAdd(LocalStackBase,
1843 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
1845 GlobalVariable *StackDescriptionGlobal =
1846 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
1847 /*AllowMerging*/ true);
1848 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
1849 IRB.CreateStore(Description, BasePlus1);
1850 // Write the PC to redzone[2].
1851 Value *BasePlus2 = IRB.CreateIntToPtr(
1852 IRB.CreateAdd(LocalStackBase,
1853 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
1855 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
1857 // Poison the stack redzones at the entry.
1858 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1859 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
1861 // (Un)poison the stack before all ret instructions.
1862 for (auto Ret : RetVec) {
1863 IRBuilder<> IRBRet(Ret);
1864 // Mark the current frame as retired.
1865 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1867 if (DoStackMalloc) {
1868 assert(StackMallocIdx >= 0);
1869 // if FakeStack != 0 // LocalStackBase == FakeStack
1870 // // In use-after-return mode, poison the whole stack frame.
1871 // if StackMallocIdx <= 4
1872 // // For small sizes inline the whole thing:
1873 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
1874 // **SavedFlagPtr(FakeStack) = 0
1876 // __asan_stack_free_N(FakeStack, LocalStackSize)
1878 // <This is not a fake stack; unpoison the redzones>
1880 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
1881 TerminatorInst *ThenTerm, *ElseTerm;
1882 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1884 IRBuilder<> IRBPoison(ThenTerm);
1885 if (StackMallocIdx <= 4) {
1886 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1887 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1888 ClassSize >> Mapping.Scale);
1889 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
1891 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1892 Value *SavedFlagPtr = IRBPoison.CreateLoad(
1893 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1894 IRBPoison.CreateStore(
1895 Constant::getNullValue(IRBPoison.getInt8Ty()),
1896 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1898 // For larger frames call __asan_stack_free_*.
1899 IRBPoison.CreateCall2(AsanStackFreeFunc[StackMallocIdx], FakeStack,
1900 ConstantInt::get(IntptrTy, LocalStackSize));
1903 IRBuilder<> IRBElse(ElseTerm);
1904 poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
1905 } else if (HavePoisonedAllocas) {
1906 // If we poisoned some allocas in llvm.lifetime analysis,
1907 // unpoison whole stack frame now.
1908 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
1910 poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
1914 // We are done. Remove the old unused alloca instructions.
1915 for (auto AI : AllocaVec) AI->eraseFromParent();
1918 void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
1919 IRBuilder<> &IRB, bool DoPoison) {
1920 // For now just insert the call to ASan runtime.
1921 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1922 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1924 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
1928 // Handling llvm.lifetime intrinsics for a given %alloca:
1929 // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1930 // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1931 // invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1932 // could be poisoned by previous llvm.lifetime.end instruction, as the
1933 // variable may go in and out of scope several times, e.g. in loops).
1934 // (3) if we poisoned at least one %alloca in a function,
1935 // unpoison the whole stack frame at function exit.
1937 AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1938 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1939 // We're intested only in allocas we can handle.
1940 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
1941 // See if we've already calculated (or started to calculate) alloca for a
1943 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1944 if (I != AllocaForValue.end()) return I->second;
1945 // Store 0 while we're calculating alloca for value V to avoid
1946 // infinite recursion if the value references itself.
1947 AllocaForValue[V] = nullptr;
1948 AllocaInst *Res = nullptr;
1949 if (CastInst *CI = dyn_cast<CastInst>(V))
1950 Res = findAllocaForValue(CI->getOperand(0));
1951 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1952 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1953 Value *IncValue = PN->getIncomingValue(i);
1954 // Allow self-referencing phi-nodes.
1955 if (IncValue == PN) continue;
1956 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1957 // AI for incoming values should exist and should all be equal.
1958 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
1963 if (Res) AllocaForValue[V] = Res;
1967 // Compute PartialRzMagic for dynamic alloca call. PartialRzMagic is
1968 // constructed from two separate 32-bit numbers: PartialRzMagic = Val1 | Val2.
1969 // (1) Val1 is resposible for forming base value for PartialRzMagic, containing
1970 // only 00 for fully addressable and 0xcb for fully poisoned bytes for each
1971 // 8-byte chunk of user memory respectively.
1972 // (2) Val2 forms the value for marking first poisoned byte in shadow memory
1973 // with appropriate value (0x01 - 0x07 or 0xcb if Padding % 8 == 0).
1975 // Shift = Padding & ~7; // the number of bits we need to shift to access first
1976 // chunk in shadow memory, containing nonzero bytes.
1978 // Padding = 21 Padding = 16
1979 // Shadow: |00|00|05|cb| Shadow: |00|00|cb|cb|
1982 // Shift = 21 & ~7 = 16 Shift = 16 & ~7 = 16
1984 // Val1 = 0xcbcbcbcb << Shift;
1985 // PartialBits = Padding ? Padding & 7 : 0xcb;
1986 // Val2 = PartialBits << Shift;
1987 // Result = Val1 | Val2;
1988 Value *FunctionStackPoisoner::computePartialRzMagic(Value *PartialSize,
1990 PartialSize = IRB.CreateIntCast(PartialSize, IRB.getInt32Ty(), false);
1991 Value *Shift = IRB.CreateAnd(PartialSize, IRB.getInt32(~7));
1992 unsigned Val1Int = kAsanAllocaPartialVal1;
1993 unsigned Val2Int = kAsanAllocaPartialVal2;
1994 if (!F.getParent()->getDataLayout().isLittleEndian()) {
1995 Val1Int = sys::getSwappedBytes(Val1Int);
1996 Val2Int = sys::getSwappedBytes(Val2Int);
1998 Value *Val1 = shiftAllocaMagic(IRB.getInt32(Val1Int), IRB, Shift);
1999 Value *PartialBits = IRB.CreateAnd(PartialSize, IRB.getInt32(7));
2000 // For BigEndian get 0x000000YZ -> 0xYZ000000.
2001 if (F.getParent()->getDataLayout().isBigEndian())
2002 PartialBits = IRB.CreateShl(PartialBits, IRB.getInt32(24));
2003 Value *Val2 = IRB.getInt32(Val2Int);
2005 IRB.CreateICmpNE(PartialBits, Constant::getNullValue(IRB.getInt32Ty()));
2006 Val2 = IRB.CreateSelect(Cond, shiftAllocaMagic(PartialBits, IRB, Shift),
2007 shiftAllocaMagic(Val2, IRB, Shift));
2008 return IRB.CreateOr(Val1, Val2);
2011 void FunctionStackPoisoner::handleDynamicAllocaCall(
2012 DynamicAllocaCall &AllocaCall) {
2013 AllocaInst *AI = AllocaCall.AI;
2014 if (!doesDominateAllExits(AI)) {
2015 // We do not yet handle complex allocas
2016 AllocaCall.Poison = false;
2020 IRBuilder<> IRB(AI);
2022 PointerType *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
2023 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
2024 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
2026 Value *Zero = Constant::getNullValue(IntptrTy);
2027 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
2028 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
2029 Value *NotAllocaRzMask = ConstantInt::get(IntptrTy, ~AllocaRedzoneMask);
2031 // Since we need to extend alloca with additional memory to locate
2032 // redzones, and OldSize is number of allocated blocks with
2033 // ElementSize size, get allocated memory size in bytes by
2034 // OldSize * ElementSize.
2035 unsigned ElementSize =
2036 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
2037 Value *OldSize = IRB.CreateMul(AI->getArraySize(),
2038 ConstantInt::get(IntptrTy, ElementSize));
2040 // PartialSize = OldSize % 32
2041 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
2043 // Misalign = kAllocaRzSize - PartialSize;
2044 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
2046 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
2047 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
2048 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
2050 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
2051 // Align is added to locate left redzone, PartialPadding for possible
2052 // partial redzone and kAllocaRzSize for right redzone respectively.
2053 Value *AdditionalChunkSize = IRB.CreateAdd(
2054 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
2056 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
2058 // Insert new alloca with new NewSize and Align params.
2059 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
2060 NewAlloca->setAlignment(Align);
2062 // NewAddress = Address + Align
2063 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
2064 ConstantInt::get(IntptrTy, Align));
2066 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2068 // LeftRzAddress = NewAddress - kAllocaRzSize
2069 Value *LeftRzAddress = IRB.CreateSub(NewAddress, AllocaRzSize);
2071 // Poisoning left redzone.
2072 AllocaCall.LeftRzAddr = ASan.memToShadow(LeftRzAddress, IRB);
2073 IRB.CreateStore(ConstantInt::get(IRB.getInt32Ty(), kAsanAllocaLeftMagic),
2074 IRB.CreateIntToPtr(AllocaCall.LeftRzAddr, Int32PtrTy));
2076 // PartialRzAligned = PartialRzAddr & ~AllocaRzMask
2077 Value *PartialRzAddr = IRB.CreateAdd(NewAddress, OldSize);
2078 Value *PartialRzAligned = IRB.CreateAnd(PartialRzAddr, NotAllocaRzMask);
2080 // Poisoning partial redzone.
2081 Value *PartialRzMagic = computePartialRzMagic(PartialSize, IRB);
2082 Value *PartialRzShadowAddr = ASan.memToShadow(PartialRzAligned, IRB);
2083 IRB.CreateStore(PartialRzMagic,
2084 IRB.CreateIntToPtr(PartialRzShadowAddr, Int32PtrTy));
2087 // = (PartialRzAddr + AllocaRzMask) & ~AllocaRzMask
2088 Value *RightRzAddress = IRB.CreateAnd(
2089 IRB.CreateAdd(PartialRzAddr, AllocaRzMask), NotAllocaRzMask);
2091 // Poisoning right redzone.
2092 AllocaCall.RightRzAddr = ASan.memToShadow(RightRzAddress, IRB);
2093 IRB.CreateStore(ConstantInt::get(IRB.getInt32Ty(), kAsanAllocaRightMagic),
2094 IRB.CreateIntToPtr(AllocaCall.RightRzAddr, Int32PtrTy));
2096 // Replace all uses of AddessReturnedByAlloca with NewAddress.
2097 AI->replaceAllUsesWith(NewAddressPtr);
2099 // We are done. Erase old alloca and store left, partial and right redzones
2100 // shadow addresses for future unpoisoning.
2101 AI->eraseFromParent();
2102 NumInstrumentedDynamicAllocas++;
2105 // isSafeAccess returns true if Addr is always inbounds with respect to its
2106 // base object. For example, it is a field access or an array access with
2107 // constant inbounds index.
2108 bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
2109 Value *Addr, uint64_t TypeSize) const {
2110 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
2111 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
2112 uint64_t Size = SizeOffset.first.getZExtValue();
2113 int64_t Offset = SizeOffset.second.getSExtValue();
2114 // Three checks are required to ensure safety:
2115 // . Offset >= 0 (since the offset is given from the base ptr)
2116 // . Size >= Offset (unsigned)
2117 // . Size - Offset >= NeededSize (unsigned)
2118 return Offset >= 0 && Size >= uint64_t(Offset) &&
2119 Size - uint64_t(Offset) >= TypeSize / 8;