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/ADT/ArrayRef.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/DepthFirstIterator.h"
19 #include "llvm/ADT/SetVector.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/Analysis/MemoryBuiltins.h"
26 #include "llvm/Analysis/TargetLibraryInfo.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/IR/CallSite.h"
29 #include "llvm/IR/DIBuilder.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/Dominators.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/IRBuilder.h"
34 #include "llvm/IR/InlineAsm.h"
35 #include "llvm/IR/InstVisitor.h"
36 #include "llvm/IR/IntrinsicInst.h"
37 #include "llvm/IR/LLVMContext.h"
38 #include "llvm/IR/MDBuilder.h"
39 #include "llvm/IR/Module.h"
40 #include "llvm/IR/Type.h"
41 #include "llvm/MC/MCSectionMachO.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/DataTypes.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/Endian.h"
46 #include "llvm/Support/SwapByteOrder.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include "llvm/Transforms/Instrumentation.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"
61 #include <system_error>
65 #define DEBUG_TYPE "asan"
67 static const uint64_t kDefaultShadowScale = 3;
68 static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
69 static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
70 static const uint64_t kDynamicShadowSentinel = ~(uint64_t)0;
71 static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
72 static const uint64_t kIOSSimShadowOffset32 = 1ULL << 30;
73 static const uint64_t kIOSSimShadowOffset64 = kDefaultShadowOffset64;
74 static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
75 static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;
76 static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
77 static const uint64_t kSystemZ_ShadowOffset64 = 1ULL << 52;
78 static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
79 static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
80 static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
81 static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
82 static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
83 static const uint64_t kPS4CPU_ShadowOffset64 = 1ULL << 40;
84 static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
85 // The shadow memory space is dynamically allocated.
86 static const uint64_t kWindowsShadowOffset64 = kDynamicShadowSentinel;
88 static const size_t kMinStackMallocSize = 1 << 6; // 64B
89 static const size_t kMaxStackMallocSize = 1 << 16; // 64K
90 static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
91 static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
93 static const char *const kAsanModuleCtorName = "asan.module_ctor";
94 static const char *const kAsanModuleDtorName = "asan.module_dtor";
95 static const uint64_t kAsanCtorAndDtorPriority = 1;
96 static const char *const kAsanReportErrorTemplate = "__asan_report_";
97 static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
98 static const char *const kAsanUnregisterGlobalsName =
99 "__asan_unregister_globals";
100 static const char *const kAsanRegisterImageGlobalsName =
101 "__asan_register_image_globals";
102 static const char *const kAsanUnregisterImageGlobalsName =
103 "__asan_unregister_image_globals";
104 static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
105 static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
106 static const char *const kAsanInitName = "__asan_init";
107 static const char *const kAsanVersionCheckName =
108 "__asan_version_mismatch_check_v8";
109 static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
110 static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
111 static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
112 static const int kMaxAsanStackMallocSizeClass = 10;
113 static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
114 static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
115 static const char *const kAsanGenPrefix = "__asan_gen_";
116 static const char *const kODRGenPrefix = "__odr_asan_gen_";
117 static const char *const kSanCovGenPrefix = "__sancov_gen_";
118 static const char *const kAsanSetShadowPrefix = "__asan_set_shadow_";
119 static const char *const kAsanPoisonStackMemoryName =
120 "__asan_poison_stack_memory";
121 static const char *const kAsanUnpoisonStackMemoryName =
122 "__asan_unpoison_stack_memory";
123 static const char *const kAsanGlobalsRegisteredFlagName =
124 "__asan_globals_registered";
126 static const char *const kAsanOptionDetectUseAfterReturn =
127 "__asan_option_detect_stack_use_after_return";
129 static const char *const kAsanShadowMemoryDynamicAddress =
130 "__asan_shadow_memory_dynamic_address";
132 static const char *const kAsanAllocaPoison = "__asan_alloca_poison";
133 static const char *const kAsanAllocasUnpoison = "__asan_allocas_unpoison";
135 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
136 static const size_t kNumberOfAccessSizes = 5;
138 static const unsigned kAllocaRzSize = 32;
140 // Command-line flags.
141 static cl::opt<bool> ClEnableKasan(
142 "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
143 cl::Hidden, cl::init(false));
144 static cl::opt<bool> ClRecover(
146 cl::desc("Enable recovery mode (continue-after-error)."),
147 cl::Hidden, cl::init(false));
149 // This flag may need to be replaced with -f[no-]asan-reads.
150 static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
151 cl::desc("instrument read instructions"),
152 cl::Hidden, cl::init(true));
153 static cl::opt<bool> ClInstrumentWrites(
154 "asan-instrument-writes", cl::desc("instrument write instructions"),
155 cl::Hidden, cl::init(true));
156 static cl::opt<bool> ClInstrumentAtomics(
157 "asan-instrument-atomics",
158 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
160 static cl::opt<bool> ClAlwaysSlowPath(
161 "asan-always-slow-path",
162 cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
164 static cl::opt<bool> ClForceDynamicShadow(
165 "asan-force-dynamic-shadow",
166 cl::desc("Load shadow address into a local variable for each function"),
167 cl::Hidden, cl::init(false));
169 // This flag limits the number of instructions to be instrumented
170 // in any given BB. Normally, this should be set to unlimited (INT_MAX),
171 // but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
173 static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
174 "asan-max-ins-per-bb", cl::init(10000),
175 cl::desc("maximal number of instructions to instrument in any given BB"),
177 // This flag may need to be replaced with -f[no]asan-stack.
178 static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
179 cl::Hidden, cl::init(true));
180 static cl::opt<uint32_t> ClMaxInlinePoisoningSize(
181 "asan-max-inline-poisoning-size",
183 "Inline shadow poisoning for blocks up to the given size in bytes."),
184 cl::Hidden, cl::init(64));
185 static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
186 cl::desc("Check stack-use-after-return"),
187 cl::Hidden, cl::init(true));
188 static cl::opt<bool> ClUseAfterScope("asan-use-after-scope",
189 cl::desc("Check stack-use-after-scope"),
190 cl::Hidden, cl::init(false));
191 // This flag may need to be replaced with -f[no]asan-globals.
192 static cl::opt<bool> ClGlobals("asan-globals",
193 cl::desc("Handle global objects"), cl::Hidden,
195 static cl::opt<bool> ClInitializers("asan-initialization-order",
196 cl::desc("Handle C++ initializer order"),
197 cl::Hidden, cl::init(true));
198 static cl::opt<bool> ClInvalidPointerPairs(
199 "asan-detect-invalid-pointer-pair",
200 cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
202 static cl::opt<unsigned> ClRealignStack(
203 "asan-realign-stack",
204 cl::desc("Realign stack to the value of this flag (power of two)"),
205 cl::Hidden, cl::init(32));
206 static cl::opt<int> ClInstrumentationWithCallsThreshold(
207 "asan-instrumentation-with-call-threshold",
209 "If the function being instrumented contains more than "
210 "this number of memory accesses, use callbacks instead of "
211 "inline checks (-1 means never use callbacks)."),
212 cl::Hidden, cl::init(7000));
213 static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
214 "asan-memory-access-callback-prefix",
215 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
216 cl::init("__asan_"));
218 ClInstrumentDynamicAllocas("asan-instrument-dynamic-allocas",
219 cl::desc("instrument dynamic allocas"),
220 cl::Hidden, cl::init(true));
221 static cl::opt<bool> ClSkipPromotableAllocas(
222 "asan-skip-promotable-allocas",
223 cl::desc("Do not instrument promotable allocas"), cl::Hidden,
226 // These flags allow to change the shadow mapping.
227 // The shadow mapping looks like
228 // Shadow = (Mem >> scale) + offset
229 static cl::opt<int> ClMappingScale("asan-mapping-scale",
230 cl::desc("scale of asan shadow mapping"),
231 cl::Hidden, cl::init(0));
232 static cl::opt<unsigned long long> ClMappingOffset(
233 "asan-mapping-offset",
234 cl::desc("offset of asan shadow mapping [EXPERIMENTAL]"), cl::Hidden,
237 // Optimization flags. Not user visible, used mostly for testing
238 // and benchmarking the tool.
239 static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
240 cl::Hidden, cl::init(true));
241 static cl::opt<bool> ClOptSameTemp(
242 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
243 cl::Hidden, cl::init(true));
244 static cl::opt<bool> ClOptGlobals("asan-opt-globals",
245 cl::desc("Don't instrument scalar globals"),
246 cl::Hidden, cl::init(true));
247 static cl::opt<bool> ClOptStack(
248 "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
249 cl::Hidden, cl::init(false));
251 static cl::opt<bool> ClDynamicAllocaStack(
252 "asan-stack-dynamic-alloca",
253 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
256 static cl::opt<uint32_t> ClForceExperiment(
257 "asan-force-experiment",
258 cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
262 ClUsePrivateAliasForGlobals("asan-use-private-alias",
263 cl::desc("Use private aliases for global"
265 cl::Hidden, cl::init(false));
268 ClUseMachOGlobalsSection("asan-globals-live-support",
269 cl::desc("Use linker features to support dead "
270 "code stripping of globals "
272 cl::Hidden, cl::init(true));
275 static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
277 static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
278 cl::Hidden, cl::init(0));
279 static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
280 cl::desc("Debug func"));
281 static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
282 cl::Hidden, cl::init(-1));
283 static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug max inst"),
284 cl::Hidden, cl::init(-1));
286 STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
287 STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
288 STATISTIC(NumOptimizedAccessesToGlobalVar,
289 "Number of optimized accesses to global vars");
290 STATISTIC(NumOptimizedAccessesToStackVar,
291 "Number of optimized accesses to stack vars");
294 /// Frontend-provided metadata for source location.
295 struct LocationMetadata {
300 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
302 bool empty() const { return Filename.empty(); }
304 void parse(MDNode *MDN) {
305 assert(MDN->getNumOperands() == 3);
306 MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
307 Filename = DIFilename->getString();
309 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
311 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
315 /// Frontend-provided metadata for global variables.
316 class GlobalsMetadata {
319 Entry() : SourceLoc(), Name(), IsDynInit(false), IsBlacklisted(false) {}
320 LocationMetadata SourceLoc;
326 GlobalsMetadata() : inited_(false) {}
333 void init(Module &M) {
336 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
337 if (!Globals) return;
338 for (auto MDN : Globals->operands()) {
339 // Metadata node contains the global and the fields of "Entry".
340 assert(MDN->getNumOperands() == 5);
341 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
342 // The optimizer may optimize away a global entirely.
344 // We can already have an entry for GV if it was merged with another
346 Entry &E = Entries[GV];
347 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
348 E.SourceLoc.parse(Loc);
349 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
350 E.Name = Name->getString();
351 ConstantInt *IsDynInit =
352 mdconst::extract<ConstantInt>(MDN->getOperand(3));
353 E.IsDynInit |= IsDynInit->isOne();
354 ConstantInt *IsBlacklisted =
355 mdconst::extract<ConstantInt>(MDN->getOperand(4));
356 E.IsBlacklisted |= IsBlacklisted->isOne();
360 /// Returns metadata entry for a given global.
361 Entry get(GlobalVariable *G) const {
362 auto Pos = Entries.find(G);
363 return (Pos != Entries.end()) ? Pos->second : Entry();
368 DenseMap<GlobalVariable *, Entry> Entries;
371 /// This struct defines the shadow mapping using the rule:
372 /// shadow = (mem >> Scale) ADD-or-OR Offset.
373 struct ShadowMapping {
379 static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
381 bool IsAndroid = TargetTriple.isAndroid();
382 bool IsIOS = TargetTriple.isiOS() || TargetTriple.isWatchOS();
383 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
384 bool IsPS4CPU = TargetTriple.isPS4CPU();
385 bool IsLinux = TargetTriple.isOSLinux();
386 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
387 TargetTriple.getArch() == llvm::Triple::ppc64le;
388 bool IsSystemZ = TargetTriple.getArch() == llvm::Triple::systemz;
389 bool IsX86 = TargetTriple.getArch() == llvm::Triple::x86;
390 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
391 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
392 TargetTriple.getArch() == llvm::Triple::mipsel;
393 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
394 TargetTriple.getArch() == llvm::Triple::mips64el;
395 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
396 bool IsWindows = TargetTriple.isOSWindows();
397 bool IsFuchsia = TargetTriple.isOSFuchsia();
399 ShadowMapping Mapping;
401 if (LongSize == 32) {
402 // Android is always PIE, which means that the beginning of the address
403 // space is always available.
407 Mapping.Offset = kMIPS32_ShadowOffset32;
409 Mapping.Offset = kFreeBSD_ShadowOffset32;
411 // If we're targeting iOS and x86, the binary is built for iOS simulator.
412 Mapping.Offset = IsX86 ? kIOSSimShadowOffset32 : kIOSShadowOffset32;
414 Mapping.Offset = kWindowsShadowOffset32;
416 Mapping.Offset = kDefaultShadowOffset32;
417 } else { // LongSize == 64
418 // Fuchsia is always PIE, which means that the beginning of the address
419 // space is always available.
423 Mapping.Offset = kPPC64_ShadowOffset64;
425 Mapping.Offset = kSystemZ_ShadowOffset64;
427 Mapping.Offset = kFreeBSD_ShadowOffset64;
429 Mapping.Offset = kPS4CPU_ShadowOffset64;
430 else if (IsLinux && IsX86_64) {
432 Mapping.Offset = kLinuxKasan_ShadowOffset64;
434 Mapping.Offset = kSmallX86_64ShadowOffset;
435 } else if (IsWindows && IsX86_64) {
436 Mapping.Offset = kWindowsShadowOffset64;
438 Mapping.Offset = kMIPS64_ShadowOffset64;
440 // If we're targeting iOS and x86, the binary is built for iOS simulator.
441 // We are using dynamic shadow offset on the 64-bit devices.
443 IsX86_64 ? kIOSSimShadowOffset64 : kDynamicShadowSentinel;
445 Mapping.Offset = kAArch64_ShadowOffset64;
447 Mapping.Offset = kDefaultShadowOffset64;
450 if (ClForceDynamicShadow) {
451 Mapping.Offset = kDynamicShadowSentinel;
454 Mapping.Scale = kDefaultShadowScale;
455 if (ClMappingScale.getNumOccurrences() > 0) {
456 Mapping.Scale = ClMappingScale;
459 if (ClMappingOffset.getNumOccurrences() > 0) {
460 Mapping.Offset = ClMappingOffset;
463 // OR-ing shadow offset if more efficient (at least on x86) if the offset
464 // is a power of two, but on ppc64 we have to use add since the shadow
465 // offset is not necessary 1/8-th of the address space. On SystemZ,
466 // we could OR the constant in a single instruction, but it's more
467 // efficient to load it once and use indexed addressing.
468 Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64 && !IsSystemZ && !IsPS4CPU &&
469 !(Mapping.Offset & (Mapping.Offset - 1)) &&
470 Mapping.Offset != kDynamicShadowSentinel;
475 static size_t RedzoneSizeForScale(int MappingScale) {
476 // Redzone used for stack and globals is at least 32 bytes.
477 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
478 return std::max(32U, 1U << MappingScale);
481 /// AddressSanitizer: instrument the code in module to find memory bugs.
482 struct AddressSanitizer : public FunctionPass {
483 explicit AddressSanitizer(bool CompileKernel = false, bool Recover = false,
484 bool UseAfterScope = false)
485 : FunctionPass(ID), CompileKernel(CompileKernel || ClEnableKasan),
486 Recover(Recover || ClRecover),
487 UseAfterScope(UseAfterScope || ClUseAfterScope),
488 LocalDynamicShadow(nullptr) {
489 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
491 StringRef getPassName() const override {
492 return "AddressSanitizerFunctionPass";
494 void getAnalysisUsage(AnalysisUsage &AU) const override {
495 AU.addRequired<DominatorTreeWrapperPass>();
496 AU.addRequired<TargetLibraryInfoWrapperPass>();
498 uint64_t getAllocaSizeInBytes(const AllocaInst &AI) const {
499 uint64_t ArraySize = 1;
500 if (AI.isArrayAllocation()) {
501 const ConstantInt *CI = dyn_cast<ConstantInt>(AI.getArraySize());
502 assert(CI && "non-constant array size");
503 ArraySize = CI->getZExtValue();
505 Type *Ty = AI.getAllocatedType();
506 uint64_t SizeInBytes =
507 AI.getModule()->getDataLayout().getTypeAllocSize(Ty);
508 return SizeInBytes * ArraySize;
510 /// Check if we want (and can) handle this alloca.
511 bool isInterestingAlloca(const AllocaInst &AI);
513 /// If it is an interesting memory access, return the PointerOperand
514 /// and set IsWrite/Alignment. Otherwise return nullptr.
515 /// MaybeMask is an output parameter for the mask Value, if we're looking at a
516 /// masked load/store.
517 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
518 uint64_t *TypeSize, unsigned *Alignment,
519 Value **MaybeMask = nullptr);
520 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
521 bool UseCalls, const DataLayout &DL);
522 void instrumentPointerComparisonOrSubtraction(Instruction *I);
523 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
524 Value *Addr, uint32_t TypeSize, bool IsWrite,
525 Value *SizeArgument, bool UseCalls, uint32_t Exp);
526 void instrumentUnusualSizeOrAlignment(Instruction *I,
527 Instruction *InsertBefore, Value *Addr,
528 uint32_t TypeSize, bool IsWrite,
529 Value *SizeArgument, bool UseCalls,
531 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
532 Value *ShadowValue, uint32_t TypeSize);
533 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
534 bool IsWrite, size_t AccessSizeIndex,
535 Value *SizeArgument, uint32_t Exp);
536 void instrumentMemIntrinsic(MemIntrinsic *MI);
537 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
538 bool runOnFunction(Function &F) override;
539 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
540 void maybeInsertDynamicShadowAtFunctionEntry(Function &F);
541 void markEscapedLocalAllocas(Function &F);
542 bool doInitialization(Module &M) override;
543 bool doFinalization(Module &M) override;
544 static char ID; // Pass identification, replacement for typeid
546 DominatorTree &getDominatorTree() const { return *DT; }
549 void initializeCallbacks(Module &M);
551 bool LooksLikeCodeInBug11395(Instruction *I);
552 bool GlobalIsLinkerInitialized(GlobalVariable *G);
553 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
554 uint64_t TypeSize) const;
556 /// Helper to cleanup per-function state.
557 struct FunctionStateRAII {
558 AddressSanitizer *Pass;
559 FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
560 assert(Pass->ProcessedAllocas.empty() &&
561 "last pass forgot to clear cache");
562 assert(!Pass->LocalDynamicShadow);
564 ~FunctionStateRAII() {
565 Pass->LocalDynamicShadow = nullptr;
566 Pass->ProcessedAllocas.clear();
577 ShadowMapping Mapping;
579 Function *AsanHandleNoReturnFunc;
580 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
581 // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
582 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
583 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
584 // This array is indexed by AccessIsWrite and Experiment.
585 Function *AsanErrorCallbackSized[2][2];
586 Function *AsanMemoryAccessCallbackSized[2][2];
587 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
589 Value *LocalDynamicShadow;
590 GlobalsMetadata GlobalsMD;
591 DenseMap<const AllocaInst *, bool> ProcessedAllocas;
593 friend struct FunctionStackPoisoner;
596 class AddressSanitizerModule : public ModulePass {
598 explicit AddressSanitizerModule(bool CompileKernel = false,
599 bool Recover = false)
600 : ModulePass(ID), CompileKernel(CompileKernel || ClEnableKasan),
601 Recover(Recover || ClRecover) {}
602 bool runOnModule(Module &M) override;
603 static char ID; // Pass identification, replacement for typeid
604 StringRef getPassName() const override { return "AddressSanitizerModule"; }
607 void initializeCallbacks(Module &M);
609 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
610 void InstrumentGlobalsCOFF(IRBuilder<> &IRB, Module &M,
611 ArrayRef<GlobalVariable *> ExtendedGlobals,
612 ArrayRef<Constant *> MetadataInitializers);
613 void InstrumentGlobalsMachO(IRBuilder<> &IRB, Module &M,
614 ArrayRef<GlobalVariable *> ExtendedGlobals,
615 ArrayRef<Constant *> MetadataInitializers);
617 InstrumentGlobalsWithMetadataArray(IRBuilder<> &IRB, Module &M,
618 ArrayRef<GlobalVariable *> ExtendedGlobals,
619 ArrayRef<Constant *> MetadataInitializers);
621 GlobalVariable *CreateMetadataGlobal(Module &M, Constant *Initializer,
622 StringRef OriginalName);
623 void SetComdatForGlobalMetadata(GlobalVariable *G, GlobalVariable *Metadata);
624 IRBuilder<> CreateAsanModuleDtor(Module &M);
626 bool ShouldInstrumentGlobal(GlobalVariable *G);
627 bool ShouldUseMachOGlobalsSection() const;
628 StringRef getGlobalMetadataSection() const;
629 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
630 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
631 size_t MinRedzoneSizeForGlobal() const {
632 return RedzoneSizeForScale(Mapping.Scale);
635 GlobalsMetadata GlobalsMD;
641 ShadowMapping Mapping;
642 Function *AsanPoisonGlobals;
643 Function *AsanUnpoisonGlobals;
644 Function *AsanRegisterGlobals;
645 Function *AsanUnregisterGlobals;
646 Function *AsanRegisterImageGlobals;
647 Function *AsanUnregisterImageGlobals;
650 // Stack poisoning does not play well with exception handling.
651 // When an exception is thrown, we essentially bypass the code
652 // that unpoisones the stack. This is why the run-time library has
653 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
654 // stack in the interceptor. This however does not work inside the
655 // actual function which catches the exception. Most likely because the
656 // compiler hoists the load of the shadow value somewhere too high.
657 // This causes asan to report a non-existing bug on 453.povray.
658 // It sounds like an LLVM bug.
659 struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
661 AddressSanitizer &ASan;
666 ShadowMapping Mapping;
668 SmallVector<AllocaInst *, 16> AllocaVec;
669 SmallVector<AllocaInst *, 16> StaticAllocasToMoveUp;
670 SmallVector<Instruction *, 8> RetVec;
671 unsigned StackAlignment;
673 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
674 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
675 Function *AsanSetShadowFunc[0x100] = {};
676 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
677 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
679 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
680 struct AllocaPoisonCall {
681 IntrinsicInst *InsBefore;
686 SmallVector<AllocaPoisonCall, 8> DynamicAllocaPoisonCallVec;
687 SmallVector<AllocaPoisonCall, 8> StaticAllocaPoisonCallVec;
689 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
690 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
691 AllocaInst *DynamicAllocaLayout = nullptr;
692 IntrinsicInst *LocalEscapeCall = nullptr;
694 // Maps Value to an AllocaInst from which the Value is originated.
695 typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
696 AllocaForValueMapTy AllocaForValue;
698 bool HasNonEmptyInlineAsm = false;
699 bool HasReturnsTwiceCall = false;
700 std::unique_ptr<CallInst> EmptyInlineAsm;
702 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
705 DIB(*F.getParent(), /*AllowUnresolved*/ false),
707 IntptrTy(ASan.IntptrTy),
708 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
709 Mapping(ASan.Mapping),
710 StackAlignment(1 << Mapping.Scale),
711 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
713 bool runOnFunction() {
714 if (!ClStack) return false;
715 // Collect alloca, ret, lifetime instructions etc.
716 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
718 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
720 initializeCallbacks(*F.getParent());
722 processDynamicAllocas();
723 processStaticAllocas();
731 // Finds all Alloca instructions and puts
732 // poisoned red zones around all of them.
733 // Then unpoison everything back before the function returns.
734 void processStaticAllocas();
735 void processDynamicAllocas();
737 void createDynamicAllocasInitStorage();
739 // ----------------------- Visitors.
740 /// \brief Collect all Ret instructions.
741 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
743 /// \brief Collect all Resume instructions.
744 void visitResumeInst(ResumeInst &RI) { RetVec.push_back(&RI); }
746 /// \brief Collect all CatchReturnInst instructions.
747 void visitCleanupReturnInst(CleanupReturnInst &CRI) { RetVec.push_back(&CRI); }
749 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
751 IRBuilder<> IRB(InstBefore);
752 Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
753 // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
754 // need to adjust extracted SP to compute the address of the most recent
755 // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
757 if (!isa<ReturnInst>(InstBefore)) {
758 Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
759 InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
762 Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
764 DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
768 IRB.CreateCall(AsanAllocasUnpoisonFunc,
769 {IRB.CreateLoad(DynamicAllocaLayout), DynamicAreaPtr});
772 // Unpoison dynamic allocas redzones.
773 void unpoisonDynamicAllocas() {
774 for (auto &Ret : RetVec)
775 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
777 for (auto &StackRestoreInst : StackRestoreVec)
778 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
779 StackRestoreInst->getOperand(0));
782 // Deploy and poison redzones around dynamic alloca call. To do this, we
783 // should replace this call with another one with changed parameters and
784 // replace all its uses with new address, so
785 // addr = alloca type, old_size, align
787 // new_size = (old_size + additional_size) * sizeof(type)
788 // tmp = alloca i8, new_size, max(align, 32)
789 // addr = tmp + 32 (first 32 bytes are for the left redzone).
790 // Additional_size is added to make new memory allocation contain not only
791 // requested memory, but also left, partial and right redzones.
792 void handleDynamicAllocaCall(AllocaInst *AI);
794 /// \brief Collect Alloca instructions we want (and can) handle.
795 void visitAllocaInst(AllocaInst &AI) {
796 if (!ASan.isInterestingAlloca(AI)) {
797 if (AI.isStaticAlloca()) {
798 // Skip over allocas that are present *before* the first instrumented
799 // alloca, we don't want to move those around.
800 if (AllocaVec.empty())
803 StaticAllocasToMoveUp.push_back(&AI);
808 StackAlignment = std::max(StackAlignment, AI.getAlignment());
809 if (!AI.isStaticAlloca())
810 DynamicAllocaVec.push_back(&AI);
812 AllocaVec.push_back(&AI);
815 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
817 void visitIntrinsicInst(IntrinsicInst &II) {
818 Intrinsic::ID ID = II.getIntrinsicID();
819 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
820 if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
821 if (!ASan.UseAfterScope)
823 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
825 // Found lifetime intrinsic, add ASan instrumentation if necessary.
826 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
827 // If size argument is undefined, don't do anything.
828 if (Size->isMinusOne()) return;
829 // Check that size doesn't saturate uint64_t and can
830 // be stored in IntptrTy.
831 const uint64_t SizeValue = Size->getValue().getLimitedValue();
832 if (SizeValue == ~0ULL ||
833 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
835 // Find alloca instruction that corresponds to llvm.lifetime argument.
836 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
837 if (!AI || !ASan.isInterestingAlloca(*AI))
839 bool DoPoison = (ID == Intrinsic::lifetime_end);
840 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
841 if (AI->isStaticAlloca())
842 StaticAllocaPoisonCallVec.push_back(APC);
843 else if (ClInstrumentDynamicAllocas)
844 DynamicAllocaPoisonCallVec.push_back(APC);
847 void visitCallSite(CallSite CS) {
848 Instruction *I = CS.getInstruction();
849 if (CallInst *CI = dyn_cast<CallInst>(I)) {
850 HasNonEmptyInlineAsm |=
851 CI->isInlineAsm() && !CI->isIdenticalTo(EmptyInlineAsm.get());
852 HasReturnsTwiceCall |= CI->canReturnTwice();
856 // ---------------------- Helpers.
857 void initializeCallbacks(Module &M);
859 bool doesDominateAllExits(const Instruction *I) const {
860 for (auto Ret : RetVec) {
861 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
866 /// Finds alloca where the value comes from.
867 AllocaInst *findAllocaForValue(Value *V);
869 // Copies bytes from ShadowBytes into shadow memory for indexes where
870 // ShadowMask is not zero. If ShadowMask[i] is zero, we assume that
871 // ShadowBytes[i] is constantly zero and doesn't need to be overwritten.
872 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
873 IRBuilder<> &IRB, Value *ShadowBase);
874 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
875 size_t Begin, size_t End, IRBuilder<> &IRB,
877 void copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
878 ArrayRef<uint8_t> ShadowBytes, size_t Begin,
879 size_t End, IRBuilder<> &IRB, Value *ShadowBase);
881 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
883 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
885 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
886 Instruction *ThenTerm, Value *ValueIfFalse);
889 } // anonymous namespace
891 char AddressSanitizer::ID = 0;
892 INITIALIZE_PASS_BEGIN(
893 AddressSanitizer, "asan",
894 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
896 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
897 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
899 AddressSanitizer, "asan",
900 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
902 FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel,
904 bool UseAfterScope) {
905 assert(!CompileKernel || Recover);
906 return new AddressSanitizer(CompileKernel, Recover, UseAfterScope);
909 char AddressSanitizerModule::ID = 0;
911 AddressSanitizerModule, "asan-module",
912 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
915 ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel,
917 assert(!CompileKernel || Recover);
918 return new AddressSanitizerModule(CompileKernel, Recover);
921 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
922 size_t Res = countTrailingZeros(TypeSize / 8);
923 assert(Res < kNumberOfAccessSizes);
927 // \brief Create a constant for Str so that we can pass it to the run-time lib.
928 static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
930 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
931 // We use private linkage for module-local strings. If they can be merged
932 // with another one, we set the unnamed_addr attribute.
934 new GlobalVariable(M, StrConst->getType(), true,
935 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
936 if (AllowMerging) GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
937 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
941 /// \brief Create a global describing a source location.
942 static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
943 LocationMetadata MD) {
944 Constant *LocData[] = {
945 createPrivateGlobalForString(M, MD.Filename, true),
946 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
947 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
949 auto LocStruct = ConstantStruct::getAnon(LocData);
950 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
951 GlobalValue::PrivateLinkage, LocStruct,
953 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
957 /// \brief Check if \p G has been created by a trusted compiler pass.
958 static bool GlobalWasGeneratedByCompiler(GlobalVariable *G) {
959 // Do not instrument asan globals.
960 if (G->getName().startswith(kAsanGenPrefix) ||
961 G->getName().startswith(kSanCovGenPrefix) ||
962 G->getName().startswith(kODRGenPrefix))
965 // Do not instrument gcov counter arrays.
966 if (G->getName() == "__llvm_gcov_ctr")
972 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
974 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
975 if (Mapping.Offset == 0) return Shadow;
976 // (Shadow >> scale) | offset
978 if (LocalDynamicShadow)
979 ShadowBase = LocalDynamicShadow;
981 ShadowBase = ConstantInt::get(IntptrTy, Mapping.Offset);
982 if (Mapping.OrShadowOffset)
983 return IRB.CreateOr(Shadow, ShadowBase);
985 return IRB.CreateAdd(Shadow, ShadowBase);
988 // Instrument memset/memmove/memcpy
989 void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
991 if (isa<MemTransferInst>(MI)) {
993 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
994 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
995 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
996 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
997 } else if (isa<MemSetInst>(MI)) {
1000 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1001 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
1002 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
1004 MI->eraseFromParent();
1007 /// Check if we want (and can) handle this alloca.
1008 bool AddressSanitizer::isInterestingAlloca(const AllocaInst &AI) {
1009 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
1011 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
1012 return PreviouslySeenAllocaInfo->getSecond();
1014 bool IsInteresting =
1015 (AI.getAllocatedType()->isSized() &&
1016 // alloca() may be called with 0 size, ignore it.
1017 ((!AI.isStaticAlloca()) || getAllocaSizeInBytes(AI) > 0) &&
1018 // We are only interested in allocas not promotable to registers.
1019 // Promotable allocas are common under -O0.
1020 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
1021 // inalloca allocas are not treated as static, and we don't want
1022 // dynamic alloca instrumentation for them as well.
1023 !AI.isUsedWithInAlloca() &&
1024 // swifterror allocas are register promoted by ISel
1025 !AI.isSwiftError());
1027 ProcessedAllocas[&AI] = IsInteresting;
1028 return IsInteresting;
1031 Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
1034 unsigned *Alignment,
1035 Value **MaybeMask) {
1036 // Skip memory accesses inserted by another instrumentation.
1037 if (I->getMetadata("nosanitize")) return nullptr;
1039 // Do not instrument the load fetching the dynamic shadow address.
1040 if (LocalDynamicShadow == I)
1043 Value *PtrOperand = nullptr;
1044 const DataLayout &DL = I->getModule()->getDataLayout();
1045 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1046 if (!ClInstrumentReads) return nullptr;
1048 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
1049 *Alignment = LI->getAlignment();
1050 PtrOperand = LI->getPointerOperand();
1051 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1052 if (!ClInstrumentWrites) return nullptr;
1054 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
1055 *Alignment = SI->getAlignment();
1056 PtrOperand = SI->getPointerOperand();
1057 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
1058 if (!ClInstrumentAtomics) return nullptr;
1060 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
1062 PtrOperand = RMW->getPointerOperand();
1063 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
1064 if (!ClInstrumentAtomics) return nullptr;
1066 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
1068 PtrOperand = XCHG->getPointerOperand();
1069 } else if (auto CI = dyn_cast<CallInst>(I)) {
1070 auto *F = dyn_cast<Function>(CI->getCalledValue());
1071 if (F && (F->getName().startswith("llvm.masked.load.") ||
1072 F->getName().startswith("llvm.masked.store."))) {
1073 unsigned OpOffset = 0;
1074 if (F->getName().startswith("llvm.masked.store.")) {
1075 if (!ClInstrumentWrites)
1077 // Masked store has an initial operand for the value.
1081 if (!ClInstrumentReads)
1086 auto BasePtr = CI->getOperand(0 + OpOffset);
1087 auto Ty = cast<PointerType>(BasePtr->getType())->getElementType();
1088 *TypeSize = DL.getTypeStoreSizeInBits(Ty);
1089 if (auto AlignmentConstant =
1090 dyn_cast<ConstantInt>(CI->getOperand(1 + OpOffset)))
1091 *Alignment = (unsigned)AlignmentConstant->getZExtValue();
1093 *Alignment = 1; // No alignment guarantees. We probably got Undef
1095 *MaybeMask = CI->getOperand(2 + OpOffset);
1096 PtrOperand = BasePtr;
1101 // Do not instrument acesses from different address spaces; we cannot deal
1103 Type *PtrTy = cast<PointerType>(PtrOperand->getType()->getScalarType());
1104 if (PtrTy->getPointerAddressSpace() != 0)
1107 // Ignore swifterror addresses.
1108 // swifterror memory addresses are mem2reg promoted by instruction
1109 // selection. As such they cannot have regular uses like an instrumentation
1110 // function and it makes no sense to track them as memory.
1111 if (PtrOperand->isSwiftError())
1115 // Treat memory accesses to promotable allocas as non-interesting since they
1116 // will not cause memory violations. This greatly speeds up the instrumented
1117 // executable at -O0.
1118 if (ClSkipPromotableAllocas)
1119 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
1120 return isInterestingAlloca(*AI) ? AI : nullptr;
1125 static bool isPointerOperand(Value *V) {
1126 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
1129 // This is a rough heuristic; it may cause both false positives and
1130 // false negatives. The proper implementation requires cooperation with
1132 static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
1133 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
1134 if (!Cmp->isRelational()) return false;
1135 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1136 if (BO->getOpcode() != Instruction::Sub) return false;
1140 return isPointerOperand(I->getOperand(0)) &&
1141 isPointerOperand(I->getOperand(1));
1144 bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
1145 // If a global variable does not have dynamic initialization we don't
1146 // have to instrument it. However, if a global does not have initializer
1147 // at all, we assume it has dynamic initializer (in other TU).
1148 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
1151 void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
1154 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
1155 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
1156 for (Value *&i : Param) {
1157 if (i->getType()->isPointerTy())
1158 i = IRB.CreatePointerCast(i, IntptrTy);
1160 IRB.CreateCall(F, Param);
1163 static void doInstrumentAddress(AddressSanitizer *Pass, Instruction *I,
1164 Instruction *InsertBefore, Value *Addr,
1165 unsigned Alignment, unsigned Granularity,
1166 uint32_t TypeSize, bool IsWrite,
1167 Value *SizeArgument, bool UseCalls,
1169 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
1170 // if the data is properly aligned.
1171 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1173 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
1174 return Pass->instrumentAddress(I, InsertBefore, Addr, TypeSize, IsWrite,
1175 nullptr, UseCalls, Exp);
1176 Pass->instrumentUnusualSizeOrAlignment(I, InsertBefore, Addr, TypeSize,
1177 IsWrite, nullptr, UseCalls, Exp);
1180 static void instrumentMaskedLoadOrStore(AddressSanitizer *Pass,
1181 const DataLayout &DL, Type *IntptrTy,
1182 Value *Mask, Instruction *I,
1183 Value *Addr, unsigned Alignment,
1184 unsigned Granularity, uint32_t TypeSize,
1185 bool IsWrite, Value *SizeArgument,
1186 bool UseCalls, uint32_t Exp) {
1187 auto *VTy = cast<PointerType>(Addr->getType())->getElementType();
1188 uint64_t ElemTypeSize = DL.getTypeStoreSizeInBits(VTy->getScalarType());
1189 unsigned Num = VTy->getVectorNumElements();
1190 auto Zero = ConstantInt::get(IntptrTy, 0);
1191 for (unsigned Idx = 0; Idx < Num; ++Idx) {
1192 Value *InstrumentedAddress = nullptr;
1193 Instruction *InsertBefore = I;
1194 if (auto *Vector = dyn_cast<ConstantVector>(Mask)) {
1195 // dyn_cast as we might get UndefValue
1196 if (auto *Masked = dyn_cast<ConstantInt>(Vector->getOperand(Idx))) {
1197 if (Masked->isNullValue())
1198 // Mask is constant false, so no instrumentation needed.
1200 // If we have a true or undef value, fall through to doInstrumentAddress
1201 // with InsertBefore == I
1205 Value *MaskElem = IRB.CreateExtractElement(Mask, Idx);
1206 TerminatorInst *ThenTerm = SplitBlockAndInsertIfThen(MaskElem, I, false);
1207 InsertBefore = ThenTerm;
1210 IRBuilder<> IRB(InsertBefore);
1211 InstrumentedAddress =
1212 IRB.CreateGEP(Addr, {Zero, ConstantInt::get(IntptrTy, Idx)});
1213 doInstrumentAddress(Pass, I, InsertBefore, InstrumentedAddress, Alignment,
1214 Granularity, ElemTypeSize, IsWrite, SizeArgument,
1219 void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
1220 Instruction *I, bool UseCalls,
1221 const DataLayout &DL) {
1222 bool IsWrite = false;
1223 unsigned Alignment = 0;
1224 uint64_t TypeSize = 0;
1225 Value *MaybeMask = nullptr;
1227 isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment, &MaybeMask);
1230 // Optimization experiments.
1231 // The experiments can be used to evaluate potential optimizations that remove
1232 // instrumentation (assess false negatives). Instead of completely removing
1233 // some instrumentation, you set Exp to a non-zero value (mask of optimization
1234 // experiments that want to remove instrumentation of this instruction).
1235 // If Exp is non-zero, this pass will emit special calls into runtime
1236 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
1237 // make runtime terminate the program in a special way (with a different
1238 // exit status). Then you run the new compiler on a buggy corpus, collect
1239 // the special terminations (ideally, you don't see them at all -- no false
1240 // negatives) and make the decision on the optimization.
1241 uint32_t Exp = ClForceExperiment;
1243 if (ClOpt && ClOptGlobals) {
1244 // If initialization order checking is disabled, a simple access to a
1245 // dynamically initialized global is always valid.
1246 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
1247 if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
1248 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1249 NumOptimizedAccessesToGlobalVar++;
1254 if (ClOpt && ClOptStack) {
1255 // A direct inbounds access to a stack variable is always valid.
1256 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
1257 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1258 NumOptimizedAccessesToStackVar++;
1264 NumInstrumentedWrites++;
1266 NumInstrumentedReads++;
1268 unsigned Granularity = 1 << Mapping.Scale;
1270 instrumentMaskedLoadOrStore(this, DL, IntptrTy, MaybeMask, I, Addr,
1271 Alignment, Granularity, TypeSize, IsWrite,
1272 nullptr, UseCalls, Exp);
1274 doInstrumentAddress(this, I, I, Addr, Alignment, Granularity, TypeSize,
1275 IsWrite, nullptr, UseCalls, Exp);
1279 Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
1280 Value *Addr, bool IsWrite,
1281 size_t AccessSizeIndex,
1282 Value *SizeArgument,
1284 IRBuilder<> IRB(InsertBefore);
1285 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1286 CallInst *Call = nullptr;
1289 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1290 {Addr, SizeArgument});
1292 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1293 {Addr, SizeArgument, ExpVal});
1297 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1299 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1303 // We don't do Call->setDoesNotReturn() because the BB already has
1304 // UnreachableInst at the end.
1305 // This EmptyAsm is required to avoid callback merge.
1306 IRB.CreateCall(EmptyAsm, {});
1310 Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
1312 uint32_t TypeSize) {
1313 size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;
1314 // Addr & (Granularity - 1)
1315 Value *LastAccessedByte =
1316 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
1317 // (Addr & (Granularity - 1)) + size - 1
1318 if (TypeSize / 8 > 1)
1319 LastAccessedByte = IRB.CreateAdd(
1320 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1321 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
1323 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
1324 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1325 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1328 void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
1329 Instruction *InsertBefore, Value *Addr,
1330 uint32_t TypeSize, bool IsWrite,
1331 Value *SizeArgument, bool UseCalls,
1333 IRBuilder<> IRB(InsertBefore);
1334 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1335 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1339 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1342 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1343 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
1348 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
1349 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1350 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1351 Value *CmpVal = Constant::getNullValue(ShadowTy);
1352 Value *ShadowValue =
1353 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
1355 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
1356 size_t Granularity = 1ULL << Mapping.Scale;
1357 TerminatorInst *CrashTerm = nullptr;
1359 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
1360 // We use branch weights for the slow path check, to indicate that the slow
1361 // path is rarely taken. This seems to be the case for SPEC benchmarks.
1362 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1363 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
1364 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
1365 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
1366 IRB.SetInsertPoint(CheckTerm);
1367 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
1369 CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
1371 BasicBlock *CrashBlock =
1372 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
1373 CrashTerm = new UnreachableInst(*C, CrashBlock);
1374 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1375 ReplaceInstWithInst(CheckTerm, NewTerm);
1378 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
1381 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
1382 AccessSizeIndex, SizeArgument, Exp);
1383 Crash->setDebugLoc(OrigIns->getDebugLoc());
1386 // Instrument unusual size or unusual alignment.
1387 // We can not do it with a single check, so we do 1-byte check for the first
1388 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1389 // to report the actual access size.
1390 void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1391 Instruction *I, Instruction *InsertBefore, Value *Addr, uint32_t TypeSize,
1392 bool IsWrite, Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1393 IRBuilder<> IRB(InsertBefore);
1394 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1395 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1398 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1401 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1402 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
1404 Value *LastByte = IRB.CreateIntToPtr(
1405 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1407 instrumentAddress(I, InsertBefore, Addr, 8, IsWrite, Size, false, Exp);
1408 instrumentAddress(I, InsertBefore, LastByte, 8, IsWrite, Size, false, Exp);
1412 void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1413 GlobalValue *ModuleName) {
1414 // Set up the arguments to our poison/unpoison functions.
1415 IRBuilder<> IRB(&GlobalInit.front(),
1416 GlobalInit.front().getFirstInsertionPt());
1418 // Add a call to poison all external globals before the given function starts.
1419 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1420 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
1422 // Add calls to unpoison all globals before each return instruction.
1423 for (auto &BB : GlobalInit.getBasicBlockList())
1424 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
1425 CallInst::Create(AsanUnpoisonGlobals, "", RI);
1428 void AddressSanitizerModule::createInitializerPoisonCalls(
1429 Module &M, GlobalValue *ModuleName) {
1430 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1432 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1433 for (Use &OP : CA->operands()) {
1434 if (isa<ConstantAggregateZero>(OP)) continue;
1435 ConstantStruct *CS = cast<ConstantStruct>(OP);
1437 // Must have a function or null ptr.
1438 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
1439 if (F->getName() == kAsanModuleCtorName) continue;
1440 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1441 // Don't instrument CTORs that will run before asan.module_ctor.
1442 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1443 poisonOneInitializer(*F, ModuleName);
1448 bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
1449 Type *Ty = G->getValueType();
1450 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
1452 if (GlobalsMD.get(G).IsBlacklisted) return false;
1453 if (!Ty->isSized()) return false;
1454 if (!G->hasInitializer()) return false;
1455 if (GlobalWasGeneratedByCompiler(G)) return false; // Our own globals.
1456 // Touch only those globals that will not be defined in other modules.
1457 // Don't handle ODR linkage types and COMDATs since other modules may be built
1459 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1460 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1461 G->getLinkage() != GlobalVariable::InternalLinkage)
1463 if (G->hasComdat()) return false;
1464 // Two problems with thread-locals:
1465 // - The address of the main thread's copy can't be computed at link-time.
1466 // - Need to poison all copies, not just the main thread's one.
1467 if (G->isThreadLocal()) return false;
1468 // For now, just ignore this Global if the alignment is large.
1469 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
1471 if (G->hasSection()) {
1472 StringRef Section = G->getSection();
1474 // Globals from llvm.metadata aren't emitted, do not instrument them.
1475 if (Section == "llvm.metadata") return false;
1476 // Do not instrument globals from special LLVM sections.
1477 if (Section.find("__llvm") != StringRef::npos || Section.find("__LLVM") != StringRef::npos) return false;
1479 // Do not instrument function pointers to initialization and termination
1480 // routines: dynamic linker will not properly handle redzones.
1481 if (Section.startswith(".preinit_array") ||
1482 Section.startswith(".init_array") ||
1483 Section.startswith(".fini_array")) {
1487 // Callbacks put into the CRT initializer/terminator sections
1488 // should not be instrumented.
1489 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1490 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1491 if (Section.startswith(".CRT")) {
1492 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1496 if (TargetTriple.isOSBinFormatMachO()) {
1497 StringRef ParsedSegment, ParsedSection;
1498 unsigned TAA = 0, StubSize = 0;
1500 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1501 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
1502 assert(ErrorCode.empty() && "Invalid section specifier.");
1504 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1505 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1507 if (ParsedSegment == "__OBJC" ||
1508 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1509 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1512 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1513 // Constant CFString instances are compiled in the following way:
1514 // -- the string buffer is emitted into
1515 // __TEXT,__cstring,cstring_literals
1516 // -- the constant NSConstantString structure referencing that buffer
1517 // is placed into __DATA,__cfstring
1518 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1519 // Moreover, it causes the linker to crash on OS X 10.7
1520 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1521 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1524 // The linker merges the contents of cstring_literals and removes the
1526 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1527 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1536 // On Mach-O platforms, we emit global metadata in a separate section of the
1537 // binary in order to allow the linker to properly dead strip. This is only
1538 // supported on recent versions of ld64.
1539 bool AddressSanitizerModule::ShouldUseMachOGlobalsSection() const {
1540 if (!ClUseMachOGlobalsSection)
1543 if (!TargetTriple.isOSBinFormatMachO())
1546 if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
1548 if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
1550 if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
1556 StringRef AddressSanitizerModule::getGlobalMetadataSection() const {
1557 switch (TargetTriple.getObjectFormat()) {
1558 case Triple::COFF: return ".ASAN$GL";
1559 case Triple::ELF: return "asan_globals";
1560 case Triple::MachO: return "__DATA,__asan_globals,regular";
1563 llvm_unreachable("unsupported object format");
1566 void AddressSanitizerModule::initializeCallbacks(Module &M) {
1567 IRBuilder<> IRB(*C);
1569 // Declare our poisoning and unpoisoning functions.
1570 AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1571 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy));
1572 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
1573 AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1574 kAsanUnpoisonGlobalsName, IRB.getVoidTy()));
1575 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1577 // Declare functions that register/unregister globals.
1578 AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1579 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy));
1580 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
1581 AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
1582 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1583 IntptrTy, IntptrTy));
1584 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1586 // Declare the functions that find globals in a shared object and then invoke
1587 // the (un)register function on them.
1588 AsanRegisterImageGlobals =
1589 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1590 kAsanRegisterImageGlobalsName, IRB.getVoidTy(), IntptrTy));
1591 AsanRegisterImageGlobals->setLinkage(Function::ExternalLinkage);
1593 AsanUnregisterImageGlobals =
1594 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1595 kAsanUnregisterImageGlobalsName, IRB.getVoidTy(), IntptrTy));
1596 AsanUnregisterImageGlobals->setLinkage(Function::ExternalLinkage);
1599 // Put the metadata and the instrumented global in the same group. This ensures
1600 // that the metadata is discarded if the instrumented global is discarded.
1601 void AddressSanitizerModule::SetComdatForGlobalMetadata(
1602 GlobalVariable *G, GlobalVariable *Metadata) {
1603 Module &M = *G->getParent();
1604 Comdat *C = G->getComdat();
1606 if (!G->hasName()) {
1607 // If G is unnamed, it must be internal. Give it an artificial name
1608 // so we can put it in a comdat.
1609 assert(G->hasLocalLinkage());
1610 G->setName(Twine(kAsanGenPrefix) + "_anon_global");
1612 C = M.getOrInsertComdat(G->getName());
1613 // Make this IMAGE_COMDAT_SELECT_NODUPLICATES on COFF.
1614 if (TargetTriple.isOSBinFormatCOFF())
1615 C->setSelectionKind(Comdat::NoDuplicates);
1619 assert(G->hasComdat());
1620 Metadata->setComdat(G->getComdat());
1623 // Create a separate metadata global and put it in the appropriate ASan
1624 // global registration section.
1626 AddressSanitizerModule::CreateMetadataGlobal(Module &M, Constant *Initializer,
1627 StringRef OriginalName) {
1628 auto Linkage = TargetTriple.isOSBinFormatMachO()
1629 ? GlobalVariable::InternalLinkage
1630 : GlobalVariable::PrivateLinkage;
1631 GlobalVariable *Metadata = new GlobalVariable(
1632 M, Initializer->getType(), false, Linkage, Initializer,
1633 Twine("__asan_global_") + GlobalValue::getRealLinkageName(OriginalName));
1634 Metadata->setSection(getGlobalMetadataSection());
1638 IRBuilder<> AddressSanitizerModule::CreateAsanModuleDtor(Module &M) {
1639 Function *AsanDtorFunction =
1640 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1641 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1642 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1643 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
1645 return IRBuilder<>(ReturnInst::Create(*C, AsanDtorBB));
1648 void AddressSanitizerModule::InstrumentGlobalsCOFF(
1649 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1650 ArrayRef<Constant *> MetadataInitializers) {
1651 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1652 auto &DL = M.getDataLayout();
1654 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1655 Constant *Initializer = MetadataInitializers[i];
1656 GlobalVariable *G = ExtendedGlobals[i];
1657 GlobalVariable *Metadata =
1658 CreateMetadataGlobal(M, Initializer, G->getName());
1660 // The MSVC linker always inserts padding when linking incrementally. We
1661 // cope with that by aligning each struct to its size, which must be a power
1663 unsigned SizeOfGlobalStruct = DL.getTypeAllocSize(Initializer->getType());
1664 assert(isPowerOf2_32(SizeOfGlobalStruct) &&
1665 "global metadata will not be padded appropriately");
1666 Metadata->setAlignment(SizeOfGlobalStruct);
1668 SetComdatForGlobalMetadata(G, Metadata);
1672 void AddressSanitizerModule::InstrumentGlobalsMachO(
1673 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1674 ArrayRef<Constant *> MetadataInitializers) {
1675 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1677 // On recent Mach-O platforms, use a structure which binds the liveness of
1678 // the global variable to the metadata struct. Keep the list of "Liveness" GV
1679 // created to be added to llvm.compiler.used
1680 StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy, nullptr);
1681 SmallVector<GlobalValue *, 16> LivenessGlobals(ExtendedGlobals.size());
1683 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1684 Constant *Initializer = MetadataInitializers[i];
1685 GlobalVariable *G = ExtendedGlobals[i];
1686 GlobalVariable *Metadata =
1687 CreateMetadataGlobal(M, Initializer, G->getName());
1689 // On recent Mach-O platforms, we emit the global metadata in a way that
1690 // allows the linker to properly strip dead globals.
1691 auto LivenessBinder = ConstantStruct::get(
1692 LivenessTy, Initializer->getAggregateElement(0u),
1693 ConstantExpr::getPointerCast(Metadata, IntptrTy), nullptr);
1694 GlobalVariable *Liveness = new GlobalVariable(
1695 M, LivenessTy, false, GlobalVariable::InternalLinkage, LivenessBinder,
1696 Twine("__asan_binder_") + G->getName());
1697 Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
1698 LivenessGlobals[i] = Liveness;
1701 // Update llvm.compiler.used, adding the new liveness globals. This is
1702 // needed so that during LTO these variables stay alive. The alternative
1703 // would be to have the linker handling the LTO symbols, but libLTO
1704 // current API does not expose access to the section for each symbol.
1705 if (!LivenessGlobals.empty())
1706 appendToCompilerUsed(M, LivenessGlobals);
1708 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1709 // to look up the loaded image that contains it. Second, we can store in it
1710 // whether registration has already occurred, to prevent duplicate
1713 // common linkage ensures that there is only one global per shared library.
1714 GlobalVariable *RegisteredFlag = new GlobalVariable(
1715 M, IntptrTy, false, GlobalVariable::CommonLinkage,
1716 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1717 RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
1719 IRB.CreateCall(AsanRegisterImageGlobals,
1720 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1722 // We also need to unregister globals at the end, e.g., when a shared library
1724 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1725 IRB_Dtor.CreateCall(AsanUnregisterImageGlobals,
1726 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1729 void AddressSanitizerModule::InstrumentGlobalsWithMetadataArray(
1730 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1731 ArrayRef<Constant *> MetadataInitializers) {
1732 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1733 unsigned N = ExtendedGlobals.size();
1736 // On platforms that don't have a custom metadata section, we emit an array
1737 // of global metadata structures.
1738 ArrayType *ArrayOfGlobalStructTy =
1739 ArrayType::get(MetadataInitializers[0]->getType(), N);
1740 auto AllGlobals = new GlobalVariable(
1741 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1742 ConstantArray::get(ArrayOfGlobalStructTy, MetadataInitializers), "");
1744 IRB.CreateCall(AsanRegisterGlobals,
1745 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1746 ConstantInt::get(IntptrTy, N)});
1748 // We also need to unregister globals at the end, e.g., when a shared library
1750 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1751 IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1752 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1753 ConstantInt::get(IntptrTy, N)});
1756 // This function replaces all global variables with new variables that have
1757 // trailing redzones. It also creates a function that poisons
1758 // redzones and inserts this function into llvm.global_ctors.
1759 bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
1762 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1764 for (auto &G : M.globals()) {
1765 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
1768 size_t n = GlobalsToChange.size();
1769 if (n == 0) return false;
1771 auto &DL = M.getDataLayout();
1773 // A global is described by a structure
1776 // size_t size_with_redzone;
1777 // const char *name;
1778 // const char *module_name;
1779 // size_t has_dynamic_init;
1780 // void *source_location;
1781 // size_t odr_indicator;
1782 // We initialize an array of such structures and pass it to a run-time call.
1783 StructType *GlobalStructTy =
1784 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
1785 IntptrTy, IntptrTy, IntptrTy, nullptr);
1786 SmallVector<GlobalVariable *, 16> NewGlobals(n);
1787 SmallVector<Constant *, 16> Initializers(n);
1789 bool HasDynamicallyInitializedGlobals = false;
1791 // We shouldn't merge same module names, as this string serves as unique
1792 // module ID in runtime.
1793 GlobalVariable *ModuleName = createPrivateGlobalForString(
1794 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
1796 for (size_t i = 0; i < n; i++) {
1797 static const uint64_t kMaxGlobalRedzone = 1 << 18;
1798 GlobalVariable *G = GlobalsToChange[i];
1800 auto MD = GlobalsMD.get(G);
1801 StringRef NameForGlobal = G->getName();
1802 // Create string holding the global name (use global name from metadata
1803 // if it's available, otherwise just write the name of global variable).
1804 GlobalVariable *Name = createPrivateGlobalForString(
1805 M, MD.Name.empty() ? NameForGlobal : MD.Name,
1806 /*AllowMerging*/ true);
1808 Type *Ty = G->getValueType();
1809 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
1810 uint64_t MinRZ = MinRedzoneSizeForGlobal();
1811 // MinRZ <= RZ <= kMaxGlobalRedzone
1812 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
1813 uint64_t RZ = std::max(
1814 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
1815 uint64_t RightRedzoneSize = RZ;
1816 // Round up to MinRZ
1817 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
1818 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
1819 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1821 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
1822 Constant *NewInitializer =
1823 ConstantStruct::get(NewTy, G->getInitializer(),
1824 Constant::getNullValue(RightRedZoneTy), nullptr);
1826 // Create a new global variable with enough space for a redzone.
1827 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1828 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1829 Linkage = GlobalValue::InternalLinkage;
1830 GlobalVariable *NewGlobal =
1831 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1832 "", G, G->getThreadLocalMode());
1833 NewGlobal->copyAttributesFrom(G);
1834 NewGlobal->setAlignment(MinRZ);
1836 // Move null-terminated C strings to "__asan_cstring" section on Darwin.
1837 if (TargetTriple.isOSBinFormatMachO() && !G->hasSection() &&
1839 auto Seq = dyn_cast<ConstantDataSequential>(G->getInitializer());
1840 if (Seq && Seq->isCString())
1841 NewGlobal->setSection("__TEXT,__asan_cstring,regular");
1844 // Transfer the debug info. The payload starts at offset zero so we can
1845 // copy the debug info over as is.
1846 SmallVector<DIGlobalVariableExpression *, 1> GVs;
1847 G->getDebugInfo(GVs);
1848 for (auto *GV : GVs)
1849 NewGlobal->addDebugInfo(GV);
1852 Indices2[0] = IRB.getInt32(0);
1853 Indices2[1] = IRB.getInt32(0);
1855 G->replaceAllUsesWith(
1856 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
1857 NewGlobal->takeName(G);
1858 G->eraseFromParent();
1859 NewGlobals[i] = NewGlobal;
1861 Constant *SourceLoc;
1862 if (!MD.SourceLoc.empty()) {
1863 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1864 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1866 SourceLoc = ConstantInt::get(IntptrTy, 0);
1869 Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
1870 GlobalValue *InstrumentedGlobal = NewGlobal;
1872 bool CanUsePrivateAliases =
1873 TargetTriple.isOSBinFormatELF() || TargetTriple.isOSBinFormatMachO() ||
1874 TargetTriple.isOSBinFormatWasm();
1875 if (CanUsePrivateAliases && ClUsePrivateAliasForGlobals) {
1876 // Create local alias for NewGlobal to avoid crash on ODR between
1877 // instrumented and non-instrumented libraries.
1878 auto *GA = GlobalAlias::create(GlobalValue::InternalLinkage,
1879 NameForGlobal + M.getName(), NewGlobal);
1881 // With local aliases, we need to provide another externally visible
1882 // symbol __odr_asan_XXX to detect ODR violation.
1883 auto *ODRIndicatorSym =
1884 new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
1885 Constant::getNullValue(IRB.getInt8Ty()),
1886 kODRGenPrefix + NameForGlobal, nullptr,
1887 NewGlobal->getThreadLocalMode());
1889 // Set meaningful attributes for indicator symbol.
1890 ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
1891 ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
1892 ODRIndicatorSym->setAlignment(1);
1893 ODRIndicator = ODRIndicatorSym;
1894 InstrumentedGlobal = GA;
1897 Constant *Initializer = ConstantStruct::get(
1899 ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
1900 ConstantInt::get(IntptrTy, SizeInBytes),
1901 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1902 ConstantExpr::getPointerCast(Name, IntptrTy),
1903 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
1904 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
1905 ConstantExpr::getPointerCast(ODRIndicator, IntptrTy), nullptr);
1907 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
1909 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
1911 Initializers[i] = Initializer;
1914 if (TargetTriple.isOSBinFormatCOFF()) {
1915 InstrumentGlobalsCOFF(IRB, M, NewGlobals, Initializers);
1916 } else if (ShouldUseMachOGlobalsSection()) {
1917 InstrumentGlobalsMachO(IRB, M, NewGlobals, Initializers);
1919 InstrumentGlobalsWithMetadataArray(IRB, M, NewGlobals, Initializers);
1922 // Create calls for poisoning before initializers run and unpoisoning after.
1923 if (HasDynamicallyInitializedGlobals)
1924 createInitializerPoisonCalls(M, ModuleName);
1930 bool AddressSanitizerModule::runOnModule(Module &M) {
1931 C = &(M.getContext());
1932 int LongSize = M.getDataLayout().getPointerSizeInBits();
1933 IntptrTy = Type::getIntNTy(*C, LongSize);
1934 TargetTriple = Triple(M.getTargetTriple());
1935 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
1936 initializeCallbacks(M);
1941 Function *AsanCtorFunction;
1942 std::tie(AsanCtorFunction, std::ignore) = createSanitizerCtorAndInitFunctions(
1943 M, kAsanModuleCtorName, kAsanInitName, /*InitArgTypes=*/{},
1944 /*InitArgs=*/{}, kAsanVersionCheckName);
1945 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
1947 bool Changed = false;
1948 // TODO(glider): temporarily disabled globals instrumentation for KASan.
1950 IRBuilder<> IRB(AsanCtorFunction->getEntryBlock().getTerminator());
1951 Changed |= InstrumentGlobals(IRB, M);
1957 void AddressSanitizer::initializeCallbacks(Module &M) {
1958 IRBuilder<> IRB(*C);
1959 // Create __asan_report* callbacks.
1960 // IsWrite, TypeSize and Exp are encoded in the function name.
1961 for (int Exp = 0; Exp < 2; Exp++) {
1962 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1963 const std::string TypeStr = AccessIsWrite ? "store" : "load";
1964 const std::string ExpStr = Exp ? "exp_" : "";
1965 const std::string SuffixStr = CompileKernel ? "N" : "_n";
1966 const std::string EndingStr = Recover ? "_noabort" : "";
1968 SmallVector<Type *, 3> Args2 = {IntptrTy, IntptrTy};
1969 SmallVector<Type *, 2> Args1{1, IntptrTy};
1971 Type *ExpType = Type::getInt32Ty(*C);
1972 Args2.push_back(ExpType);
1973 Args1.push_back(ExpType);
1975 AsanErrorCallbackSized[AccessIsWrite][Exp] =
1976 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1977 kAsanReportErrorTemplate + ExpStr + TypeStr + SuffixStr +
1979 FunctionType::get(IRB.getVoidTy(), Args2, false)));
1981 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
1982 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1983 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
1984 FunctionType::get(IRB.getVoidTy(), Args2, false)));
1986 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1987 AccessSizeIndex++) {
1988 const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
1989 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
1990 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1991 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
1992 FunctionType::get(IRB.getVoidTy(), Args1, false)));
1994 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
1995 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1996 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
1997 FunctionType::get(IRB.getVoidTy(), Args1, false)));
2002 const std::string MemIntrinCallbackPrefix =
2003 CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
2004 AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2005 MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
2006 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy));
2007 AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2008 MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
2009 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy));
2010 AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2011 MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
2012 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy));
2014 AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
2015 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy()));
2017 AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2018 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy));
2019 AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2020 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy));
2021 // We insert an empty inline asm after __asan_report* to avoid callback merge.
2022 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
2023 StringRef(""), StringRef(""),
2024 /*hasSideEffects=*/true);
2028 bool AddressSanitizer::doInitialization(Module &M) {
2029 // Initialize the private fields. No one has accessed them before.
2032 C = &(M.getContext());
2033 LongSize = M.getDataLayout().getPointerSizeInBits();
2034 IntptrTy = Type::getIntNTy(*C, LongSize);
2035 TargetTriple = Triple(M.getTargetTriple());
2037 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
2041 bool AddressSanitizer::doFinalization(Module &M) {
2046 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
2047 // For each NSObject descendant having a +load method, this method is invoked
2048 // by the ObjC runtime before any of the static constructors is called.
2049 // Therefore we need to instrument such methods with a call to __asan_init
2050 // at the beginning in order to initialize our runtime before any access to
2051 // the shadow memory.
2052 // We cannot just ignore these methods, because they may call other
2053 // instrumented functions.
2054 if (F.getName().find(" load]") != std::string::npos) {
2055 Function *AsanInitFunction =
2056 declareSanitizerInitFunction(*F.getParent(), kAsanInitName, {});
2057 IRBuilder<> IRB(&F.front(), F.front().begin());
2058 IRB.CreateCall(AsanInitFunction, {});
2064 void AddressSanitizer::maybeInsertDynamicShadowAtFunctionEntry(Function &F) {
2065 // Generate code only when dynamic addressing is needed.
2066 if (Mapping.Offset != kDynamicShadowSentinel)
2069 IRBuilder<> IRB(&F.front().front());
2070 Value *GlobalDynamicAddress = F.getParent()->getOrInsertGlobal(
2071 kAsanShadowMemoryDynamicAddress, IntptrTy);
2072 LocalDynamicShadow = IRB.CreateLoad(GlobalDynamicAddress);
2075 void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
2076 // Find the one possible call to llvm.localescape and pre-mark allocas passed
2077 // to it as uninteresting. This assumes we haven't started processing allocas
2078 // yet. This check is done up front because iterating the use list in
2079 // isInterestingAlloca would be algorithmically slower.
2080 assert(ProcessedAllocas.empty() && "must process localescape before allocas");
2082 // Try to get the declaration of llvm.localescape. If it's not in the module,
2083 // we can exit early.
2084 if (!F.getParent()->getFunction("llvm.localescape")) return;
2086 // Look for a call to llvm.localescape call in the entry block. It can't be in
2088 for (Instruction &I : F.getEntryBlock()) {
2089 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
2090 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
2091 // We found a call. Mark all the allocas passed in as uninteresting.
2092 for (Value *Arg : II->arg_operands()) {
2093 AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
2094 assert(AI && AI->isStaticAlloca() &&
2095 "non-static alloca arg to localescape");
2096 ProcessedAllocas[AI] = false;
2103 bool AddressSanitizer::runOnFunction(Function &F) {
2104 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
2105 if (!ClDebugFunc.empty() && ClDebugFunc == F.getName()) return false;
2106 if (F.getName().startswith("__asan_")) return false;
2108 bool FunctionModified = false;
2110 // If needed, insert __asan_init before checking for SanitizeAddress attr.
2111 // This function needs to be called even if the function body is not
2113 if (maybeInsertAsanInitAtFunctionEntry(F))
2114 FunctionModified = true;
2116 // Leave if the function doesn't need instrumentation.
2117 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return FunctionModified;
2119 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
2121 initializeCallbacks(*F.getParent());
2122 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2124 FunctionStateRAII CleanupObj(this);
2126 maybeInsertDynamicShadowAtFunctionEntry(F);
2128 // We can't instrument allocas used with llvm.localescape. Only static allocas
2129 // can be passed to that intrinsic.
2130 markEscapedLocalAllocas(F);
2132 // We want to instrument every address only once per basic block (unless there
2133 // are calls between uses).
2134 SmallSet<Value *, 16> TempsToInstrument;
2135 SmallVector<Instruction *, 16> ToInstrument;
2136 SmallVector<Instruction *, 8> NoReturnCalls;
2137 SmallVector<BasicBlock *, 16> AllBlocks;
2138 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
2143 const TargetLibraryInfo *TLI =
2144 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
2146 // Fill the set of memory operations to instrument.
2147 for (auto &BB : F) {
2148 AllBlocks.push_back(&BB);
2149 TempsToInstrument.clear();
2150 int NumInsnsPerBB = 0;
2151 for (auto &Inst : BB) {
2152 if (LooksLikeCodeInBug11395(&Inst)) return false;
2153 Value *MaybeMask = nullptr;
2154 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
2155 &Alignment, &MaybeMask)) {
2156 if (ClOpt && ClOptSameTemp) {
2157 // If we have a mask, skip instrumentation if we've already
2158 // instrumented the full object. But don't add to TempsToInstrument
2159 // because we might get another load/store with a different mask.
2161 if (TempsToInstrument.count(Addr))
2162 continue; // We've seen this (whole) temp in the current BB.
2164 if (!TempsToInstrument.insert(Addr).second)
2165 continue; // We've seen this temp in the current BB.
2168 } else if (ClInvalidPointerPairs &&
2169 isInterestingPointerComparisonOrSubtraction(&Inst)) {
2170 PointerComparisonsOrSubtracts.push_back(&Inst);
2172 } else if (isa<MemIntrinsic>(Inst)) {
2175 if (isa<AllocaInst>(Inst)) NumAllocas++;
2178 // A call inside BB.
2179 TempsToInstrument.clear();
2180 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
2182 if (CallInst *CI = dyn_cast<CallInst>(&Inst))
2183 maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
2186 ToInstrument.push_back(&Inst);
2188 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
2194 (ClInstrumentationWithCallsThreshold >= 0 &&
2195 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
2196 const DataLayout &DL = F.getParent()->getDataLayout();
2197 ObjectSizeOpts ObjSizeOpts;
2198 ObjSizeOpts.RoundToAlign = true;
2199 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(), ObjSizeOpts);
2202 int NumInstrumented = 0;
2203 for (auto Inst : ToInstrument) {
2204 if (ClDebugMin < 0 || ClDebugMax < 0 ||
2205 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
2206 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
2207 instrumentMop(ObjSizeVis, Inst, UseCalls,
2208 F.getParent()->getDataLayout());
2210 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
2215 FunctionStackPoisoner FSP(F, *this);
2216 bool ChangedStack = FSP.runOnFunction();
2218 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
2219 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
2220 for (auto CI : NoReturnCalls) {
2221 IRBuilder<> IRB(CI);
2222 IRB.CreateCall(AsanHandleNoReturnFunc, {});
2225 for (auto Inst : PointerComparisonsOrSubtracts) {
2226 instrumentPointerComparisonOrSubtraction(Inst);
2230 if (NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty())
2231 FunctionModified = true;
2233 DEBUG(dbgs() << "ASAN done instrumenting: " << FunctionModified << " "
2236 return FunctionModified;
2239 // Workaround for bug 11395: we don't want to instrument stack in functions
2240 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
2241 // FIXME: remove once the bug 11395 is fixed.
2242 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
2243 if (LongSize != 32) return false;
2244 CallInst *CI = dyn_cast<CallInst>(I);
2245 if (!CI || !CI->isInlineAsm()) return false;
2246 if (CI->getNumArgOperands() <= 5) return false;
2247 // We have inline assembly with quite a few arguments.
2251 void FunctionStackPoisoner::initializeCallbacks(Module &M) {
2252 IRBuilder<> IRB(*C);
2253 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
2254 std::string Suffix = itostr(i);
2255 AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
2256 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
2258 AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
2259 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
2260 IRB.getVoidTy(), IntptrTy, IntptrTy));
2262 if (ASan.UseAfterScope) {
2263 AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2264 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
2265 IntptrTy, IntptrTy));
2266 AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2267 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
2268 IntptrTy, IntptrTy));
2271 for (size_t Val : {0x00, 0xf1, 0xf2, 0xf3, 0xf5, 0xf8}) {
2272 std::ostringstream Name;
2273 Name << kAsanSetShadowPrefix;
2274 Name << std::setw(2) << std::setfill('0') << std::hex << Val;
2275 AsanSetShadowFunc[Val] =
2276 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2277 Name.str(), IRB.getVoidTy(), IntptrTy, IntptrTy));
2280 AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2281 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy));
2282 AsanAllocasUnpoisonFunc =
2283 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2284 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy));
2287 void FunctionStackPoisoner::copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
2288 ArrayRef<uint8_t> ShadowBytes,
2289 size_t Begin, size_t End,
2291 Value *ShadowBase) {
2295 const size_t LargestStoreSizeInBytes =
2296 std::min<size_t>(sizeof(uint64_t), ASan.LongSize / 8);
2298 const bool IsLittleEndian = F.getParent()->getDataLayout().isLittleEndian();
2300 // Poison given range in shadow using larges store size with out leading and
2301 // trailing zeros in ShadowMask. Zeros never change, so they need neither
2302 // poisoning nor up-poisoning. Still we don't mind if some of them get into a
2303 // middle of a store.
2304 for (size_t i = Begin; i < End;) {
2305 if (!ShadowMask[i]) {
2306 assert(!ShadowBytes[i]);
2311 size_t StoreSizeInBytes = LargestStoreSizeInBytes;
2312 // Fit store size into the range.
2313 while (StoreSizeInBytes > End - i)
2314 StoreSizeInBytes /= 2;
2316 // Minimize store size by trimming trailing zeros.
2317 for (size_t j = StoreSizeInBytes - 1; j && !ShadowMask[i + j]; --j) {
2318 while (j <= StoreSizeInBytes / 2)
2319 StoreSizeInBytes /= 2;
2323 for (size_t j = 0; j < StoreSizeInBytes; j++) {
2325 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
2327 Val = (Val << 8) | ShadowBytes[i + j];
2330 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
2331 Value *Poison = IRB.getIntN(StoreSizeInBytes * 8, Val);
2332 IRB.CreateAlignedStore(
2333 Poison, IRB.CreateIntToPtr(Ptr, Poison->getType()->getPointerTo()), 1);
2335 i += StoreSizeInBytes;
2339 void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2340 ArrayRef<uint8_t> ShadowBytes,
2341 IRBuilder<> &IRB, Value *ShadowBase) {
2342 copyToShadow(ShadowMask, ShadowBytes, 0, ShadowMask.size(), IRB, ShadowBase);
2345 void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2346 ArrayRef<uint8_t> ShadowBytes,
2347 size_t Begin, size_t End,
2348 IRBuilder<> &IRB, Value *ShadowBase) {
2349 assert(ShadowMask.size() == ShadowBytes.size());
2350 size_t Done = Begin;
2351 for (size_t i = Begin, j = Begin + 1; i < End; i = j++) {
2352 if (!ShadowMask[i]) {
2353 assert(!ShadowBytes[i]);
2356 uint8_t Val = ShadowBytes[i];
2357 if (!AsanSetShadowFunc[Val])
2360 // Skip same values.
2361 for (; j < End && ShadowMask[j] && Val == ShadowBytes[j]; ++j) {
2364 if (j - i >= ClMaxInlinePoisoningSize) {
2365 copyToShadowInline(ShadowMask, ShadowBytes, Done, i, IRB, ShadowBase);
2366 IRB.CreateCall(AsanSetShadowFunc[Val],
2367 {IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i)),
2368 ConstantInt::get(IntptrTy, j - i)});
2373 copyToShadowInline(ShadowMask, ShadowBytes, Done, End, IRB, ShadowBase);
2376 // Fake stack allocator (asan_fake_stack.h) has 11 size classes
2377 // for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
2378 static int StackMallocSizeClass(uint64_t LocalStackSize) {
2379 assert(LocalStackSize <= kMaxStackMallocSize);
2380 uint64_t MaxSize = kMinStackMallocSize;
2381 for (int i = 0;; i++, MaxSize *= 2)
2382 if (LocalStackSize <= MaxSize) return i;
2383 llvm_unreachable("impossible LocalStackSize");
2386 PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
2388 Instruction *ThenTerm,
2389 Value *ValueIfFalse) {
2390 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
2391 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
2392 PHI->addIncoming(ValueIfFalse, CondBlock);
2393 BasicBlock *ThenBlock = ThenTerm->getParent();
2394 PHI->addIncoming(ValueIfTrue, ThenBlock);
2398 Value *FunctionStackPoisoner::createAllocaForLayout(
2399 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
2402 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
2403 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
2406 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
2407 nullptr, "MyAlloca");
2408 assert(Alloca->isStaticAlloca());
2410 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
2411 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
2412 Alloca->setAlignment(FrameAlignment);
2413 return IRB.CreatePointerCast(Alloca, IntptrTy);
2416 void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
2417 BasicBlock &FirstBB = *F.begin();
2418 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
2419 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
2420 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
2421 DynamicAllocaLayout->setAlignment(32);
2424 void FunctionStackPoisoner::processDynamicAllocas() {
2425 if (!ClInstrumentDynamicAllocas || DynamicAllocaVec.empty()) {
2426 assert(DynamicAllocaPoisonCallVec.empty());
2430 // Insert poison calls for lifetime intrinsics for dynamic allocas.
2431 for (const auto &APC : DynamicAllocaPoisonCallVec) {
2432 assert(APC.InsBefore);
2434 assert(ASan.isInterestingAlloca(*APC.AI));
2435 assert(!APC.AI->isStaticAlloca());
2437 IRBuilder<> IRB(APC.InsBefore);
2438 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
2439 // Dynamic allocas will be unpoisoned unconditionally below in
2440 // unpoisonDynamicAllocas.
2441 // Flag that we need unpoison static allocas.
2444 // Handle dynamic allocas.
2445 createDynamicAllocasInitStorage();
2446 for (auto &AI : DynamicAllocaVec)
2447 handleDynamicAllocaCall(AI);
2448 unpoisonDynamicAllocas();
2451 void FunctionStackPoisoner::processStaticAllocas() {
2452 if (AllocaVec.empty()) {
2453 assert(StaticAllocaPoisonCallVec.empty());
2457 int StackMallocIdx = -1;
2458 DebugLoc EntryDebugLocation;
2459 if (auto SP = F.getSubprogram())
2460 EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
2462 Instruction *InsBefore = AllocaVec[0];
2463 IRBuilder<> IRB(InsBefore);
2464 IRB.SetCurrentDebugLocation(EntryDebugLocation);
2466 // Make sure non-instrumented allocas stay in the entry block. Otherwise,
2467 // debug info is broken, because only entry-block allocas are treated as
2468 // regular stack slots.
2469 auto InsBeforeB = InsBefore->getParent();
2470 assert(InsBeforeB == &F.getEntryBlock());
2471 for (auto *AI : StaticAllocasToMoveUp)
2472 if (AI->getParent() == InsBeforeB)
2473 AI->moveBefore(InsBefore);
2475 // If we have a call to llvm.localescape, keep it in the entry block.
2476 if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
2478 SmallVector<ASanStackVariableDescription, 16> SVD;
2479 SVD.reserve(AllocaVec.size());
2480 for (AllocaInst *AI : AllocaVec) {
2481 ASanStackVariableDescription D = {AI->getName().data(),
2482 ASan.getAllocaSizeInBytes(*AI),
2491 // Minimal header size (left redzone) is 4 pointers,
2492 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
2493 size_t MinHeaderSize = ASan.LongSize / 2;
2494 const ASanStackFrameLayout &L =
2495 ComputeASanStackFrameLayout(SVD, 1ULL << Mapping.Scale, MinHeaderSize);
2497 // Build AllocaToSVDMap for ASanStackVariableDescription lookup.
2498 DenseMap<const AllocaInst *, ASanStackVariableDescription *> AllocaToSVDMap;
2499 for (auto &Desc : SVD)
2500 AllocaToSVDMap[Desc.AI] = &Desc;
2502 // Update SVD with information from lifetime intrinsics.
2503 for (const auto &APC : StaticAllocaPoisonCallVec) {
2504 assert(APC.InsBefore);
2506 assert(ASan.isInterestingAlloca(*APC.AI));
2507 assert(APC.AI->isStaticAlloca());
2509 ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
2510 Desc.LifetimeSize = Desc.Size;
2511 if (const DILocation *FnLoc = EntryDebugLocation.get()) {
2512 if (const DILocation *LifetimeLoc = APC.InsBefore->getDebugLoc().get()) {
2513 if (LifetimeLoc->getFile() == FnLoc->getFile())
2514 if (unsigned Line = LifetimeLoc->getLine())
2515 Desc.Line = std::min(Desc.Line ? Desc.Line : Line, Line);
2520 auto DescriptionString = ComputeASanStackFrameDescription(SVD);
2521 DEBUG(dbgs() << DescriptionString << " --- " << L.FrameSize << "\n");
2522 uint64_t LocalStackSize = L.FrameSize;
2523 bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
2524 LocalStackSize <= kMaxStackMallocSize;
2525 bool DoDynamicAlloca = ClDynamicAllocaStack;
2526 // Don't do dynamic alloca or stack malloc if:
2527 // 1) There is inline asm: too often it makes assumptions on which registers
2529 // 2) There is a returns_twice call (typically setjmp), which is
2530 // optimization-hostile, and doesn't play well with introduced indirect
2531 // register-relative calculation of local variable addresses.
2532 DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2533 DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2535 Value *StaticAlloca =
2536 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
2539 Value *LocalStackBase;
2541 if (DoStackMalloc) {
2542 // void *FakeStack = __asan_option_detect_stack_use_after_return
2543 // ? __asan_stack_malloc_N(LocalStackSize)
2545 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
2546 Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
2547 kAsanOptionDetectUseAfterReturn, IRB.getInt32Ty());
2548 Value *UseAfterReturnIsEnabled =
2549 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUseAfterReturn),
2550 Constant::getNullValue(IRB.getInt32Ty()));
2552 SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
2553 IRBuilder<> IRBIf(Term);
2554 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2555 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
2556 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
2557 Value *FakeStackValue =
2558 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
2559 ConstantInt::get(IntptrTy, LocalStackSize));
2560 IRB.SetInsertPoint(InsBefore);
2561 IRB.SetCurrentDebugLocation(EntryDebugLocation);
2562 FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
2563 ConstantInt::get(IntptrTy, 0));
2565 Value *NoFakeStack =
2566 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
2567 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
2568 IRBIf.SetInsertPoint(Term);
2569 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2570 Value *AllocaValue =
2571 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
2572 IRB.SetInsertPoint(InsBefore);
2573 IRB.SetCurrentDebugLocation(EntryDebugLocation);
2574 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
2576 // void *FakeStack = nullptr;
2577 // void *LocalStackBase = alloca(LocalStackSize);
2578 FakeStack = ConstantInt::get(IntptrTy, 0);
2580 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
2583 // Replace Alloca instructions with base+offset.
2584 for (const auto &Desc : SVD) {
2585 AllocaInst *AI = Desc.AI;
2586 Value *NewAllocaPtr = IRB.CreateIntToPtr(
2587 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
2589 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/false);
2590 AI->replaceAllUsesWith(NewAllocaPtr);
2593 // The left-most redzone has enough space for at least 4 pointers.
2594 // Write the Magic value to redzone[0].
2595 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
2596 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
2598 // Write the frame description constant to redzone[1].
2599 Value *BasePlus1 = IRB.CreateIntToPtr(
2600 IRB.CreateAdd(LocalStackBase,
2601 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
2603 GlobalVariable *StackDescriptionGlobal =
2604 createPrivateGlobalForString(*F.getParent(), DescriptionString,
2605 /*AllowMerging*/ true);
2606 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
2607 IRB.CreateStore(Description, BasePlus1);
2608 // Write the PC to redzone[2].
2609 Value *BasePlus2 = IRB.CreateIntToPtr(
2610 IRB.CreateAdd(LocalStackBase,
2611 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
2613 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
2615 const auto &ShadowAfterScope = GetShadowBytesAfterScope(SVD, L);
2617 // Poison the stack red zones at the entry.
2618 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
2619 // As mask we must use most poisoned case: red zones and after scope.
2620 // As bytes we can use either the same or just red zones only.
2621 copyToShadow(ShadowAfterScope, ShadowAfterScope, IRB, ShadowBase);
2623 if (!StaticAllocaPoisonCallVec.empty()) {
2624 const auto &ShadowInScope = GetShadowBytes(SVD, L);
2626 // Poison static allocas near lifetime intrinsics.
2627 for (const auto &APC : StaticAllocaPoisonCallVec) {
2628 const ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
2629 assert(Desc.Offset % L.Granularity == 0);
2630 size_t Begin = Desc.Offset / L.Granularity;
2631 size_t End = Begin + (APC.Size + L.Granularity - 1) / L.Granularity;
2633 IRBuilder<> IRB(APC.InsBefore);
2634 copyToShadow(ShadowAfterScope,
2635 APC.DoPoison ? ShadowAfterScope : ShadowInScope, Begin, End,
2640 SmallVector<uint8_t, 64> ShadowClean(ShadowAfterScope.size(), 0);
2641 SmallVector<uint8_t, 64> ShadowAfterReturn;
2643 // (Un)poison the stack before all ret instructions.
2644 for (auto Ret : RetVec) {
2645 IRBuilder<> IRBRet(Ret);
2646 // Mark the current frame as retired.
2647 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
2649 if (DoStackMalloc) {
2650 assert(StackMallocIdx >= 0);
2651 // if FakeStack != 0 // LocalStackBase == FakeStack
2652 // // In use-after-return mode, poison the whole stack frame.
2653 // if StackMallocIdx <= 4
2654 // // For small sizes inline the whole thing:
2655 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
2656 // **SavedFlagPtr(FakeStack) = 0
2658 // __asan_stack_free_N(FakeStack, LocalStackSize)
2660 // <This is not a fake stack; unpoison the redzones>
2662 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
2663 TerminatorInst *ThenTerm, *ElseTerm;
2664 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
2666 IRBuilder<> IRBPoison(ThenTerm);
2667 if (StackMallocIdx <= 4) {
2668 int ClassSize = kMinStackMallocSize << StackMallocIdx;
2669 ShadowAfterReturn.resize(ClassSize / L.Granularity,
2670 kAsanStackUseAfterReturnMagic);
2671 copyToShadow(ShadowAfterReturn, ShadowAfterReturn, IRBPoison,
2673 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
2675 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
2676 Value *SavedFlagPtr = IRBPoison.CreateLoad(
2677 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
2678 IRBPoison.CreateStore(
2679 Constant::getNullValue(IRBPoison.getInt8Ty()),
2680 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
2682 // For larger frames call __asan_stack_free_*.
2683 IRBPoison.CreateCall(
2684 AsanStackFreeFunc[StackMallocIdx],
2685 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
2688 IRBuilder<> IRBElse(ElseTerm);
2689 copyToShadow(ShadowAfterScope, ShadowClean, IRBElse, ShadowBase);
2691 copyToShadow(ShadowAfterScope, ShadowClean, IRBRet, ShadowBase);
2695 // We are done. Remove the old unused alloca instructions.
2696 for (auto AI : AllocaVec) AI->eraseFromParent();
2699 void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
2700 IRBuilder<> &IRB, bool DoPoison) {
2701 // For now just insert the call to ASan runtime.
2702 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
2703 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
2705 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
2706 {AddrArg, SizeArg});
2709 // Handling llvm.lifetime intrinsics for a given %alloca:
2710 // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
2711 // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
2712 // invalid accesses) and unpoison it for llvm.lifetime.start (the memory
2713 // could be poisoned by previous llvm.lifetime.end instruction, as the
2714 // variable may go in and out of scope several times, e.g. in loops).
2715 // (3) if we poisoned at least one %alloca in a function,
2716 // unpoison the whole stack frame at function exit.
2718 AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
2719 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
2720 // We're interested only in allocas we can handle.
2721 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
2722 // See if we've already calculated (or started to calculate) alloca for a
2724 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
2725 if (I != AllocaForValue.end()) return I->second;
2726 // Store 0 while we're calculating alloca for value V to avoid
2727 // infinite recursion if the value references itself.
2728 AllocaForValue[V] = nullptr;
2729 AllocaInst *Res = nullptr;
2730 if (CastInst *CI = dyn_cast<CastInst>(V))
2731 Res = findAllocaForValue(CI->getOperand(0));
2732 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
2733 for (Value *IncValue : PN->incoming_values()) {
2734 // Allow self-referencing phi-nodes.
2735 if (IncValue == PN) continue;
2736 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
2737 // AI for incoming values should exist and should all be equal.
2738 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
2742 } else if (GetElementPtrInst *EP = dyn_cast<GetElementPtrInst>(V)) {
2743 Res = findAllocaForValue(EP->getPointerOperand());
2745 DEBUG(dbgs() << "Alloca search canceled on unknown instruction: " << *V << "\n");
2747 if (Res) AllocaForValue[V] = Res;
2751 void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
2752 IRBuilder<> IRB(AI);
2754 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
2755 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
2757 Value *Zero = Constant::getNullValue(IntptrTy);
2758 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
2759 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
2761 // Since we need to extend alloca with additional memory to locate
2762 // redzones, and OldSize is number of allocated blocks with
2763 // ElementSize size, get allocated memory size in bytes by
2764 // OldSize * ElementSize.
2765 const unsigned ElementSize =
2766 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
2768 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
2769 ConstantInt::get(IntptrTy, ElementSize));
2771 // PartialSize = OldSize % 32
2772 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
2774 // Misalign = kAllocaRzSize - PartialSize;
2775 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
2777 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
2778 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
2779 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
2781 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
2782 // Align is added to locate left redzone, PartialPadding for possible
2783 // partial redzone and kAllocaRzSize for right redzone respectively.
2784 Value *AdditionalChunkSize = IRB.CreateAdd(
2785 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
2787 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
2789 // Insert new alloca with new NewSize and Align params.
2790 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
2791 NewAlloca->setAlignment(Align);
2793 // NewAddress = Address + Align
2794 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
2795 ConstantInt::get(IntptrTy, Align));
2797 // Insert __asan_alloca_poison call for new created alloca.
2798 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
2800 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
2801 // for unpoisoning stuff.
2802 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
2804 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2806 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
2807 AI->replaceAllUsesWith(NewAddressPtr);
2809 // We are done. Erase old alloca from parent.
2810 AI->eraseFromParent();
2813 // isSafeAccess returns true if Addr is always inbounds with respect to its
2814 // base object. For example, it is a field access or an array access with
2815 // constant inbounds index.
2816 bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
2817 Value *Addr, uint64_t TypeSize) const {
2818 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
2819 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
2820 uint64_t Size = SizeOffset.first.getZExtValue();
2821 int64_t Offset = SizeOffset.second.getSExtValue();
2822 // Three checks are required to ensure safety:
2823 // . Offset >= 0 (since the offset is given from the base ptr)
2824 // . Size >= Offset (unsigned)
2825 // . Size - Offset >= NeededSize (unsigned)
2826 return Offset >= 0 && Size >= uint64_t(Offset) &&
2827 Size - uint64_t(Offset) >= TypeSize / 8;