1 //===- AddressSanitizer.cpp - memory error detector -----------------------===//
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 // https://github.com/google/sanitizers/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/SmallSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Analysis/MemoryBuiltins.h"
27 #include "llvm/Analysis/TargetLibraryInfo.h"
28 #include "llvm/Transforms/Utils/Local.h"
29 #include "llvm/Analysis/ValueTracking.h"
30 #include "llvm/BinaryFormat/MachO.h"
31 #include "llvm/IR/Argument.h"
32 #include "llvm/IR/Attributes.h"
33 #include "llvm/IR/BasicBlock.h"
34 #include "llvm/IR/CallSite.h"
35 #include "llvm/IR/Comdat.h"
36 #include "llvm/IR/Constant.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/DIBuilder.h"
39 #include "llvm/IR/DataLayout.h"
40 #include "llvm/IR/DebugInfoMetadata.h"
41 #include "llvm/IR/DebugLoc.h"
42 #include "llvm/IR/DerivedTypes.h"
43 #include "llvm/IR/Dominators.h"
44 #include "llvm/IR/Function.h"
45 #include "llvm/IR/GlobalAlias.h"
46 #include "llvm/IR/GlobalValue.h"
47 #include "llvm/IR/GlobalVariable.h"
48 #include "llvm/IR/IRBuilder.h"
49 #include "llvm/IR/InlineAsm.h"
50 #include "llvm/IR/InstVisitor.h"
51 #include "llvm/IR/InstrTypes.h"
52 #include "llvm/IR/Instruction.h"
53 #include "llvm/IR/Instructions.h"
54 #include "llvm/IR/IntrinsicInst.h"
55 #include "llvm/IR/Intrinsics.h"
56 #include "llvm/IR/LLVMContext.h"
57 #include "llvm/IR/MDBuilder.h"
58 #include "llvm/IR/Metadata.h"
59 #include "llvm/IR/Module.h"
60 #include "llvm/IR/Type.h"
61 #include "llvm/IR/Use.h"
62 #include "llvm/IR/Value.h"
63 #include "llvm/MC/MCSectionMachO.h"
64 #include "llvm/Pass.h"
65 #include "llvm/Support/Casting.h"
66 #include "llvm/Support/CommandLine.h"
67 #include "llvm/Support/Debug.h"
68 #include "llvm/Support/ErrorHandling.h"
69 #include "llvm/Support/MathExtras.h"
70 #include "llvm/Support/ScopedPrinter.h"
71 #include "llvm/Support/raw_ostream.h"
72 #include "llvm/Transforms/Instrumentation.h"
73 #include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
74 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
75 #include "llvm/Transforms/Utils/ModuleUtils.h"
76 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
90 #define DEBUG_TYPE "asan"
92 static const uint64_t kDefaultShadowScale = 3;
93 static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
94 static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
95 static const uint64_t kDynamicShadowSentinel =
96 std::numeric_limits<uint64_t>::max();
97 static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
98 static const uint64_t kIOSSimShadowOffset32 = 1ULL << 30;
99 static const uint64_t kIOSSimShadowOffset64 = kDefaultShadowOffset64;
100 static const uint64_t kSmallX86_64ShadowOffsetBase = 0x7FFFFFFF; // < 2G.
101 static const uint64_t kSmallX86_64ShadowOffsetAlignMask = ~0xFFFULL;
102 static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;
103 static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 44;
104 static const uint64_t kSystemZ_ShadowOffset64 = 1ULL << 52;
105 static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
106 static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
107 static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
108 static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
109 static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
110 static const uint64_t kNetBSD_ShadowOffset32 = 1ULL << 30;
111 static const uint64_t kNetBSD_ShadowOffset64 = 1ULL << 46;
112 static const uint64_t kPS4CPU_ShadowOffset64 = 1ULL << 40;
113 static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
115 static const uint64_t kMyriadShadowScale = 5;
116 static const uint64_t kMyriadMemoryOffset32 = 0x80000000ULL;
117 static const uint64_t kMyriadMemorySize32 = 0x20000000ULL;
118 static const uint64_t kMyriadTagShift = 29;
119 static const uint64_t kMyriadDDRTag = 4;
120 static const uint64_t kMyriadCacheBitMask32 = 0x40000000ULL;
122 // The shadow memory space is dynamically allocated.
123 static const uint64_t kWindowsShadowOffset64 = kDynamicShadowSentinel;
125 static const size_t kMinStackMallocSize = 1 << 6; // 64B
126 static const size_t kMaxStackMallocSize = 1 << 16; // 64K
127 static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
128 static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
130 static const char *const kAsanModuleCtorName = "asan.module_ctor";
131 static const char *const kAsanModuleDtorName = "asan.module_dtor";
132 static const uint64_t kAsanCtorAndDtorPriority = 1;
133 static const char *const kAsanReportErrorTemplate = "__asan_report_";
134 static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
135 static const char *const kAsanUnregisterGlobalsName =
136 "__asan_unregister_globals";
137 static const char *const kAsanRegisterImageGlobalsName =
138 "__asan_register_image_globals";
139 static const char *const kAsanUnregisterImageGlobalsName =
140 "__asan_unregister_image_globals";
141 static const char *const kAsanRegisterElfGlobalsName =
142 "__asan_register_elf_globals";
143 static const char *const kAsanUnregisterElfGlobalsName =
144 "__asan_unregister_elf_globals";
145 static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
146 static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
147 static const char *const kAsanInitName = "__asan_init";
148 static const char *const kAsanVersionCheckNamePrefix =
149 "__asan_version_mismatch_check_v";
150 static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
151 static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
152 static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
153 static const int kMaxAsanStackMallocSizeClass = 10;
154 static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
155 static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
156 static const char *const kAsanGenPrefix = "__asan_gen_";
157 static const char *const kODRGenPrefix = "__odr_asan_gen_";
158 static const char *const kSanCovGenPrefix = "__sancov_gen_";
159 static const char *const kAsanSetShadowPrefix = "__asan_set_shadow_";
160 static const char *const kAsanPoisonStackMemoryName =
161 "__asan_poison_stack_memory";
162 static const char *const kAsanUnpoisonStackMemoryName =
163 "__asan_unpoison_stack_memory";
165 // ASan version script has __asan_* wildcard. Triple underscore prevents a
166 // linker (gold) warning about attempting to export a local symbol.
167 static const char *const kAsanGlobalsRegisteredFlagName =
168 "___asan_globals_registered";
170 static const char *const kAsanOptionDetectUseAfterReturn =
171 "__asan_option_detect_stack_use_after_return";
173 static const char *const kAsanShadowMemoryDynamicAddress =
174 "__asan_shadow_memory_dynamic_address";
176 static const char *const kAsanAllocaPoison = "__asan_alloca_poison";
177 static const char *const kAsanAllocasUnpoison = "__asan_allocas_unpoison";
179 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
180 static const size_t kNumberOfAccessSizes = 5;
182 static const unsigned kAllocaRzSize = 32;
184 // Command-line flags.
186 static cl::opt<bool> ClEnableKasan(
187 "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
188 cl::Hidden, cl::init(false));
190 static cl::opt<bool> ClRecover(
192 cl::desc("Enable recovery mode (continue-after-error)."),
193 cl::Hidden, cl::init(false));
195 // This flag may need to be replaced with -f[no-]asan-reads.
196 static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
197 cl::desc("instrument read instructions"),
198 cl::Hidden, cl::init(true));
200 static cl::opt<bool> ClInstrumentWrites(
201 "asan-instrument-writes", cl::desc("instrument write instructions"),
202 cl::Hidden, cl::init(true));
204 static cl::opt<bool> ClInstrumentAtomics(
205 "asan-instrument-atomics",
206 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
209 static cl::opt<bool> ClAlwaysSlowPath(
210 "asan-always-slow-path",
211 cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
214 static cl::opt<bool> ClForceDynamicShadow(
215 "asan-force-dynamic-shadow",
216 cl::desc("Load shadow address into a local variable for each function"),
217 cl::Hidden, cl::init(false));
220 ClWithIfunc("asan-with-ifunc",
221 cl::desc("Access dynamic shadow through an ifunc global on "
222 "platforms that support this"),
223 cl::Hidden, cl::init(true));
225 static cl::opt<bool> ClWithIfuncSuppressRemat(
226 "asan-with-ifunc-suppress-remat",
227 cl::desc("Suppress rematerialization of dynamic shadow address by passing "
228 "it through inline asm in prologue."),
229 cl::Hidden, cl::init(true));
231 // This flag limits the number of instructions to be instrumented
232 // in any given BB. Normally, this should be set to unlimited (INT_MAX),
233 // but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
235 static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
236 "asan-max-ins-per-bb", cl::init(10000),
237 cl::desc("maximal number of instructions to instrument in any given BB"),
240 // This flag may need to be replaced with -f[no]asan-stack.
241 static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
242 cl::Hidden, cl::init(true));
243 static cl::opt<uint32_t> ClMaxInlinePoisoningSize(
244 "asan-max-inline-poisoning-size",
246 "Inline shadow poisoning for blocks up to the given size in bytes."),
247 cl::Hidden, cl::init(64));
249 static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
250 cl::desc("Check stack-use-after-return"),
251 cl::Hidden, cl::init(true));
253 static cl::opt<bool> ClRedzoneByvalArgs("asan-redzone-byval-args",
254 cl::desc("Create redzones for byval "
255 "arguments (extra copy "
256 "required)"), cl::Hidden,
259 static cl::opt<bool> ClUseAfterScope("asan-use-after-scope",
260 cl::desc("Check stack-use-after-scope"),
261 cl::Hidden, cl::init(false));
263 // This flag may need to be replaced with -f[no]asan-globals.
264 static cl::opt<bool> ClGlobals("asan-globals",
265 cl::desc("Handle global objects"), cl::Hidden,
268 static cl::opt<bool> ClInitializers("asan-initialization-order",
269 cl::desc("Handle C++ initializer order"),
270 cl::Hidden, cl::init(true));
272 static cl::opt<bool> ClInvalidPointerPairs(
273 "asan-detect-invalid-pointer-pair",
274 cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
277 static cl::opt<unsigned> ClRealignStack(
278 "asan-realign-stack",
279 cl::desc("Realign stack to the value of this flag (power of two)"),
280 cl::Hidden, cl::init(32));
282 static cl::opt<int> ClInstrumentationWithCallsThreshold(
283 "asan-instrumentation-with-call-threshold",
285 "If the function being instrumented contains more than "
286 "this number of memory accesses, use callbacks instead of "
287 "inline checks (-1 means never use callbacks)."),
288 cl::Hidden, cl::init(7000));
290 static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
291 "asan-memory-access-callback-prefix",
292 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
293 cl::init("__asan_"));
296 ClInstrumentDynamicAllocas("asan-instrument-dynamic-allocas",
297 cl::desc("instrument dynamic allocas"),
298 cl::Hidden, cl::init(true));
300 static cl::opt<bool> ClSkipPromotableAllocas(
301 "asan-skip-promotable-allocas",
302 cl::desc("Do not instrument promotable allocas"), cl::Hidden,
305 // These flags allow to change the shadow mapping.
306 // The shadow mapping looks like
307 // Shadow = (Mem >> scale) + offset
309 static cl::opt<int> ClMappingScale("asan-mapping-scale",
310 cl::desc("scale of asan shadow mapping"),
311 cl::Hidden, cl::init(0));
313 static cl::opt<unsigned long long> ClMappingOffset(
314 "asan-mapping-offset",
315 cl::desc("offset of asan shadow mapping [EXPERIMENTAL]"), cl::Hidden,
318 // Optimization flags. Not user visible, used mostly for testing
319 // and benchmarking the tool.
321 static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
322 cl::Hidden, cl::init(true));
324 static cl::opt<bool> ClOptSameTemp(
325 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
326 cl::Hidden, cl::init(true));
328 static cl::opt<bool> ClOptGlobals("asan-opt-globals",
329 cl::desc("Don't instrument scalar globals"),
330 cl::Hidden, cl::init(true));
332 static cl::opt<bool> ClOptStack(
333 "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
334 cl::Hidden, cl::init(false));
336 static cl::opt<bool> ClDynamicAllocaStack(
337 "asan-stack-dynamic-alloca",
338 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
341 static cl::opt<uint32_t> ClForceExperiment(
342 "asan-force-experiment",
343 cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
347 ClUsePrivateAliasForGlobals("asan-use-private-alias",
348 cl::desc("Use private aliases for global"
350 cl::Hidden, cl::init(false));
353 ClUseGlobalsGC("asan-globals-live-support",
354 cl::desc("Use linker features to support dead "
355 "code stripping of globals"),
356 cl::Hidden, cl::init(true));
358 // This is on by default even though there is a bug in gold:
359 // https://sourceware.org/bugzilla/show_bug.cgi?id=19002
361 ClWithComdat("asan-with-comdat",
362 cl::desc("Place ASan constructors in comdat sections"),
363 cl::Hidden, cl::init(true));
367 static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
370 static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
371 cl::Hidden, cl::init(0));
373 static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
374 cl::desc("Debug func"));
376 static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
377 cl::Hidden, cl::init(-1));
379 static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug max inst"),
380 cl::Hidden, cl::init(-1));
382 STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
383 STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
384 STATISTIC(NumOptimizedAccessesToGlobalVar,
385 "Number of optimized accesses to global vars");
386 STATISTIC(NumOptimizedAccessesToStackVar,
387 "Number of optimized accesses to stack vars");
391 /// Frontend-provided metadata for source location.
392 struct LocationMetadata {
397 LocationMetadata() = default;
399 bool empty() const { return Filename.empty(); }
401 void parse(MDNode *MDN) {
402 assert(MDN->getNumOperands() == 3);
403 MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
404 Filename = DIFilename->getString();
406 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
408 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
412 /// Frontend-provided metadata for global variables.
413 class GlobalsMetadata {
416 LocationMetadata SourceLoc;
418 bool IsDynInit = false;
419 bool IsBlacklisted = false;
424 GlobalsMetadata() = default;
431 void init(Module &M) {
434 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
435 if (!Globals) return;
436 for (auto MDN : Globals->operands()) {
437 // Metadata node contains the global and the fields of "Entry".
438 assert(MDN->getNumOperands() == 5);
439 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
440 // The optimizer may optimize away a global entirely.
442 // We can already have an entry for GV if it was merged with another
444 Entry &E = Entries[GV];
445 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
446 E.SourceLoc.parse(Loc);
447 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
448 E.Name = Name->getString();
449 ConstantInt *IsDynInit =
450 mdconst::extract<ConstantInt>(MDN->getOperand(3));
451 E.IsDynInit |= IsDynInit->isOne();
452 ConstantInt *IsBlacklisted =
453 mdconst::extract<ConstantInt>(MDN->getOperand(4));
454 E.IsBlacklisted |= IsBlacklisted->isOne();
458 /// Returns metadata entry for a given global.
459 Entry get(GlobalVariable *G) const {
460 auto Pos = Entries.find(G);
461 return (Pos != Entries.end()) ? Pos->second : Entry();
465 bool inited_ = false;
466 DenseMap<GlobalVariable *, Entry> Entries;
469 /// This struct defines the shadow mapping using the rule:
470 /// shadow = (mem >> Scale) ADD-or-OR Offset.
471 /// If InGlobal is true, then
472 /// extern char __asan_shadow[];
473 /// shadow = (mem >> Scale) + &__asan_shadow
474 struct ShadowMapping {
481 } // end anonymous namespace
483 static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
485 bool IsAndroid = TargetTriple.isAndroid();
486 bool IsIOS = TargetTriple.isiOS() || TargetTriple.isWatchOS();
487 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
488 bool IsNetBSD = TargetTriple.isOSNetBSD();
489 bool IsPS4CPU = TargetTriple.isPS4CPU();
490 bool IsLinux = TargetTriple.isOSLinux();
491 bool IsPPC64 = TargetTriple.getArch() == Triple::ppc64 ||
492 TargetTriple.getArch() == Triple::ppc64le;
493 bool IsSystemZ = TargetTriple.getArch() == Triple::systemz;
494 bool IsX86 = TargetTriple.getArch() == Triple::x86;
495 bool IsX86_64 = TargetTriple.getArch() == Triple::x86_64;
496 bool IsMIPS32 = TargetTriple.getArch() == Triple::mips ||
497 TargetTriple.getArch() == Triple::mipsel;
498 bool IsMIPS64 = TargetTriple.getArch() == Triple::mips64 ||
499 TargetTriple.getArch() == Triple::mips64el;
500 bool IsArmOrThumb = TargetTriple.isARM() || TargetTriple.isThumb();
501 bool IsAArch64 = TargetTriple.getArch() == Triple::aarch64;
502 bool IsWindows = TargetTriple.isOSWindows();
503 bool IsFuchsia = TargetTriple.isOSFuchsia();
504 bool IsMyriad = TargetTriple.getVendor() == llvm::Triple::Myriad;
506 ShadowMapping Mapping;
508 Mapping.Scale = IsMyriad ? kMyriadShadowScale : kDefaultShadowScale;
509 if (ClMappingScale.getNumOccurrences() > 0) {
510 Mapping.Scale = ClMappingScale;
513 if (LongSize == 32) {
515 Mapping.Offset = kDynamicShadowSentinel;
517 Mapping.Offset = kMIPS32_ShadowOffset32;
519 Mapping.Offset = kFreeBSD_ShadowOffset32;
521 Mapping.Offset = kNetBSD_ShadowOffset32;
523 // If we're targeting iOS and x86, the binary is built for iOS simulator.
524 Mapping.Offset = IsX86 ? kIOSSimShadowOffset32 : kIOSShadowOffset32;
526 Mapping.Offset = kWindowsShadowOffset32;
528 uint64_t ShadowOffset = (kMyriadMemoryOffset32 + kMyriadMemorySize32 -
529 (kMyriadMemorySize32 >> Mapping.Scale));
530 Mapping.Offset = ShadowOffset - (kMyriadMemoryOffset32 >> Mapping.Scale);
533 Mapping.Offset = kDefaultShadowOffset32;
534 } else { // LongSize == 64
535 // Fuchsia is always PIE, which means that the beginning of the address
536 // space is always available.
540 Mapping.Offset = kPPC64_ShadowOffset64;
542 Mapping.Offset = kSystemZ_ShadowOffset64;
544 Mapping.Offset = kFreeBSD_ShadowOffset64;
546 Mapping.Offset = kNetBSD_ShadowOffset64;
548 Mapping.Offset = kPS4CPU_ShadowOffset64;
549 else if (IsLinux && IsX86_64) {
551 Mapping.Offset = kLinuxKasan_ShadowOffset64;
553 Mapping.Offset = (kSmallX86_64ShadowOffsetBase &
554 (kSmallX86_64ShadowOffsetAlignMask << Mapping.Scale));
555 } else if (IsWindows && IsX86_64) {
556 Mapping.Offset = kWindowsShadowOffset64;
558 Mapping.Offset = kMIPS64_ShadowOffset64;
560 // If we're targeting iOS and x86, the binary is built for iOS simulator.
561 // We are using dynamic shadow offset on the 64-bit devices.
563 IsX86_64 ? kIOSSimShadowOffset64 : kDynamicShadowSentinel;
565 Mapping.Offset = kAArch64_ShadowOffset64;
567 Mapping.Offset = kDefaultShadowOffset64;
570 if (ClForceDynamicShadow) {
571 Mapping.Offset = kDynamicShadowSentinel;
574 if (ClMappingOffset.getNumOccurrences() > 0) {
575 Mapping.Offset = ClMappingOffset;
578 // OR-ing shadow offset if more efficient (at least on x86) if the offset
579 // is a power of two, but on ppc64 we have to use add since the shadow
580 // offset is not necessary 1/8-th of the address space. On SystemZ,
581 // we could OR the constant in a single instruction, but it's more
582 // efficient to load it once and use indexed addressing.
583 Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64 && !IsSystemZ && !IsPS4CPU &&
584 !(Mapping.Offset & (Mapping.Offset - 1)) &&
585 Mapping.Offset != kDynamicShadowSentinel;
586 bool IsAndroidWithIfuncSupport =
587 IsAndroid && !TargetTriple.isAndroidVersionLT(21);
588 Mapping.InGlobal = ClWithIfunc && IsAndroidWithIfuncSupport && IsArmOrThumb;
593 static size_t RedzoneSizeForScale(int MappingScale) {
594 // Redzone used for stack and globals is at least 32 bytes.
595 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
596 return std::max(32U, 1U << MappingScale);
601 /// AddressSanitizer: instrument the code in module to find memory bugs.
602 struct AddressSanitizer : public FunctionPass {
603 // Pass identification, replacement for typeid
606 explicit AddressSanitizer(bool CompileKernel = false, bool Recover = false,
607 bool UseAfterScope = false)
608 : FunctionPass(ID), UseAfterScope(UseAfterScope || ClUseAfterScope) {
609 this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
610 this->CompileKernel = ClEnableKasan.getNumOccurrences() > 0 ?
611 ClEnableKasan : CompileKernel;
612 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
615 StringRef getPassName() const override {
616 return "AddressSanitizerFunctionPass";
619 void getAnalysisUsage(AnalysisUsage &AU) const override {
620 AU.addRequired<DominatorTreeWrapperPass>();
621 AU.addRequired<TargetLibraryInfoWrapperPass>();
624 uint64_t getAllocaSizeInBytes(const AllocaInst &AI) const {
625 uint64_t ArraySize = 1;
626 if (AI.isArrayAllocation()) {
627 const ConstantInt *CI = dyn_cast<ConstantInt>(AI.getArraySize());
628 assert(CI && "non-constant array size");
629 ArraySize = CI->getZExtValue();
631 Type *Ty = AI.getAllocatedType();
632 uint64_t SizeInBytes =
633 AI.getModule()->getDataLayout().getTypeAllocSize(Ty);
634 return SizeInBytes * ArraySize;
637 /// Check if we want (and can) handle this alloca.
638 bool isInterestingAlloca(const AllocaInst &AI);
640 /// If it is an interesting memory access, return the PointerOperand
641 /// and set IsWrite/Alignment. Otherwise return nullptr.
642 /// MaybeMask is an output parameter for the mask Value, if we're looking at a
643 /// masked load/store.
644 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
645 uint64_t *TypeSize, unsigned *Alignment,
646 Value **MaybeMask = nullptr);
648 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
649 bool UseCalls, const DataLayout &DL);
650 void instrumentPointerComparisonOrSubtraction(Instruction *I);
651 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
652 Value *Addr, uint32_t TypeSize, bool IsWrite,
653 Value *SizeArgument, bool UseCalls, uint32_t Exp);
654 void instrumentUnusualSizeOrAlignment(Instruction *I,
655 Instruction *InsertBefore, Value *Addr,
656 uint32_t TypeSize, bool IsWrite,
657 Value *SizeArgument, bool UseCalls,
659 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
660 Value *ShadowValue, uint32_t TypeSize);
661 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
662 bool IsWrite, size_t AccessSizeIndex,
663 Value *SizeArgument, uint32_t Exp);
664 void instrumentMemIntrinsic(MemIntrinsic *MI);
665 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
666 bool runOnFunction(Function &F) override;
667 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
668 void maybeInsertDynamicShadowAtFunctionEntry(Function &F);
669 void markEscapedLocalAllocas(Function &F);
670 bool doInitialization(Module &M) override;
671 bool doFinalization(Module &M) override;
673 DominatorTree &getDominatorTree() const { return *DT; }
676 friend struct FunctionStackPoisoner;
678 void initializeCallbacks(Module &M);
680 bool LooksLikeCodeInBug11395(Instruction *I);
681 bool GlobalIsLinkerInitialized(GlobalVariable *G);
682 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
683 uint64_t TypeSize) const;
685 /// Helper to cleanup per-function state.
686 struct FunctionStateRAII {
687 AddressSanitizer *Pass;
689 FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
690 assert(Pass->ProcessedAllocas.empty() &&
691 "last pass forgot to clear cache");
692 assert(!Pass->LocalDynamicShadow);
695 ~FunctionStateRAII() {
696 Pass->LocalDynamicShadow = nullptr;
697 Pass->ProcessedAllocas.clear();
708 ShadowMapping Mapping;
710 Function *AsanHandleNoReturnFunc;
711 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
712 Constant *AsanShadowGlobal;
714 // These arrays is indexed by AccessIsWrite, Experiment and log2(AccessSize).
715 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
716 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
718 // These arrays is indexed by AccessIsWrite and Experiment.
719 Function *AsanErrorCallbackSized[2][2];
720 Function *AsanMemoryAccessCallbackSized[2][2];
722 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
724 Value *LocalDynamicShadow = nullptr;
725 GlobalsMetadata GlobalsMD;
726 DenseMap<const AllocaInst *, bool> ProcessedAllocas;
729 class AddressSanitizerModule : public ModulePass {
731 // Pass identification, replacement for typeid
734 explicit AddressSanitizerModule(bool CompileKernel = false,
735 bool Recover = false,
736 bool UseGlobalsGC = true)
738 UseGlobalsGC(UseGlobalsGC && ClUseGlobalsGC),
739 // Not a typo: ClWithComdat is almost completely pointless without
740 // ClUseGlobalsGC (because then it only works on modules without
741 // globals, which are rare); it is a prerequisite for ClUseGlobalsGC;
742 // and both suffer from gold PR19002 for which UseGlobalsGC constructor
743 // argument is designed as workaround. Therefore, disable both
744 // ClWithComdat and ClUseGlobalsGC unless the frontend says it's ok to
746 UseCtorComdat(UseGlobalsGC && ClWithComdat) {
747 this->Recover = ClRecover.getNumOccurrences() > 0 ?
749 this->CompileKernel = ClEnableKasan.getNumOccurrences() > 0 ?
750 ClEnableKasan : CompileKernel;
753 bool runOnModule(Module &M) override;
754 StringRef getPassName() const override { return "AddressSanitizerModule"; }
757 void initializeCallbacks(Module &M);
759 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M, bool *CtorComdat);
760 void InstrumentGlobalsCOFF(IRBuilder<> &IRB, Module &M,
761 ArrayRef<GlobalVariable *> ExtendedGlobals,
762 ArrayRef<Constant *> MetadataInitializers);
763 void InstrumentGlobalsELF(IRBuilder<> &IRB, Module &M,
764 ArrayRef<GlobalVariable *> ExtendedGlobals,
765 ArrayRef<Constant *> MetadataInitializers,
766 const std::string &UniqueModuleId);
767 void InstrumentGlobalsMachO(IRBuilder<> &IRB, Module &M,
768 ArrayRef<GlobalVariable *> ExtendedGlobals,
769 ArrayRef<Constant *> MetadataInitializers);
771 InstrumentGlobalsWithMetadataArray(IRBuilder<> &IRB, Module &M,
772 ArrayRef<GlobalVariable *> ExtendedGlobals,
773 ArrayRef<Constant *> MetadataInitializers);
775 GlobalVariable *CreateMetadataGlobal(Module &M, Constant *Initializer,
776 StringRef OriginalName);
777 void SetComdatForGlobalMetadata(GlobalVariable *G, GlobalVariable *Metadata,
778 StringRef InternalSuffix);
779 IRBuilder<> CreateAsanModuleDtor(Module &M);
781 bool ShouldInstrumentGlobal(GlobalVariable *G);
782 bool ShouldUseMachOGlobalsSection() const;
783 StringRef getGlobalMetadataSection() const;
784 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
785 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
786 size_t MinRedzoneSizeForGlobal() const {
787 return RedzoneSizeForScale(Mapping.Scale);
789 int GetAsanVersion(const Module &M) const;
791 GlobalsMetadata GlobalsMD;
799 ShadowMapping Mapping;
800 Function *AsanPoisonGlobals;
801 Function *AsanUnpoisonGlobals;
802 Function *AsanRegisterGlobals;
803 Function *AsanUnregisterGlobals;
804 Function *AsanRegisterImageGlobals;
805 Function *AsanUnregisterImageGlobals;
806 Function *AsanRegisterElfGlobals;
807 Function *AsanUnregisterElfGlobals;
809 Function *AsanCtorFunction = nullptr;
810 Function *AsanDtorFunction = nullptr;
813 // Stack poisoning does not play well with exception handling.
814 // When an exception is thrown, we essentially bypass the code
815 // that unpoisones the stack. This is why the run-time library has
816 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
817 // stack in the interceptor. This however does not work inside the
818 // actual function which catches the exception. Most likely because the
819 // compiler hoists the load of the shadow value somewhere too high.
820 // This causes asan to report a non-existing bug on 453.povray.
821 // It sounds like an LLVM bug.
822 struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
824 AddressSanitizer &ASan;
829 ShadowMapping Mapping;
831 SmallVector<AllocaInst *, 16> AllocaVec;
832 SmallVector<AllocaInst *, 16> StaticAllocasToMoveUp;
833 SmallVector<Instruction *, 8> RetVec;
834 unsigned StackAlignment;
836 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
837 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
838 Function *AsanSetShadowFunc[0x100] = {};
839 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
840 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
842 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
843 struct AllocaPoisonCall {
844 IntrinsicInst *InsBefore;
849 SmallVector<AllocaPoisonCall, 8> DynamicAllocaPoisonCallVec;
850 SmallVector<AllocaPoisonCall, 8> StaticAllocaPoisonCallVec;
852 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
853 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
854 AllocaInst *DynamicAllocaLayout = nullptr;
855 IntrinsicInst *LocalEscapeCall = nullptr;
857 // Maps Value to an AllocaInst from which the Value is originated.
858 using AllocaForValueMapTy = DenseMap<Value *, AllocaInst *>;
859 AllocaForValueMapTy AllocaForValue;
861 bool HasNonEmptyInlineAsm = false;
862 bool HasReturnsTwiceCall = false;
863 std::unique_ptr<CallInst> EmptyInlineAsm;
865 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
868 DIB(*F.getParent(), /*AllowUnresolved*/ false),
870 IntptrTy(ASan.IntptrTy),
871 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
872 Mapping(ASan.Mapping),
873 StackAlignment(1 << Mapping.Scale),
874 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
876 bool runOnFunction() {
877 if (!ClStack) return false;
879 if (ClRedzoneByvalArgs)
880 copyArgsPassedByValToAllocas();
882 // Collect alloca, ret, lifetime instructions etc.
883 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
885 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
887 initializeCallbacks(*F.getParent());
889 processDynamicAllocas();
890 processStaticAllocas();
893 LLVM_DEBUG(dbgs() << F);
898 // Arguments marked with the "byval" attribute are implicitly copied without
899 // using an alloca instruction. To produce redzones for those arguments, we
900 // copy them a second time into memory allocated with an alloca instruction.
901 void copyArgsPassedByValToAllocas();
903 // Finds all Alloca instructions and puts
904 // poisoned red zones around all of them.
905 // Then unpoison everything back before the function returns.
906 void processStaticAllocas();
907 void processDynamicAllocas();
909 void createDynamicAllocasInitStorage();
911 // ----------------------- Visitors.
912 /// Collect all Ret instructions.
913 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
915 /// Collect all Resume instructions.
916 void visitResumeInst(ResumeInst &RI) { RetVec.push_back(&RI); }
918 /// Collect all CatchReturnInst instructions.
919 void visitCleanupReturnInst(CleanupReturnInst &CRI) { RetVec.push_back(&CRI); }
921 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
923 IRBuilder<> IRB(InstBefore);
924 Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
925 // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
926 // need to adjust extracted SP to compute the address of the most recent
927 // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
929 if (!isa<ReturnInst>(InstBefore)) {
930 Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
931 InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
934 Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
936 DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
940 IRB.CreateCall(AsanAllocasUnpoisonFunc,
941 {IRB.CreateLoad(DynamicAllocaLayout), DynamicAreaPtr});
944 // Unpoison dynamic allocas redzones.
945 void unpoisonDynamicAllocas() {
946 for (auto &Ret : RetVec)
947 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
949 for (auto &StackRestoreInst : StackRestoreVec)
950 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
951 StackRestoreInst->getOperand(0));
954 // Deploy and poison redzones around dynamic alloca call. To do this, we
955 // should replace this call with another one with changed parameters and
956 // replace all its uses with new address, so
957 // addr = alloca type, old_size, align
959 // new_size = (old_size + additional_size) * sizeof(type)
960 // tmp = alloca i8, new_size, max(align, 32)
961 // addr = tmp + 32 (first 32 bytes are for the left redzone).
962 // Additional_size is added to make new memory allocation contain not only
963 // requested memory, but also left, partial and right redzones.
964 void handleDynamicAllocaCall(AllocaInst *AI);
966 /// Collect Alloca instructions we want (and can) handle.
967 void visitAllocaInst(AllocaInst &AI) {
968 if (!ASan.isInterestingAlloca(AI)) {
969 if (AI.isStaticAlloca()) {
970 // Skip over allocas that are present *before* the first instrumented
971 // alloca, we don't want to move those around.
972 if (AllocaVec.empty())
975 StaticAllocasToMoveUp.push_back(&AI);
980 StackAlignment = std::max(StackAlignment, AI.getAlignment());
981 if (!AI.isStaticAlloca())
982 DynamicAllocaVec.push_back(&AI);
984 AllocaVec.push_back(&AI);
987 /// Collect lifetime intrinsic calls to check for use-after-scope
989 void visitIntrinsicInst(IntrinsicInst &II) {
990 Intrinsic::ID ID = II.getIntrinsicID();
991 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
992 if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
993 if (!ASan.UseAfterScope)
995 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
997 // Found lifetime intrinsic, add ASan instrumentation if necessary.
998 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
999 // If size argument is undefined, don't do anything.
1000 if (Size->isMinusOne()) return;
1001 // Check that size doesn't saturate uint64_t and can
1002 // be stored in IntptrTy.
1003 const uint64_t SizeValue = Size->getValue().getLimitedValue();
1004 if (SizeValue == ~0ULL ||
1005 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
1007 // Find alloca instruction that corresponds to llvm.lifetime argument.
1008 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
1009 if (!AI || !ASan.isInterestingAlloca(*AI))
1011 bool DoPoison = (ID == Intrinsic::lifetime_end);
1012 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
1013 if (AI->isStaticAlloca())
1014 StaticAllocaPoisonCallVec.push_back(APC);
1015 else if (ClInstrumentDynamicAllocas)
1016 DynamicAllocaPoisonCallVec.push_back(APC);
1019 void visitCallSite(CallSite CS) {
1020 Instruction *I = CS.getInstruction();
1021 if (CallInst *CI = dyn_cast<CallInst>(I)) {
1022 HasNonEmptyInlineAsm |= CI->isInlineAsm() &&
1023 !CI->isIdenticalTo(EmptyInlineAsm.get()) &&
1024 I != ASan.LocalDynamicShadow;
1025 HasReturnsTwiceCall |= CI->canReturnTwice();
1029 // ---------------------- Helpers.
1030 void initializeCallbacks(Module &M);
1032 bool doesDominateAllExits(const Instruction *I) const {
1033 for (auto Ret : RetVec) {
1034 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
1039 /// Finds alloca where the value comes from.
1040 AllocaInst *findAllocaForValue(Value *V);
1042 // Copies bytes from ShadowBytes into shadow memory for indexes where
1043 // ShadowMask is not zero. If ShadowMask[i] is zero, we assume that
1044 // ShadowBytes[i] is constantly zero and doesn't need to be overwritten.
1045 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
1046 IRBuilder<> &IRB, Value *ShadowBase);
1047 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
1048 size_t Begin, size_t End, IRBuilder<> &IRB,
1050 void copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
1051 ArrayRef<uint8_t> ShadowBytes, size_t Begin,
1052 size_t End, IRBuilder<> &IRB, Value *ShadowBase);
1054 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
1056 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
1058 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
1059 Instruction *ThenTerm, Value *ValueIfFalse);
1062 } // end anonymous namespace
1064 char AddressSanitizer::ID = 0;
1066 INITIALIZE_PASS_BEGIN(
1067 AddressSanitizer, "asan",
1068 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
1070 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1071 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1072 INITIALIZE_PASS_END(
1073 AddressSanitizer, "asan",
1074 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
1077 FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel,
1079 bool UseAfterScope) {
1080 assert(!CompileKernel || Recover);
1081 return new AddressSanitizer(CompileKernel, Recover, UseAfterScope);
1084 char AddressSanitizerModule::ID = 0;
1087 AddressSanitizerModule, "asan-module",
1088 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
1092 ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel,
1094 bool UseGlobalsGC) {
1095 assert(!CompileKernel || Recover);
1096 return new AddressSanitizerModule(CompileKernel, Recover, UseGlobalsGC);
1099 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
1100 size_t Res = countTrailingZeros(TypeSize / 8);
1101 assert(Res < kNumberOfAccessSizes);
1105 // Create a constant for Str so that we can pass it to the run-time lib.
1106 static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
1107 bool AllowMerging) {
1108 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
1109 // We use private linkage for module-local strings. If they can be merged
1110 // with another one, we set the unnamed_addr attribute.
1111 GlobalVariable *GV =
1112 new GlobalVariable(M, StrConst->getType(), true,
1113 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
1114 if (AllowMerging) GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1115 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
1119 /// Create a global describing a source location.
1120 static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
1121 LocationMetadata MD) {
1122 Constant *LocData[] = {
1123 createPrivateGlobalForString(M, MD.Filename, true),
1124 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
1125 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
1127 auto LocStruct = ConstantStruct::getAnon(LocData);
1128 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
1129 GlobalValue::PrivateLinkage, LocStruct,
1131 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1135 /// Check if \p G has been created by a trusted compiler pass.
1136 static bool GlobalWasGeneratedByCompiler(GlobalVariable *G) {
1137 // Do not instrument asan globals.
1138 if (G->getName().startswith(kAsanGenPrefix) ||
1139 G->getName().startswith(kSanCovGenPrefix) ||
1140 G->getName().startswith(kODRGenPrefix))
1143 // Do not instrument gcov counter arrays.
1144 if (G->getName() == "__llvm_gcov_ctr")
1150 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
1152 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
1153 if (Mapping.Offset == 0) return Shadow;
1154 // (Shadow >> scale) | offset
1156 if (LocalDynamicShadow)
1157 ShadowBase = LocalDynamicShadow;
1159 ShadowBase = ConstantInt::get(IntptrTy, Mapping.Offset);
1160 if (Mapping.OrShadowOffset)
1161 return IRB.CreateOr(Shadow, ShadowBase);
1163 return IRB.CreateAdd(Shadow, ShadowBase);
1166 // Instrument memset/memmove/memcpy
1167 void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
1168 IRBuilder<> IRB(MI);
1169 if (isa<MemTransferInst>(MI)) {
1171 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
1172 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1173 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
1174 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
1175 } else if (isa<MemSetInst>(MI)) {
1178 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1179 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
1180 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
1182 MI->eraseFromParent();
1185 /// Check if we want (and can) handle this alloca.
1186 bool AddressSanitizer::isInterestingAlloca(const AllocaInst &AI) {
1187 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
1189 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
1190 return PreviouslySeenAllocaInfo->getSecond();
1192 bool IsInteresting =
1193 (AI.getAllocatedType()->isSized() &&
1194 // alloca() may be called with 0 size, ignore it.
1195 ((!AI.isStaticAlloca()) || getAllocaSizeInBytes(AI) > 0) &&
1196 // We are only interested in allocas not promotable to registers.
1197 // Promotable allocas are common under -O0.
1198 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
1199 // inalloca allocas are not treated as static, and we don't want
1200 // dynamic alloca instrumentation for them as well.
1201 !AI.isUsedWithInAlloca() &&
1202 // swifterror allocas are register promoted by ISel
1203 !AI.isSwiftError());
1205 ProcessedAllocas[&AI] = IsInteresting;
1206 return IsInteresting;
1209 Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
1212 unsigned *Alignment,
1213 Value **MaybeMask) {
1214 // Skip memory accesses inserted by another instrumentation.
1215 if (I->getMetadata("nosanitize")) return nullptr;
1217 // Do not instrument the load fetching the dynamic shadow address.
1218 if (LocalDynamicShadow == I)
1221 Value *PtrOperand = nullptr;
1222 const DataLayout &DL = I->getModule()->getDataLayout();
1223 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1224 if (!ClInstrumentReads) return nullptr;
1226 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
1227 *Alignment = LI->getAlignment();
1228 PtrOperand = LI->getPointerOperand();
1229 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1230 if (!ClInstrumentWrites) return nullptr;
1232 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
1233 *Alignment = SI->getAlignment();
1234 PtrOperand = SI->getPointerOperand();
1235 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
1236 if (!ClInstrumentAtomics) return nullptr;
1238 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
1240 PtrOperand = RMW->getPointerOperand();
1241 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
1242 if (!ClInstrumentAtomics) return nullptr;
1244 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
1246 PtrOperand = XCHG->getPointerOperand();
1247 } else if (auto CI = dyn_cast<CallInst>(I)) {
1248 auto *F = dyn_cast<Function>(CI->getCalledValue());
1249 if (F && (F->getName().startswith("llvm.masked.load.") ||
1250 F->getName().startswith("llvm.masked.store."))) {
1251 unsigned OpOffset = 0;
1252 if (F->getName().startswith("llvm.masked.store.")) {
1253 if (!ClInstrumentWrites)
1255 // Masked store has an initial operand for the value.
1259 if (!ClInstrumentReads)
1264 auto BasePtr = CI->getOperand(0 + OpOffset);
1265 auto Ty = cast<PointerType>(BasePtr->getType())->getElementType();
1266 *TypeSize = DL.getTypeStoreSizeInBits(Ty);
1267 if (auto AlignmentConstant =
1268 dyn_cast<ConstantInt>(CI->getOperand(1 + OpOffset)))
1269 *Alignment = (unsigned)AlignmentConstant->getZExtValue();
1271 *Alignment = 1; // No alignment guarantees. We probably got Undef
1273 *MaybeMask = CI->getOperand(2 + OpOffset);
1274 PtrOperand = BasePtr;
1279 // Do not instrument acesses from different address spaces; we cannot deal
1281 Type *PtrTy = cast<PointerType>(PtrOperand->getType()->getScalarType());
1282 if (PtrTy->getPointerAddressSpace() != 0)
1285 // Ignore swifterror addresses.
1286 // swifterror memory addresses are mem2reg promoted by instruction
1287 // selection. As such they cannot have regular uses like an instrumentation
1288 // function and it makes no sense to track them as memory.
1289 if (PtrOperand->isSwiftError())
1293 // Treat memory accesses to promotable allocas as non-interesting since they
1294 // will not cause memory violations. This greatly speeds up the instrumented
1295 // executable at -O0.
1296 if (ClSkipPromotableAllocas)
1297 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
1298 return isInterestingAlloca(*AI) ? AI : nullptr;
1303 static bool isPointerOperand(Value *V) {
1304 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
1307 // This is a rough heuristic; it may cause both false positives and
1308 // false negatives. The proper implementation requires cooperation with
1310 static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
1311 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
1312 if (!Cmp->isRelational()) return false;
1313 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1314 if (BO->getOpcode() != Instruction::Sub) return false;
1318 return isPointerOperand(I->getOperand(0)) &&
1319 isPointerOperand(I->getOperand(1));
1322 bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
1323 // If a global variable does not have dynamic initialization we don't
1324 // have to instrument it. However, if a global does not have initializer
1325 // at all, we assume it has dynamic initializer (in other TU).
1326 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
1329 void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
1332 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
1333 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
1334 for (Value *&i : Param) {
1335 if (i->getType()->isPointerTy())
1336 i = IRB.CreatePointerCast(i, IntptrTy);
1338 IRB.CreateCall(F, Param);
1341 static void doInstrumentAddress(AddressSanitizer *Pass, Instruction *I,
1342 Instruction *InsertBefore, Value *Addr,
1343 unsigned Alignment, unsigned Granularity,
1344 uint32_t TypeSize, bool IsWrite,
1345 Value *SizeArgument, bool UseCalls,
1347 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
1348 // if the data is properly aligned.
1349 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1351 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
1352 return Pass->instrumentAddress(I, InsertBefore, Addr, TypeSize, IsWrite,
1353 nullptr, UseCalls, Exp);
1354 Pass->instrumentUnusualSizeOrAlignment(I, InsertBefore, Addr, TypeSize,
1355 IsWrite, nullptr, UseCalls, Exp);
1358 static void instrumentMaskedLoadOrStore(AddressSanitizer *Pass,
1359 const DataLayout &DL, Type *IntptrTy,
1360 Value *Mask, Instruction *I,
1361 Value *Addr, unsigned Alignment,
1362 unsigned Granularity, uint32_t TypeSize,
1363 bool IsWrite, Value *SizeArgument,
1364 bool UseCalls, uint32_t Exp) {
1365 auto *VTy = cast<PointerType>(Addr->getType())->getElementType();
1366 uint64_t ElemTypeSize = DL.getTypeStoreSizeInBits(VTy->getScalarType());
1367 unsigned Num = VTy->getVectorNumElements();
1368 auto Zero = ConstantInt::get(IntptrTy, 0);
1369 for (unsigned Idx = 0; Idx < Num; ++Idx) {
1370 Value *InstrumentedAddress = nullptr;
1371 Instruction *InsertBefore = I;
1372 if (auto *Vector = dyn_cast<ConstantVector>(Mask)) {
1373 // dyn_cast as we might get UndefValue
1374 if (auto *Masked = dyn_cast<ConstantInt>(Vector->getOperand(Idx))) {
1375 if (Masked->isZero())
1376 // Mask is constant false, so no instrumentation needed.
1378 // If we have a true or undef value, fall through to doInstrumentAddress
1379 // with InsertBefore == I
1383 Value *MaskElem = IRB.CreateExtractElement(Mask, Idx);
1384 TerminatorInst *ThenTerm = SplitBlockAndInsertIfThen(MaskElem, I, false);
1385 InsertBefore = ThenTerm;
1388 IRBuilder<> IRB(InsertBefore);
1389 InstrumentedAddress =
1390 IRB.CreateGEP(Addr, {Zero, ConstantInt::get(IntptrTy, Idx)});
1391 doInstrumentAddress(Pass, I, InsertBefore, InstrumentedAddress, Alignment,
1392 Granularity, ElemTypeSize, IsWrite, SizeArgument,
1397 void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
1398 Instruction *I, bool UseCalls,
1399 const DataLayout &DL) {
1400 bool IsWrite = false;
1401 unsigned Alignment = 0;
1402 uint64_t TypeSize = 0;
1403 Value *MaybeMask = nullptr;
1405 isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment, &MaybeMask);
1408 // Optimization experiments.
1409 // The experiments can be used to evaluate potential optimizations that remove
1410 // instrumentation (assess false negatives). Instead of completely removing
1411 // some instrumentation, you set Exp to a non-zero value (mask of optimization
1412 // experiments that want to remove instrumentation of this instruction).
1413 // If Exp is non-zero, this pass will emit special calls into runtime
1414 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
1415 // make runtime terminate the program in a special way (with a different
1416 // exit status). Then you run the new compiler on a buggy corpus, collect
1417 // the special terminations (ideally, you don't see them at all -- no false
1418 // negatives) and make the decision on the optimization.
1419 uint32_t Exp = ClForceExperiment;
1421 if (ClOpt && ClOptGlobals) {
1422 // If initialization order checking is disabled, a simple access to a
1423 // dynamically initialized global is always valid.
1424 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
1425 if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
1426 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1427 NumOptimizedAccessesToGlobalVar++;
1432 if (ClOpt && ClOptStack) {
1433 // A direct inbounds access to a stack variable is always valid.
1434 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
1435 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1436 NumOptimizedAccessesToStackVar++;
1442 NumInstrumentedWrites++;
1444 NumInstrumentedReads++;
1446 unsigned Granularity = 1 << Mapping.Scale;
1448 instrumentMaskedLoadOrStore(this, DL, IntptrTy, MaybeMask, I, Addr,
1449 Alignment, Granularity, TypeSize, IsWrite,
1450 nullptr, UseCalls, Exp);
1452 doInstrumentAddress(this, I, I, Addr, Alignment, Granularity, TypeSize,
1453 IsWrite, nullptr, UseCalls, Exp);
1457 Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
1458 Value *Addr, bool IsWrite,
1459 size_t AccessSizeIndex,
1460 Value *SizeArgument,
1462 IRBuilder<> IRB(InsertBefore);
1463 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1464 CallInst *Call = nullptr;
1467 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1468 {Addr, SizeArgument});
1470 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1471 {Addr, SizeArgument, ExpVal});
1475 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1477 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1481 // We don't do Call->setDoesNotReturn() because the BB already has
1482 // UnreachableInst at the end.
1483 // This EmptyAsm is required to avoid callback merge.
1484 IRB.CreateCall(EmptyAsm, {});
1488 Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
1490 uint32_t TypeSize) {
1491 size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;
1492 // Addr & (Granularity - 1)
1493 Value *LastAccessedByte =
1494 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
1495 // (Addr & (Granularity - 1)) + size - 1
1496 if (TypeSize / 8 > 1)
1497 LastAccessedByte = IRB.CreateAdd(
1498 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1499 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
1501 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
1502 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1503 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1506 void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
1507 Instruction *InsertBefore, Value *Addr,
1508 uint32_t TypeSize, bool IsWrite,
1509 Value *SizeArgument, bool UseCalls,
1511 bool IsMyriad = TargetTriple.getVendor() == llvm::Triple::Myriad;
1513 IRBuilder<> IRB(InsertBefore);
1514 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1515 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1519 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1522 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1523 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
1528 // Strip the cache bit and do range check.
1529 // AddrLong &= ~kMyriadCacheBitMask32
1530 AddrLong = IRB.CreateAnd(AddrLong, ~kMyriadCacheBitMask32);
1531 // Tag = AddrLong >> kMyriadTagShift
1532 Value *Tag = IRB.CreateLShr(AddrLong, kMyriadTagShift);
1533 // Tag == kMyriadDDRTag
1535 IRB.CreateICmpEQ(Tag, ConstantInt::get(IntptrTy, kMyriadDDRTag));
1537 TerminatorInst *TagCheckTerm = SplitBlockAndInsertIfThen(
1538 TagCheck, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
1539 assert(cast<BranchInst>(TagCheckTerm)->isUnconditional());
1540 IRB.SetInsertPoint(TagCheckTerm);
1541 InsertBefore = TagCheckTerm;
1545 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
1546 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1547 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1548 Value *CmpVal = Constant::getNullValue(ShadowTy);
1549 Value *ShadowValue =
1550 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
1552 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
1553 size_t Granularity = 1ULL << Mapping.Scale;
1554 TerminatorInst *CrashTerm = nullptr;
1556 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
1557 // We use branch weights for the slow path check, to indicate that the slow
1558 // path is rarely taken. This seems to be the case for SPEC benchmarks.
1559 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1560 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
1561 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
1562 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
1563 IRB.SetInsertPoint(CheckTerm);
1564 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
1566 CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
1568 BasicBlock *CrashBlock =
1569 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
1570 CrashTerm = new UnreachableInst(*C, CrashBlock);
1571 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1572 ReplaceInstWithInst(CheckTerm, NewTerm);
1575 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
1578 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
1579 AccessSizeIndex, SizeArgument, Exp);
1580 Crash->setDebugLoc(OrigIns->getDebugLoc());
1583 // Instrument unusual size or unusual alignment.
1584 // We can not do it with a single check, so we do 1-byte check for the first
1585 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1586 // to report the actual access size.
1587 void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1588 Instruction *I, Instruction *InsertBefore, Value *Addr, uint32_t TypeSize,
1589 bool IsWrite, Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1590 IRBuilder<> IRB(InsertBefore);
1591 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1592 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1595 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1598 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1599 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
1601 Value *LastByte = IRB.CreateIntToPtr(
1602 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1604 instrumentAddress(I, InsertBefore, Addr, 8, IsWrite, Size, false, Exp);
1605 instrumentAddress(I, InsertBefore, LastByte, 8, IsWrite, Size, false, Exp);
1609 void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1610 GlobalValue *ModuleName) {
1611 // Set up the arguments to our poison/unpoison functions.
1612 IRBuilder<> IRB(&GlobalInit.front(),
1613 GlobalInit.front().getFirstInsertionPt());
1615 // Add a call to poison all external globals before the given function starts.
1616 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1617 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
1619 // Add calls to unpoison all globals before each return instruction.
1620 for (auto &BB : GlobalInit.getBasicBlockList())
1621 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
1622 CallInst::Create(AsanUnpoisonGlobals, "", RI);
1625 void AddressSanitizerModule::createInitializerPoisonCalls(
1626 Module &M, GlobalValue *ModuleName) {
1627 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1631 ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());
1635 for (Use &OP : CA->operands()) {
1636 if (isa<ConstantAggregateZero>(OP)) continue;
1637 ConstantStruct *CS = cast<ConstantStruct>(OP);
1639 // Must have a function or null ptr.
1640 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
1641 if (F->getName() == kAsanModuleCtorName) continue;
1642 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1643 // Don't instrument CTORs that will run before asan.module_ctor.
1644 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1645 poisonOneInitializer(*F, ModuleName);
1650 bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
1651 Type *Ty = G->getValueType();
1652 LLVM_DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
1654 if (GlobalsMD.get(G).IsBlacklisted) return false;
1655 if (!Ty->isSized()) return false;
1656 if (!G->hasInitializer()) return false;
1657 if (GlobalWasGeneratedByCompiler(G)) return false; // Our own globals.
1658 // Touch only those globals that will not be defined in other modules.
1659 // Don't handle ODR linkage types and COMDATs since other modules may be built
1661 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1662 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1663 G->getLinkage() != GlobalVariable::InternalLinkage)
1665 if (G->hasComdat()) return false;
1666 // Two problems with thread-locals:
1667 // - The address of the main thread's copy can't be computed at link-time.
1668 // - Need to poison all copies, not just the main thread's one.
1669 if (G->isThreadLocal()) return false;
1670 // For now, just ignore this Global if the alignment is large.
1671 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
1673 if (G->hasSection()) {
1674 StringRef Section = G->getSection();
1676 // Globals from llvm.metadata aren't emitted, do not instrument them.
1677 if (Section == "llvm.metadata") return false;
1678 // Do not instrument globals from special LLVM sections.
1679 if (Section.find("__llvm") != StringRef::npos || Section.find("__LLVM") != StringRef::npos) return false;
1681 // Do not instrument function pointers to initialization and termination
1682 // routines: dynamic linker will not properly handle redzones.
1683 if (Section.startswith(".preinit_array") ||
1684 Section.startswith(".init_array") ||
1685 Section.startswith(".fini_array")) {
1689 // Callbacks put into the CRT initializer/terminator sections
1690 // should not be instrumented.
1691 // See https://github.com/google/sanitizers/issues/305
1692 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1693 if (Section.startswith(".CRT")) {
1694 LLVM_DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G
1699 if (TargetTriple.isOSBinFormatMachO()) {
1700 StringRef ParsedSegment, ParsedSection;
1701 unsigned TAA = 0, StubSize = 0;
1703 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1704 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
1705 assert(ErrorCode.empty() && "Invalid section specifier.");
1707 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1708 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1710 if (ParsedSegment == "__OBJC" ||
1711 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1712 LLVM_DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1715 // See https://github.com/google/sanitizers/issues/32
1716 // Constant CFString instances are compiled in the following way:
1717 // -- the string buffer is emitted into
1718 // __TEXT,__cstring,cstring_literals
1719 // -- the constant NSConstantString structure referencing that buffer
1720 // is placed into __DATA,__cfstring
1721 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1722 // Moreover, it causes the linker to crash on OS X 10.7
1723 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1724 LLVM_DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1727 // The linker merges the contents of cstring_literals and removes the
1729 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1730 LLVM_DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1739 // On Mach-O platforms, we emit global metadata in a separate section of the
1740 // binary in order to allow the linker to properly dead strip. This is only
1741 // supported on recent versions of ld64.
1742 bool AddressSanitizerModule::ShouldUseMachOGlobalsSection() const {
1743 if (!TargetTriple.isOSBinFormatMachO())
1746 if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
1748 if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
1750 if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
1756 StringRef AddressSanitizerModule::getGlobalMetadataSection() const {
1757 switch (TargetTriple.getObjectFormat()) {
1758 case Triple::COFF: return ".ASAN$GL";
1759 case Triple::ELF: return "asan_globals";
1760 case Triple::MachO: return "__DATA,__asan_globals,regular";
1763 llvm_unreachable("unsupported object format");
1766 void AddressSanitizerModule::initializeCallbacks(Module &M) {
1767 IRBuilder<> IRB(*C);
1769 // Declare our poisoning and unpoisoning functions.
1770 AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1771 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy));
1772 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
1773 AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1774 kAsanUnpoisonGlobalsName, IRB.getVoidTy()));
1775 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1777 // Declare functions that register/unregister globals.
1778 AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1779 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy));
1780 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
1781 AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
1782 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1783 IntptrTy, IntptrTy));
1784 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1786 // Declare the functions that find globals in a shared object and then invoke
1787 // the (un)register function on them.
1788 AsanRegisterImageGlobals =
1789 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1790 kAsanRegisterImageGlobalsName, IRB.getVoidTy(), IntptrTy));
1791 AsanRegisterImageGlobals->setLinkage(Function::ExternalLinkage);
1793 AsanUnregisterImageGlobals =
1794 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1795 kAsanUnregisterImageGlobalsName, IRB.getVoidTy(), IntptrTy));
1796 AsanUnregisterImageGlobals->setLinkage(Function::ExternalLinkage);
1798 AsanRegisterElfGlobals = checkSanitizerInterfaceFunction(
1799 M.getOrInsertFunction(kAsanRegisterElfGlobalsName, IRB.getVoidTy(),
1800 IntptrTy, IntptrTy, IntptrTy));
1801 AsanRegisterElfGlobals->setLinkage(Function::ExternalLinkage);
1803 AsanUnregisterElfGlobals = checkSanitizerInterfaceFunction(
1804 M.getOrInsertFunction(kAsanUnregisterElfGlobalsName, IRB.getVoidTy(),
1805 IntptrTy, IntptrTy, IntptrTy));
1806 AsanUnregisterElfGlobals->setLinkage(Function::ExternalLinkage);
1809 // Put the metadata and the instrumented global in the same group. This ensures
1810 // that the metadata is discarded if the instrumented global is discarded.
1811 void AddressSanitizerModule::SetComdatForGlobalMetadata(
1812 GlobalVariable *G, GlobalVariable *Metadata, StringRef InternalSuffix) {
1813 Module &M = *G->getParent();
1814 Comdat *C = G->getComdat();
1816 if (!G->hasName()) {
1817 // If G is unnamed, it must be internal. Give it an artificial name
1818 // so we can put it in a comdat.
1819 assert(G->hasLocalLinkage());
1820 G->setName(Twine(kAsanGenPrefix) + "_anon_global");
1823 if (!InternalSuffix.empty() && G->hasLocalLinkage()) {
1824 std::string Name = G->getName();
1825 Name += InternalSuffix;
1826 C = M.getOrInsertComdat(Name);
1828 C = M.getOrInsertComdat(G->getName());
1831 // Make this IMAGE_COMDAT_SELECT_NODUPLICATES on COFF. Also upgrade private
1832 // linkage to internal linkage so that a symbol table entry is emitted. This
1833 // is necessary in order to create the comdat group.
1834 if (TargetTriple.isOSBinFormatCOFF()) {
1835 C->setSelectionKind(Comdat::NoDuplicates);
1836 if (G->hasPrivateLinkage())
1837 G->setLinkage(GlobalValue::InternalLinkage);
1842 assert(G->hasComdat());
1843 Metadata->setComdat(G->getComdat());
1846 // Create a separate metadata global and put it in the appropriate ASan
1847 // global registration section.
1849 AddressSanitizerModule::CreateMetadataGlobal(Module &M, Constant *Initializer,
1850 StringRef OriginalName) {
1851 auto Linkage = TargetTriple.isOSBinFormatMachO()
1852 ? GlobalVariable::InternalLinkage
1853 : GlobalVariable::PrivateLinkage;
1854 GlobalVariable *Metadata = new GlobalVariable(
1855 M, Initializer->getType(), false, Linkage, Initializer,
1856 Twine("__asan_global_") + GlobalValue::dropLLVMManglingEscape(OriginalName));
1857 Metadata->setSection(getGlobalMetadataSection());
1861 IRBuilder<> AddressSanitizerModule::CreateAsanModuleDtor(Module &M) {
1863 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1864 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1865 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1867 return IRBuilder<>(ReturnInst::Create(*C, AsanDtorBB));
1870 void AddressSanitizerModule::InstrumentGlobalsCOFF(
1871 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1872 ArrayRef<Constant *> MetadataInitializers) {
1873 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1874 auto &DL = M.getDataLayout();
1876 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1877 Constant *Initializer = MetadataInitializers[i];
1878 GlobalVariable *G = ExtendedGlobals[i];
1879 GlobalVariable *Metadata =
1880 CreateMetadataGlobal(M, Initializer, G->getName());
1882 // The MSVC linker always inserts padding when linking incrementally. We
1883 // cope with that by aligning each struct to its size, which must be a power
1885 unsigned SizeOfGlobalStruct = DL.getTypeAllocSize(Initializer->getType());
1886 assert(isPowerOf2_32(SizeOfGlobalStruct) &&
1887 "global metadata will not be padded appropriately");
1888 Metadata->setAlignment(SizeOfGlobalStruct);
1890 SetComdatForGlobalMetadata(G, Metadata, "");
1894 void AddressSanitizerModule::InstrumentGlobalsELF(
1895 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1896 ArrayRef<Constant *> MetadataInitializers,
1897 const std::string &UniqueModuleId) {
1898 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1900 SmallVector<GlobalValue *, 16> MetadataGlobals(ExtendedGlobals.size());
1901 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1902 GlobalVariable *G = ExtendedGlobals[i];
1903 GlobalVariable *Metadata =
1904 CreateMetadataGlobal(M, MetadataInitializers[i], G->getName());
1905 MDNode *MD = MDNode::get(M.getContext(), ValueAsMetadata::get(G));
1906 Metadata->setMetadata(LLVMContext::MD_associated, MD);
1907 MetadataGlobals[i] = Metadata;
1909 SetComdatForGlobalMetadata(G, Metadata, UniqueModuleId);
1912 // Update llvm.compiler.used, adding the new metadata globals. This is
1913 // needed so that during LTO these variables stay alive.
1914 if (!MetadataGlobals.empty())
1915 appendToCompilerUsed(M, MetadataGlobals);
1917 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1918 // to look up the loaded image that contains it. Second, we can store in it
1919 // whether registration has already occurred, to prevent duplicate
1922 // Common linkage ensures that there is only one global per shared library.
1923 GlobalVariable *RegisteredFlag = new GlobalVariable(
1924 M, IntptrTy, false, GlobalVariable::CommonLinkage,
1925 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1926 RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
1928 // Create start and stop symbols.
1929 GlobalVariable *StartELFMetadata = new GlobalVariable(
1930 M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
1931 "__start_" + getGlobalMetadataSection());
1932 StartELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
1933 GlobalVariable *StopELFMetadata = new GlobalVariable(
1934 M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
1935 "__stop_" + getGlobalMetadataSection());
1936 StopELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
1938 // Create a call to register the globals with the runtime.
1939 IRB.CreateCall(AsanRegisterElfGlobals,
1940 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
1941 IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
1942 IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
1944 // We also need to unregister globals at the end, e.g., when a shared library
1946 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1947 IRB_Dtor.CreateCall(AsanUnregisterElfGlobals,
1948 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
1949 IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
1950 IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
1953 void AddressSanitizerModule::InstrumentGlobalsMachO(
1954 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1955 ArrayRef<Constant *> MetadataInitializers) {
1956 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1958 // On recent Mach-O platforms, use a structure which binds the liveness of
1959 // the global variable to the metadata struct. Keep the list of "Liveness" GV
1960 // created to be added to llvm.compiler.used
1961 StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy);
1962 SmallVector<GlobalValue *, 16> LivenessGlobals(ExtendedGlobals.size());
1964 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1965 Constant *Initializer = MetadataInitializers[i];
1966 GlobalVariable *G = ExtendedGlobals[i];
1967 GlobalVariable *Metadata =
1968 CreateMetadataGlobal(M, Initializer, G->getName());
1970 // On recent Mach-O platforms, we emit the global metadata in a way that
1971 // allows the linker to properly strip dead globals.
1972 auto LivenessBinder =
1973 ConstantStruct::get(LivenessTy, Initializer->getAggregateElement(0u),
1974 ConstantExpr::getPointerCast(Metadata, IntptrTy));
1975 GlobalVariable *Liveness = new GlobalVariable(
1976 M, LivenessTy, false, GlobalVariable::InternalLinkage, LivenessBinder,
1977 Twine("__asan_binder_") + G->getName());
1978 Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
1979 LivenessGlobals[i] = Liveness;
1982 // Update llvm.compiler.used, adding the new liveness globals. This is
1983 // needed so that during LTO these variables stay alive. The alternative
1984 // would be to have the linker handling the LTO symbols, but libLTO
1985 // current API does not expose access to the section for each symbol.
1986 if (!LivenessGlobals.empty())
1987 appendToCompilerUsed(M, LivenessGlobals);
1989 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1990 // to look up the loaded image that contains it. Second, we can store in it
1991 // whether registration has already occurred, to prevent duplicate
1994 // common linkage ensures that there is only one global per shared library.
1995 GlobalVariable *RegisteredFlag = new GlobalVariable(
1996 M, IntptrTy, false, GlobalVariable::CommonLinkage,
1997 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1998 RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
2000 IRB.CreateCall(AsanRegisterImageGlobals,
2001 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
2003 // We also need to unregister globals at the end, e.g., when a shared library
2005 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
2006 IRB_Dtor.CreateCall(AsanUnregisterImageGlobals,
2007 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
2010 void AddressSanitizerModule::InstrumentGlobalsWithMetadataArray(
2011 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
2012 ArrayRef<Constant *> MetadataInitializers) {
2013 assert(ExtendedGlobals.size() == MetadataInitializers.size());
2014 unsigned N = ExtendedGlobals.size();
2017 // On platforms that don't have a custom metadata section, we emit an array
2018 // of global metadata structures.
2019 ArrayType *ArrayOfGlobalStructTy =
2020 ArrayType::get(MetadataInitializers[0]->getType(), N);
2021 auto AllGlobals = new GlobalVariable(
2022 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
2023 ConstantArray::get(ArrayOfGlobalStructTy, MetadataInitializers), "");
2024 if (Mapping.Scale > 3)
2025 AllGlobals->setAlignment(1ULL << Mapping.Scale);
2027 IRB.CreateCall(AsanRegisterGlobals,
2028 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
2029 ConstantInt::get(IntptrTy, N)});
2031 // We also need to unregister globals at the end, e.g., when a shared library
2033 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
2034 IRB_Dtor.CreateCall(AsanUnregisterGlobals,
2035 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
2036 ConstantInt::get(IntptrTy, N)});
2039 // This function replaces all global variables with new variables that have
2040 // trailing redzones. It also creates a function that poisons
2041 // redzones and inserts this function into llvm.global_ctors.
2042 // Sets *CtorComdat to true if the global registration code emitted into the
2043 // asan constructor is comdat-compatible.
2044 bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M, bool *CtorComdat) {
2045 *CtorComdat = false;
2048 SmallVector<GlobalVariable *, 16> GlobalsToChange;
2050 for (auto &G : M.globals()) {
2051 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
2054 size_t n = GlobalsToChange.size();
2060 auto &DL = M.getDataLayout();
2062 // A global is described by a structure
2065 // size_t size_with_redzone;
2066 // const char *name;
2067 // const char *module_name;
2068 // size_t has_dynamic_init;
2069 // void *source_location;
2070 // size_t odr_indicator;
2071 // We initialize an array of such structures and pass it to a run-time call.
2072 StructType *GlobalStructTy =
2073 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
2074 IntptrTy, IntptrTy, IntptrTy);
2075 SmallVector<GlobalVariable *, 16> NewGlobals(n);
2076 SmallVector<Constant *, 16> Initializers(n);
2078 bool HasDynamicallyInitializedGlobals = false;
2080 // We shouldn't merge same module names, as this string serves as unique
2081 // module ID in runtime.
2082 GlobalVariable *ModuleName = createPrivateGlobalForString(
2083 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
2085 for (size_t i = 0; i < n; i++) {
2086 static const uint64_t kMaxGlobalRedzone = 1 << 18;
2087 GlobalVariable *G = GlobalsToChange[i];
2089 auto MD = GlobalsMD.get(G);
2090 StringRef NameForGlobal = G->getName();
2091 // Create string holding the global name (use global name from metadata
2092 // if it's available, otherwise just write the name of global variable).
2093 GlobalVariable *Name = createPrivateGlobalForString(
2094 M, MD.Name.empty() ? NameForGlobal : MD.Name,
2095 /*AllowMerging*/ true);
2097 Type *Ty = G->getValueType();
2098 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
2099 uint64_t MinRZ = MinRedzoneSizeForGlobal();
2100 // MinRZ <= RZ <= kMaxGlobalRedzone
2101 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
2102 uint64_t RZ = std::max(
2103 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
2104 uint64_t RightRedzoneSize = RZ;
2105 // Round up to MinRZ
2106 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
2107 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
2108 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
2110 StructType *NewTy = StructType::get(Ty, RightRedZoneTy);
2111 Constant *NewInitializer = ConstantStruct::get(
2112 NewTy, G->getInitializer(), Constant::getNullValue(RightRedZoneTy));
2114 // Create a new global variable with enough space for a redzone.
2115 GlobalValue::LinkageTypes Linkage = G->getLinkage();
2116 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
2117 Linkage = GlobalValue::InternalLinkage;
2118 GlobalVariable *NewGlobal =
2119 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
2120 "", G, G->getThreadLocalMode());
2121 NewGlobal->copyAttributesFrom(G);
2122 NewGlobal->setAlignment(MinRZ);
2124 // Move null-terminated C strings to "__asan_cstring" section on Darwin.
2125 if (TargetTriple.isOSBinFormatMachO() && !G->hasSection() &&
2127 auto Seq = dyn_cast<ConstantDataSequential>(G->getInitializer());
2128 if (Seq && Seq->isCString())
2129 NewGlobal->setSection("__TEXT,__asan_cstring,regular");
2132 // Transfer the debug info. The payload starts at offset zero so we can
2133 // copy the debug info over as is.
2134 SmallVector<DIGlobalVariableExpression *, 1> GVs;
2135 G->getDebugInfo(GVs);
2136 for (auto *GV : GVs)
2137 NewGlobal->addDebugInfo(GV);
2140 Indices2[0] = IRB.getInt32(0);
2141 Indices2[1] = IRB.getInt32(0);
2143 G->replaceAllUsesWith(
2144 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
2145 NewGlobal->takeName(G);
2146 G->eraseFromParent();
2147 NewGlobals[i] = NewGlobal;
2149 Constant *SourceLoc;
2150 if (!MD.SourceLoc.empty()) {
2151 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
2152 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
2154 SourceLoc = ConstantInt::get(IntptrTy, 0);
2157 Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
2158 GlobalValue *InstrumentedGlobal = NewGlobal;
2160 bool CanUsePrivateAliases =
2161 TargetTriple.isOSBinFormatELF() || TargetTriple.isOSBinFormatMachO() ||
2162 TargetTriple.isOSBinFormatWasm();
2163 if (CanUsePrivateAliases && ClUsePrivateAliasForGlobals) {
2164 // Create local alias for NewGlobal to avoid crash on ODR between
2165 // instrumented and non-instrumented libraries.
2166 auto *GA = GlobalAlias::create(GlobalValue::InternalLinkage,
2167 NameForGlobal + M.getName(), NewGlobal);
2169 // With local aliases, we need to provide another externally visible
2170 // symbol __odr_asan_XXX to detect ODR violation.
2171 auto *ODRIndicatorSym =
2172 new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
2173 Constant::getNullValue(IRB.getInt8Ty()),
2174 kODRGenPrefix + NameForGlobal, nullptr,
2175 NewGlobal->getThreadLocalMode());
2177 // Set meaningful attributes for indicator symbol.
2178 ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
2179 ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
2180 ODRIndicatorSym->setAlignment(1);
2181 ODRIndicator = ODRIndicatorSym;
2182 InstrumentedGlobal = GA;
2185 Constant *Initializer = ConstantStruct::get(
2187 ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
2188 ConstantInt::get(IntptrTy, SizeInBytes),
2189 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
2190 ConstantExpr::getPointerCast(Name, IntptrTy),
2191 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
2192 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
2193 ConstantExpr::getPointerCast(ODRIndicator, IntptrTy));
2195 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
2197 LLVM_DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
2199 Initializers[i] = Initializer;
2202 // Add instrumented globals to llvm.compiler.used list to avoid LTO from
2203 // ConstantMerge'ing them.
2204 SmallVector<GlobalValue *, 16> GlobalsToAddToUsedList;
2205 for (size_t i = 0; i < n; i++) {
2206 GlobalVariable *G = NewGlobals[i];
2207 if (G->getName().empty()) continue;
2208 GlobalsToAddToUsedList.push_back(G);
2210 appendToCompilerUsed(M, ArrayRef<GlobalValue *>(GlobalsToAddToUsedList));
2212 std::string ELFUniqueModuleId =
2213 (UseGlobalsGC && TargetTriple.isOSBinFormatELF()) ? getUniqueModuleId(&M)
2216 if (!ELFUniqueModuleId.empty()) {
2217 InstrumentGlobalsELF(IRB, M, NewGlobals, Initializers, ELFUniqueModuleId);
2219 } else if (UseGlobalsGC && TargetTriple.isOSBinFormatCOFF()) {
2220 InstrumentGlobalsCOFF(IRB, M, NewGlobals, Initializers);
2221 } else if (UseGlobalsGC && ShouldUseMachOGlobalsSection()) {
2222 InstrumentGlobalsMachO(IRB, M, NewGlobals, Initializers);
2224 InstrumentGlobalsWithMetadataArray(IRB, M, NewGlobals, Initializers);
2227 // Create calls for poisoning before initializers run and unpoisoning after.
2228 if (HasDynamicallyInitializedGlobals)
2229 createInitializerPoisonCalls(M, ModuleName);
2231 LLVM_DEBUG(dbgs() << M);
2235 int AddressSanitizerModule::GetAsanVersion(const Module &M) const {
2236 int LongSize = M.getDataLayout().getPointerSizeInBits();
2237 bool isAndroid = Triple(M.getTargetTriple()).isAndroid();
2239 // 32-bit Android is one version ahead because of the switch to dynamic
2241 Version += (LongSize == 32 && isAndroid);
2245 bool AddressSanitizerModule::runOnModule(Module &M) {
2246 C = &(M.getContext());
2247 int LongSize = M.getDataLayout().getPointerSizeInBits();
2248 IntptrTy = Type::getIntNTy(*C, LongSize);
2249 TargetTriple = Triple(M.getTargetTriple());
2250 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
2251 initializeCallbacks(M);
2256 // Create a module constructor. A destructor is created lazily because not all
2257 // platforms, and not all modules need it.
2258 std::string VersionCheckName =
2259 kAsanVersionCheckNamePrefix + std::to_string(GetAsanVersion(M));
2260 std::tie(AsanCtorFunction, std::ignore) = createSanitizerCtorAndInitFunctions(
2261 M, kAsanModuleCtorName, kAsanInitName, /*InitArgTypes=*/{},
2262 /*InitArgs=*/{}, VersionCheckName);
2264 bool CtorComdat = true;
2265 bool Changed = false;
2266 // TODO(glider): temporarily disabled globals instrumentation for KASan.
2268 IRBuilder<> IRB(AsanCtorFunction->getEntryBlock().getTerminator());
2269 Changed |= InstrumentGlobals(IRB, M, &CtorComdat);
2272 // Put the constructor and destructor in comdat if both
2273 // (1) global instrumentation is not TU-specific
2274 // (2) target is ELF.
2275 if (UseCtorComdat && TargetTriple.isOSBinFormatELF() && CtorComdat) {
2276 AsanCtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleCtorName));
2277 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority,
2279 if (AsanDtorFunction) {
2280 AsanDtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleDtorName));
2281 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority,
2285 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
2286 if (AsanDtorFunction)
2287 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
2293 void AddressSanitizer::initializeCallbacks(Module &M) {
2294 IRBuilder<> IRB(*C);
2295 // Create __asan_report* callbacks.
2296 // IsWrite, TypeSize and Exp are encoded in the function name.
2297 for (int Exp = 0; Exp < 2; Exp++) {
2298 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
2299 const std::string TypeStr = AccessIsWrite ? "store" : "load";
2300 const std::string ExpStr = Exp ? "exp_" : "";
2301 const std::string EndingStr = Recover ? "_noabort" : "";
2303 SmallVector<Type *, 3> Args2 = {IntptrTy, IntptrTy};
2304 SmallVector<Type *, 2> Args1{1, IntptrTy};
2306 Type *ExpType = Type::getInt32Ty(*C);
2307 Args2.push_back(ExpType);
2308 Args1.push_back(ExpType);
2310 AsanErrorCallbackSized[AccessIsWrite][Exp] =
2311 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2312 kAsanReportErrorTemplate + ExpStr + TypeStr + "_n" + EndingStr,
2313 FunctionType::get(IRB.getVoidTy(), Args2, false)));
2315 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
2316 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2317 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
2318 FunctionType::get(IRB.getVoidTy(), Args2, false)));
2320 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
2321 AccessSizeIndex++) {
2322 const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
2323 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2324 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2325 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
2326 FunctionType::get(IRB.getVoidTy(), Args1, false)));
2328 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2329 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2330 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
2331 FunctionType::get(IRB.getVoidTy(), Args1, false)));
2336 const std::string MemIntrinCallbackPrefix =
2337 CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
2338 AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2339 MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
2340 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy));
2341 AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2342 MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
2343 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy));
2344 AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2345 MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
2346 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy));
2348 AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
2349 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy()));
2351 AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2352 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy));
2353 AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2354 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy));
2355 // We insert an empty inline asm after __asan_report* to avoid callback merge.
2356 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
2357 StringRef(""), StringRef(""),
2358 /*hasSideEffects=*/true);
2359 if (Mapping.InGlobal)
2360 AsanShadowGlobal = M.getOrInsertGlobal("__asan_shadow",
2361 ArrayType::get(IRB.getInt8Ty(), 0));
2365 bool AddressSanitizer::doInitialization(Module &M) {
2366 // Initialize the private fields. No one has accessed them before.
2369 C = &(M.getContext());
2370 LongSize = M.getDataLayout().getPointerSizeInBits();
2371 IntptrTy = Type::getIntNTy(*C, LongSize);
2372 TargetTriple = Triple(M.getTargetTriple());
2374 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
2378 bool AddressSanitizer::doFinalization(Module &M) {
2383 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
2384 // For each NSObject descendant having a +load method, this method is invoked
2385 // by the ObjC runtime before any of the static constructors is called.
2386 // Therefore we need to instrument such methods with a call to __asan_init
2387 // at the beginning in order to initialize our runtime before any access to
2388 // the shadow memory.
2389 // We cannot just ignore these methods, because they may call other
2390 // instrumented functions.
2391 if (F.getName().find(" load]") != std::string::npos) {
2392 Function *AsanInitFunction =
2393 declareSanitizerInitFunction(*F.getParent(), kAsanInitName, {});
2394 IRBuilder<> IRB(&F.front(), F.front().begin());
2395 IRB.CreateCall(AsanInitFunction, {});
2401 void AddressSanitizer::maybeInsertDynamicShadowAtFunctionEntry(Function &F) {
2402 // Generate code only when dynamic addressing is needed.
2403 if (Mapping.Offset != kDynamicShadowSentinel)
2406 IRBuilder<> IRB(&F.front().front());
2407 if (Mapping.InGlobal) {
2408 if (ClWithIfuncSuppressRemat) {
2409 // An empty inline asm with input reg == output reg.
2410 // An opaque pointer-to-int cast, basically.
2411 InlineAsm *Asm = InlineAsm::get(
2412 FunctionType::get(IntptrTy, {AsanShadowGlobal->getType()}, false),
2413 StringRef(""), StringRef("=r,0"),
2414 /*hasSideEffects=*/false);
2415 LocalDynamicShadow =
2416 IRB.CreateCall(Asm, {AsanShadowGlobal}, ".asan.shadow");
2418 LocalDynamicShadow =
2419 IRB.CreatePointerCast(AsanShadowGlobal, IntptrTy, ".asan.shadow");
2422 Value *GlobalDynamicAddress = F.getParent()->getOrInsertGlobal(
2423 kAsanShadowMemoryDynamicAddress, IntptrTy);
2424 LocalDynamicShadow = IRB.CreateLoad(GlobalDynamicAddress);
2428 void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
2429 // Find the one possible call to llvm.localescape and pre-mark allocas passed
2430 // to it as uninteresting. This assumes we haven't started processing allocas
2431 // yet. This check is done up front because iterating the use list in
2432 // isInterestingAlloca would be algorithmically slower.
2433 assert(ProcessedAllocas.empty() && "must process localescape before allocas");
2435 // Try to get the declaration of llvm.localescape. If it's not in the module,
2436 // we can exit early.
2437 if (!F.getParent()->getFunction("llvm.localescape")) return;
2439 // Look for a call to llvm.localescape call in the entry block. It can't be in
2441 for (Instruction &I : F.getEntryBlock()) {
2442 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
2443 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
2444 // We found a call. Mark all the allocas passed in as uninteresting.
2445 for (Value *Arg : II->arg_operands()) {
2446 AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
2447 assert(AI && AI->isStaticAlloca() &&
2448 "non-static alloca arg to localescape");
2449 ProcessedAllocas[AI] = false;
2456 bool AddressSanitizer::runOnFunction(Function &F) {
2457 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
2458 if (!ClDebugFunc.empty() && ClDebugFunc == F.getName()) return false;
2459 if (F.getName().startswith("__asan_")) return false;
2461 bool FunctionModified = false;
2463 // If needed, insert __asan_init before checking for SanitizeAddress attr.
2464 // This function needs to be called even if the function body is not
2466 if (maybeInsertAsanInitAtFunctionEntry(F))
2467 FunctionModified = true;
2469 // Leave if the function doesn't need instrumentation.
2470 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return FunctionModified;
2472 LLVM_DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
2474 initializeCallbacks(*F.getParent());
2475 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2477 FunctionStateRAII CleanupObj(this);
2479 maybeInsertDynamicShadowAtFunctionEntry(F);
2481 // We can't instrument allocas used with llvm.localescape. Only static allocas
2482 // can be passed to that intrinsic.
2483 markEscapedLocalAllocas(F);
2485 // We want to instrument every address only once per basic block (unless there
2486 // are calls between uses).
2487 SmallSet<Value *, 16> TempsToInstrument;
2488 SmallVector<Instruction *, 16> ToInstrument;
2489 SmallVector<Instruction *, 8> NoReturnCalls;
2490 SmallVector<BasicBlock *, 16> AllBlocks;
2491 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
2496 const TargetLibraryInfo *TLI =
2497 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
2499 // Fill the set of memory operations to instrument.
2500 for (auto &BB : F) {
2501 AllBlocks.push_back(&BB);
2502 TempsToInstrument.clear();
2503 int NumInsnsPerBB = 0;
2504 for (auto &Inst : BB) {
2505 if (LooksLikeCodeInBug11395(&Inst)) return false;
2506 Value *MaybeMask = nullptr;
2507 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
2508 &Alignment, &MaybeMask)) {
2509 if (ClOpt && ClOptSameTemp) {
2510 // If we have a mask, skip instrumentation if we've already
2511 // instrumented the full object. But don't add to TempsToInstrument
2512 // because we might get another load/store with a different mask.
2514 if (TempsToInstrument.count(Addr))
2515 continue; // We've seen this (whole) temp in the current BB.
2517 if (!TempsToInstrument.insert(Addr).second)
2518 continue; // We've seen this temp in the current BB.
2521 } else if (ClInvalidPointerPairs &&
2522 isInterestingPointerComparisonOrSubtraction(&Inst)) {
2523 PointerComparisonsOrSubtracts.push_back(&Inst);
2525 } else if (isa<MemIntrinsic>(Inst)) {
2528 if (isa<AllocaInst>(Inst)) NumAllocas++;
2531 // A call inside BB.
2532 TempsToInstrument.clear();
2533 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
2535 if (CallInst *CI = dyn_cast<CallInst>(&Inst))
2536 maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
2539 ToInstrument.push_back(&Inst);
2541 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
2546 (ClInstrumentationWithCallsThreshold >= 0 &&
2547 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
2548 const DataLayout &DL = F.getParent()->getDataLayout();
2549 ObjectSizeOpts ObjSizeOpts;
2550 ObjSizeOpts.RoundToAlign = true;
2551 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(), ObjSizeOpts);
2554 int NumInstrumented = 0;
2555 for (auto Inst : ToInstrument) {
2556 if (ClDebugMin < 0 || ClDebugMax < 0 ||
2557 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
2558 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
2559 instrumentMop(ObjSizeVis, Inst, UseCalls,
2560 F.getParent()->getDataLayout());
2562 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
2567 FunctionStackPoisoner FSP(F, *this);
2568 bool ChangedStack = FSP.runOnFunction();
2570 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
2571 // See e.g. https://github.com/google/sanitizers/issues/37
2572 for (auto CI : NoReturnCalls) {
2573 IRBuilder<> IRB(CI);
2574 IRB.CreateCall(AsanHandleNoReturnFunc, {});
2577 for (auto Inst : PointerComparisonsOrSubtracts) {
2578 instrumentPointerComparisonOrSubtraction(Inst);
2582 if (NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty())
2583 FunctionModified = true;
2585 LLVM_DEBUG(dbgs() << "ASAN done instrumenting: " << FunctionModified << " "
2588 return FunctionModified;
2591 // Workaround for bug 11395: we don't want to instrument stack in functions
2592 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
2593 // FIXME: remove once the bug 11395 is fixed.
2594 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
2595 if (LongSize != 32) return false;
2596 CallInst *CI = dyn_cast<CallInst>(I);
2597 if (!CI || !CI->isInlineAsm()) return false;
2598 if (CI->getNumArgOperands() <= 5) return false;
2599 // We have inline assembly with quite a few arguments.
2603 void FunctionStackPoisoner::initializeCallbacks(Module &M) {
2604 IRBuilder<> IRB(*C);
2605 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
2606 std::string Suffix = itostr(i);
2607 AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
2608 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
2610 AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
2611 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
2612 IRB.getVoidTy(), IntptrTy, IntptrTy));
2614 if (ASan.UseAfterScope) {
2615 AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2616 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
2617 IntptrTy, IntptrTy));
2618 AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2619 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
2620 IntptrTy, IntptrTy));
2623 for (size_t Val : {0x00, 0xf1, 0xf2, 0xf3, 0xf5, 0xf8}) {
2624 std::ostringstream Name;
2625 Name << kAsanSetShadowPrefix;
2626 Name << std::setw(2) << std::setfill('0') << std::hex << Val;
2627 AsanSetShadowFunc[Val] =
2628 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2629 Name.str(), IRB.getVoidTy(), IntptrTy, IntptrTy));
2632 AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2633 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy));
2634 AsanAllocasUnpoisonFunc =
2635 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2636 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy));
2639 void FunctionStackPoisoner::copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
2640 ArrayRef<uint8_t> ShadowBytes,
2641 size_t Begin, size_t End,
2643 Value *ShadowBase) {
2647 const size_t LargestStoreSizeInBytes =
2648 std::min<size_t>(sizeof(uint64_t), ASan.LongSize / 8);
2650 const bool IsLittleEndian = F.getParent()->getDataLayout().isLittleEndian();
2652 // Poison given range in shadow using larges store size with out leading and
2653 // trailing zeros in ShadowMask. Zeros never change, so they need neither
2654 // poisoning nor up-poisoning. Still we don't mind if some of them get into a
2655 // middle of a store.
2656 for (size_t i = Begin; i < End;) {
2657 if (!ShadowMask[i]) {
2658 assert(!ShadowBytes[i]);
2663 size_t StoreSizeInBytes = LargestStoreSizeInBytes;
2664 // Fit store size into the range.
2665 while (StoreSizeInBytes > End - i)
2666 StoreSizeInBytes /= 2;
2668 // Minimize store size by trimming trailing zeros.
2669 for (size_t j = StoreSizeInBytes - 1; j && !ShadowMask[i + j]; --j) {
2670 while (j <= StoreSizeInBytes / 2)
2671 StoreSizeInBytes /= 2;
2675 for (size_t j = 0; j < StoreSizeInBytes; j++) {
2677 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
2679 Val = (Val << 8) | ShadowBytes[i + j];
2682 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
2683 Value *Poison = IRB.getIntN(StoreSizeInBytes * 8, Val);
2684 IRB.CreateAlignedStore(
2685 Poison, IRB.CreateIntToPtr(Ptr, Poison->getType()->getPointerTo()), 1);
2687 i += StoreSizeInBytes;
2691 void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2692 ArrayRef<uint8_t> ShadowBytes,
2693 IRBuilder<> &IRB, Value *ShadowBase) {
2694 copyToShadow(ShadowMask, ShadowBytes, 0, ShadowMask.size(), IRB, ShadowBase);
2697 void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2698 ArrayRef<uint8_t> ShadowBytes,
2699 size_t Begin, size_t End,
2700 IRBuilder<> &IRB, Value *ShadowBase) {
2701 assert(ShadowMask.size() == ShadowBytes.size());
2702 size_t Done = Begin;
2703 for (size_t i = Begin, j = Begin + 1; i < End; i = j++) {
2704 if (!ShadowMask[i]) {
2705 assert(!ShadowBytes[i]);
2708 uint8_t Val = ShadowBytes[i];
2709 if (!AsanSetShadowFunc[Val])
2712 // Skip same values.
2713 for (; j < End && ShadowMask[j] && Val == ShadowBytes[j]; ++j) {
2716 if (j - i >= ClMaxInlinePoisoningSize) {
2717 copyToShadowInline(ShadowMask, ShadowBytes, Done, i, IRB, ShadowBase);
2718 IRB.CreateCall(AsanSetShadowFunc[Val],
2719 {IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i)),
2720 ConstantInt::get(IntptrTy, j - i)});
2725 copyToShadowInline(ShadowMask, ShadowBytes, Done, End, IRB, ShadowBase);
2728 // Fake stack allocator (asan_fake_stack.h) has 11 size classes
2729 // for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
2730 static int StackMallocSizeClass(uint64_t LocalStackSize) {
2731 assert(LocalStackSize <= kMaxStackMallocSize);
2732 uint64_t MaxSize = kMinStackMallocSize;
2733 for (int i = 0;; i++, MaxSize *= 2)
2734 if (LocalStackSize <= MaxSize) return i;
2735 llvm_unreachable("impossible LocalStackSize");
2738 void FunctionStackPoisoner::copyArgsPassedByValToAllocas() {
2739 Instruction *CopyInsertPoint = &F.front().front();
2740 if (CopyInsertPoint == ASan.LocalDynamicShadow) {
2741 // Insert after the dynamic shadow location is determined
2742 CopyInsertPoint = CopyInsertPoint->getNextNode();
2743 assert(CopyInsertPoint);
2745 IRBuilder<> IRB(CopyInsertPoint);
2746 const DataLayout &DL = F.getParent()->getDataLayout();
2747 for (Argument &Arg : F.args()) {
2748 if (Arg.hasByValAttr()) {
2749 Type *Ty = Arg.getType()->getPointerElementType();
2750 unsigned Align = Arg.getParamAlignment();
2751 if (Align == 0) Align = DL.getABITypeAlignment(Ty);
2753 AllocaInst *AI = IRB.CreateAlloca(
2755 (Arg.hasName() ? Arg.getName() : "Arg" + Twine(Arg.getArgNo())) +
2757 AI->setAlignment(Align);
2758 Arg.replaceAllUsesWith(AI);
2760 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
2761 IRB.CreateMemCpy(AI, Align, &Arg, Align, AllocSize);
2766 PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
2768 Instruction *ThenTerm,
2769 Value *ValueIfFalse) {
2770 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
2771 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
2772 PHI->addIncoming(ValueIfFalse, CondBlock);
2773 BasicBlock *ThenBlock = ThenTerm->getParent();
2774 PHI->addIncoming(ValueIfTrue, ThenBlock);
2778 Value *FunctionStackPoisoner::createAllocaForLayout(
2779 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
2782 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
2783 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
2786 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
2787 nullptr, "MyAlloca");
2788 assert(Alloca->isStaticAlloca());
2790 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
2791 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
2792 Alloca->setAlignment(FrameAlignment);
2793 return IRB.CreatePointerCast(Alloca, IntptrTy);
2796 void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
2797 BasicBlock &FirstBB = *F.begin();
2798 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
2799 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
2800 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
2801 DynamicAllocaLayout->setAlignment(32);
2804 void FunctionStackPoisoner::processDynamicAllocas() {
2805 if (!ClInstrumentDynamicAllocas || DynamicAllocaVec.empty()) {
2806 assert(DynamicAllocaPoisonCallVec.empty());
2810 // Insert poison calls for lifetime intrinsics for dynamic allocas.
2811 for (const auto &APC : DynamicAllocaPoisonCallVec) {
2812 assert(APC.InsBefore);
2814 assert(ASan.isInterestingAlloca(*APC.AI));
2815 assert(!APC.AI->isStaticAlloca());
2817 IRBuilder<> IRB(APC.InsBefore);
2818 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
2819 // Dynamic allocas will be unpoisoned unconditionally below in
2820 // unpoisonDynamicAllocas.
2821 // Flag that we need unpoison static allocas.
2824 // Handle dynamic allocas.
2825 createDynamicAllocasInitStorage();
2826 for (auto &AI : DynamicAllocaVec)
2827 handleDynamicAllocaCall(AI);
2828 unpoisonDynamicAllocas();
2831 void FunctionStackPoisoner::processStaticAllocas() {
2832 if (AllocaVec.empty()) {
2833 assert(StaticAllocaPoisonCallVec.empty());
2837 int StackMallocIdx = -1;
2838 DebugLoc EntryDebugLocation;
2839 if (auto SP = F.getSubprogram())
2840 EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
2842 Instruction *InsBefore = AllocaVec[0];
2843 IRBuilder<> IRB(InsBefore);
2844 IRB.SetCurrentDebugLocation(EntryDebugLocation);
2846 // Make sure non-instrumented allocas stay in the entry block. Otherwise,
2847 // debug info is broken, because only entry-block allocas are treated as
2848 // regular stack slots.
2849 auto InsBeforeB = InsBefore->getParent();
2850 assert(InsBeforeB == &F.getEntryBlock());
2851 for (auto *AI : StaticAllocasToMoveUp)
2852 if (AI->getParent() == InsBeforeB)
2853 AI->moveBefore(InsBefore);
2855 // If we have a call to llvm.localescape, keep it in the entry block.
2856 if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
2858 SmallVector<ASanStackVariableDescription, 16> SVD;
2859 SVD.reserve(AllocaVec.size());
2860 for (AllocaInst *AI : AllocaVec) {
2861 ASanStackVariableDescription D = {AI->getName().data(),
2862 ASan.getAllocaSizeInBytes(*AI),
2871 // Minimal header size (left redzone) is 4 pointers,
2872 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
2873 size_t Granularity = 1ULL << Mapping.Scale;
2874 size_t MinHeaderSize = std::max((size_t)ASan.LongSize / 2, Granularity);
2875 const ASanStackFrameLayout &L =
2876 ComputeASanStackFrameLayout(SVD, Granularity, MinHeaderSize);
2878 // Build AllocaToSVDMap for ASanStackVariableDescription lookup.
2879 DenseMap<const AllocaInst *, ASanStackVariableDescription *> AllocaToSVDMap;
2880 for (auto &Desc : SVD)
2881 AllocaToSVDMap[Desc.AI] = &Desc;
2883 // Update SVD with information from lifetime intrinsics.
2884 for (const auto &APC : StaticAllocaPoisonCallVec) {
2885 assert(APC.InsBefore);
2887 assert(ASan.isInterestingAlloca(*APC.AI));
2888 assert(APC.AI->isStaticAlloca());
2890 ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
2891 Desc.LifetimeSize = Desc.Size;
2892 if (const DILocation *FnLoc = EntryDebugLocation.get()) {
2893 if (const DILocation *LifetimeLoc = APC.InsBefore->getDebugLoc().get()) {
2894 if (LifetimeLoc->getFile() == FnLoc->getFile())
2895 if (unsigned Line = LifetimeLoc->getLine())
2896 Desc.Line = std::min(Desc.Line ? Desc.Line : Line, Line);
2901 auto DescriptionString = ComputeASanStackFrameDescription(SVD);
2902 LLVM_DEBUG(dbgs() << DescriptionString << " --- " << L.FrameSize << "\n");
2903 uint64_t LocalStackSize = L.FrameSize;
2904 bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
2905 LocalStackSize <= kMaxStackMallocSize;
2906 bool DoDynamicAlloca = ClDynamicAllocaStack;
2907 // Don't do dynamic alloca or stack malloc if:
2908 // 1) There is inline asm: too often it makes assumptions on which registers
2910 // 2) There is a returns_twice call (typically setjmp), which is
2911 // optimization-hostile, and doesn't play well with introduced indirect
2912 // register-relative calculation of local variable addresses.
2913 DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2914 DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2916 Value *StaticAlloca =
2917 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
2920 Value *LocalStackBase;
2921 Value *LocalStackBaseAlloca;
2924 if (DoStackMalloc) {
2925 LocalStackBaseAlloca =
2926 IRB.CreateAlloca(IntptrTy, nullptr, "asan_local_stack_base");
2927 // void *FakeStack = __asan_option_detect_stack_use_after_return
2928 // ? __asan_stack_malloc_N(LocalStackSize)
2930 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
2931 Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
2932 kAsanOptionDetectUseAfterReturn, IRB.getInt32Ty());
2933 Value *UseAfterReturnIsEnabled =
2934 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUseAfterReturn),
2935 Constant::getNullValue(IRB.getInt32Ty()));
2937 SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
2938 IRBuilder<> IRBIf(Term);
2939 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2940 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
2941 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
2942 Value *FakeStackValue =
2943 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
2944 ConstantInt::get(IntptrTy, LocalStackSize));
2945 IRB.SetInsertPoint(InsBefore);
2946 IRB.SetCurrentDebugLocation(EntryDebugLocation);
2947 FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
2948 ConstantInt::get(IntptrTy, 0));
2950 Value *NoFakeStack =
2951 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
2952 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
2953 IRBIf.SetInsertPoint(Term);
2954 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2955 Value *AllocaValue =
2956 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
2958 IRB.SetInsertPoint(InsBefore);
2959 IRB.SetCurrentDebugLocation(EntryDebugLocation);
2960 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
2961 IRB.SetCurrentDebugLocation(EntryDebugLocation);
2962 IRB.CreateStore(LocalStackBase, LocalStackBaseAlloca);
2965 // void *FakeStack = nullptr;
2966 // void *LocalStackBase = alloca(LocalStackSize);
2967 FakeStack = ConstantInt::get(IntptrTy, 0);
2969 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
2970 LocalStackBaseAlloca = LocalStackBase;
2974 // Replace Alloca instructions with base+offset.
2975 for (const auto &Desc : SVD) {
2976 AllocaInst *AI = Desc.AI;
2977 replaceDbgDeclareForAlloca(AI, LocalStackBaseAlloca, DIB, Deref,
2978 Desc.Offset, DIExpression::NoDeref);
2979 Value *NewAllocaPtr = IRB.CreateIntToPtr(
2980 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
2982 AI->replaceAllUsesWith(NewAllocaPtr);
2985 // The left-most redzone has enough space for at least 4 pointers.
2986 // Write the Magic value to redzone[0].
2987 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
2988 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
2990 // Write the frame description constant to redzone[1].
2991 Value *BasePlus1 = IRB.CreateIntToPtr(
2992 IRB.CreateAdd(LocalStackBase,
2993 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
2995 GlobalVariable *StackDescriptionGlobal =
2996 createPrivateGlobalForString(*F.getParent(), DescriptionString,
2997 /*AllowMerging*/ true);
2998 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
2999 IRB.CreateStore(Description, BasePlus1);
3000 // Write the PC to redzone[2].
3001 Value *BasePlus2 = IRB.CreateIntToPtr(
3002 IRB.CreateAdd(LocalStackBase,
3003 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
3005 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
3007 const auto &ShadowAfterScope = GetShadowBytesAfterScope(SVD, L);
3009 // Poison the stack red zones at the entry.
3010 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
3011 // As mask we must use most poisoned case: red zones and after scope.
3012 // As bytes we can use either the same or just red zones only.
3013 copyToShadow(ShadowAfterScope, ShadowAfterScope, IRB, ShadowBase);
3015 if (!StaticAllocaPoisonCallVec.empty()) {
3016 const auto &ShadowInScope = GetShadowBytes(SVD, L);
3018 // Poison static allocas near lifetime intrinsics.
3019 for (const auto &APC : StaticAllocaPoisonCallVec) {
3020 const ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
3021 assert(Desc.Offset % L.Granularity == 0);
3022 size_t Begin = Desc.Offset / L.Granularity;
3023 size_t End = Begin + (APC.Size + L.Granularity - 1) / L.Granularity;
3025 IRBuilder<> IRB(APC.InsBefore);
3026 copyToShadow(ShadowAfterScope,
3027 APC.DoPoison ? ShadowAfterScope : ShadowInScope, Begin, End,
3032 SmallVector<uint8_t, 64> ShadowClean(ShadowAfterScope.size(), 0);
3033 SmallVector<uint8_t, 64> ShadowAfterReturn;
3035 // (Un)poison the stack before all ret instructions.
3036 for (auto Ret : RetVec) {
3037 IRBuilder<> IRBRet(Ret);
3038 // Mark the current frame as retired.
3039 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
3041 if (DoStackMalloc) {
3042 assert(StackMallocIdx >= 0);
3043 // if FakeStack != 0 // LocalStackBase == FakeStack
3044 // // In use-after-return mode, poison the whole stack frame.
3045 // if StackMallocIdx <= 4
3046 // // For small sizes inline the whole thing:
3047 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
3048 // **SavedFlagPtr(FakeStack) = 0
3050 // __asan_stack_free_N(FakeStack, LocalStackSize)
3052 // <This is not a fake stack; unpoison the redzones>
3054 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
3055 TerminatorInst *ThenTerm, *ElseTerm;
3056 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
3058 IRBuilder<> IRBPoison(ThenTerm);
3059 if (StackMallocIdx <= 4) {
3060 int ClassSize = kMinStackMallocSize << StackMallocIdx;
3061 ShadowAfterReturn.resize(ClassSize / L.Granularity,
3062 kAsanStackUseAfterReturnMagic);
3063 copyToShadow(ShadowAfterReturn, ShadowAfterReturn, IRBPoison,
3065 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
3067 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
3068 Value *SavedFlagPtr = IRBPoison.CreateLoad(
3069 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
3070 IRBPoison.CreateStore(
3071 Constant::getNullValue(IRBPoison.getInt8Ty()),
3072 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
3074 // For larger frames call __asan_stack_free_*.
3075 IRBPoison.CreateCall(
3076 AsanStackFreeFunc[StackMallocIdx],
3077 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
3080 IRBuilder<> IRBElse(ElseTerm);
3081 copyToShadow(ShadowAfterScope, ShadowClean, IRBElse, ShadowBase);
3083 copyToShadow(ShadowAfterScope, ShadowClean, IRBRet, ShadowBase);
3087 // We are done. Remove the old unused alloca instructions.
3088 for (auto AI : AllocaVec) AI->eraseFromParent();
3091 void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
3092 IRBuilder<> &IRB, bool DoPoison) {
3093 // For now just insert the call to ASan runtime.
3094 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
3095 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
3097 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
3098 {AddrArg, SizeArg});
3101 // Handling llvm.lifetime intrinsics for a given %alloca:
3102 // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
3103 // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
3104 // invalid accesses) and unpoison it for llvm.lifetime.start (the memory
3105 // could be poisoned by previous llvm.lifetime.end instruction, as the
3106 // variable may go in and out of scope several times, e.g. in loops).
3107 // (3) if we poisoned at least one %alloca in a function,
3108 // unpoison the whole stack frame at function exit.
3110 AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
3111 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
3112 // We're interested only in allocas we can handle.
3113 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
3114 // See if we've already calculated (or started to calculate) alloca for a
3116 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
3117 if (I != AllocaForValue.end()) return I->second;
3118 // Store 0 while we're calculating alloca for value V to avoid
3119 // infinite recursion if the value references itself.
3120 AllocaForValue[V] = nullptr;
3121 AllocaInst *Res = nullptr;
3122 if (CastInst *CI = dyn_cast<CastInst>(V))
3123 Res = findAllocaForValue(CI->getOperand(0));
3124 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
3125 for (Value *IncValue : PN->incoming_values()) {
3126 // Allow self-referencing phi-nodes.
3127 if (IncValue == PN) continue;
3128 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
3129 // AI for incoming values should exist and should all be equal.
3130 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
3134 } else if (GetElementPtrInst *EP = dyn_cast<GetElementPtrInst>(V)) {
3135 Res = findAllocaForValue(EP->getPointerOperand());
3137 LLVM_DEBUG(dbgs() << "Alloca search canceled on unknown instruction: " << *V
3140 if (Res) AllocaForValue[V] = Res;
3144 void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
3145 IRBuilder<> IRB(AI);
3147 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
3148 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
3150 Value *Zero = Constant::getNullValue(IntptrTy);
3151 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
3152 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
3154 // Since we need to extend alloca with additional memory to locate
3155 // redzones, and OldSize is number of allocated blocks with
3156 // ElementSize size, get allocated memory size in bytes by
3157 // OldSize * ElementSize.
3158 const unsigned ElementSize =
3159 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
3161 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
3162 ConstantInt::get(IntptrTy, ElementSize));
3164 // PartialSize = OldSize % 32
3165 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
3167 // Misalign = kAllocaRzSize - PartialSize;
3168 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
3170 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
3171 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
3172 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
3174 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
3175 // Align is added to locate left redzone, PartialPadding for possible
3176 // partial redzone and kAllocaRzSize for right redzone respectively.
3177 Value *AdditionalChunkSize = IRB.CreateAdd(
3178 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
3180 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
3182 // Insert new alloca with new NewSize and Align params.
3183 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
3184 NewAlloca->setAlignment(Align);
3186 // NewAddress = Address + Align
3187 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
3188 ConstantInt::get(IntptrTy, Align));
3190 // Insert __asan_alloca_poison call for new created alloca.
3191 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
3193 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
3194 // for unpoisoning stuff.
3195 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
3197 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
3199 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
3200 AI->replaceAllUsesWith(NewAddressPtr);
3202 // We are done. Erase old alloca from parent.
3203 AI->eraseFromParent();
3206 // isSafeAccess returns true if Addr is always inbounds with respect to its
3207 // base object. For example, it is a field access or an array access with
3208 // constant inbounds index.
3209 bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
3210 Value *Addr, uint64_t TypeSize) const {
3211 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
3212 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
3213 uint64_t Size = SizeOffset.first.getZExtValue();
3214 int64_t Offset = SizeOffset.second.getSExtValue();
3215 // Three checks are required to ensure safety:
3216 // . Offset >= 0 (since the offset is given from the base ptr)
3217 // . Size >= Offset (unsigned)
3218 // . Size - Offset >= NeededSize (unsigned)
3219 return Offset >= 0 && Size >= uint64_t(Offset) &&
3220 Size - uint64_t(Offset) >= TypeSize / 8;