LLVM 17.0.0git
AddressSanitizer.cpp
Go to the documentation of this file.
1//===- AddressSanitizer.cpp - memory error detector -----------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file is a part of AddressSanitizer, an address basic correctness
10// checker.
11// Details of the algorithm:
12// https://github.com/google/sanitizers/wiki/AddressSanitizerAlgorithm
13//
14// FIXME: This sanitizer does not yet handle scalable vectors
15//
16//===----------------------------------------------------------------------===//
17
19#include "llvm/ADT/ArrayRef.h"
20#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/Statistic.h"
26#include "llvm/ADT/StringRef.h"
27#include "llvm/ADT/Twine.h"
35#include "llvm/IR/Argument.h"
36#include "llvm/IR/Attributes.h"
37#include "llvm/IR/BasicBlock.h"
38#include "llvm/IR/Comdat.h"
39#include "llvm/IR/Constant.h"
40#include "llvm/IR/Constants.h"
41#include "llvm/IR/DIBuilder.h"
42#include "llvm/IR/DataLayout.h"
44#include "llvm/IR/DebugLoc.h"
46#include "llvm/IR/Function.h"
47#include "llvm/IR/GlobalAlias.h"
48#include "llvm/IR/GlobalValue.h"
50#include "llvm/IR/IRBuilder.h"
51#include "llvm/IR/InlineAsm.h"
52#include "llvm/IR/InstVisitor.h"
53#include "llvm/IR/InstrTypes.h"
54#include "llvm/IR/Instruction.h"
57#include "llvm/IR/Intrinsics.h"
58#include "llvm/IR/LLVMContext.h"
59#include "llvm/IR/MDBuilder.h"
60#include "llvm/IR/Metadata.h"
61#include "llvm/IR/Module.h"
62#include "llvm/IR/Type.h"
63#include "llvm/IR/Use.h"
64#include "llvm/IR/Value.h"
68#include "llvm/Support/Debug.h"
81#include <algorithm>
82#include <cassert>
83#include <cstddef>
84#include <cstdint>
85#include <iomanip>
86#include <limits>
87#include <sstream>
88#include <string>
89#include <tuple>
90
91using namespace llvm;
92
93#define DEBUG_TYPE "asan"
94
96static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
97static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
99 std::numeric_limits<uint64_t>::max();
100static const uint64_t kSmallX86_64ShadowOffsetBase = 0x7FFFFFFF; // < 2G.
102static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;
103static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 44;
104static const uint64_t kSystemZ_ShadowOffset64 = 1ULL << 52;
105static const uint64_t kMIPS_ShadowOffsetN32 = 1ULL << 29;
106static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
107static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
108static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
109static const uint64_t kLoongArch64_ShadowOffset64 = 1ULL << 46;
110static const uint64_t kRISCV64_ShadowOffset64 = 0xd55550000;
111static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
112static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
113static const uint64_t kFreeBSDAArch64_ShadowOffset64 = 1ULL << 47;
114static const uint64_t kFreeBSDKasan_ShadowOffset64 = 0xdffff7c000000000;
115static const uint64_t kNetBSD_ShadowOffset32 = 1ULL << 30;
116static const uint64_t kNetBSD_ShadowOffset64 = 1ULL << 46;
117static const uint64_t kNetBSDKasan_ShadowOffset64 = 0xdfff900000000000;
118static const uint64_t kPS_ShadowOffset64 = 1ULL << 40;
119static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
121
122// The shadow memory space is dynamically allocated.
124
125static const size_t kMinStackMallocSize = 1 << 6; // 64B
126static const size_t kMaxStackMallocSize = 1 << 16; // 64K
127static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
128static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
129
130const char kAsanModuleCtorName[] = "asan.module_ctor";
131const char kAsanModuleDtorName[] = "asan.module_dtor";
133// On Emscripten, the system needs more than one priorities for constructors.
135const char kAsanReportErrorTemplate[] = "__asan_report_";
136const char kAsanRegisterGlobalsName[] = "__asan_register_globals";
137const char kAsanUnregisterGlobalsName[] = "__asan_unregister_globals";
138const char kAsanRegisterImageGlobalsName[] = "__asan_register_image_globals";
140 "__asan_unregister_image_globals";
141const char kAsanRegisterElfGlobalsName[] = "__asan_register_elf_globals";
142const char kAsanUnregisterElfGlobalsName[] = "__asan_unregister_elf_globals";
143const char kAsanPoisonGlobalsName[] = "__asan_before_dynamic_init";
144const char kAsanUnpoisonGlobalsName[] = "__asan_after_dynamic_init";
145const char kAsanInitName[] = "__asan_init";
146const char kAsanVersionCheckNamePrefix[] = "__asan_version_mismatch_check_v";
147const char kAsanPtrCmp[] = "__sanitizer_ptr_cmp";
148const char kAsanPtrSub[] = "__sanitizer_ptr_sub";
149const char kAsanHandleNoReturnName[] = "__asan_handle_no_return";
150static const int kMaxAsanStackMallocSizeClass = 10;
151const char kAsanStackMallocNameTemplate[] = "__asan_stack_malloc_";
153 "__asan_stack_malloc_always_";
154const char kAsanStackFreeNameTemplate[] = "__asan_stack_free_";
155const char kAsanGenPrefix[] = "___asan_gen_";
156const char kODRGenPrefix[] = "__odr_asan_gen_";
157const char kSanCovGenPrefix[] = "__sancov_gen_";
158const char kAsanSetShadowPrefix[] = "__asan_set_shadow_";
159const char kAsanPoisonStackMemoryName[] = "__asan_poison_stack_memory";
160const char kAsanUnpoisonStackMemoryName[] = "__asan_unpoison_stack_memory";
161
162// ASan version script has __asan_* wildcard. Triple underscore prevents a
163// linker (gold) warning about attempting to export a local symbol.
164const char kAsanGlobalsRegisteredFlagName[] = "___asan_globals_registered";
165
167 "__asan_option_detect_stack_use_after_return";
168
170 "__asan_shadow_memory_dynamic_address";
171
172const char kAsanAllocaPoison[] = "__asan_alloca_poison";
173const char kAsanAllocasUnpoison[] = "__asan_allocas_unpoison";
174
175const char kAMDGPUAddressSharedName[] = "llvm.amdgcn.is.shared";
176const char kAMDGPUAddressPrivateName[] = "llvm.amdgcn.is.private";
177
178// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
179static const size_t kNumberOfAccessSizes = 5;
180
181static const uint64_t kAllocaRzSize = 32;
182
183// ASanAccessInfo implementation constants.
184constexpr size_t kCompileKernelShift = 0;
185constexpr size_t kCompileKernelMask = 0x1;
186constexpr size_t kAccessSizeIndexShift = 1;
187constexpr size_t kAccessSizeIndexMask = 0xf;
188constexpr size_t kIsWriteShift = 5;
189constexpr size_t kIsWriteMask = 0x1;
190
191// Command-line flags.
192
194 "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
195 cl::Hidden, cl::init(false));
196
198 "asan-recover",
199 cl::desc("Enable recovery mode (continue-after-error)."),
200 cl::Hidden, cl::init(false));
201
203 "asan-guard-against-version-mismatch",
204 cl::desc("Guard against compiler/runtime version mismatch."),
205 cl::Hidden, cl::init(true));
206
207// This flag may need to be replaced with -f[no-]asan-reads.
208static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
209 cl::desc("instrument read instructions"),
210 cl::Hidden, cl::init(true));
211
213 "asan-instrument-writes", cl::desc("instrument write instructions"),
214 cl::Hidden, cl::init(true));
215
216static cl::opt<bool>
217 ClUseStackSafety("asan-use-stack-safety", cl::Hidden, cl::init(false),
218 cl::Hidden, cl::desc("Use Stack Safety analysis results"),
220
222 "asan-instrument-atomics",
223 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
224 cl::init(true));
225
226static cl::opt<bool>
227 ClInstrumentByval("asan-instrument-byval",
228 cl::desc("instrument byval call arguments"), cl::Hidden,
229 cl::init(true));
230
232 "asan-always-slow-path",
233 cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
234 cl::init(false));
235
237 "asan-force-dynamic-shadow",
238 cl::desc("Load shadow address into a local variable for each function"),
239 cl::Hidden, cl::init(false));
240
241static cl::opt<bool>
242 ClWithIfunc("asan-with-ifunc",
243 cl::desc("Access dynamic shadow through an ifunc global on "
244 "platforms that support this"),
245 cl::Hidden, cl::init(true));
246
248 "asan-with-ifunc-suppress-remat",
249 cl::desc("Suppress rematerialization of dynamic shadow address by passing "
250 "it through inline asm in prologue."),
251 cl::Hidden, cl::init(true));
252
253// This flag limits the number of instructions to be instrumented
254// in any given BB. Normally, this should be set to unlimited (INT_MAX),
255// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
256// set it to 10000.
258 "asan-max-ins-per-bb", cl::init(10000),
259 cl::desc("maximal number of instructions to instrument in any given BB"),
260 cl::Hidden);
261
262// This flag may need to be replaced with -f[no]asan-stack.
263static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
264 cl::Hidden, cl::init(true));
266 "asan-max-inline-poisoning-size",
267 cl::desc(
268 "Inline shadow poisoning for blocks up to the given size in bytes."),
269 cl::Hidden, cl::init(64));
270
272 "asan-use-after-return",
273 cl::desc("Sets the mode of detection for stack-use-after-return."),
275 clEnumValN(AsanDetectStackUseAfterReturnMode::Never, "never",
276 "Never detect stack use after return."),
278 AsanDetectStackUseAfterReturnMode::Runtime, "runtime",
279 "Detect stack use after return if "
280 "binary flag 'ASAN_OPTIONS=detect_stack_use_after_return' is set."),
281 clEnumValN(AsanDetectStackUseAfterReturnMode::Always, "always",
282 "Always detect stack use after return.")),
283 cl::Hidden, cl::init(AsanDetectStackUseAfterReturnMode::Runtime));
284
285static cl::opt<bool> ClRedzoneByvalArgs("asan-redzone-byval-args",
286 cl::desc("Create redzones for byval "
287 "arguments (extra copy "
288 "required)"), cl::Hidden,
289 cl::init(true));
290
291static cl::opt<bool> ClUseAfterScope("asan-use-after-scope",
292 cl::desc("Check stack-use-after-scope"),
293 cl::Hidden, cl::init(false));
294
295// This flag may need to be replaced with -f[no]asan-globals.
296static cl::opt<bool> ClGlobals("asan-globals",
297 cl::desc("Handle global objects"), cl::Hidden,
298 cl::init(true));
299
300static cl::opt<bool> ClInitializers("asan-initialization-order",
301 cl::desc("Handle C++ initializer order"),
302 cl::Hidden, cl::init(true));
303
305 "asan-detect-invalid-pointer-pair",
306 cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
307 cl::init(false));
308
310 "asan-detect-invalid-pointer-cmp",
311 cl::desc("Instrument <, <=, >, >= with pointer operands"), cl::Hidden,
312 cl::init(false));
313
315 "asan-detect-invalid-pointer-sub",
316 cl::desc("Instrument - operations with pointer operands"), cl::Hidden,
317 cl::init(false));
318
320 "asan-realign-stack",
321 cl::desc("Realign stack to the value of this flag (power of two)"),
322 cl::Hidden, cl::init(32));
323
325 "asan-instrumentation-with-call-threshold",
326 cl::desc(
327 "If the function being instrumented contains more than "
328 "this number of memory accesses, use callbacks instead of "
329 "inline checks (-1 means never use callbacks)."),
330 cl::Hidden, cl::init(7000));
331
333 "asan-memory-access-callback-prefix",
334 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
335 cl::init("__asan_"));
336
338 "asan-kernel-mem-intrinsic-prefix",
339 cl::desc("Use prefix for memory intrinsics in KASAN mode"), cl::Hidden,
340 cl::init(false));
341
342static cl::opt<bool>
343 ClInstrumentDynamicAllocas("asan-instrument-dynamic-allocas",
344 cl::desc("instrument dynamic allocas"),
345 cl::Hidden, cl::init(true));
346
348 "asan-skip-promotable-allocas",
349 cl::desc("Do not instrument promotable allocas"), cl::Hidden,
350 cl::init(true));
351
353 "asan-constructor-kind",
354 cl::desc("Sets the ASan constructor kind"),
355 cl::values(clEnumValN(AsanCtorKind::None, "none", "No constructors"),
356 clEnumValN(AsanCtorKind::Global, "global",
357 "Use global constructors")),
358 cl::init(AsanCtorKind::Global), cl::Hidden);
359// These flags allow to change the shadow mapping.
360// The shadow mapping looks like
361// Shadow = (Mem >> scale) + offset
362
363static cl::opt<int> ClMappingScale("asan-mapping-scale",
364 cl::desc("scale of asan shadow mapping"),
365 cl::Hidden, cl::init(0));
366
368 ClMappingOffset("asan-mapping-offset",
369 cl::desc("offset of asan shadow mapping [EXPERIMENTAL]"),
370 cl::Hidden, cl::init(0));
371
372// Optimization flags. Not user visible, used mostly for testing
373// and benchmarking the tool.
374
375static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
376 cl::Hidden, cl::init(true));
377
378static cl::opt<bool> ClOptimizeCallbacks("asan-optimize-callbacks",
379 cl::desc("Optimize callbacks"),
380 cl::Hidden, cl::init(false));
381
383 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
384 cl::Hidden, cl::init(true));
385
386static cl::opt<bool> ClOptGlobals("asan-opt-globals",
387 cl::desc("Don't instrument scalar globals"),
388 cl::Hidden, cl::init(true));
389
391 "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
392 cl::Hidden, cl::init(false));
393
395 "asan-stack-dynamic-alloca",
396 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
397 cl::init(true));
398
400 "asan-force-experiment",
401 cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
402 cl::init(0));
403
404static cl::opt<bool>
405 ClUsePrivateAlias("asan-use-private-alias",
406 cl::desc("Use private aliases for global variables"),
407 cl::Hidden, cl::init(true));
408
409static cl::opt<bool>
410 ClUseOdrIndicator("asan-use-odr-indicator",
411 cl::desc("Use odr indicators to improve ODR reporting"),
412 cl::Hidden, cl::init(true));
413
414static cl::opt<bool>
415 ClUseGlobalsGC("asan-globals-live-support",
416 cl::desc("Use linker features to support dead "
417 "code stripping of globals"),
418 cl::Hidden, cl::init(true));
419
420// This is on by default even though there is a bug in gold:
421// https://sourceware.org/bugzilla/show_bug.cgi?id=19002
422static cl::opt<bool>
423 ClWithComdat("asan-with-comdat",
424 cl::desc("Place ASan constructors in comdat sections"),
425 cl::Hidden, cl::init(true));
426
428 "asan-destructor-kind",
429 cl::desc("Sets the ASan destructor kind. The default is to use the value "
430 "provided to the pass constructor"),
431 cl::values(clEnumValN(AsanDtorKind::None, "none", "No destructors"),
432 clEnumValN(AsanDtorKind::Global, "global",
433 "Use global destructors")),
434 cl::init(AsanDtorKind::Invalid), cl::Hidden);
435
436// Debug flags.
437
438static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
439 cl::init(0));
440
441static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
442 cl::Hidden, cl::init(0));
443
445 cl::desc("Debug func"));
446
447static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
448 cl::Hidden, cl::init(-1));
449
450static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug max inst"),
451 cl::Hidden, cl::init(-1));
452
453STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
454STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
455STATISTIC(NumOptimizedAccessesToGlobalVar,
456 "Number of optimized accesses to global vars");
457STATISTIC(NumOptimizedAccessesToStackVar,
458 "Number of optimized accesses to stack vars");
459
460namespace {
461
462/// This struct defines the shadow mapping using the rule:
463/// shadow = (mem >> Scale) ADD-or-OR Offset.
464/// If InGlobal is true, then
465/// extern char __asan_shadow[];
466/// shadow = (mem >> Scale) + &__asan_shadow
467struct ShadowMapping {
468 int Scale;
469 uint64_t Offset;
470 bool OrShadowOffset;
471 bool InGlobal;
472};
473
474} // end anonymous namespace
475
476static ShadowMapping getShadowMapping(const Triple &TargetTriple, int LongSize,
477 bool IsKasan) {
478 bool IsAndroid = TargetTriple.isAndroid();
479 bool IsIOS = TargetTriple.isiOS() || TargetTriple.isWatchOS() ||
480 TargetTriple.isDriverKit();
481 bool IsMacOS = TargetTriple.isMacOSX();
482 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
483 bool IsNetBSD = TargetTriple.isOSNetBSD();
484 bool IsPS = TargetTriple.isPS();
485 bool IsLinux = TargetTriple.isOSLinux();
486 bool IsPPC64 = TargetTriple.getArch() == Triple::ppc64 ||
487 TargetTriple.getArch() == Triple::ppc64le;
488 bool IsSystemZ = TargetTriple.getArch() == Triple::systemz;
489 bool IsX86_64 = TargetTriple.getArch() == Triple::x86_64;
490 bool IsMIPSN32ABI = TargetTriple.getEnvironment() == Triple::GNUABIN32;
491 bool IsMIPS32 = TargetTriple.isMIPS32();
492 bool IsMIPS64 = TargetTriple.isMIPS64();
493 bool IsArmOrThumb = TargetTriple.isARM() || TargetTriple.isThumb();
494 bool IsAArch64 = TargetTriple.getArch() == Triple::aarch64;
495 bool IsLoongArch64 = TargetTriple.getArch() == Triple::loongarch64;
496 bool IsRISCV64 = TargetTriple.getArch() == Triple::riscv64;
497 bool IsWindows = TargetTriple.isOSWindows();
498 bool IsFuchsia = TargetTriple.isOSFuchsia();
499 bool IsEmscripten = TargetTriple.isOSEmscripten();
500 bool IsAMDGPU = TargetTriple.isAMDGPU();
501
502 ShadowMapping Mapping;
503
504 Mapping.Scale = kDefaultShadowScale;
505 if (ClMappingScale.getNumOccurrences() > 0) {
506 Mapping.Scale = ClMappingScale;
507 }
508
509 if (LongSize == 32) {
510 if (IsAndroid)
511 Mapping.Offset = kDynamicShadowSentinel;
512 else if (IsMIPSN32ABI)
513 Mapping.Offset = kMIPS_ShadowOffsetN32;
514 else if (IsMIPS32)
515 Mapping.Offset = kMIPS32_ShadowOffset32;
516 else if (IsFreeBSD)
517 Mapping.Offset = kFreeBSD_ShadowOffset32;
518 else if (IsNetBSD)
519 Mapping.Offset = kNetBSD_ShadowOffset32;
520 else if (IsIOS)
521 Mapping.Offset = kDynamicShadowSentinel;
522 else if (IsWindows)
523 Mapping.Offset = kWindowsShadowOffset32;
524 else if (IsEmscripten)
525 Mapping.Offset = kEmscriptenShadowOffset;
526 else
527 Mapping.Offset = kDefaultShadowOffset32;
528 } else { // LongSize == 64
529 // Fuchsia is always PIE, which means that the beginning of the address
530 // space is always available.
531 if (IsFuchsia)
532 Mapping.Offset = 0;
533 else if (IsPPC64)
534 Mapping.Offset = kPPC64_ShadowOffset64;
535 else if (IsSystemZ)
536 Mapping.Offset = kSystemZ_ShadowOffset64;
537 else if (IsFreeBSD && IsAArch64)
538 Mapping.Offset = kFreeBSDAArch64_ShadowOffset64;
539 else if (IsFreeBSD && !IsMIPS64) {
540 if (IsKasan)
541 Mapping.Offset = kFreeBSDKasan_ShadowOffset64;
542 else
543 Mapping.Offset = kFreeBSD_ShadowOffset64;
544 } else if (IsNetBSD) {
545 if (IsKasan)
546 Mapping.Offset = kNetBSDKasan_ShadowOffset64;
547 else
548 Mapping.Offset = kNetBSD_ShadowOffset64;
549 } else if (IsPS)
550 Mapping.Offset = kPS_ShadowOffset64;
551 else if (IsLinux && IsX86_64) {
552 if (IsKasan)
553 Mapping.Offset = kLinuxKasan_ShadowOffset64;
554 else
555 Mapping.Offset = (kSmallX86_64ShadowOffsetBase &
556 (kSmallX86_64ShadowOffsetAlignMask << Mapping.Scale));
557 } else if (IsWindows && IsX86_64) {
558 Mapping.Offset = kWindowsShadowOffset64;
559 } else if (IsMIPS64)
560 Mapping.Offset = kMIPS64_ShadowOffset64;
561 else if (IsIOS)
562 Mapping.Offset = kDynamicShadowSentinel;
563 else if (IsMacOS && IsAArch64)
564 Mapping.Offset = kDynamicShadowSentinel;
565 else if (IsAArch64)
566 Mapping.Offset = kAArch64_ShadowOffset64;
567 else if (IsLoongArch64)
568 Mapping.Offset = kLoongArch64_ShadowOffset64;
569 else if (IsRISCV64)
570 Mapping.Offset = kRISCV64_ShadowOffset64;
571 else if (IsAMDGPU)
572 Mapping.Offset = (kSmallX86_64ShadowOffsetBase &
573 (kSmallX86_64ShadowOffsetAlignMask << Mapping.Scale));
574 else
575 Mapping.Offset = kDefaultShadowOffset64;
576 }
577
579 Mapping.Offset = kDynamicShadowSentinel;
580 }
581
582 if (ClMappingOffset.getNumOccurrences() > 0) {
583 Mapping.Offset = ClMappingOffset;
584 }
585
586 // OR-ing shadow offset if more efficient (at least on x86) if the offset
587 // is a power of two, but on ppc64 and loongarch64 we have to use add since
588 // the shadow offset is not necessarily 1/8-th of the address space. On
589 // SystemZ, we could OR the constant in a single instruction, but it's more
590 // efficient to load it once and use indexed addressing.
591 Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64 && !IsSystemZ && !IsPS &&
592 !IsRISCV64 && !IsLoongArch64 &&
593 !(Mapping.Offset & (Mapping.Offset - 1)) &&
594 Mapping.Offset != kDynamicShadowSentinel;
595 bool IsAndroidWithIfuncSupport =
596 IsAndroid && !TargetTriple.isAndroidVersionLT(21);
597 Mapping.InGlobal = ClWithIfunc && IsAndroidWithIfuncSupport && IsArmOrThumb;
598
599 return Mapping;
600}
601
602namespace llvm {
603void getAddressSanitizerParams(const Triple &TargetTriple, int LongSize,
604 bool IsKasan, uint64_t *ShadowBase,
605 int *MappingScale, bool *OrShadowOffset) {
606 auto Mapping = getShadowMapping(TargetTriple, LongSize, IsKasan);
607 *ShadowBase = Mapping.Offset;
608 *MappingScale = Mapping.Scale;
609 *OrShadowOffset = Mapping.OrShadowOffset;
610}
611
613 : Packed(Packed),
614 AccessSizeIndex((Packed >> kAccessSizeIndexShift) & kAccessSizeIndexMask),
615 IsWrite((Packed >> kIsWriteShift) & kIsWriteMask),
616 CompileKernel((Packed >> kCompileKernelShift) & kCompileKernelMask) {}
617
618ASanAccessInfo::ASanAccessInfo(bool IsWrite, bool CompileKernel,
619 uint8_t AccessSizeIndex)
620 : Packed((IsWrite << kIsWriteShift) +
621 (CompileKernel << kCompileKernelShift) +
622 (AccessSizeIndex << kAccessSizeIndexShift)),
623 AccessSizeIndex(AccessSizeIndex), IsWrite(IsWrite),
624 CompileKernel(CompileKernel) {}
625
626} // namespace llvm
627
628static uint64_t getRedzoneSizeForScale(int MappingScale) {
629 // Redzone used for stack and globals is at least 32 bytes.
630 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
631 return std::max(32U, 1U << MappingScale);
632}
633
635 if (TargetTriple.isOSEmscripten()) {
637 } else {
639 }
640}
641
642namespace {
643
644/// AddressSanitizer: instrument the code in module to find memory bugs.
645struct AddressSanitizer {
646 AddressSanitizer(Module &M, const StackSafetyGlobalInfo *SSGI,
647 bool CompileKernel = false, bool Recover = false,
648 bool UseAfterScope = false,
649 AsanDetectStackUseAfterReturnMode UseAfterReturn =
650 AsanDetectStackUseAfterReturnMode::Runtime)
651 : CompileKernel(ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan
652 : CompileKernel),
653 Recover(ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover),
654 UseAfterScope(UseAfterScope || ClUseAfterScope),
655 UseAfterReturn(ClUseAfterReturn.getNumOccurrences() ? ClUseAfterReturn
656 : UseAfterReturn),
657 SSGI(SSGI) {
658 C = &(M.getContext());
659 DL = &M.getDataLayout();
660 LongSize = M.getDataLayout().getPointerSizeInBits();
661 IntptrTy = Type::getIntNTy(*C, LongSize);
662 Int8PtrTy = Type::getInt8PtrTy(*C);
664 TargetTriple = Triple(M.getTargetTriple());
665
666 Mapping = getShadowMapping(TargetTriple, LongSize, this->CompileKernel);
667
668 assert(this->UseAfterReturn != AsanDetectStackUseAfterReturnMode::Invalid);
669 }
670
671 TypeSize getAllocaSizeInBytes(const AllocaInst &AI) const {
672 return *AI.getAllocationSize(AI.getModule()->getDataLayout());
673 }
674
675 /// Check if we want (and can) handle this alloca.
676 bool isInterestingAlloca(const AllocaInst &AI);
677
678 bool ignoreAccess(Instruction *Inst, Value *Ptr);
679 void getInterestingMemoryOperands(
681
682 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
683 InterestingMemoryOperand &O, bool UseCalls,
684 const DataLayout &DL);
685 void instrumentPointerComparisonOrSubtraction(Instruction *I);
686 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
687 Value *Addr, uint32_t TypeStoreSize, bool IsWrite,
688 Value *SizeArgument, bool UseCalls, uint32_t Exp);
689 Instruction *instrumentAMDGPUAddress(Instruction *OrigIns,
690 Instruction *InsertBefore, Value *Addr,
691 uint32_t TypeStoreSize, bool IsWrite,
692 Value *SizeArgument);
693 void instrumentUnusualSizeOrAlignment(Instruction *I,
694 Instruction *InsertBefore, Value *Addr,
695 TypeSize TypeStoreSize, bool IsWrite,
696 Value *SizeArgument, bool UseCalls,
697 uint32_t Exp);
698 void instrumentMaskedLoadOrStore(AddressSanitizer *Pass, const DataLayout &DL,
699 Type *IntptrTy, Value *Mask, Value *EVL,
700 Value *Stride, Instruction *I, Value *Addr,
701 MaybeAlign Alignment, unsigned Granularity,
702 Type *OpType, bool IsWrite,
703 Value *SizeArgument, bool UseCalls,
704 uint32_t Exp);
705 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
706 Value *ShadowValue, uint32_t TypeStoreSize);
707 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
708 bool IsWrite, size_t AccessSizeIndex,
709 Value *SizeArgument, uint32_t Exp);
710 void instrumentMemIntrinsic(MemIntrinsic *MI);
711 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
712 bool suppressInstrumentationSiteForDebug(int &Instrumented);
713 bool instrumentFunction(Function &F, const TargetLibraryInfo *TLI);
714 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
715 bool maybeInsertDynamicShadowAtFunctionEntry(Function &F);
716 void markEscapedLocalAllocas(Function &F);
717
718private:
719 friend struct FunctionStackPoisoner;
720
721 void initializeCallbacks(Module &M, const TargetLibraryInfo *TLI);
722
723 bool LooksLikeCodeInBug11395(Instruction *I);
724 bool GlobalIsLinkerInitialized(GlobalVariable *G);
725 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
726 TypeSize TypeStoreSize) const;
727
728 /// Helper to cleanup per-function state.
729 struct FunctionStateRAII {
730 AddressSanitizer *Pass;
731
732 FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
733 assert(Pass->ProcessedAllocas.empty() &&
734 "last pass forgot to clear cache");
735 assert(!Pass->LocalDynamicShadow);
736 }
737
738 ~FunctionStateRAII() {
739 Pass->LocalDynamicShadow = nullptr;
740 Pass->ProcessedAllocas.clear();
741 }
742 };
743
744 LLVMContext *C;
745 const DataLayout *DL;
746 Triple TargetTriple;
747 int LongSize;
748 bool CompileKernel;
749 bool Recover;
750 bool UseAfterScope;
752 Type *IntptrTy;
753 Type *Int8PtrTy;
754 Type *Int32Ty;
755 ShadowMapping Mapping;
756 FunctionCallee AsanHandleNoReturnFunc;
757 FunctionCallee AsanPtrCmpFunction, AsanPtrSubFunction;
758 Constant *AsanShadowGlobal;
759
760 // These arrays is indexed by AccessIsWrite, Experiment and log2(AccessSize).
761 FunctionCallee AsanErrorCallback[2][2][kNumberOfAccessSizes];
762 FunctionCallee AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
763
764 // These arrays is indexed by AccessIsWrite and Experiment.
765 FunctionCallee AsanErrorCallbackSized[2][2];
766 FunctionCallee AsanMemoryAccessCallbackSized[2][2];
767
768 FunctionCallee AsanMemmove, AsanMemcpy, AsanMemset;
769 Value *LocalDynamicShadow = nullptr;
770 const StackSafetyGlobalInfo *SSGI;
771 DenseMap<const AllocaInst *, bool> ProcessedAllocas;
772
773 FunctionCallee AMDGPUAddressShared;
774 FunctionCallee AMDGPUAddressPrivate;
775};
776
777class ModuleAddressSanitizer {
778public:
779 ModuleAddressSanitizer(Module &M, bool CompileKernel = false,
780 bool Recover = false, bool UseGlobalsGC = true,
781 bool UseOdrIndicator = true,
782 AsanDtorKind DestructorKind = AsanDtorKind::Global,
783 AsanCtorKind ConstructorKind = AsanCtorKind::Global)
784 : CompileKernel(ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan
785 : CompileKernel),
786 Recover(ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover),
787 UseGlobalsGC(UseGlobalsGC && ClUseGlobalsGC && !this->CompileKernel),
788 // Enable aliases as they should have no downside with ODR indicators.
789 UsePrivateAlias(ClUsePrivateAlias.getNumOccurrences() > 0
791 : UseOdrIndicator),
792 UseOdrIndicator(ClUseOdrIndicator.getNumOccurrences() > 0
794 : UseOdrIndicator),
795 // Not a typo: ClWithComdat is almost completely pointless without
796 // ClUseGlobalsGC (because then it only works on modules without
797 // globals, which are rare); it is a prerequisite for ClUseGlobalsGC;
798 // and both suffer from gold PR19002 for which UseGlobalsGC constructor
799 // argument is designed as workaround. Therefore, disable both
800 // ClWithComdat and ClUseGlobalsGC unless the frontend says it's ok to
801 // do globals-gc.
802 UseCtorComdat(UseGlobalsGC && ClWithComdat && !this->CompileKernel),
803 DestructorKind(DestructorKind),
804 ConstructorKind(ConstructorKind) {
805 C = &(M.getContext());
806 int LongSize = M.getDataLayout().getPointerSizeInBits();
807 IntptrTy = Type::getIntNTy(*C, LongSize);
808 TargetTriple = Triple(M.getTargetTriple());
809 Mapping = getShadowMapping(TargetTriple, LongSize, this->CompileKernel);
810
811 if (ClOverrideDestructorKind != AsanDtorKind::Invalid)
812 this->DestructorKind = ClOverrideDestructorKind;
813 assert(this->DestructorKind != AsanDtorKind::Invalid);
814 }
815
816 bool instrumentModule(Module &);
817
818private:
819 void initializeCallbacks(Module &M);
820
821 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M, bool *CtorComdat);
822 void InstrumentGlobalsCOFF(IRBuilder<> &IRB, Module &M,
823 ArrayRef<GlobalVariable *> ExtendedGlobals,
824 ArrayRef<Constant *> MetadataInitializers);
825 void InstrumentGlobalsELF(IRBuilder<> &IRB, Module &M,
826 ArrayRef<GlobalVariable *> ExtendedGlobals,
827 ArrayRef<Constant *> MetadataInitializers,
828 const std::string &UniqueModuleId);
829 void InstrumentGlobalsMachO(IRBuilder<> &IRB, Module &M,
830 ArrayRef<GlobalVariable *> ExtendedGlobals,
831 ArrayRef<Constant *> MetadataInitializers);
832 void
833 InstrumentGlobalsWithMetadataArray(IRBuilder<> &IRB, Module &M,
834 ArrayRef<GlobalVariable *> ExtendedGlobals,
835 ArrayRef<Constant *> MetadataInitializers);
836
837 GlobalVariable *CreateMetadataGlobal(Module &M, Constant *Initializer,
838 StringRef OriginalName);
839 void SetComdatForGlobalMetadata(GlobalVariable *G, GlobalVariable *Metadata,
840 StringRef InternalSuffix);
841 Instruction *CreateAsanModuleDtor(Module &M);
842
843 const GlobalVariable *getExcludedAliasedGlobal(const GlobalAlias &GA) const;
844 bool shouldInstrumentGlobal(GlobalVariable *G) const;
845 bool ShouldUseMachOGlobalsSection() const;
846 StringRef getGlobalMetadataSection() const;
847 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
848 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
849 uint64_t getMinRedzoneSizeForGlobal() const {
850 return getRedzoneSizeForScale(Mapping.Scale);
851 }
852 uint64_t getRedzoneSizeForGlobal(uint64_t SizeInBytes) const;
853 int GetAsanVersion(const Module &M) const;
854
855 bool CompileKernel;
856 bool Recover;
857 bool UseGlobalsGC;
858 bool UsePrivateAlias;
859 bool UseOdrIndicator;
860 bool UseCtorComdat;
861 AsanDtorKind DestructorKind;
862 AsanCtorKind ConstructorKind;
863 Type *IntptrTy;
864 LLVMContext *C;
865 Triple TargetTriple;
866 ShadowMapping Mapping;
867 FunctionCallee AsanPoisonGlobals;
868 FunctionCallee AsanUnpoisonGlobals;
869 FunctionCallee AsanRegisterGlobals;
870 FunctionCallee AsanUnregisterGlobals;
871 FunctionCallee AsanRegisterImageGlobals;
872 FunctionCallee AsanUnregisterImageGlobals;
873 FunctionCallee AsanRegisterElfGlobals;
874 FunctionCallee AsanUnregisterElfGlobals;
875
876 Function *AsanCtorFunction = nullptr;
877 Function *AsanDtorFunction = nullptr;
878};
879
880// Stack poisoning does not play well with exception handling.
881// When an exception is thrown, we essentially bypass the code
882// that unpoisones the stack. This is why the run-time library has
883// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
884// stack in the interceptor. This however does not work inside the
885// actual function which catches the exception. Most likely because the
886// compiler hoists the load of the shadow value somewhere too high.
887// This causes asan to report a non-existing bug on 453.povray.
888// It sounds like an LLVM bug.
889struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
890 Function &F;
891 AddressSanitizer &ASan;
892 DIBuilder DIB;
893 LLVMContext *C;
894 Type *IntptrTy;
895 Type *IntptrPtrTy;
896 ShadowMapping Mapping;
897
899 SmallVector<AllocaInst *, 16> StaticAllocasToMoveUp;
901
902 FunctionCallee AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
903 AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
904 FunctionCallee AsanSetShadowFunc[0x100] = {};
905 FunctionCallee AsanPoisonStackMemoryFunc, AsanUnpoisonStackMemoryFunc;
906 FunctionCallee AsanAllocaPoisonFunc, AsanAllocasUnpoisonFunc;
907
908 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
909 struct AllocaPoisonCall {
910 IntrinsicInst *InsBefore;
911 AllocaInst *AI;
913 bool DoPoison;
914 };
915 SmallVector<AllocaPoisonCall, 8> DynamicAllocaPoisonCallVec;
916 SmallVector<AllocaPoisonCall, 8> StaticAllocaPoisonCallVec;
917 bool HasUntracedLifetimeIntrinsic = false;
918
919 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
920 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
921 AllocaInst *DynamicAllocaLayout = nullptr;
922 IntrinsicInst *LocalEscapeCall = nullptr;
923
924 bool HasInlineAsm = false;
925 bool HasReturnsTwiceCall = false;
926 bool PoisonStack;
927
928 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
929 : F(F), ASan(ASan), DIB(*F.getParent(), /*AllowUnresolved*/ false),
930 C(ASan.C), IntptrTy(ASan.IntptrTy),
931 IntptrPtrTy(PointerType::get(IntptrTy, 0)), Mapping(ASan.Mapping),
932 PoisonStack(ClStack &&
933 !Triple(F.getParent()->getTargetTriple()).isAMDGPU()) {}
934
935 bool runOnFunction() {
936 if (!PoisonStack)
937 return false;
938
940 copyArgsPassedByValToAllocas();
941
942 // Collect alloca, ret, lifetime instructions etc.
943 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
944
945 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
946
947 initializeCallbacks(*F.getParent());
948
949 if (HasUntracedLifetimeIntrinsic) {
950 // If there are lifetime intrinsics which couldn't be traced back to an
951 // alloca, we may not know exactly when a variable enters scope, and
952 // therefore should "fail safe" by not poisoning them.
953 StaticAllocaPoisonCallVec.clear();
954 DynamicAllocaPoisonCallVec.clear();
955 }
956
957 processDynamicAllocas();
958 processStaticAllocas();
959
960 if (ClDebugStack) {
961 LLVM_DEBUG(dbgs() << F);
962 }
963 return true;
964 }
965
966 // Arguments marked with the "byval" attribute are implicitly copied without
967 // using an alloca instruction. To produce redzones for those arguments, we
968 // copy them a second time into memory allocated with an alloca instruction.
969 void copyArgsPassedByValToAllocas();
970
971 // Finds all Alloca instructions and puts
972 // poisoned red zones around all of them.
973 // Then unpoison everything back before the function returns.
974 void processStaticAllocas();
975 void processDynamicAllocas();
976
977 void createDynamicAllocasInitStorage();
978
979 // ----------------------- Visitors.
980 /// Collect all Ret instructions, or the musttail call instruction if it
981 /// precedes the return instruction.
982 void visitReturnInst(ReturnInst &RI) {
984 RetVec.push_back(CI);
985 else
986 RetVec.push_back(&RI);
987 }
988
989 /// Collect all Resume instructions.
990 void visitResumeInst(ResumeInst &RI) { RetVec.push_back(&RI); }
991
992 /// Collect all CatchReturnInst instructions.
993 void visitCleanupReturnInst(CleanupReturnInst &CRI) { RetVec.push_back(&CRI); }
994
995 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
996 Value *SavedStack) {
997 IRBuilder<> IRB(InstBefore);
998 Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
999 // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
1000 // need to adjust extracted SP to compute the address of the most recent
1001 // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
1002 // this purpose.
1003 if (!isa<ReturnInst>(InstBefore)) {
1004 Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
1005 InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
1006 {IntptrTy});
1007
1008 Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
1009
1010 DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
1011 DynamicAreaOffset);
1012 }
1013
1014 IRB.CreateCall(
1015 AsanAllocasUnpoisonFunc,
1016 {IRB.CreateLoad(IntptrTy, DynamicAllocaLayout), DynamicAreaPtr});
1017 }
1018
1019 // Unpoison dynamic allocas redzones.
1020 void unpoisonDynamicAllocas() {
1021 for (Instruction *Ret : RetVec)
1022 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
1023
1024 for (Instruction *StackRestoreInst : StackRestoreVec)
1025 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
1026 StackRestoreInst->getOperand(0));
1027 }
1028
1029 // Deploy and poison redzones around dynamic alloca call. To do this, we
1030 // should replace this call with another one with changed parameters and
1031 // replace all its uses with new address, so
1032 // addr = alloca type, old_size, align
1033 // is replaced by
1034 // new_size = (old_size + additional_size) * sizeof(type)
1035 // tmp = alloca i8, new_size, max(align, 32)
1036 // addr = tmp + 32 (first 32 bytes are for the left redzone).
1037 // Additional_size is added to make new memory allocation contain not only
1038 // requested memory, but also left, partial and right redzones.
1039 void handleDynamicAllocaCall(AllocaInst *AI);
1040
1041 /// Collect Alloca instructions we want (and can) handle.
1042 void visitAllocaInst(AllocaInst &AI) {
1043 // FIXME: Handle scalable vectors instead of ignoring them.
1044 if (!ASan.isInterestingAlloca(AI) ||
1045 isa<ScalableVectorType>(AI.getAllocatedType())) {
1046 if (AI.isStaticAlloca()) {
1047 // Skip over allocas that are present *before* the first instrumented
1048 // alloca, we don't want to move those around.
1049 if (AllocaVec.empty())
1050 return;
1051
1052 StaticAllocasToMoveUp.push_back(&AI);
1053 }
1054 return;
1055 }
1056
1057 if (!AI.isStaticAlloca())
1058 DynamicAllocaVec.push_back(&AI);
1059 else
1060 AllocaVec.push_back(&AI);
1061 }
1062
1063 /// Collect lifetime intrinsic calls to check for use-after-scope
1064 /// errors.
1067 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
1068 if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
1069 if (!ASan.UseAfterScope)
1070 return;
1071 if (!II.isLifetimeStartOrEnd())
1072 return;
1073 // Found lifetime intrinsic, add ASan instrumentation if necessary.
1074 auto *Size = cast<ConstantInt>(II.getArgOperand(0));
1075 // If size argument is undefined, don't do anything.
1076 if (Size->isMinusOne()) return;
1077 // Check that size doesn't saturate uint64_t and can
1078 // be stored in IntptrTy.
1079 const uint64_t SizeValue = Size->getValue().getLimitedValue();
1080 if (SizeValue == ~0ULL ||
1081 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
1082 return;
1083 // Find alloca instruction that corresponds to llvm.lifetime argument.
1084 // Currently we can only handle lifetime markers pointing to the
1085 // beginning of the alloca.
1086 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1), true);
1087 if (!AI) {
1088 HasUntracedLifetimeIntrinsic = true;
1089 return;
1090 }
1091 // We're interested only in allocas we can handle.
1092 if (!ASan.isInterestingAlloca(*AI))
1093 return;
1094 bool DoPoison = (ID == Intrinsic::lifetime_end);
1095 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
1096 if (AI->isStaticAlloca())
1097 StaticAllocaPoisonCallVec.push_back(APC);
1099 DynamicAllocaPoisonCallVec.push_back(APC);
1100 }
1101
1102 void visitCallBase(CallBase &CB) {
1103 if (CallInst *CI = dyn_cast<CallInst>(&CB)) {
1104 HasInlineAsm |= CI->isInlineAsm() && &CB != ASan.LocalDynamicShadow;
1105 HasReturnsTwiceCall |= CI->canReturnTwice();
1106 }
1107 }
1108
1109 // ---------------------- Helpers.
1110 void initializeCallbacks(Module &M);
1111
1112 // Copies bytes from ShadowBytes into shadow memory for indexes where
1113 // ShadowMask is not zero. If ShadowMask[i] is zero, we assume that
1114 // ShadowBytes[i] is constantly zero and doesn't need to be overwritten.
1115 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
1116 IRBuilder<> &IRB, Value *ShadowBase);
1117 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
1118 size_t Begin, size_t End, IRBuilder<> &IRB,
1119 Value *ShadowBase);
1120 void copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
1121 ArrayRef<uint8_t> ShadowBytes, size_t Begin,
1122 size_t End, IRBuilder<> &IRB, Value *ShadowBase);
1123
1124 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
1125
1126 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
1127 bool Dynamic);
1128 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
1129 Instruction *ThenTerm, Value *ValueIfFalse);
1130};
1131
1132} // end anonymous namespace
1133
1135 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
1137 OS, MapClassName2PassName);
1138 OS << '<';
1139 if (Options.CompileKernel)
1140 OS << "kernel";
1141 OS << '>';
1142}
1143
1145 const AddressSanitizerOptions &Options, bool UseGlobalGC,
1146 bool UseOdrIndicator, AsanDtorKind DestructorKind,
1147 AsanCtorKind ConstructorKind)
1148 : Options(Options), UseGlobalGC(UseGlobalGC),
1149 UseOdrIndicator(UseOdrIndicator), DestructorKind(DestructorKind),
1150 ConstructorKind(ClConstructorKind) {}
1151
1154 ModuleAddressSanitizer ModuleSanitizer(M, Options.CompileKernel,
1155 Options.Recover, UseGlobalGC,
1156 UseOdrIndicator, DestructorKind,
1157 ConstructorKind);
1158 bool Modified = false;
1159 auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1160 const StackSafetyGlobalInfo *const SSGI =
1162 for (Function &F : M) {
1163 AddressSanitizer FunctionSanitizer(M, SSGI, Options.CompileKernel,
1164 Options.Recover, Options.UseAfterScope,
1165 Options.UseAfterReturn);
1167 Modified |= FunctionSanitizer.instrumentFunction(F, &TLI);
1168 }
1169 Modified |= ModuleSanitizer.instrumentModule(M);
1170 if (!Modified)
1171 return PreservedAnalyses::all();
1172
1174 // GlobalsAA is considered stateless and does not get invalidated unless
1175 // explicitly invalidated; PreservedAnalyses::none() is not enough. Sanitizers
1176 // make changes that require GlobalsAA to be invalidated.
1177 PA.abandon<GlobalsAA>();
1178 return PA;
1179}
1180
1182 size_t Res = llvm::countr_zero(TypeSize / 8);
1184 return Res;
1185}
1186
1187/// Check if \p G has been created by a trusted compiler pass.
1189 // Do not instrument @llvm.global_ctors, @llvm.used, etc.
1190 if (G->getName().startswith("llvm.") ||
1191 // Do not instrument gcov counter arrays.
1192 G->getName().startswith("__llvm_gcov_ctr") ||
1193 // Do not instrument rtti proxy symbols for function sanitizer.
1194 G->getName().startswith("__llvm_rtti_proxy"))
1195 return true;
1196
1197 // Do not instrument asan globals.
1198 if (G->getName().startswith(kAsanGenPrefix) ||
1199 G->getName().startswith(kSanCovGenPrefix) ||
1200 G->getName().startswith(kODRGenPrefix))
1201 return true;
1202
1203 return false;
1204}
1205
1207 Type *PtrTy = cast<PointerType>(Addr->getType()->getScalarType());
1208 unsigned int AddrSpace = PtrTy->getPointerAddressSpace();
1209 if (AddrSpace == 3 || AddrSpace == 5)
1210 return true;
1211 return false;
1212}
1213
1214Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
1215 // Shadow >> scale
1216 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
1217 if (Mapping.Offset == 0) return Shadow;
1218 // (Shadow >> scale) | offset
1219 Value *ShadowBase;
1220 if (LocalDynamicShadow)
1221 ShadowBase = LocalDynamicShadow;
1222 else
1223 ShadowBase = ConstantInt::get(IntptrTy, Mapping.Offset);
1224 if (Mapping.OrShadowOffset)
1225 return IRB.CreateOr(Shadow, ShadowBase);
1226 else
1227 return IRB.CreateAdd(Shadow, ShadowBase);
1228}
1229
1230// Instrument memset/memmove/memcpy
1231void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
1232 IRBuilder<> IRB(MI);
1233 if (isa<MemTransferInst>(MI)) {
1234 IRB.CreateCall(
1235 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
1236 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1237 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
1238 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
1239 } else if (isa<MemSetInst>(MI)) {
1240 IRB.CreateCall(
1241 AsanMemset,
1242 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1243 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
1244 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
1245 }
1246 MI->eraseFromParent();
1247}
1248
1249/// Check if we want (and can) handle this alloca.
1250bool AddressSanitizer::isInterestingAlloca(const AllocaInst &AI) {
1251 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
1252
1253 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
1254 return PreviouslySeenAllocaInfo->getSecond();
1255
1256 bool IsInteresting =
1257 (AI.getAllocatedType()->isSized() &&
1258 // alloca() may be called with 0 size, ignore it.
1259 ((!AI.isStaticAlloca()) || !getAllocaSizeInBytes(AI).isZero()) &&
1260 // We are only interested in allocas not promotable to registers.
1261 // Promotable allocas are common under -O0.
1263 // inalloca allocas are not treated as static, and we don't want
1264 // dynamic alloca instrumentation for them as well.
1265 !AI.isUsedWithInAlloca() &&
1266 // swifterror allocas are register promoted by ISel
1267 !AI.isSwiftError() &&
1268 // safe allocas are not interesting
1269 !(SSGI && SSGI->isSafe(AI)));
1270
1271 ProcessedAllocas[&AI] = IsInteresting;
1272 return IsInteresting;
1273}
1274
1275bool AddressSanitizer::ignoreAccess(Instruction *Inst, Value *Ptr) {
1276 // Instrument accesses from different address spaces only for AMDGPU.
1277 Type *PtrTy = cast<PointerType>(Ptr->getType()->getScalarType());
1278 if (PtrTy->getPointerAddressSpace() != 0 &&
1279 !(TargetTriple.isAMDGPU() && !isUnsupportedAMDGPUAddrspace(Ptr)))
1280 return true;
1281
1282 // Ignore swifterror addresses.
1283 // swifterror memory addresses are mem2reg promoted by instruction
1284 // selection. As such they cannot have regular uses like an instrumentation
1285 // function and it makes no sense to track them as memory.
1286 if (Ptr->isSwiftError())
1287 return true;
1288
1289 // Treat memory accesses to promotable allocas as non-interesting since they
1290 // will not cause memory violations. This greatly speeds up the instrumented
1291 // executable at -O0.
1292 if (auto AI = dyn_cast_or_null<AllocaInst>(Ptr))
1293 if (ClSkipPromotableAllocas && !isInterestingAlloca(*AI))
1294 return true;
1295
1296 if (SSGI != nullptr && SSGI->stackAccessIsSafe(*Inst) &&
1298 return true;
1299
1300 return false;
1301}
1302
1303void AddressSanitizer::getInterestingMemoryOperands(
1305 // Do not instrument the load fetching the dynamic shadow address.
1306 if (LocalDynamicShadow == I)
1307 return;
1308
1309 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1310 if (!ClInstrumentReads || ignoreAccess(I, LI->getPointerOperand()))
1311 return;
1312 Interesting.emplace_back(I, LI->getPointerOperandIndex(), false,
1313 LI->getType(), LI->getAlign());
1314 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1315 if (!ClInstrumentWrites || ignoreAccess(I, SI->getPointerOperand()))
1316 return;
1317 Interesting.emplace_back(I, SI->getPointerOperandIndex(), true,
1318 SI->getValueOperand()->getType(), SI->getAlign());
1319 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
1320 if (!ClInstrumentAtomics || ignoreAccess(I, RMW->getPointerOperand()))
1321 return;
1322 Interesting.emplace_back(I, RMW->getPointerOperandIndex(), true,
1323 RMW->getValOperand()->getType(), std::nullopt);
1324 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
1325 if (!ClInstrumentAtomics || ignoreAccess(I, XCHG->getPointerOperand()))
1326 return;
1327 Interesting.emplace_back(I, XCHG->getPointerOperandIndex(), true,
1328 XCHG->getCompareOperand()->getType(),
1329 std::nullopt);
1330 } else if (auto CI = dyn_cast<CallInst>(I)) {
1331 switch (CI->getIntrinsicID()) {
1332 case Intrinsic::masked_load:
1333 case Intrinsic::masked_store: {
1334 bool IsWrite = CI->getIntrinsicID() == Intrinsic::masked_store;
1335 // Masked store has an initial operand for the value.
1336 unsigned OpOffset = IsWrite ? 1 : 0;
1337 if (IsWrite ? !ClInstrumentWrites : !ClInstrumentReads)
1338 return;
1339
1340 auto BasePtr = CI->getOperand(OpOffset);
1341 if (ignoreAccess(I, BasePtr))
1342 return;
1343 Type *Ty = IsWrite ? CI->getArgOperand(0)->getType() : CI->getType();
1344 MaybeAlign Alignment = Align(1);
1345 // Otherwise no alignment guarantees. We probably got Undef.
1346 if (auto *Op = dyn_cast<ConstantInt>(CI->getOperand(1 + OpOffset)))
1347 Alignment = Op->getMaybeAlignValue();
1348 Value *Mask = CI->getOperand(2 + OpOffset);
1349 Interesting.emplace_back(I, OpOffset, IsWrite, Ty, Alignment, Mask);
1350 break;
1351 }
1352 case Intrinsic::vp_load:
1353 case Intrinsic::vp_store:
1354 case Intrinsic::experimental_vp_strided_load:
1355 case Intrinsic::experimental_vp_strided_store: {
1356 auto *VPI = cast<VPIntrinsic>(CI);
1357 unsigned IID = CI->getIntrinsicID();
1358 bool IsWrite = CI->getType()->isVoidTy();
1359 if (IsWrite ? !ClInstrumentWrites : !ClInstrumentReads)
1360 return;
1361 unsigned PtrOpNo = *VPI->getMemoryPointerParamPos(IID);
1362 Type *Ty = IsWrite ? CI->getArgOperand(0)->getType() : CI->getType();
1363 MaybeAlign Alignment = VPI->getOperand(PtrOpNo)->getPointerAlignment(*DL);
1364 Value *Stride = nullptr;
1365 if (IID == Intrinsic::experimental_vp_strided_store ||
1366 IID == Intrinsic::experimental_vp_strided_load) {
1367 Stride = VPI->getOperand(PtrOpNo + 1);
1368 // Use the pointer alignment as the element alignment if the stride is a
1369 // mutiple of the pointer alignment. Otherwise, the element alignment
1370 // should be Align(1).
1371 unsigned PointerAlign = Alignment.valueOrOne().value();
1372 if (!isa<ConstantInt>(Stride) ||
1373 cast<ConstantInt>(Stride)->getZExtValue() % PointerAlign != 0)
1374 Alignment = Align(1);
1375 }
1376 Interesting.emplace_back(I, PtrOpNo, IsWrite, Ty, Alignment,
1377 VPI->getMaskParam(), VPI->getVectorLengthParam(),
1378 Stride);
1379 break;
1380 }
1381 case Intrinsic::vp_gather:
1382 case Intrinsic::vp_scatter: {
1383 auto *VPI = cast<VPIntrinsic>(CI);
1384 unsigned IID = CI->getIntrinsicID();
1385 bool IsWrite = IID == Intrinsic::vp_scatter;
1386 if (IsWrite ? !ClInstrumentWrites : !ClInstrumentReads)
1387 return;
1388 unsigned PtrOpNo = *VPI->getMemoryPointerParamPos(IID);
1389 Type *Ty = IsWrite ? CI->getArgOperand(0)->getType() : CI->getType();
1390 MaybeAlign Alignment = VPI->getPointerAlignment();
1391 Interesting.emplace_back(I, PtrOpNo, IsWrite, Ty, Alignment,
1392 VPI->getMaskParam(),
1393 VPI->getVectorLengthParam());
1394 break;
1395 }
1396 default:
1397 for (unsigned ArgNo = 0; ArgNo < CI->arg_size(); ArgNo++) {
1398 if (!ClInstrumentByval || !CI->isByValArgument(ArgNo) ||
1399 ignoreAccess(I, CI->getArgOperand(ArgNo)))
1400 continue;
1401 Type *Ty = CI->getParamByValType(ArgNo);
1402 Interesting.emplace_back(I, ArgNo, false, Ty, Align(1));
1403 }
1404 }
1405 }
1406}
1407
1408static bool isPointerOperand(Value *V) {
1409 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
1410}
1411
1412// This is a rough heuristic; it may cause both false positives and
1413// false negatives. The proper implementation requires cooperation with
1414// the frontend.
1416 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
1417 if (!Cmp->isRelational())
1418 return false;
1419 } else {
1420 return false;
1421 }
1422 return isPointerOperand(I->getOperand(0)) &&
1423 isPointerOperand(I->getOperand(1));
1424}
1425
1426// This is a rough heuristic; it may cause both false positives and
1427// false negatives. The proper implementation requires cooperation with
1428// the frontend.
1430 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1431 if (BO->getOpcode() != Instruction::Sub)
1432 return false;
1433 } else {
1434 return false;
1435 }
1436 return isPointerOperand(I->getOperand(0)) &&
1437 isPointerOperand(I->getOperand(1));
1438}
1439
1440bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
1441 // If a global variable does not have dynamic initialization we don't
1442 // have to instrument it. However, if a global does not have initializer
1443 // at all, we assume it has dynamic initializer (in other TU).
1444 if (!G->hasInitializer())
1445 return false;
1446
1447 if (G->hasSanitizerMetadata() && G->getSanitizerMetadata().IsDynInit)
1448 return false;
1449
1450 return true;
1451}
1452
1453void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
1454 Instruction *I) {
1455 IRBuilder<> IRB(I);
1456 FunctionCallee F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
1457 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
1458 for (Value *&i : Param) {
1459 if (i->getType()->isPointerTy())
1460 i = IRB.CreatePointerCast(i, IntptrTy);
1461 }
1462 IRB.CreateCall(F, Param);
1463}
1464
1465static void doInstrumentAddress(AddressSanitizer *Pass, Instruction *I,
1466 Instruction *InsertBefore, Value *Addr,
1467 MaybeAlign Alignment, unsigned Granularity,
1468 TypeSize TypeStoreSize, bool IsWrite,
1469 Value *SizeArgument, bool UseCalls,
1470 uint32_t Exp) {
1471 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
1472 // if the data is properly aligned.
1473 if (!TypeStoreSize.isScalable()) {
1474 const auto FixedSize = TypeStoreSize.getFixedValue();
1475 switch (FixedSize) {
1476 case 8:
1477 case 16:
1478 case 32:
1479 case 64:
1480 case 128:
1481 if (!Alignment || *Alignment >= Granularity ||
1482 *Alignment >= FixedSize / 8)
1483 return Pass->instrumentAddress(I, InsertBefore, Addr, FixedSize,
1484 IsWrite, nullptr, UseCalls, Exp);
1485 }
1486 }
1487 Pass->instrumentUnusualSizeOrAlignment(I, InsertBefore, Addr, TypeStoreSize,
1488 IsWrite, nullptr, UseCalls, Exp);
1489}
1490
1491void AddressSanitizer::instrumentMaskedLoadOrStore(
1492 AddressSanitizer *Pass, const DataLayout &DL, Type *IntptrTy, Value *Mask,
1493 Value *EVL, Value *Stride, Instruction *I, Value *Addr,
1494 MaybeAlign Alignment, unsigned Granularity, Type *OpType, bool IsWrite,
1495 Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1496 auto *VTy = cast<VectorType>(OpType);
1497 TypeSize ElemTypeSize = DL.getTypeStoreSizeInBits(VTy->getScalarType());
1498 auto Zero = ConstantInt::get(IntptrTy, 0);
1499
1500 IRBuilder IB(I);
1501 Instruction *LoopInsertBefore = I;
1502 if (EVL) {
1503 // The end argument of SplitBlockAndInsertForLane is assumed bigger
1504 // than zero, so we should check whether EVL is zero here.
1505 Type *EVLType = EVL->getType();
1506 Value *IsEVLZero = IB.CreateICmpNE(EVL, ConstantInt::get(EVLType, 0));
1507 LoopInsertBefore = SplitBlockAndInsertIfThen(IsEVLZero, I, false);
1508 IB.SetInsertPoint(LoopInsertBefore);
1509 // Cast EVL to IntptrTy.
1510 EVL = IB.CreateZExtOrTrunc(EVL, IntptrTy);
1511 // To avoid undefined behavior for extracting with out of range index, use
1512 // the minimum of evl and element count as trip count.
1513 Value *EC = IB.CreateElementCount(IntptrTy, VTy->getElementCount());
1514 EVL = IB.CreateBinaryIntrinsic(Intrinsic::umin, EVL, EC);
1515 } else {
1516 EVL = IB.CreateElementCount(IntptrTy, VTy->getElementCount());
1517 }
1518
1519 // Cast Stride to IntptrTy.
1520 if (Stride)
1521 Stride = IB.CreateZExtOrTrunc(Stride, IntptrTy);
1522
1523 SplitBlockAndInsertForEachLane(EVL, LoopInsertBefore,
1524 [&](IRBuilderBase &IRB, Value *Index) {
1525 Value *MaskElem = IRB.CreateExtractElement(Mask, Index);
1526 if (auto *MaskElemC = dyn_cast<ConstantInt>(MaskElem)) {
1527 if (MaskElemC->isZero())
1528 // No check
1529 return;
1530 // Unconditional check
1531 } else {
1532 // Conditional check
1534 MaskElem, &*IRB.GetInsertPoint(), false);
1535 IRB.SetInsertPoint(ThenTerm);
1536 }
1537
1538 Value *InstrumentedAddress;
1539 if (isa<VectorType>(Addr->getType())) {
1540 assert(
1541 cast<VectorType>(Addr->getType())->getElementType()->isPointerTy() &&
1542 "Expected vector of pointer.");
1543 InstrumentedAddress = IRB.CreateExtractElement(Addr, Index);
1544 } else if (Stride) {
1545 Index = IRB.CreateMul(Index, Stride);
1547 InstrumentedAddress = IRB.CreateGEP(Type::getInt8Ty(*C), Addr, {Index});
1548 } else {
1549 InstrumentedAddress = IRB.CreateGEP(VTy, Addr, {Zero, Index});
1550 }
1552 InstrumentedAddress, Alignment, Granularity,
1553 ElemTypeSize, IsWrite, SizeArgument, UseCalls, Exp);
1554 });
1555}
1556
1557void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
1558 InterestingMemoryOperand &O, bool UseCalls,
1559 const DataLayout &DL) {
1560 Value *Addr = O.getPtr();
1561
1562 // Optimization experiments.
1563 // The experiments can be used to evaluate potential optimizations that remove
1564 // instrumentation (assess false negatives). Instead of completely removing
1565 // some instrumentation, you set Exp to a non-zero value (mask of optimization
1566 // experiments that want to remove instrumentation of this instruction).
1567 // If Exp is non-zero, this pass will emit special calls into runtime
1568 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
1569 // make runtime terminate the program in a special way (with a different
1570 // exit status). Then you run the new compiler on a buggy corpus, collect
1571 // the special terminations (ideally, you don't see them at all -- no false
1572 // negatives) and make the decision on the optimization.
1574
1575 if (ClOpt && ClOptGlobals) {
1576 // If initialization order checking is disabled, a simple access to a
1577 // dynamically initialized global is always valid.
1578 GlobalVariable *G = dyn_cast<GlobalVariable>(getUnderlyingObject(Addr));
1579 if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
1580 isSafeAccess(ObjSizeVis, Addr, O.TypeStoreSize)) {
1581 NumOptimizedAccessesToGlobalVar++;
1582 return;
1583 }
1584 }
1585
1586 if (ClOpt && ClOptStack) {
1587 // A direct inbounds access to a stack variable is always valid.
1588 if (isa<AllocaInst>(getUnderlyingObject(Addr)) &&
1589 isSafeAccess(ObjSizeVis, Addr, O.TypeStoreSize)) {
1590 NumOptimizedAccessesToStackVar++;
1591 return;
1592 }
1593 }
1594
1595 if (O.IsWrite)
1596 NumInstrumentedWrites++;
1597 else
1598 NumInstrumentedReads++;
1599
1600 unsigned Granularity = 1 << Mapping.Scale;
1601 if (O.MaybeMask) {
1602 instrumentMaskedLoadOrStore(this, DL, IntptrTy, O.MaybeMask, O.MaybeEVL,
1603 O.MaybeStride, O.getInsn(), Addr, O.Alignment,
1604 Granularity, O.OpType, O.IsWrite, nullptr,
1605 UseCalls, Exp);
1606 } else {
1607 doInstrumentAddress(this, O.getInsn(), O.getInsn(), Addr, O.Alignment,
1608 Granularity, O.TypeStoreSize, O.IsWrite, nullptr, UseCalls,
1609 Exp);
1610 }
1611}
1612
1613Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
1614 Value *Addr, bool IsWrite,
1615 size_t AccessSizeIndex,
1616 Value *SizeArgument,
1617 uint32_t Exp) {
1618 IRBuilder<> IRB(InsertBefore);
1619 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1620 CallInst *Call = nullptr;
1621 if (SizeArgument) {
1622 if (Exp == 0)
1623 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1624 {Addr, SizeArgument});
1625 else
1626 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1627 {Addr, SizeArgument, ExpVal});
1628 } else {
1629 if (Exp == 0)
1630 Call =
1631 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1632 else
1633 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1634 {Addr, ExpVal});
1635 }
1636
1637 Call->setCannotMerge();
1638 return Call;
1639}
1640
1641Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
1642 Value *ShadowValue,
1643 uint32_t TypeStoreSize) {
1644 size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;
1645 // Addr & (Granularity - 1)
1646 Value *LastAccessedByte =
1647 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
1648 // (Addr & (Granularity - 1)) + size - 1
1649 if (TypeStoreSize / 8 > 1)
1650 LastAccessedByte = IRB.CreateAdd(
1651 LastAccessedByte, ConstantInt::get(IntptrTy, TypeStoreSize / 8 - 1));
1652 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
1653 LastAccessedByte =
1654 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
1655 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1656 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1657}
1658
1659Instruction *AddressSanitizer::instrumentAMDGPUAddress(
1660 Instruction *OrigIns, Instruction *InsertBefore, Value *Addr,
1661 uint32_t TypeStoreSize, bool IsWrite, Value *SizeArgument) {
1662 // Do not instrument unsupported addrspaces.
1664 return nullptr;
1665 Type *PtrTy = cast<PointerType>(Addr->getType()->getScalarType());
1666 // Follow host instrumentation for global and constant addresses.
1667 if (PtrTy->getPointerAddressSpace() != 0)
1668 return InsertBefore;
1669 // Instrument generic addresses in supported addressspaces.
1670 IRBuilder<> IRB(InsertBefore);
1671 Value *AddrLong = IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy());
1672 Value *IsShared = IRB.CreateCall(AMDGPUAddressShared, {AddrLong});
1673 Value *IsPrivate = IRB.CreateCall(AMDGPUAddressPrivate, {AddrLong});
1674 Value *IsSharedOrPrivate = IRB.CreateOr(IsShared, IsPrivate);
1675 Value *Cmp = IRB.CreateNot(IsSharedOrPrivate);
1676 Value *AddrSpaceZeroLanding =
1677 SplitBlockAndInsertIfThen(Cmp, InsertBefore, false);
1678 InsertBefore = cast<Instruction>(AddrSpaceZeroLanding);
1679 return InsertBefore;
1680}
1681
1682void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
1683 Instruction *InsertBefore, Value *Addr,
1684 uint32_t TypeStoreSize, bool IsWrite,
1685 Value *SizeArgument, bool UseCalls,
1686 uint32_t Exp) {
1687 if (TargetTriple.isAMDGPU()) {
1688 InsertBefore = instrumentAMDGPUAddress(OrigIns, InsertBefore, Addr,
1689 TypeStoreSize, IsWrite, SizeArgument);
1690 if (!InsertBefore)
1691 return;
1692 }
1693
1694 IRBuilder<> IRB(InsertBefore);
1695 size_t AccessSizeIndex = TypeStoreSizeToSizeIndex(TypeStoreSize);
1696 const ASanAccessInfo AccessInfo(IsWrite, CompileKernel, AccessSizeIndex);
1697
1698 if (UseCalls && ClOptimizeCallbacks) {
1699 const ASanAccessInfo AccessInfo(IsWrite, CompileKernel, AccessSizeIndex);
1700 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
1701 IRB.CreateCall(
1702 Intrinsic::getDeclaration(M, Intrinsic::asan_check_memaccess),
1703 {IRB.CreatePointerCast(Addr, Int8PtrTy),
1704 ConstantInt::get(Int32Ty, AccessInfo.Packed)});
1705 return;
1706 }
1707
1708 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1709 if (UseCalls) {
1710 if (Exp == 0)
1711 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1712 AddrLong);
1713 else
1714 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1715 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
1716 return;
1717 }
1718
1719 Type *ShadowTy =
1720 IntegerType::get(*C, std::max(8U, TypeStoreSize >> Mapping.Scale));
1721 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1722 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1723 Value *ShadowValue =
1724 IRB.CreateLoad(ShadowTy, IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
1725
1726 Value *Cmp = IRB.CreateIsNotNull(ShadowValue);
1727 size_t Granularity = 1ULL << Mapping.Scale;
1728 Instruction *CrashTerm = nullptr;
1729
1730 if (ClAlwaysSlowPath || (TypeStoreSize < 8 * Granularity)) {
1731 // We use branch weights for the slow path check, to indicate that the slow
1732 // path is rarely taken. This seems to be the case for SPEC benchmarks.
1734 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
1735 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
1736 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
1737 IRB.SetInsertPoint(CheckTerm);
1738 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeStoreSize);
1739 if (Recover) {
1740 CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
1741 } else {
1742 BasicBlock *CrashBlock =
1743 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
1744 CrashTerm = new UnreachableInst(*C, CrashBlock);
1745 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1746 ReplaceInstWithInst(CheckTerm, NewTerm);
1747 }
1748 } else {
1749 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
1750 }
1751
1752 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
1753 AccessSizeIndex, SizeArgument, Exp);
1754 Crash->setDebugLoc(OrigIns->getDebugLoc());
1755}
1756
1757// Instrument unusual size or unusual alignment.
1758// We can not do it with a single check, so we do 1-byte check for the first
1759// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1760// to report the actual access size.
1761void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1762 Instruction *I, Instruction *InsertBefore, Value *Addr, TypeSize TypeStoreSize,
1763 bool IsWrite, Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1764 IRBuilder<> IRB(InsertBefore);
1765 Value *NumBits = IRB.CreateTypeSize(IntptrTy, TypeStoreSize);
1766 Value *Size = IRB.CreateLShr(NumBits, ConstantInt::get(IntptrTy, 3));
1767
1768 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1769 if (UseCalls) {
1770 if (Exp == 0)
1771 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1772 {AddrLong, Size});
1773 else
1774 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1775 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
1776 } else {
1777 Value *SizeMinusOne = IRB.CreateSub(Size, ConstantInt::get(IntptrTy, 1));
1778 Value *LastByte = IRB.CreateIntToPtr(
1779 IRB.CreateAdd(AddrLong, SizeMinusOne),
1780 Addr->getType());
1781 instrumentAddress(I, InsertBefore, Addr, 8, IsWrite, Size, false, Exp);
1782 instrumentAddress(I, InsertBefore, LastByte, 8, IsWrite, Size, false, Exp);
1783 }
1784}
1785
1786void ModuleAddressSanitizer::poisonOneInitializer(Function &GlobalInit,
1788 // Set up the arguments to our poison/unpoison functions.
1789 IRBuilder<> IRB(&GlobalInit.front(),
1790 GlobalInit.front().getFirstInsertionPt());
1791
1792 // Add a call to poison all external globals before the given function starts.
1793 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1794 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
1795
1796 // Add calls to unpoison all globals before each return instruction.
1797 for (auto &BB : GlobalInit)
1798 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
1799 CallInst::Create(AsanUnpoisonGlobals, "", RI);
1800}
1801
1802void ModuleAddressSanitizer::createInitializerPoisonCalls(
1804 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1805 if (!GV)
1806 return;
1807
1808 ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());
1809 if (!CA)
1810 return;
1811
1812 for (Use &OP : CA->operands()) {
1813 if (isa<ConstantAggregateZero>(OP)) continue;
1814 ConstantStruct *CS = cast<ConstantStruct>(OP);
1815
1816 // Must have a function or null ptr.
1817 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
1818 if (F->getName() == kAsanModuleCtorName) continue;
1819 auto *Priority = cast<ConstantInt>(CS->getOperand(0));
1820 // Don't instrument CTORs that will run before asan.module_ctor.
1821 if (Priority->getLimitedValue() <= GetCtorAndDtorPriority(TargetTriple))
1822 continue;
1823 poisonOneInitializer(*F, ModuleName);
1824 }
1825 }
1826}
1827
1828const GlobalVariable *
1829ModuleAddressSanitizer::getExcludedAliasedGlobal(const GlobalAlias &GA) const {
1830 // In case this function should be expanded to include rules that do not just
1831 // apply when CompileKernel is true, either guard all existing rules with an
1832 // 'if (CompileKernel) { ... }' or be absolutely sure that all these rules
1833 // should also apply to user space.
1834 assert(CompileKernel && "Only expecting to be called when compiling kernel");
1835
1836 const Constant *C = GA.getAliasee();
1837
1838 // When compiling the kernel, globals that are aliased by symbols prefixed
1839 // by "__" are special and cannot be padded with a redzone.
1840 if (GA.getName().startswith("__"))
1841 return dyn_cast<GlobalVariable>(C->stripPointerCastsAndAliases());
1842
1843 return nullptr;
1844}
1845
1846bool ModuleAddressSanitizer::shouldInstrumentGlobal(GlobalVariable *G) const {
1847 Type *Ty = G->getValueType();
1848 LLVM_DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
1849
1850 if (G->hasSanitizerMetadata() && G->getSanitizerMetadata().NoAddress)
1851 return false;
1852 if (!Ty->isSized()) return false;
1853 if (!G->hasInitializer()) return false;
1854 // Globals in address space 1 and 4 are supported for AMDGPU.
1855 if (G->getAddressSpace() &&
1856 !(TargetTriple.isAMDGPU() && !isUnsupportedAMDGPUAddrspace(G)))
1857 return false;
1858 if (GlobalWasGeneratedByCompiler(G)) return false; // Our own globals.
1859 // Two problems with thread-locals:
1860 // - The address of the main thread's copy can't be computed at link-time.
1861 // - Need to poison all copies, not just the main thread's one.
1862 if (G->isThreadLocal()) return false;
1863 // For now, just ignore this Global if the alignment is large.
1864 if (G->getAlign() && *G->getAlign() > getMinRedzoneSizeForGlobal()) return false;
1865
1866 // For non-COFF targets, only instrument globals known to be defined by this
1867 // TU.
1868 // FIXME: We can instrument comdat globals on ELF if we are using the
1869 // GC-friendly metadata scheme.
1870 if (!TargetTriple.isOSBinFormatCOFF()) {
1871 if (!G->hasExactDefinition() || G->hasComdat())
1872 return false;
1873 } else {
1874 // On COFF, don't instrument non-ODR linkages.
1875 if (G->isInterposable())
1876 return false;
1877 }
1878
1879 // If a comdat is present, it must have a selection kind that implies ODR
1880 // semantics: no duplicates, any, or exact match.
1881 if (Comdat *C = G->getComdat()) {
1882 switch (C->getSelectionKind()) {
1883 case Comdat::Any:
1884 case Comdat::ExactMatch:
1886 break;
1887 case Comdat::Largest:
1888 case Comdat::SameSize:
1889 return false;
1890 }
1891 }
1892
1893 if (G->hasSection()) {
1894 // The kernel uses explicit sections for mostly special global variables
1895 // that we should not instrument. E.g. the kernel may rely on their layout
1896 // without redzones, or remove them at link time ("discard.*"), etc.
1897 if (CompileKernel)
1898 return false;
1899
1900 StringRef Section = G->getSection();
1901
1902 // Globals from llvm.metadata aren't emitted, do not instrument them.
1903 if (Section == "llvm.metadata") return false;
1904 // Do not instrument globals from special LLVM sections.
1905 if (Section.contains("__llvm") || Section.contains("__LLVM"))
1906 return false;
1907
1908 // Do not instrument function pointers to initialization and termination
1909 // routines: dynamic linker will not properly handle redzones.
1910 if (Section.startswith(".preinit_array") ||
1911 Section.startswith(".init_array") ||
1912 Section.startswith(".fini_array")) {
1913 return false;
1914 }
1915
1916 // Do not instrument user-defined sections (with names resembling
1917 // valid C identifiers)
1918 if (TargetTriple.isOSBinFormatELF()) {
1919 if (llvm::all_of(Section,
1920 [](char c) { return llvm::isAlnum(c) || c == '_'; }))
1921 return false;
1922 }
1923
1924 // On COFF, if the section name contains '$', it is highly likely that the
1925 // user is using section sorting to create an array of globals similar to
1926 // the way initialization callbacks are registered in .init_array and
1927 // .CRT$XCU. The ATL also registers things in .ATL$__[azm]. Adding redzones
1928 // to such globals is counterproductive, because the intent is that they
1929 // will form an array, and out-of-bounds accesses are expected.
1930 // See https://github.com/google/sanitizers/issues/305
1931 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1932 if (TargetTriple.isOSBinFormatCOFF() && Section.contains('$')) {
1933 LLVM_DEBUG(dbgs() << "Ignoring global in sorted section (contains '$'): "
1934 << *G << "\n");
1935 return false;
1936 }
1937
1938 if (TargetTriple.isOSBinFormatMachO()) {
1939 StringRef ParsedSegment, ParsedSection;
1940 unsigned TAA = 0, StubSize = 0;
1941 bool TAAParsed;
1943 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize));
1944
1945 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1946 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1947 // them.
1948 if (ParsedSegment == "__OBJC" ||
1949 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1950 LLVM_DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1951 return false;
1952 }
1953 // See https://github.com/google/sanitizers/issues/32
1954 // Constant CFString instances are compiled in the following way:
1955 // -- the string buffer is emitted into
1956 // __TEXT,__cstring,cstring_literals
1957 // -- the constant NSConstantString structure referencing that buffer
1958 // is placed into __DATA,__cfstring
1959 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1960 // Moreover, it causes the linker to crash on OS X 10.7
1961 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1962 LLVM_DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1963 return false;
1964 }
1965 // The linker merges the contents of cstring_literals and removes the
1966 // trailing zeroes.
1967 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1968 LLVM_DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1969 return false;
1970 }
1971 }
1972 }
1973
1974 if (CompileKernel) {
1975 // Globals that prefixed by "__" are special and cannot be padded with a
1976 // redzone.
1977 if (G->getName().startswith("__"))
1978 return false;
1979 }
1980
1981 return true;
1982}
1983
1984// On Mach-O platforms, we emit global metadata in a separate section of the
1985// binary in order to allow the linker to properly dead strip. This is only
1986// supported on recent versions of ld64.
1987bool ModuleAddressSanitizer::ShouldUseMachOGlobalsSection() const {
1988 if (!TargetTriple.isOSBinFormatMachO())
1989 return false;
1990
1991 if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
1992 return true;
1993 if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
1994 return true;
1995 if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
1996 return true;
1997 if (TargetTriple.isDriverKit())
1998 return true;
1999
2000 return false;
2001}
2002
2003StringRef ModuleAddressSanitizer::getGlobalMetadataSection() const {
2004 switch (TargetTriple.getObjectFormat()) {
2005 case Triple::COFF: return ".ASAN$GL";
2006 case Triple::ELF: return "asan_globals";
2007 case Triple::MachO: return "__DATA,__asan_globals,regular";
2008 case Triple::Wasm:
2009 case Triple::GOFF:
2010 case Triple::SPIRV:
2011 case Triple::XCOFF:
2014 "ModuleAddressSanitizer not implemented for object file format");
2016 break;
2017 }
2018 llvm_unreachable("unsupported object format");
2019}
2020
2021void ModuleAddressSanitizer::initializeCallbacks(Module &M) {
2022 IRBuilder<> IRB(*C);
2023
2024 // Declare our poisoning and unpoisoning functions.
2025 AsanPoisonGlobals =
2026 M.getOrInsertFunction(kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy);
2027 AsanUnpoisonGlobals =
2028 M.getOrInsertFunction(kAsanUnpoisonGlobalsName, IRB.getVoidTy());
2029
2030 // Declare functions that register/unregister globals.
2031 AsanRegisterGlobals = M.getOrInsertFunction(
2032 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy);
2033 AsanUnregisterGlobals = M.getOrInsertFunction(
2034 kAsanUnregisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy);
2035
2036 // Declare the functions that find globals in a shared object and then invoke
2037 // the (un)register function on them.
2038 AsanRegisterImageGlobals = M.getOrInsertFunction(
2039 kAsanRegisterImageGlobalsName, IRB.getVoidTy(), IntptrTy);
2040 AsanUnregisterImageGlobals = M.getOrInsertFunction(
2042
2043 AsanRegisterElfGlobals =
2044 M.getOrInsertFunction(kAsanRegisterElfGlobalsName, IRB.getVoidTy(),
2045 IntptrTy, IntptrTy, IntptrTy);
2046 AsanUnregisterElfGlobals =
2047 M.getOrInsertFunction(kAsanUnregisterElfGlobalsName, IRB.getVoidTy(),
2048 IntptrTy, IntptrTy, IntptrTy);
2049}
2050
2051// Put the metadata and the instrumented global in the same group. This ensures
2052// that the metadata is discarded if the instrumented global is discarded.
2053void ModuleAddressSanitizer::SetComdatForGlobalMetadata(
2054 GlobalVariable *G, GlobalVariable *Metadata, StringRef InternalSuffix) {
2055 Module &M = *G->getParent();
2056 Comdat *C = G->getComdat();
2057 if (!C) {
2058 if (!G->hasName()) {
2059 // If G is unnamed, it must be internal. Give it an artificial name
2060 // so we can put it in a comdat.
2061 assert(G->hasLocalLinkage());
2062 G->setName(Twine(kAsanGenPrefix) + "_anon_global");
2063 }
2064
2065 if (!InternalSuffix.empty() && G->hasLocalLinkage()) {
2066 std::string Name = std::string(G->getName());
2067 Name += InternalSuffix;
2068 C = M.getOrInsertComdat(Name);
2069 } else {
2070 C = M.getOrInsertComdat(G->getName());
2071 }
2072
2073 // Make this IMAGE_COMDAT_SELECT_NODUPLICATES on COFF. Also upgrade private
2074 // linkage to internal linkage so that a symbol table entry is emitted. This
2075 // is necessary in order to create the comdat group.
2076 if (TargetTriple.isOSBinFormatCOFF()) {
2077 C->setSelectionKind(Comdat::NoDeduplicate);
2078 if (G->hasPrivateLinkage())
2079 G->setLinkage(GlobalValue::InternalLinkage);
2080 }
2081 G->setComdat(C);
2082 }
2083
2084 assert(G->hasComdat());
2085 Metadata->setComdat(G->getComdat());
2086}
2087
2088// Create a separate metadata global and put it in the appropriate ASan
2089// global registration section.
2091ModuleAddressSanitizer::CreateMetadataGlobal(Module &M, Constant *Initializer,
2092 StringRef OriginalName) {
2093 auto Linkage = TargetTriple.isOSBinFormatMachO()
2097 M, Initializer->getType(), false, Linkage, Initializer,
2098 Twine("__asan_global_") + GlobalValue::dropLLVMManglingEscape(OriginalName));
2099 Metadata->setSection(getGlobalMetadataSection());
2100 return Metadata;
2101}
2102
2103Instruction *ModuleAddressSanitizer::CreateAsanModuleDtor(Module &M) {
2104 AsanDtorFunction = Function::createWithDefaultAttr(
2107 AsanDtorFunction->addFnAttr(Attribute::NoUnwind);
2108 // Ensure Dtor cannot be discarded, even if in a comdat.
2109 appendToUsed(M, {AsanDtorFunction});
2110 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
2111
2112 return ReturnInst::Create(*C, AsanDtorBB);
2113}
2114
2115void ModuleAddressSanitizer::InstrumentGlobalsCOFF(
2116 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
2117 ArrayRef<Constant *> MetadataInitializers) {
2118 assert(ExtendedGlobals.size() == MetadataInitializers.size());
2119 auto &DL = M.getDataLayout();
2120
2121 SmallVector<GlobalValue *, 16> MetadataGlobals(ExtendedGlobals.size());
2122 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
2123 Constant *Initializer = MetadataInitializers[i];
2124 GlobalVariable *G = ExtendedGlobals[i];
2126 CreateMetadataGlobal(M, Initializer, G->getName());
2127 MDNode *MD = MDNode::get(M.getContext(), ValueAsMetadata::get(G));
2128 Metadata->setMetadata(LLVMContext::MD_associated, MD);
2129 MetadataGlobals[i] = Metadata;
2130
2131 // The MSVC linker always inserts padding when linking incrementally. We
2132 // cope with that by aligning each struct to its size, which must be a power
2133 // of two.
2134 unsigned SizeOfGlobalStruct = DL.getTypeAllocSize(Initializer->getType());
2135 assert(isPowerOf2_32(SizeOfGlobalStruct) &&
2136 "global metadata will not be padded appropriately");
2137 Metadata->setAlignment(assumeAligned(SizeOfGlobalStruct));
2138
2139 SetComdatForGlobalMetadata(G, Metadata, "");
2140 }
2141
2142 // Update llvm.compiler.used, adding the new metadata globals. This is
2143 // needed so that during LTO these variables stay alive.
2144 if (!MetadataGlobals.empty())
2145 appendToCompilerUsed(M, MetadataGlobals);
2146}
2147
2148void ModuleAddressSanitizer::InstrumentGlobalsELF(
2149 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
2150 ArrayRef<Constant *> MetadataInitializers,
2151 const std::string &UniqueModuleId) {
2152 assert(ExtendedGlobals.size() == MetadataInitializers.size());
2153
2154 // Putting globals in a comdat changes the semantic and potentially cause
2155 // false negative odr violations at link time. If odr indicators are used, we
2156 // keep the comdat sections, as link time odr violations will be dectected on
2157 // the odr indicator symbols.
2158 bool UseComdatForGlobalsGC = UseOdrIndicator;
2159
2160 SmallVector<GlobalValue *, 16> MetadataGlobals(ExtendedGlobals.size());
2161 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
2162 GlobalVariable *G = ExtendedGlobals[i];
2164 CreateMetadataGlobal(M, MetadataInitializers[i], G->getName());
2165 MDNode *MD = MDNode::get(M.getContext(), ValueAsMetadata::get(G));
2166 Metadata->setMetadata(LLVMContext::MD_associated, MD);
2167 MetadataGlobals[i] = Metadata;
2168
2169 if (UseComdatForGlobalsGC)
2170 SetComdatForGlobalMetadata(G, Metadata, UniqueModuleId);
2171 }
2172
2173 // Update llvm.compiler.used, adding the new metadata globals. This is
2174 // needed so that during LTO these variables stay alive.
2175 if (!MetadataGlobals.empty())
2176 appendToCompilerUsed(M, MetadataGlobals);
2177
2178 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
2179 // to look up the loaded image that contains it. Second, we can store in it
2180 // whether registration has already occurred, to prevent duplicate
2181 // registration.
2182 //
2183 // Common linkage ensures that there is only one global per shared library.
2184 GlobalVariable *RegisteredFlag = new GlobalVariable(
2185 M, IntptrTy, false, GlobalVariable::CommonLinkage,
2188
2189 // Create start and stop symbols.
2190 GlobalVariable *StartELFMetadata = new GlobalVariable(
2191 M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
2192 "__start_" + getGlobalMetadataSection());
2194 GlobalVariable *StopELFMetadata = new GlobalVariable(
2195 M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
2196 "__stop_" + getGlobalMetadataSection());
2198
2199 // Create a call to register the globals with the runtime.
2200 if (ConstructorKind == AsanCtorKind::Global)
2201 IRB.CreateCall(AsanRegisterElfGlobals,
2202 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
2203 IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
2204 IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
2205
2206 // We also need to unregister globals at the end, e.g., when a shared library
2207 // gets closed.
2208 if (DestructorKind != AsanDtorKind::None) {
2209 IRBuilder<> IrbDtor(CreateAsanModuleDtor(M));
2210 IrbDtor.CreateCall(AsanUnregisterElfGlobals,
2211 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
2212 IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
2213 IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
2214 }
2215}
2216
2217void ModuleAddressSanitizer::InstrumentGlobalsMachO(
2218 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
2219 ArrayRef<Constant *> MetadataInitializers) {
2220 assert(ExtendedGlobals.size() == MetadataInitializers.size());
2221
2222 // On recent Mach-O platforms, use a structure which binds the liveness of
2223 // the global variable to the metadata struct. Keep the list of "Liveness" GV
2224 // created to be added to llvm.compiler.used
2225 StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy);
2226 SmallVector<GlobalValue *, 16> LivenessGlobals(ExtendedGlobals.size());
2227
2228 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
2229 Constant *Initializer = MetadataInitializers[i];
2230 GlobalVariable *G = ExtendedGlobals[i];
2232 CreateMetadataGlobal(M, Initializer, G->getName());
2233
2234 // On recent Mach-O platforms, we emit the global metadata in a way that
2235 // allows the linker to properly strip dead globals.
2236 auto LivenessBinder =
2237 ConstantStruct::get(LivenessTy, Initializer->getAggregateElement(0u),
2239 GlobalVariable *Liveness = new GlobalVariable(
2240 M, LivenessTy, false, GlobalVariable::InternalLinkage, LivenessBinder,
2241 Twine("__asan_binder_") + G->getName());
2242 Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
2243 LivenessGlobals[i] = Liveness;
2244 }
2245
2246 // Update llvm.compiler.used, adding the new liveness globals. This is
2247 // needed so that during LTO these variables stay alive. The alternative
2248 // would be to have the linker handling the LTO symbols, but libLTO
2249 // current API does not expose access to the section for each symbol.
2250 if (!LivenessGlobals.empty())
2251 appendToCompilerUsed(M, LivenessGlobals);
2252
2253 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
2254 // to look up the loaded image that contains it. Second, we can store in it
2255 // whether registration has already occurred, to prevent duplicate
2256 // registration.
2257 //
2258 // common linkage ensures that there is only one global per shared library.
2259 GlobalVariable *RegisteredFlag = new GlobalVariable(
2260 M, IntptrTy, false, GlobalVariable::CommonLinkage,
2263
2264 if (ConstructorKind == AsanCtorKind::Global)
2265 IRB.CreateCall(AsanRegisterImageGlobals,
2266 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
2267
2268 // We also need to unregister globals at the end, e.g., when a shared library
2269 // gets closed.
2270 if (DestructorKind != AsanDtorKind::None) {
2271 IRBuilder<> IrbDtor(CreateAsanModuleDtor(M));
2272 IrbDtor.CreateCall(AsanUnregisterImageGlobals,
2273 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
2274 }
2275}
2276
2277void ModuleAddressSanitizer::InstrumentGlobalsWithMetadataArray(
2278 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
2279 ArrayRef<Constant *> MetadataInitializers) {
2280 assert(ExtendedGlobals.size() == MetadataInitializers.size());
2281 unsigned N = ExtendedGlobals.size();
2282 assert(N > 0);
2283
2284 // On platforms that don't have a custom metadata section, we emit an array
2285 // of global metadata structures.
2286 ArrayType *ArrayOfGlobalStructTy =
2287 ArrayType::get(MetadataInitializers[0]->getType(), N);
2288 auto AllGlobals = new GlobalVariable(
2289 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
2290 ConstantArray::get(ArrayOfGlobalStructTy, MetadataInitializers), "");
2291 if (Mapping.Scale > 3)
2292 AllGlobals->setAlignment(Align(1ULL << Mapping.Scale));
2293
2294 if (ConstructorKind == AsanCtorKind::Global)
2295 IRB.CreateCall(AsanRegisterGlobals,
2296 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
2297 ConstantInt::get(IntptrTy, N)});
2298
2299 // We also need to unregister globals at the end, e.g., when a shared library
2300 // gets closed.
2301 if (DestructorKind != AsanDtorKind::None) {
2302 IRBuilder<> IrbDtor(CreateAsanModuleDtor(M));
2303 IrbDtor.CreateCall(AsanUnregisterGlobals,
2304 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
2305 ConstantInt::get(IntptrTy, N)});
2306 }
2307}
2308
2309// This function replaces all global variables with new variables that have
2310// trailing redzones. It also creates a function that poisons
2311// redzones and inserts this function into llvm.global_ctors.
2312// Sets *CtorComdat to true if the global registration code emitted into the
2313// asan constructor is comdat-compatible.
2314bool ModuleAddressSanitizer::InstrumentGlobals(IRBuilder<> &IRB, Module &M,
2315 bool *CtorComdat) {
2316 *CtorComdat = false;
2317
2318 // Build set of globals that are aliased by some GA, where
2319 // getExcludedAliasedGlobal(GA) returns the relevant GlobalVariable.
2320 SmallPtrSet<const GlobalVariable *, 16> AliasedGlobalExclusions;
2321 if (CompileKernel) {
2322 for (auto &GA : M.aliases()) {
2323 if (const GlobalVariable *GV = getExcludedAliasedGlobal(GA))
2324 AliasedGlobalExclusions.insert(GV);
2325 }
2326 }
2327
2328 SmallVector<GlobalVariable *, 16> GlobalsToChange;
2329 for (auto &G : M.globals()) {
2330 if (!AliasedGlobalExclusions.count(&G) && shouldInstrumentGlobal(&G))
2331 GlobalsToChange.push_back(&G);
2332 }
2333
2334 size_t n = GlobalsToChange.size();
2335 if (n == 0) {
2336 *CtorComdat = true;
2337 return false;
2338 }
2339
2340 auto &DL = M.getDataLayout();
2341
2342 // A global is described by a structure
2343 // size_t beg;
2344 // size_t size;
2345 // size_t size_with_redzone;
2346 // const char *name;
2347 // const char *module_name;
2348 // size_t has_dynamic_init;
2349 // size_t padding_for_windows_msvc_incremental_link;
2350 // size_t odr_indicator;
2351 // We initialize an array of such structures and pass it to a run-time call.
2352 StructType *GlobalStructTy =
2353 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
2354 IntptrTy, IntptrTy, IntptrTy);
2356 SmallVector<Constant *, 16> Initializers(n);
2357
2358 bool HasDynamicallyInitializedGlobals = false;
2359
2360 // We shouldn't merge same module names, as this string serves as unique
2361 // module ID in runtime.
2363 M, M.getModuleIdentifier(), /*AllowMerging*/ false, kAsanGenPrefix);
2364
2365 for (size_t i = 0; i < n; i++) {
2366 GlobalVariable *G = GlobalsToChange[i];
2367
2369 if (G->hasSanitizerMetadata())
2370 MD = G->getSanitizerMetadata();
2371
2372 // The runtime library tries demangling symbol names in the descriptor but
2373 // functionality like __cxa_demangle may be unavailable (e.g.
2374 // -static-libstdc++). So we demangle the symbol names here.
2375 std::string NameForGlobal = G->getName().str();
2378 /*AllowMerging*/ true, kAsanGenPrefix);
2379
2380 Type *Ty = G->getValueType();
2381 const uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
2382 const uint64_t RightRedzoneSize = getRedzoneSizeForGlobal(SizeInBytes);
2383 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
2384
2385 StructType *NewTy = StructType::get(Ty, RightRedZoneTy);
2386 Constant *NewInitializer = ConstantStruct::get(
2387 NewTy, G->getInitializer(), Constant::getNullValue(RightRedZoneTy));
2388
2389 // Create a new global variable with enough space for a redzone.
2390 GlobalValue::LinkageTypes Linkage = G->getLinkage();
2391 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
2393 GlobalVariable *NewGlobal = new GlobalVariable(
2394 M, NewTy, G->isConstant(), Linkage, NewInitializer, "", G,
2395 G->getThreadLocalMode(), G->getAddressSpace());
2396 NewGlobal->copyAttributesFrom(G);
2397 NewGlobal->setComdat(G->getComdat());
2398 NewGlobal->setAlignment(Align(getMinRedzoneSizeForGlobal()));
2399 // Don't fold globals with redzones. ODR violation detector and redzone
2400 // poisoning implicitly creates a dependence on the global's address, so it
2401 // is no longer valid for it to be marked unnamed_addr.
2403
2404 // Move null-terminated C strings to "__asan_cstring" section on Darwin.
2405 if (TargetTriple.isOSBinFormatMachO() && !G->hasSection() &&
2406 G->isConstant()) {
2407 auto Seq = dyn_cast<ConstantDataSequential>(G->getInitializer());
2408 if (Seq && Seq->isCString())
2409 NewGlobal->setSection("__TEXT,__asan_cstring,regular");
2410 }
2411
2412 // Transfer the debug info and type metadata. The payload starts at offset
2413 // zero so we can copy the metadata over as is.
2414 NewGlobal->copyMetadata(G, 0);
2415
2416 Value *Indices2[2];
2417 Indices2[0] = IRB.getInt32(0);
2418 Indices2[1] = IRB.getInt32(0);
2419
2420 G->replaceAllUsesWith(
2421 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
2422 NewGlobal->takeName(G);
2423 G->eraseFromParent();
2424 NewGlobals[i] = NewGlobal;
2425
2426 Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
2427 GlobalValue *InstrumentedGlobal = NewGlobal;
2428
2429 bool CanUsePrivateAliases =
2430 TargetTriple.isOSBinFormatELF() || TargetTriple.isOSBinFormatMachO() ||
2431 TargetTriple.isOSBinFormatWasm();
2432 if (CanUsePrivateAliases && UsePrivateAlias) {
2433 // Create local alias for NewGlobal to avoid crash on ODR between
2434 // instrumented and non-instrumented libraries.
2435 InstrumentedGlobal =
2437 }
2438
2439 // ODR should not happen for local linkage.
2440 if (NewGlobal->hasLocalLinkage()) {
2441 ODRIndicator = ConstantExpr::getIntToPtr(ConstantInt::get(IntptrTy, -1),
2442 IRB.getInt8PtrTy());
2443 } else if (UseOdrIndicator) {
2444 // With local aliases, we need to provide another externally visible
2445 // symbol __odr_asan_XXX to detect ODR violation.
2446 auto *ODRIndicatorSym =
2447 new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
2449 kODRGenPrefix + NameForGlobal, nullptr,
2450 NewGlobal->getThreadLocalMode());
2451
2452 // Set meaningful attributes for indicator symbol.
2453 ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
2454 ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
2455 ODRIndicatorSym->setAlignment(Align(1));
2456 ODRIndicator = ODRIndicatorSym;
2457 }
2458
2459 Constant *Initializer = ConstantStruct::get(
2460 GlobalStructTy,
2461 ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
2462 ConstantInt::get(IntptrTy, SizeInBytes),
2463 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
2466 ConstantInt::get(IntptrTy, MD.IsDynInit),
2467 Constant::getNullValue(IntptrTy),
2468 ConstantExpr::getPointerCast(ODRIndicator, IntptrTy));
2469
2470 if (ClInitializers && MD.IsDynInit)
2471 HasDynamicallyInitializedGlobals = true;
2472
2473 LLVM_DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
2474
2475 Initializers[i] = Initializer;
2476 }
2477
2478 // Add instrumented globals to llvm.compiler.used list to avoid LTO from
2479 // ConstantMerge'ing them.
2480 SmallVector<GlobalValue *, 16> GlobalsToAddToUsedList;
2481 for (size_t i = 0; i < n; i++) {
2482 GlobalVariable *G = NewGlobals[i];
2483 if (G->getName().empty()) continue;
2484 GlobalsToAddToUsedList.push_back(G);
2485 }
2486 appendToCompilerUsed(M, ArrayRef<GlobalValue *>(GlobalsToAddToUsedList));
2487
2488 std::string ELFUniqueModuleId =
2489 (UseGlobalsGC && TargetTriple.isOSBinFormatELF()) ? getUniqueModuleId(&M)
2490 : "";
2491
2492 if (!ELFUniqueModuleId.empty()) {
2493 InstrumentGlobalsELF(IRB, M, NewGlobals, Initializers, ELFUniqueModuleId);
2494 *CtorComdat = true;
2495 } else if (UseGlobalsGC && TargetTriple.isOSBinFormatCOFF()) {
2496 InstrumentGlobalsCOFF(IRB, M, NewGlobals, Initializers);
2497 } else if (UseGlobalsGC && ShouldUseMachOGlobalsSection()) {
2498 InstrumentGlobalsMachO(IRB, M, NewGlobals, Initializers);
2499 } else {
2500 InstrumentGlobalsWithMetadataArray(IRB, M, NewGlobals, Initializers);
2501 }
2502
2503 // Create calls for poisoning before initializers run and unpoisoning after.
2504 if (HasDynamicallyInitializedGlobals)
2505 createInitializerPoisonCalls(M, ModuleName);
2506
2507 LLVM_DEBUG(dbgs() << M);
2508 return true;
2509}
2510
2512ModuleAddressSanitizer::getRedzoneSizeForGlobal(uint64_t SizeInBytes) const {
2513 constexpr uint64_t kMaxRZ = 1 << 18;
2514 const uint64_t MinRZ = getMinRedzoneSizeForGlobal();
2515
2516 uint64_t RZ = 0;
2517 if (SizeInBytes <= MinRZ / 2) {
2518 // Reduce redzone size for small size objects, e.g. int, char[1]. MinRZ is
2519 // at least 32 bytes, optimize when SizeInBytes is less than or equal to
2520 // half of MinRZ.
2521 RZ = MinRZ - SizeInBytes;
2522 } else {
2523 // Calculate RZ, where MinRZ <= RZ <= MaxRZ, and RZ ~ 1/4 * SizeInBytes.
2524 RZ = std::clamp((SizeInBytes / MinRZ / 4) * MinRZ, MinRZ, kMaxRZ);
2525
2526 // Round up to multiple of MinRZ.
2527 if (SizeInBytes % MinRZ)
2528 RZ += MinRZ - (SizeInBytes % MinRZ);
2529 }
2530
2531 assert((RZ + SizeInBytes) % MinRZ == 0);
2532
2533 return RZ;
2534}
2535
2536int ModuleAddressSanitizer::GetAsanVersion(const Module &M) const {
2537 int LongSize = M.getDataLayout().getPointerSizeInBits();
2538 bool isAndroid = Triple(M.getTargetTriple()).isAndroid();
2539 int Version = 8;
2540 // 32-bit Android is one version ahead because of the switch to dynamic
2541 // shadow.
2542 Version += (LongSize == 32 && isAndroid);
2543 return Version;
2544}
2545
2546bool ModuleAddressSanitizer::instrumentModule(Module &M) {
2547 initializeCallbacks(M);
2548
2549 // Create a module constructor. A destructor is created lazily because not all
2550 // platforms, and not all modules need it.
2551 if (ConstructorKind == AsanCtorKind::Global) {
2552 if (CompileKernel) {
2553 // The kernel always builds with its own runtime, and therefore does not
2554 // need the init and version check calls.
2555 AsanCtorFunction = createSanitizerCtor(M, kAsanModuleCtorName);
2556 } else {
2557 std::string AsanVersion = std::to_string(GetAsanVersion(M));
2558 std::string VersionCheckName =
2560 std::tie(AsanCtorFunction, std::ignore) =
2562 kAsanInitName, /*InitArgTypes=*/{},
2563 /*InitArgs=*/{}, VersionCheckName);
2564 }
2565 }
2566
2567 bool CtorComdat = true;
2568 if (ClGlobals) {
2569 assert(AsanCtorFunction || ConstructorKind == AsanCtorKind::None);
2570 if (AsanCtorFunction) {
2571 IRBuilder<> IRB(AsanCtorFunction->getEntryBlock().getTerminator());
2572 InstrumentGlobals(IRB, M, &CtorComdat);
2573 } else {
2574 IRBuilder<> IRB(*C);
2575 InstrumentGlobals(IRB, M, &CtorComdat);
2576 }
2577 }
2578
2579 const uint64_t Priority = GetCtorAndDtorPriority(TargetTriple);
2580
2581 // Put the constructor and destructor in comdat if both
2582 // (1) global instrumentation is not TU-specific
2583 // (2) target is ELF.
2584 if (UseCtorComdat && TargetTriple.isOSBinFormatELF() && CtorComdat) {
2585 if (AsanCtorFunction) {
2586 AsanCtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleCtorName));
2587 appendToGlobalCtors(M, AsanCtorFunction, Priority, AsanCtorFunction);
2588 }
2589 if (AsanDtorFunction) {
2590 AsanDtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleDtorName));
2591 appendToGlobalDtors(M, AsanDtorFunction, Priority, AsanDtorFunction);
2592 }
2593 } else {
2594 if (AsanCtorFunction)
2595 appendToGlobalCtors(M, AsanCtorFunction, Priority);
2596 if (AsanDtorFunction)
2597 appendToGlobalDtors(M, AsanDtorFunction, Priority);
2598 }
2599
2600 return true;
2601}
2602
2603void AddressSanitizer::initializeCallbacks(Module &M, const TargetLibraryInfo *TLI) {
2604 IRBuilder<> IRB(*C);
2605 // Create __asan_report* callbacks.
2606 // IsWrite, TypeSize and Exp are encoded in the function name.
2607 for (int Exp = 0; Exp < 2; Exp++) {
2608 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
2609 const std::string TypeStr = AccessIsWrite ? "store" : "load";
2610 const std::string ExpStr = Exp ? "exp_" : "";
2611 const std::string EndingStr = Recover ? "_noabort" : "";
2612
2613 SmallVector<Type *, 3> Args2 = {IntptrTy, IntptrTy};
2614 SmallVector<Type *, 2> Args1{1, IntptrTy};
2615 AttributeList AL2;
2616 AttributeList AL1;
2617 if (Exp) {
2618 Type *ExpType = Type::getInt32Ty(*C);
2619 Args2.push_back(ExpType);
2620 Args1.push_back(ExpType);
2621 if (auto AK = TLI->getExtAttrForI32Param(false)) {
2622 AL2 = AL2.addParamAttribute(*C, 2, AK);
2623 AL1 = AL1.addParamAttribute(*C, 1, AK);
2624 }
2625 }
2626 AsanErrorCallbackSized[AccessIsWrite][Exp] = M.getOrInsertFunction(
2627 kAsanReportErrorTemplate + ExpStr + TypeStr + "_n" + EndingStr,
2628 FunctionType::get(IRB.getVoidTy(), Args2, false), AL2);
2629
2630 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] = M.getOrInsertFunction(
2631 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
2632 FunctionType::get(IRB.getVoidTy(), Args2, false), AL2);
2633
2634 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
2635 AccessSizeIndex++) {
2636 const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
2637 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2638 M.getOrInsertFunction(
2639 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
2640 FunctionType::get(IRB.getVoidTy(), Args1, false), AL1);
2641
2642 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2643 M.getOrInsertFunction(
2644 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
2645 FunctionType::get(IRB.getVoidTy(), Args1, false), AL1);
2646 }
2647 }
2648 }
2649
2650 const std::string MemIntrinCallbackPrefix =
2651 (CompileKernel && !ClKasanMemIntrinCallbackPrefix)
2652 ? std::string("")
2654 AsanMemmove = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memmove",
2655 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
2656 IRB.getInt8PtrTy(), IntptrTy);
2657 AsanMemcpy = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memcpy",
2658 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
2659 IRB.getInt8PtrTy(), IntptrTy);
2660 AsanMemset = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memset",
2661 TLI->getAttrList(C, {1}, /*Signed=*/false),
2662 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
2663 IRB.getInt32Ty(), IntptrTy);
2664
2665 AsanHandleNoReturnFunc =
2666 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy());
2667
2668 AsanPtrCmpFunction =
2669 M.getOrInsertFunction(kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy);
2670 AsanPtrSubFunction =
2671 M.getOrInsertFunction(kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy);
2672 if (Mapping.InGlobal)
2673 AsanShadowGlobal = M.getOrInsertGlobal("__asan_shadow",
2674 ArrayType::get(IRB.getInt8Ty(), 0));
2675
2676 AMDGPUAddressShared = M.getOrInsertFunction(
2678 AMDGPUAddressPrivate = M.getOrInsertFunction(
2680}
2681
2682bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
2683 // For each NSObject descendant having a +load method, this method is invoked
2684 // by the ObjC runtime before any of the static constructors is called.
2685 // Therefore we need to instrument such methods with a call to __asan_init
2686 // at the beginning in order to initialize our runtime before any access to
2687 // the shadow memory.
2688 // We cannot just ignore these methods, because they may call other
2689 // instrumented functions.
2690 if (F.getName().find(" load]") != std::string::npos) {
2691 FunctionCallee AsanInitFunction =
2692 declareSanitizerInitFunction(*F.getParent(), kAsanInitName, {});
2693 IRBuilder<> IRB(&F.front(), F.front().begin());
2694 IRB.CreateCall(AsanInitFunction, {});
2695 return true;
2696 }
2697 return false;
2698}
2699
2700bool AddressSanitizer::maybeInsertDynamicShadowAtFunctionEntry(Function &F) {
2701 // Generate code only when dynamic addressing is needed.
2702 if (Mapping.Offset != kDynamicShadowSentinel)
2703 return false;
2704
2705 IRBuilder<> IRB(&F.front().front());
2706 if (Mapping.InGlobal) {
2708 // An empty inline asm with input reg == output reg.
2709 // An opaque pointer-to-int cast, basically.
2711 FunctionType::get(IntptrTy, {AsanShadowGlobal->getType()}, false),
2712 StringRef(""), StringRef("=r,0"),
2713 /*hasSideEffects=*/false);
2714 LocalDynamicShadow =
2715 IRB.CreateCall(Asm, {AsanShadowGlobal}, ".asan.shadow");
2716 } else {
2717 LocalDynamicShadow =
2718 IRB.CreatePointerCast(AsanShadowGlobal, IntptrTy, ".asan.shadow");
2719 }
2720 } else {
2721 Value *GlobalDynamicAddress = F.getParent()->getOrInsertGlobal(
2723 LocalDynamicShadow = IRB.CreateLoad(IntptrTy, GlobalDynamicAddress);
2724 }
2725 return true;
2726}
2727
2728void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
2729 // Find the one possible call to llvm.localescape and pre-mark allocas passed
2730 // to it as uninteresting. This assumes we haven't started processing allocas
2731 // yet. This check is done up front because iterating the use list in
2732 // isInterestingAlloca would be algorithmically slower.
2733 assert(ProcessedAllocas.empty() && "must process localescape before allocas");
2734
2735 // Try to get the declaration of llvm.localescape. If it's not in the module,
2736 // we can exit early.
2737 if (!F.getParent()->getFunction("llvm.localescape")) return;
2738
2739 // Look for a call to llvm.localescape call in the entry block. It can't be in
2740 // any other block.
2741 for (Instruction &I : F.getEntryBlock()) {
2742 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
2743 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
2744 // We found a call. Mark all the allocas passed in as uninteresting.
2745 for (Value *Arg : II->args()) {
2746 AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
2747 assert(AI && AI->isStaticAlloca() &&
2748 "non-static alloca arg to localescape");
2749 ProcessedAllocas[AI] = false;
2750 }
2751 break;
2752 }
2753 }
2754}
2755
2756bool AddressSanitizer::suppressInstrumentationSiteForDebug(int &Instrumented) {
2757 bool ShouldInstrument =
2758 ClDebugMin < 0 || ClDebugMax < 0 ||
2759 (Instrumented >= ClDebugMin && Instrumented <= ClDebugMax);
2760 Instrumented++;
2761 return !ShouldInstrument;
2762}
2763
2764bool AddressSanitizer::instrumentFunction(Function &F,
2765 const TargetLibraryInfo *TLI) {
2766 if (F.empty())
2767 return false;
2768 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
2769 if (!ClDebugFunc.empty() && ClDebugFunc == F.getName()) return false;
2770 if (F.getName().startswith("__asan_")) return false;
2771
2772 bool FunctionModified = false;
2773
2774 // If needed, insert __asan_init before checking for SanitizeAddress attr.
2775 // This function needs to be called even if the function body is not
2776 // instrumented.
2777 if (maybeInsertAsanInitAtFunctionEntry(F))
2778 FunctionModified = true;
2779
2780 // Leave if the function doesn't need instrumentation.
2781 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return FunctionModified;
2782
2783 if (F.hasFnAttribute(Attribute::DisableSanitizerInstrumentation))
2784 return FunctionModified;
2785
2786 LLVM_DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
2787
2788 initializeCallbacks(*F.getParent(), TLI);
2789
2790 FunctionStateRAII CleanupObj(this);
2791
2792 FunctionModified |= maybeInsertDynamicShadowAtFunctionEntry(F);
2793
2794 // We can't instrument allocas used with llvm.localescape. Only static allocas
2795 // can be passed to that intrinsic.
2796 markEscapedLocalAllocas(F);
2797
2798 // We want to instrument every address only once per basic block (unless there
2799 // are calls between uses).
2800 SmallPtrSet<Value *, 16> TempsToInstrument;
2801 SmallVector<InterestingMemoryOperand, 16> OperandsToInstrument;
2802 SmallVector<MemIntrinsic *, 16> IntrinToInstrument;
2803 SmallVector<Instruction *, 8> NoReturnCalls;
2805 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
2806
2807 // Fill the set of memory operations to instrument.
2808 for (auto &BB : F) {
2809 AllBlocks.push_back(&BB);
2810 TempsToInstrument.clear();
2811 int NumInsnsPerBB = 0;
2812 for (auto &Inst : BB) {
2813 if (LooksLikeCodeInBug11395(&Inst)) return false;
2814 // Skip instructions inserted by another instrumentation.
2815 if (Inst.hasMetadata(LLVMContext::MD_nosanitize))
2816 continue;
2817 SmallVector<InterestingMemoryOperand, 1> InterestingOperands;
2818 getInterestingMemoryOperands(&Inst, InterestingOperands);
2819
2820 if (!InterestingOperands.empty()) {
2821 for (auto &Operand : InterestingOperands) {
2822 if (ClOpt && ClOptSameTemp) {
2823 Value *Ptr = Operand.getPtr();
2824 // If we have a mask, skip instrumentation if we've already
2825 // instrumented the full object. But don't add to TempsToInstrument
2826 // because we might get another load/store with a different mask.
2827 if (Operand.MaybeMask) {
2828 if (TempsToInstrument.count(Ptr))
2829 continue; // We've seen this (whole) temp in the current BB.
2830 } else {
2831 if (!TempsToInstrument.insert(Ptr).second)
2832 continue; // We've seen this temp in the current BB.
2833 }
2834 }
2835 OperandsToInstrument.push_back(Operand);
2836 NumInsnsPerBB++;
2837 }
2838 } else if (((ClInvalidPointerPairs || ClInvalidPointerCmp) &&
2842 PointerComparisonsOrSubtracts.push_back(&Inst);
2843 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&Inst)) {
2844 // ok, take it.
2845 IntrinToInstrument.push_back(MI);
2846 NumInsnsPerBB++;
2847 } else {
2848 if (auto *CB = dyn_cast<CallBase>(&Inst)) {
2849 // A call inside BB.
2850 TempsToInstrument.clear();
2851 if (CB->doesNotReturn())
2852 NoReturnCalls.push_back(CB);
2853 }
2854 if (CallInst *CI = dyn_cast<CallInst>(&Inst))
2856 }
2857 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
2858 }
2859 }
2860
2861 bool UseCalls = (ClInstrumentationWithCallsThreshold >= 0 &&
2862 OperandsToInstrument.size() + IntrinToInstrument.size() >
2864 const DataLayout &DL = F.getParent()->getDataLayout();
2865 ObjectSizeOpts ObjSizeOpts;
2866 ObjSizeOpts.RoundToAlign = true;
2867 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(), ObjSizeOpts);
2868
2869 // Instrument.
2870 int NumInstrumented = 0;
2871 for (auto &Operand : OperandsToInstrument) {
2872 if (!suppressInstrumentationSiteForDebug(NumInstrumented))
2873 instrumentMop(ObjSizeVis, Operand, UseCalls,
2874 F.getParent()->getDataLayout());
2875 FunctionModified = true;
2876 }
2877 for (auto *Inst : IntrinToInstrument) {
2878 if (!suppressInstrumentationSiteForDebug(NumInstrumented))
2879 instrumentMemIntrinsic(Inst);
2880 FunctionModified = true;
2881 }
2882
2883 FunctionStackPoisoner FSP(F, *this);
2884 bool ChangedStack = FSP.runOnFunction();
2885
2886 // We must unpoison the stack before NoReturn calls (throw, _exit, etc).
2887 // See e.g. https://github.com/google/sanitizers/issues/37
2888 for (auto *CI : NoReturnCalls) {
2889 IRBuilder<> IRB(CI);
2890 IRB.CreateCall(AsanHandleNoReturnFunc, {});
2891 }
2892
2893 for (auto *Inst : PointerComparisonsOrSubtracts) {
2894 instrumentPointerComparisonOrSubtraction(Inst);
2895 FunctionModified = true;
2896 }
2897
2898 if (ChangedStack || !NoReturnCalls.empty())
2899 FunctionModified = true;
2900
2901 LLVM_DEBUG(dbgs() << "ASAN done instrumenting: " << FunctionModified << " "
2902 << F << "\n");
2903
2904 return FunctionModified;
2905}
2906
2907// Workaround for bug 11395: we don't want to instrument stack in functions
2908// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
2909// FIXME: remove once the bug 11395 is fixed.
2910bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
2911 if (LongSize != 32) return false;
2912 CallInst *CI = dyn_cast<CallInst>(I);
2913 if (!CI || !CI->isInlineAsm()) return false;
2914 if (CI->arg_size() <= 5)
2915 return false;
2916 // We have inline assembly with quite a few arguments.
2917 return true;
2918}
2919
2920void FunctionStackPoisoner::initializeCallbacks(Module &M) {
2921 IRBuilder<> IRB(*C);
2922 if (ASan.UseAfterReturn == AsanDetectStackUseAfterReturnMode::Always ||
2923 ASan.UseAfterReturn == AsanDetectStackUseAfterReturnMode::Runtime) {
2924 const char *MallocNameTemplate =
2925 ASan.UseAfterReturn == AsanDetectStackUseAfterReturnMode::Always
2928 for (int Index = 0; Index <= kMaxAsanStackMallocSizeClass; Index++) {
2929 std::string Suffix = itostr(Index);
2930 AsanStackMallocFunc[Index] = M.getOrInsertFunction(
2931 MallocNameTemplate + Suffix, IntptrTy, IntptrTy);
2932 AsanStackFreeFunc[Index] =
2933 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
2934 IRB.getVoidTy(), IntptrTy, IntptrTy);
2935 }
2936 }
2937 if (ASan.UseAfterScope) {
2938 AsanPoisonStackMemoryFunc = M.getOrInsertFunction(
2939 kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy);
2940 AsanUnpoisonStackMemoryFunc = M.getOrInsertFunction(
2941 kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy);
2942 }
2943
2944 for (size_t Val : {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0xf1, 0xf2,
2945 0xf3, 0xf5, 0xf8}) {
2946 std::ostringstream Name;
2948 Name << std::setw(2) << std::setfill('0') << std::hex << Val;
2949 AsanSetShadowFunc[Val] =
2950 M.getOrInsertFunction(Name.str(), IRB.getVoidTy(), IntptrTy, IntptrTy);
2951 }
2952
2953 AsanAllocaPoisonFunc = M.getOrInsertFunction(
2954 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy);
2955 AsanAllocasUnpoisonFunc = M.getOrInsertFunction(
2956 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy);
2957}
2958
2959void FunctionStackPoisoner::copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
2960 ArrayRef<uint8_t> ShadowBytes,
2961 size_t Begin, size_t End,
2962 IRBuilder<> &IRB,
2963 Value *ShadowBase) {
2964 if (Begin >= End)
2965 return;
2966
2967 const size_t LargestStoreSizeInBytes =
2968 std::min<size_t>(sizeof(uint64_t), ASan.LongSize / 8);
2969
2970 const bool IsLittleEndian = F.getParent()->getDataLayout().isLittleEndian();
2971
2972 // Poison given range in shadow using larges store size with out leading and
2973 // trailing zeros in ShadowMask. Zeros never change, so they need neither
2974 // poisoning nor up-poisoning. Still we don't mind if some of them get into a
2975 // middle of a store.
2976 for (size_t i = Begin; i < End;) {
2977 if (!ShadowMask[i]) {
2978 assert(!ShadowBytes[i]);
2979 ++i;
2980 continue;
2981 }
2982
2983 size_t StoreSizeInBytes = LargestStoreSizeInBytes;
2984 // Fit store size into the range.
2985 while (StoreSizeInBytes > End - i)
2986 StoreSizeInBytes /= 2;
2987
2988 // Minimize store size by trimming trailing zeros.
2989 for (size_t j = StoreSizeInBytes - 1; j && !ShadowMask[i + j]; --j) {
2990 while (j <= StoreSizeInBytes / 2)
2991 StoreSizeInBytes /= 2;
2992 }
2993
2994 uint64_t Val = 0;
2995 for (size_t j = 0; j < StoreSizeInBytes; j++) {
2996 if (IsLittleEndian)
2997 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
2998 else
2999 Val = (Val << 8) | ShadowBytes[i + j];
3000 }
3001
3002 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
3003 Value *Poison = IRB.getIntN(StoreSizeInBytes * 8, Val);
3005 Poison, IRB.CreateIntToPtr(Ptr, Poison->getType()->getPointerTo()),
3006 Align(1));
3007
3008 i += StoreSizeInBytes;
3009 }
3010}
3011
3012void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
3013 ArrayRef<uint8_t> ShadowBytes,
3014 IRBuilder<> &IRB, Value *ShadowBase) {
3015 copyToShadow(ShadowMask, ShadowBytes, 0, ShadowMask.size(), IRB, ShadowBase);
3016}
3017
3018void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
3019 ArrayRef<uint8_t> ShadowBytes,
3020 size_t Begin, size_t End,
3021 IRBuilder<> &IRB, Value *ShadowBase) {
3022 assert(ShadowMask.size() == ShadowBytes.size());
3023 size_t Done = Begin;
3024 for (size_t i = Begin, j = Begin + 1; i < End; i = j++) {
3025 if (!ShadowMask[i]) {
3026 assert(!ShadowBytes[i]);
3027 continue;
3028 }
3029 uint8_t Val = ShadowBytes[i];
3030 if (!AsanSetShadowFunc[Val])
3031 continue;
3032
3033 // Skip same values.
3034 for (; j < End && ShadowMask[j] && Val == ShadowBytes[j]; ++j) {
3035 }
3036
3037 if (j - i >= ClMaxInlinePoisoningSize) {
3038 copyToShadowInline(ShadowMask, ShadowBytes, Done, i, IRB, ShadowBase);
3039 IRB.CreateCall(AsanSetShadowFunc[Val],
3040 {IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i)),
3041 ConstantInt::get(IntptrTy, j - i)});
3042 Done = j;
3043 }
3044 }
3045
3046 copyToShadowInline(ShadowMask, ShadowBytes, Done, End, IRB, ShadowBase);
3047}
3048
3049// Fake stack allocator (asan_fake_stack.h) has 11 size classes
3050// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
3051static int StackMallocSizeClass(uint64_t LocalStackSize) {
3052 assert(LocalStackSize <= kMaxStackMallocSize);
3053 uint64_t MaxSize = kMinStackMallocSize;
3054 for (int i = 0;; i++, MaxSize *= 2)
3055 if (LocalStackSize <= MaxSize) return i;
3056 llvm_unreachable("impossible LocalStackSize");
3057}
3058
3059void FunctionStackPoisoner::copyArgsPassedByValToAllocas() {
3060 Instruction *CopyInsertPoint = &F.front().front();
3061 if (CopyInsertPoint == ASan.LocalDynamicShadow) {
3062 // Insert after the dynamic shadow location is determined
3063 CopyInsertPoint = CopyInsertPoint->getNextNode();
3064 assert(CopyInsertPoint);
3065 }
3066 IRBuilder<> IRB(CopyInsertPoint);
3067 const DataLayout &DL = F.getParent()->getDataLayout();
3068 for (Argument &Arg : F.args()) {
3069 if (Arg.hasByValAttr()) {
3070 Type *Ty = Arg.getParamByValType();
3071 const Align Alignment =
3072 DL.getValueOrABITypeAlignment(Arg.getParamAlign(), Ty);
3073
3074 AllocaInst *AI = IRB.CreateAlloca(
3075 Ty, nullptr,
3076 (Arg.hasName() ? Arg.getName() : "Arg" + Twine(Arg.getArgNo())) +
3077 ".byval");
3078 AI->setAlignment(Alignment);
3079 Arg.replaceAllUsesWith(AI);
3080
3081 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3082 IRB.CreateMemCpy(AI, Alignment, &Arg, Alignment, AllocSize);
3083 }
3084 }
3085}
3086
3087PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
3088 Value *ValueIfTrue,
3089 Instruction *ThenTerm,
3090 Value *ValueIfFalse) {
3091 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
3092 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
3093 PHI->addIncoming(ValueIfFalse, CondBlock);
3094 BasicBlock *ThenBlock = ThenTerm->getParent();
3095 PHI->addIncoming(ValueIfTrue, ThenBlock);
3096 return PHI;
3097}
3098
3099Value *FunctionStackPoisoner::createAllocaForLayout(
3100 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
3101 AllocaInst *Alloca;
3102 if (Dynamic) {
3103 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
3104 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
3105 "MyAlloca");
3106 } else {
3107 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
3108 nullptr, "MyAlloca");
3109 assert(Alloca->isStaticAlloca());
3110 }
3111 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
3112 uint64_t FrameAlignment = std::max(L.FrameAlignment, uint64_t(ClRealignStack));
3113 Alloca->setAlignment(Align(FrameAlignment));
3114 return IRB.CreatePointerCast(Alloca, IntptrTy);
3115}
3116
3117void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
3118 BasicBlock &FirstBB = *F.begin();
3119 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
3120 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
3121 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
3122 DynamicAllocaLayout->setAlignment(Align(32));
3123}
3124
3125void FunctionStackPoisoner::processDynamicAllocas() {
3126 if (!ClInstrumentDynamicAllocas || DynamicAllocaVec.empty()) {
3127 assert(DynamicAllocaPoisonCallVec.empty());
3128 return;
3129 }
3130
3131 // Insert poison calls for lifetime intrinsics for dynamic allocas.
3132 for (const auto &APC : DynamicAllocaPoisonCallVec) {
3133 assert(APC.InsBefore);
3134 assert(APC.AI);
3135 assert(ASan.isInterestingAlloca(*APC.AI));
3136 assert(!APC.AI->isStaticAlloca());
3137
3138 IRBuilder<> IRB(APC.InsBefore);
3139 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
3140 // Dynamic allocas will be unpoisoned unconditionally below in
3141 // unpoisonDynamicAllocas.
3142 // Flag that we need unpoison static allocas.
3143 }
3144
3145 // Handle dynamic allocas.
3146 createDynamicAllocasInitStorage();
3147 for (auto &AI : DynamicAllocaVec)
3148 handleDynamicAllocaCall(AI);
3149 unpoisonDynamicAllocas();
3150}
3151
3152/// Collect instructions in the entry block after \p InsBefore which initialize
3153/// permanent storage for a function argument. These instructions must remain in
3154/// the entry block so that uninitialized values do not appear in backtraces. An
3155/// added benefit is that this conserves spill slots. This does not move stores
3156/// before instrumented / "interesting" allocas.
3158 AddressSanitizer &ASan, Instruction &InsBefore,
3159 SmallVectorImpl<Instruction *> &InitInsts) {
3160 Instruction *Start = InsBefore.getNextNonDebugInstruction();
3161 for (Instruction *It = Start; It; It = It->getNextNonDebugInstruction()) {
3162 // Argument initialization looks like:
3163 // 1) store <Argument>, <Alloca> OR
3164 // 2) <CastArgument> = cast <Argument> to ...
3165 // store <CastArgument> to <Alloca>
3166 // Do not consider any other kind of instruction.
3167 //
3168 // Note: This covers all known cases, but may not be exhaustive. An
3169 // alternative to pattern-matching stores is to DFS over all Argument uses:
3170 // this might be more general, but is probably much more complicated.
3171 if (isa<AllocaInst>(It) || isa<CastInst>(It))
3172 continue;
3173 if (auto *Store = dyn_cast<StoreInst>(It)) {
3174 // The store destination must be an alloca that isn't interesting for
3175 // ASan to instrument. These are moved up before InsBefore, and they're
3176 // not interesting because allocas for arguments can be mem2reg'd.
3177 auto *Alloca = dyn_cast<AllocaInst>(Store->getPointerOperand());
3178 if (!Alloca || ASan.isInterestingAlloca(*Alloca))
3179 continue;
3180
3181 Value *Val = Store->getValueOperand();
3182 bool IsDirectArgInit = isa<Argument>(Val);
3183 bool IsArgInitViaCast =
3184 isa<CastInst>(Val) &&
3185 isa<Argument>(cast<CastInst>(Val)->getOperand(0)) &&
3186 // Check that the cast appears directly before the store. Otherwise
3187 // moving the cast before InsBefore may break the IR.
3188 Val == It->getPrevNonDebugInstruction();
3189 bool IsArgInit = IsDirectArgInit || IsArgInitViaCast;
3190 if (!IsArgInit)
3191 continue;
3192
3193 if (IsArgInitViaCast)
3194 InitInsts.push_back(cast<Instruction>(Val));
3195 InitInsts.push_back(Store);
3196 continue;
3197 }
3198
3199 // Do not reorder past unknown instructions: argument initialization should
3200 // only involve casts and stores.
3201 return;
3202 }
3203}
3204
3205void FunctionStackPoisoner::processStaticAllocas() {
3206 if (AllocaVec.empty()) {
3207 assert(StaticAllocaPoisonCallVec.empty());
3208 return;
3209 }
3210
3211 int StackMallocIdx = -1;
3212 DebugLoc EntryDebugLocation;
3213 if (auto SP = F.getSubprogram())
3214 EntryDebugLocation =
3215 DILocation::get(SP->getContext(), SP->getScopeLine(), 0, SP);
3216
3217 Instruction *InsBefore = AllocaVec[0];
3218 IRBuilder<> IRB(InsBefore);
3219
3220 // Make sure non-instrumented allocas stay in the entry block. Otherwise,
3221 // debug info is broken, because only entry-block allocas are treated as
3222 // regular stack slots.
3223 auto InsBeforeB = InsBefore->getParent();
3224 assert(InsBeforeB == &F.getEntryBlock());
3225 for (auto *AI : StaticAllocasToMoveUp)
3226 if (AI->getParent() == InsBeforeB)
3227 AI->moveBefore(InsBefore);
3228
3229 // Move stores of arguments into entry-block allocas as well. This prevents
3230 // extra stack slots from being generated (to house the argument values until
3231 // they can be stored into the allocas). This also prevents uninitialized
3232 // values from being shown in backtraces.
3233 SmallVector<Instruction *, 8> ArgInitInsts;
3234 findStoresToUninstrumentedArgAllocas(ASan, *InsBefore, ArgInitInsts);
3235 for (Instruction *ArgInitInst : ArgInitInsts)
3236 ArgInitInst->moveBefore(InsBefore);
3237
3238 // If we have a call to llvm.localescape, keep it in the entry block.
3239 if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
3240
3242 SVD.reserve(AllocaVec.size());
3243 for (AllocaInst *AI : AllocaVec) {
3245 ASan.getAllocaSizeInBytes(*AI),
3246 0,
3247 AI->getAlign().value(),
3248 AI,
3249 0,
3250 0};
3251 SVD.push_back(D);
3252 }
3253
3254 // Minimal header size (left redzone) is 4 pointers,
3255 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
3256 uint64_t Granularity = 1ULL << Mapping.Scale;
3257 uint64_t MinHeaderSize = std::max((uint64_t)ASan.LongSize / 2, Granularity);
3258 const ASanStackFrameLayout &L =
3259 ComputeASanStackFrameLayout(SVD, Granularity, MinHeaderSize);
3260
3261 // Build AllocaToSVDMap for ASanStackVariableDescription lookup.
3263 for (auto &Desc : SVD)
3264 AllocaToSVDMap[Desc.AI] = &Desc;
3265
3266 // Update SVD with information from lifetime intrinsics.
3267 for (const auto &APC : StaticAllocaPoisonCallVec) {
3268 assert(APC.InsBefore);
3269 assert(APC.AI);
3270 assert(ASan.isInterestingAlloca(*APC.AI));
3271 assert(APC.AI->isStaticAlloca());
3272
3273 ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
3274 Desc.LifetimeSize = Desc.Size;
3275 if (const DILocation *FnLoc = EntryDebugLocation.get()) {
3276 if (const DILocation *LifetimeLoc = APC.InsBefore->getDebugLoc().get()) {
3277 if (LifetimeLoc->getFile() == FnLoc->getFile())
3278 if (unsigned Line = LifetimeLoc->getLine())
3279 Desc.Line = std::min(Desc.Line ? Desc.Line : Line, Line);
3280 }
3281 }
3282 }
3283
3284 auto DescriptionString = ComputeASanStackFrameDescription(SVD);
3285 LLVM_DEBUG(dbgs() << DescriptionString << " --- " << L.FrameSize << "\n");
3286 uint64_t LocalStackSize = L.FrameSize;
3287 bool DoStackMalloc =
3288 ASan.UseAfterReturn != AsanDetectStackUseAfterReturnMode::Never &&
3289 !ASan.CompileKernel && LocalStackSize <= kMaxStackMallocSize;
3290 bool DoDynamicAlloca = ClDynamicAllocaStack;
3291 // Don't do dynamic alloca or stack malloc if:
3292 // 1) There is inline asm: too often it makes assumptions on which registers
3293 // are available.
3294 // 2) There is a returns_twice call (typically setjmp), which is
3295 // optimization-hostile, and doesn't play well with introduced indirect
3296 // register-relative calculation of local variable addresses.
3297 DoDynamicAlloca &= !HasInlineAsm && !HasReturnsTwiceCall;
3298 DoStackMalloc &= !HasInlineAsm && !HasReturnsTwiceCall;
3299
3300 Value *StaticAlloca =
3301 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
3302
3303 Value *FakeStack;
3304 Value *LocalStackBase;
3305 Value *LocalStackBaseAlloca;
3306 uint8_t DIExprFlags = DIExpression::ApplyOffset;
3307
3308 if (DoStackMalloc) {
3309 LocalStackBaseAlloca =
3310 IRB.CreateAlloca(IntptrTy, nullptr, "asan_local_stack_base");
3311 if (ASan.UseAfterReturn == AsanDetectStackUseAfterReturnMode::Runtime) {
3312 // void *FakeStack = __asan_option_detect_stack_use_after_return
3313 // ? __asan_stack_malloc_N(LocalStackSize)
3314 // : nullptr;
3315 // void *LocalStackBase = (FakeStack) ? FakeStack :
3316 // alloca(LocalStackSize);
3317 Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
3319 Value *UseAfterReturnIsEnabled = IRB.CreateICmpNE(
3320 IRB.CreateLoad(IRB.getInt32Ty(), OptionDetectUseAfterReturn),
3322 Instruction *Term =
3323 SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
3324 IRBuilder<> IRBIf(Term);
3325 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
3326 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
3327 Value *FakeStackValue =
3328 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
3329 ConstantInt::get(IntptrTy, LocalStackSize));
3330 IRB.SetInsertPoint(InsBefore);
3331 FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
3332 ConstantInt::get(IntptrTy, 0));
3333 } else {
3334 // assert(ASan.UseAfterReturn == AsanDetectStackUseAfterReturnMode:Always)
3335 // void *FakeStack = __asan_stack_malloc_N(LocalStackSize);
3336 // void *LocalStackBase = (FakeStack) ? FakeStack :
3337 // alloca(LocalStackSize);
3338 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
3339 FakeStack = IRB.CreateCall(AsanStackMallocFunc[StackMallocIdx],
3340 ConstantInt::get(IntptrTy, LocalStackSize));
3341 }
3342 Value *NoFakeStack =
3343 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
3344 Instruction *Term =
3345 SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
3346 IRBuilder<> IRBIf(Term);
3347 Value *AllocaValue =
3348 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
3349
3350 IRB.SetInsertPoint(InsBefore);
3351 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
3352 IRB.CreateStore(LocalStackBase, LocalStackBaseAlloca);
3353 DIExprFlags |= DIExpression::DerefBefore;
3354 } else {
3355 // void *FakeStack = nullptr;
3356 // void *LocalStackBase = alloca(LocalStackSize);
3357 FakeStack = ConstantInt::get(IntptrTy, 0);
3358 LocalStackBase =
3359 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
3360 LocalStackBaseAlloca = LocalStackBase;
3361 }
3362
3363 // It shouldn't matter whether we pass an `alloca` or a `ptrtoint` as the
3364 // dbg.declare address opereand, but passing a `ptrtoint` seems to confuse
3365 // later passes and can result in dropped variable coverage in debug info.
3366 Value *LocalStackBaseAllocaPtr =
3367 isa<PtrToIntInst>(LocalStackBaseAlloca)
3368 ? cast<PtrToIntInst>(LocalStackBaseAlloca)->getPointerOperand()
3369 : LocalStackBaseAlloca;
3370 assert(isa<AllocaInst>(LocalStackBaseAllocaPtr) &&
3371 "Variable descriptions relative to ASan stack base will be dropped");
3372
3373 // Replace Alloca instructions with base+offset.
3374 for (const auto &Desc : SVD) {
3375 AllocaInst *AI = Desc.AI;
3376 replaceDbgDeclare(AI, LocalStackBaseAllocaPtr, DIB, DIExprFlags,
3377 Desc.Offset);
3378 Value *NewAllocaPtr = IRB.CreateIntToPtr(
3379 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
3380 AI->getType());
3381 AI->replaceAllUsesWith(NewAllocaPtr);
3382 }
3383
3384 // The left-most redzone has enough space for at least 4 pointers.
3385 // Write the Magic value to redzone[0].
3386 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
3388 BasePlus0);
3389 // Write the frame description constant to redzone[1].
3390 Value *BasePlus1 = IRB.CreateIntToPtr(
3391 IRB.CreateAdd(LocalStackBase,
3392 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
3393 IntptrPtrTy);
3394 GlobalVariable *StackDescriptionGlobal =
3395 createPrivateGlobalForString(*F.getParent(), DescriptionString,
3396 /*AllowMerging*/ true, kAsanGenPrefix);
3397 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
3398 IRB.CreateStore(Description, BasePlus1);
3399 // Write the PC to redzone[2].
3400 Value *BasePlus2 = IRB.CreateIntToPtr(
3401 IRB.CreateAdd(LocalStackBase,
3402 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
3403 IntptrPtrTy);
3404 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
3405
3406 const auto &ShadowAfterScope = GetShadowBytesAfterScope(SVD, L);
3407
3408 // Poison the stack red zones at the entry.
3409 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
3410 // As mask we must use most poisoned case: red zones and after scope.
3411 // As bytes we can use either the same or just red zones only.
3412 copyToShadow(ShadowAfterScope, ShadowAfterScope, IRB, ShadowBase);
3413
3414 if (!StaticAllocaPoisonCallVec.empty()) {
3415 const auto &ShadowInScope = GetShadowBytes(SVD, L);
3416
3417 // Poison static allocas near lifetime intrinsics.
3418 for (const auto &APC : StaticAllocaPoisonCallVec) {
3419 const ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
3420 assert(Desc.Offset % L.Granularity == 0);
3421 size_t Begin = Desc.Offset / L.Granularity;
3422 size_t End = Begin + (APC.Size + L.Granularity - 1) / L.Granularity;
3423
3424 IRBuilder<> IRB(APC.InsBefore);
3425 copyToShadow(ShadowAfterScope,
3426 APC.DoPoison ? ShadowAfterScope : ShadowInScope, Begin, End,
3427 IRB, ShadowBase);
3428 }
3429 }
3430
3431 SmallVector<uint8_t, 64> ShadowClean(ShadowAfterScope.size(), 0);
3432 SmallVector<uint8_t, 64> ShadowAfterReturn;
3433
3434 // (Un)poison the stack before all ret instructions.
3435 for (Instruction *Ret : RetVec) {
3436 IRBuilder<> IRBRet(Ret);
3437 // Mark the current frame as retired.
3438 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
3439 BasePlus0);
3440 if (DoStackMalloc) {
3441 assert(StackMallocIdx >= 0);
3442 // if FakeStack != 0 // LocalStackBase == FakeStack
3443 // // In use-after-return mode, poison the whole stack frame.
3444 // if StackMallocIdx <= 4
3445 // // For small sizes inline the whole thing:
3446 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
3447 // **SavedFlagPtr(FakeStack) = 0
3448 // else
3449 // __asan_stack_free_N(FakeStack, LocalStackSize)
3450 // else
3451 // <This is not a fake stack; unpoison the redzones>
3452 Value *Cmp =
3453 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
3454 Instruction *ThenTerm, *ElseTerm;
3455 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
3456
3457 IRBuilder<> IRBPoison(ThenTerm);
3458 if (StackMallocIdx <= 4) {
3459 int ClassSize = kMinStackMallocSize << StackMallocIdx;
3460 ShadowAfterReturn.resize(ClassSize / L.Granularity,
3462 copyToShadow(ShadowAfterReturn, ShadowAfterReturn, IRBPoison,
3463 ShadowBase);
3464 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
3465 FakeStack,
3466 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
3467 Value *SavedFlagPtr = IRBPoison.CreateLoad(
3468 IntptrTy, IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
3469 IRBPoison.CreateStore(
3470 Constant::getNullValue(IRBPoison.getInt8Ty()),
3471 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
3472 } else {
3473 // For larger frames call __asan_stack_free_*.
3474 IRBPoison.CreateCall(
3475 AsanStackFreeFunc[StackMallocIdx],
3476 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
3477 }
3478
3479 IRBuilder<> IRBElse(ElseTerm);
3480 copyToShadow(ShadowAfterScope, ShadowClean, IRBElse, ShadowBase);
3481 } else {
3482 copyToShadow(ShadowAfterScope, ShadowClean, IRBRet, ShadowBase);
3483 }
3484 }
3485
3486 // We are done. Remove the old unused alloca instructions.
3487 for (auto *AI : AllocaVec)
3488 AI->eraseFromParent();
3489}
3490
3491void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
3492 IRBuilder<> &IRB, bool DoPoison) {
3493 // For now just insert the call to ASan runtime.
3494 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
3495 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
3496 IRB.CreateCall(
3497 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
3498 {AddrArg, SizeArg});
3499}
3500
3501// Handling llvm.lifetime intrinsics for a given %alloca:
3502// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
3503// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
3504// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
3505// could be poisoned by previous llvm.lifetime.end instruction, as the
3506// variable may go in and out of scope several times, e.g. in loops).
3507// (3) if we poisoned at least one %alloca in a function,
3508// unpoison the whole stack frame at function exit.
3509void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
3510 IRBuilder<> IRB(AI);
3511
3512 const Align Alignment = std::max(Align(kAllocaRzSize), AI->getAlign());
3513 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
3514
3515 Value *Zero = Constant::getNullValue(IntptrTy);
3516 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
3517 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
3518
3519 // Since we need to extend alloca with additional memory to locate
3520 // redzones, and OldSize is number of allocated blocks with
3521 // ElementSize size, get allocated memory size in bytes by
3522 // OldSize * ElementSize.
3523 const unsigned ElementSize =
3524 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
3525 Value *OldSize =
3526 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
3527 ConstantInt::get(IntptrTy, ElementSize));
3528
3529 // PartialSize = OldSize % 32
3530 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
3531
3532 // Misalign = kAllocaRzSize - PartialSize;
3533 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
3534
3535 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
3536 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
3537 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
3538
3539 // AdditionalChunkSize = Alignment + PartialPadding + kAllocaRzSize
3540 // Alignment is added to locate left redzone, PartialPadding for possible
3541 // partial redzone and kAllocaRzSize for right redzone respectively.
3542 Value *AdditionalChunkSize = IRB.CreateAdd(
3543 ConstantInt::get(IntptrTy, Alignment.value() + kAllocaRzSize),
3544 PartialPadding);
3545
3546 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
3547
3548 // Insert new alloca with new NewSize and Alignment params.
3549 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
3550 NewAlloca->setAlignment(Alignment);
3551
3552 // NewAddress = Address + Alignment
3553 Value *NewAddress =
3554 IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
3555 ConstantInt::get(IntptrTy, Alignment.value()));
3556
3557 // Insert __asan_alloca_poison call for new created alloca.
3558 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
3559
3560 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
3561 // for unpoisoning stuff.
3562 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
3563
3564 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
3565
3566 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
3567 AI->replaceAllUsesWith(NewAddressPtr);
3568
3569 // We are done. Erase old alloca from parent.
3570 AI->eraseFromParent();
3571}
3572
3573// isSafeAccess returns true if Addr is always inbounds with respect to its
3574// base object. For example, it is a field access or an array access with
3575// constant inbounds index.
3576bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
3577 Value *Addr, TypeSize TypeStoreSize) const {
3578 if (TypeStoreSize.isScalable())
3579 // TODO: We can use vscale_range to convert a scalable value to an
3580 // upper bound on the access size.
3581 return false;
3582 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
3583 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
3584 uint64_t Size = SizeOffset.first.getZExtValue();
3585 int64_t Offset = SizeOffset.second.getSExtValue();
3586 // Three checks are required to ensure safety:
3587 // . Offset >= 0 (since the offset is given from the base ptr)
3588 // . Size >= Offset (unsigned)
3589 // . Size - Offset >= NeededSize (unsigned)
3590 return Offset >= 0 && Size >= uint64_t(Offset) &&
3591 Size - uint64_t(Offset) >= TypeStoreSize / 8;
3592}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static cl::opt< bool > ClUseStackSafety("stack-tagging-use-stack-safety", cl::Hidden, cl::init(true), cl::desc("Use Stack Safety analysis results"))
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
Rewrite undef for PHI
static void findStoresToUninstrumentedArgAllocas(AddressSanitizer &ASan, Instruction &InsBefore, SmallVectorImpl< Instruction * > &InitInsts)
Collect instructions in the entry block after InsBefore which initialize permanent storage for a func...
static const uint64_t kDefaultShadowScale
constexpr size_t kAccessSizeIndexMask
static cl::opt< int > ClDebugMin("asan-debug-min", cl::desc("Debug min inst"), cl::Hidden, cl::init(-1))
static cl::opt< bool > ClUsePrivateAlias("asan-use-private-alias", cl::desc("Use private aliases for global variables"), cl::Hidden, cl::init(true))
static const uint64_t kPS_ShadowOffset64
static const uint64_t kFreeBSD_ShadowOffset32
constexpr size_t kIsWriteShift
static const uint64_t kSmallX86_64ShadowOffsetAlignMask
static bool isInterestingPointerSubtraction(Instruction *I)
const char kAMDGPUAddressSharedName[]
const char kAsanStackFreeNameTemplate[]
constexpr size_t kCompileKernelMask
static cl::opt< bool > ClForceDynamicShadow("asan-force-dynamic-shadow", cl::desc("Load shadow address into a local variable for each function"), cl::Hidden, cl::init(false))
const char kAsanOptionDetectUseAfterReturn[]
static cl::opt< std::string > ClMemoryAccessCallbackPrefix("asan-memory-access-callback-prefix", cl::desc("Prefix for memory access callbacks"), cl::Hidden, cl::init("__asan_"))
static const uint64_t kRISCV64_ShadowOffset64
static cl::opt< bool > ClInsertVersionCheck("asan-guard-against-version-mismatch", cl::desc("Guard against compiler/runtime version mismatch."), cl::Hidden, cl::init(true))
const char kAsanSetShadowPrefix[]
static cl::opt< AsanDtorKind > ClOverrideDestructorKind("asan-destructor-kind", cl::desc("Sets the ASan destructor kind. The default is to use the value " "provided to the pass constructor"), cl::values(clEnumValN(AsanDtorKind::None, "none", "No destructors"), clEnumValN(AsanDtorKind::Global, "global", "Use global destructors")), cl::init(AsanDtorKind::Invalid), cl::Hidden)
static cl::opt< bool > ClInstrumentWrites("asan-instrument-writes", cl::desc("instrument write instructions"), cl::Hidden, cl::init(true))
const char kAsanPtrCmp[]
static uint64_t GetCtorAndDtorPriority(Triple &TargetTriple)
const char kAsanStackMallocNameTemplate[]
static cl::opt< bool > ClInstrumentByval("asan-instrument-byval", cl::desc("instrument byval call arguments"), cl::Hidden, cl::init(true))
const char kAsanInitName[]
static cl::opt< bool > ClGlobals("asan-globals", cl::desc("Handle global objects"), cl::Hidden, cl::init(true))
static cl::opt< bool > ClRedzoneByvalArgs("asan-redzone-byval-args", cl::desc("Create redzones for byval " "arguments (extra copy " "required)"), cl::Hidden, cl::init(true))
static const uint64_t kWindowsShadowOffset64
static const uint64_t kEmscriptenShadowOffset
const char kAsanGenPrefix[]
constexpr size_t kIsWriteMask
static uint64_t getRedzoneSizeForScale(int MappingScale)
static void doInstrumentAddress(AddressSanitizer *Pass, Instruction *I, Instruction *InsertBefore, Value *Addr, MaybeAlign Alignment, unsigned Granularity, TypeSize TypeStoreSize, bool IsWrite, Value *SizeArgument, bool UseCalls, uint32_t Exp)
static const uint64_t kDefaultShadowOffset64
static cl::opt< bool > ClOptimizeCallbacks("asan-optimize-callbacks", cl::desc("Optimize callbacks"), cl::Hidden, cl::init(false))
const char kAsanUnregisterGlobalsName[]
static const uint64_t kAsanCtorAndDtorPriority
static cl::opt< bool > ClUseStackSafety("asan-use-stack-safety", cl::Hidden, cl::init(false), cl::Hidden, cl::desc("Use Stack Safety analysis results"), cl::Optional)
const char kAsanUnpoisonGlobalsName[]
static cl::opt< bool > ClWithIfuncSuppressRemat("asan-with-ifunc-suppress-remat", cl::desc("Suppress rematerialization of dynamic shadow address by passing " "it through inline asm in prologue."), cl::Hidden, cl::init(true))
static cl::opt< int > ClDebugStack("asan-debug-stack", cl::desc("debug stack"), cl::Hidden, cl::init(0))
const char kAsanUnregisterElfGlobalsName[]
static bool isUnsupportedAMDGPUAddrspace(Value *Addr)
const char kAsanRegisterImageGlobalsName[]
static cl::opt< bool > ClOpt("asan-opt", cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true))
static const uint64_t kAllocaRzSize
const char kODRGenPrefix[]
static const uint64_t kSystemZ_ShadowOffset64
static const uint64_t kDefaultShadowOffset32
const char kAsanShadowMemoryDynamicAddress[]
static cl::opt< bool > ClUseOdrIndicator("asan-use-odr-indicator", cl::desc("Use odr indicators to improve ODR reporting"), cl::Hidden, cl::init(true))
static bool GlobalWasGeneratedByCompiler(GlobalVariable *G)
Check if G has been created by a trusted compiler pass.
const char kAsanStackMallocAlwaysNameTemplate[]
static cl::opt< bool > ClInvalidPointerCmp("asan-detect-invalid-pointer-cmp", cl::desc("Instrument <, <=, >, >= with pointer operands"), cl::Hidden, cl::init(false))
static const uint64_t kAsanEmscriptenCtorAndDtorPriority
static cl::opt< int > ClDebugMax("asan-debug-max", cl::desc("Debug max inst"), cl::Hidden, cl::init(-1))
static cl::opt< bool > ClInvalidPointerSub("asan-detect-invalid-pointer-sub", cl::desc("Instrument - operations with pointer operands"), cl::Hidden, cl::init(false))
static bool isPointerOperand(Value *V)
static const uint64_t kFreeBSD_ShadowOffset64
static cl::opt< uint32_t > ClForceExperiment("asan-force-experiment", cl::desc("Force optimization experiment (for testing)"), cl::Hidden, cl::init(0))
const char kSanCovGenPrefix[]
static const uint64_t kFreeBSDKasan_ShadowOffset64
const char kAsanModuleDtorName[]
static const uint64_t kDynamicShadowSentinel
static bool isInterestingPointerComparison(Instruction *I)
static cl::opt< bool > ClStack("asan-stack", cl::desc("Handle stack memory"), cl::Hidden, cl::init(true))
static const uint64_t kMIPS64_ShadowOffset64
static const uint64_t kLinuxKasan_ShadowOffset64
static int StackMallocSizeClass(uint64_t LocalStackSize)
static cl::opt< uint32_t > ClMaxInlinePoisoningSize("asan-max-inline-poisoning-size", cl::desc("Inline shadow poisoning for blocks up to the given size in bytes."), cl::Hidden, cl::init(64))
static cl::opt< bool > ClInstrumentAtomics("asan-instrument-atomics", cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden, cl::init(true))
static cl::opt< bool > ClUseAfterScope("asan-use-after-scope", cl::desc("Check stack-use-after-scope"), cl::Hidden, cl::init(false))
constexpr size_t kAccessSizeIndexShift
static cl::opt< int > ClMappingScale("asan-mapping-scale", cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0))
const char kAsanPoisonStackMemoryName[]
static cl::opt< bool > ClEnableKasan("asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"), cl::Hidden, cl::init(false))
static cl::opt< std::string > ClDebugFunc("asan-debug-func", cl::Hidden, cl::desc("Debug func"))
static cl::opt< bool > ClUseGlobalsGC("asan-globals-live-support", cl::desc("Use linker features to support dead " "code stripping of globals"), cl::Hidden, cl::init(true))
static const size_t kNumberOfAccessSizes
const char kAsanUnpoisonStackMemoryName[]
static const uint64_t kLoongArch64_ShadowOffset64
const char kAsanRegisterGlobalsName[]
static cl::opt< bool > ClInstrumentDynamicAllocas("asan-instrument-dynamic-allocas", cl::desc("instrument dynamic allocas"), cl::Hidden, cl::init(true))
const char kAsanModuleCtorName[]
const char kAsanGlobalsRegisteredFlagName[]
static const size_t kMaxStackMallocSize
static cl::opt< bool > ClRecover("asan-recover", cl::desc("Enable recovery mode (continue-after-error)."), cl::Hidden, cl::init(false))
static cl::opt< bool > ClOptSameTemp("asan-opt-same-temp", cl::desc("Instrument the same temp just once"), cl::Hidden, cl::init(true))
static cl::opt< bool > ClDynamicAllocaStack("asan-stack-dynamic-alloca", cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden, cl::init(true))
static cl::opt< bool > ClOptStack("asan-opt-stack", cl::desc("Don't instrument scalar stack variables"), cl::Hidden, cl::init(false))
static const uint64_t kMIPS_ShadowOffsetN32
const char kAsanUnregisterImageGlobalsName[]
static cl::opt< AsanDetectStackUseAfterReturnMode > ClUseAfterReturn("asan-use-after-return", cl::desc("Sets the mode of detection for stack-use-after-return."), cl::values(clEnumValN(AsanDetectStackUseAfterReturnMode::Never, "never", "Never detect stack use after return."), clEnumValN(AsanDetectStackUseAfterReturnMode::Runtime, "runtime", "Detect stack use after return if " "binary flag 'ASAN_OPTIONS=detect_stack_use_after_return' is set."), clEnumValN(AsanDetectStackUseAfterReturnMode::Always, "always", "Always detect stack use after return.")), cl::Hidden, cl::init(AsanDetectStackUseAfterReturnMode::Runtime))
static cl::opt< bool > ClOptGlobals("asan-opt-globals", cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true))
static const uintptr_t kCurrentStackFrameMagic
static cl::opt< int > ClInstrumentationWithCallsThreshold("asan-instrumentation-with-call-threshold", cl::desc("If the function being instrumented contains more than " "this number of memory accesses, use callbacks instead of " "inline checks (-1 means never use callbacks)."), cl::Hidden, cl::init(7000))
static ShadowMapping getShadowMapping(const Triple &TargetTriple, int LongSize, bool IsKasan)
static const uint64_t kPPC64_ShadowOffset64
static cl::opt< AsanCtorKind > ClConstructorKind("asan-constructor-kind", cl::desc("Sets the ASan constructor kind"), cl::values(clEnumValN(AsanCtorKind::None, "none", "No constructors"), clEnumValN(AsanCtorKind::Global, "global", "Use global constructors")), cl::init(AsanCtorKind::Global), cl::Hidden)
static const int kMaxAsanStackMallocSizeClass
static const uint64_t kMIPS32_ShadowOffset32
static cl::opt< bool > ClAlwaysSlowPath("asan-always-slow-path", cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden, cl::init(false))
static const uint64_t kNetBSD_ShadowOffset32
static const uint64_t kFreeBSDAArch64_ShadowOffset64
static const uint64_t kSmallX86_64ShadowOffsetBase
static cl::opt< bool > ClInitializers("asan-initialization-order", cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(true))
static const uint64_t kNetBSD_ShadowOffset64
const char kAsanPtrSub[]
static cl::opt< unsigned > ClRealignStack("asan-realign-stack", cl::desc("Realign stack to the value of this flag (power of two)"), cl::Hidden, cl::init(32))
static const uint64_t kWindowsShadowOffset32
static cl::opt< bool > ClInstrumentReads("asan-instrument-reads", cl::desc("instrument read instructions"), cl::Hidden, cl::init(true))
static size_t TypeStoreSizeToSizeIndex(uint32_t TypeSize)
const char kAsanAllocaPoison[]
constexpr size_t kCompileKernelShift
static cl::opt< bool > ClWithIfunc("asan-with-ifunc", cl::desc("Access dynamic shadow through an ifunc global on " "platforms that support this"), cl::Hidden, cl::init(true))
static cl::opt< bool > ClKasanMemIntrinCallbackPrefix("asan-kernel-mem-intrinsic-prefix", cl::desc("Use prefix for memory intrinsics in KASAN mode"), cl::Hidden, cl::init(false))
const char kAsanVersionCheckNamePrefix[]
const char kAMDGPUAddressPrivateName[]
static const uint64_t kNetBSDKasan_ShadowOffset64
const char kAsanRegisterElfGlobalsName[]
static cl::opt< uint64_t > ClMappingOffset("asan-mapping-offset", cl::desc("offset of asan shadow mapping [EXPERIMENTAL]"), cl::Hidden, cl::init(0))
const char kAsanReportErrorTemplate[]
static cl::opt< bool > ClWithComdat("asan-with-comdat", cl::desc("Place ASan constructors in comdat sections"), cl::Hidden, cl::init(true))
static cl::opt< bool > ClSkipPromotableAllocas("asan-skip-promotable-allocas", cl::desc("Do not instrument promotable allocas"), cl::Hidden, cl::init(true))
static cl::opt< int > ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb", cl::init(10000), cl::desc("maximal number of instructions to instrument in any given BB"), cl::Hidden)
static const uintptr_t kRetiredStackFrameMagic
const char kAsanPoisonGlobalsName[]
const char kAsanHandleNoReturnName[]
static const size_t kMinStackMallocSize
static cl::opt< int > ClDebug("asan-debug", cl::desc("debug"), cl::Hidden, cl::init(0))
const char kAsanAllocasUnpoison[]
static const uint64_t kAArch64_ShadowOffset64
static cl::opt< bool > ClInvalidPointerPairs("asan-detect-invalid-pointer-pair", cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden, cl::init(false))
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
SmallVector< MachineOperand, 4 > Cond
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
Definition: CommandLine.h:678
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define LLVM_DEBUG(X)
Definition: Debug.h:101
This file defines the DenseMap class.
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
uint64_t Addr
std::string Name
uint64_t Size
bool End
Definition: ELF_riscv.cpp:464
static bool runOnFunction(Function &F, bool PostInlining)
This is the interface for a simple mod/ref and alias analysis over globals.
IRTranslator LLVM IR MI
static LVOptions Options
Definition: LVOptions.cpp:25
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
#define G(x, y, z)
Definition: MD5.cpp:56
This file contains the declarations for metadata subclasses.
Module.h This file contains the declarations for the Module class.
IntegerType * Int32Ty
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
@ SI
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:167
This file contains some functions that are useful when dealing with strings.
static SymbolRef::Type getType(const Symbol *Sym)
Definition: TapiFile.cpp:40
This defines the Use class.
AddressSanitizerPass(const AddressSanitizerOptions &Options, bool UseGlobalGC=true, bool UseOdrIndicator=true, AsanDtorKind DestructorKind=AsanDtorKind::Global, AsanCtorKind ConstructorKind=AsanCtorKind::Global)
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
an instruction to allocate memory on the stack
Definition: Instructions.h:58
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
Definition: Instructions.h:150
bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
Definition: Instructions.h:125
PointerType * getType() const
Overload to return most specific pointer type.
Definition: Instructions.h:100
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
Definition: Instructions.h:118
bool isUsedWithInAlloca() const
Return true if this alloca is used as an inalloca argument to a call.
Definition: Instructions.h:140
std::optional< TypeSize > getAllocationSize(const DataLayout &DL) const
Get allocation size in bytes.
void setAlignment(Align Align)
Definition: Instructions.h:129
const Value * getArraySize() const
Get the number of elements allocated.
Definition: Instructions.h:96
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:620
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:774
This class represents an incoming formal argument to a Function.
Definition: Argument.h:28
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:163
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
Definition: Type.cpp:708
An instruction that atomically checks whether a specified value is in a memory location,...
Definition: Instructions.h:513
an instruction that atomically reads a memory location, combines it with another value,...
Definition: Instructions.h:718
AttributeList addParamAttribute(LLVMContext &C, unsigned ArgNo, Attribute::AttrKind Kind) const
Add an argument attribute to the list.
Definition: Attributes.h:576
LLVM Basic Block Representation.
Definition: BasicBlock.h:56
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:323
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:254
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:105
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:112
const CallInst * getTerminatingMustTailCall() const
Returns the call instruction marked 'musttail' prior to the terminating return instruction of this ba...
Definition: BasicBlock.cpp:150
Conditional or Unconditional Branch instruction.
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1190
bool isInlineAsm() const
Check if this call is an inline asm statement.
Definition: InstrTypes.h:1480
Value * getArgOperand(unsigned i) const
Definition: InstrTypes.h:1357
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
Definition: InstrTypes.h:1348
bool doesNotReturn() const
Determine if the call cannot return.
Definition: InstrTypes.h:1920
unsigned arg_size() const
Definition: InstrTypes.h:1355
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
@ Largest
The linker will choose the largest COMDAT.
Definition: Comdat.h:38
@ SameSize
The data referenced by the COMDAT must be the same size.
Definition: Comdat.h:40
@ Any
The linker may choose any COMDAT.
Definition: Comdat.h:36
@ NoDeduplicate
No deduplication is performed.
Definition: Comdat.h:39
@ ExactMatch
The data referenced by the COMDAT must be the same.
Definition: Comdat.h:37
ConstantArray - Constant Array Declarations.
Definition: Constants.h:408
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1235
static Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2199
static Constant * getPointerCast(Constant *C, Type *Ty)
Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant expression.
Definition: Constants.cpp:2025
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, bool InBounds=false, std::optional< unsigned > InRangeIndex=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition: Constants.h:1227
static bool isValueValidForType(Type *Ty, uint64_t V)
This static method returns true if the type Ty is big enough to represent the value V.
Definition: Constants.cpp:1504
static Constant * get(Type *Ty, uint64_t V, bool IsSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:888
static Constant * get(StructType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1300
This is an important base class in LLVM.
Definition: Constant.h:41
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:356
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
Definition: Constants.cpp:418
Debug location.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
A debug info location.
Definition: DebugLoc.h:33
DILocation * get() const
Get the underlying DILocation.
Definition: DebugLoc.cpp:20
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
Definition: DerivedTypes.h:165
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
const BasicBlock & front() const
Definition: Function.h:772
static Function * createWithDefaultAttr(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Creates a function with some attributes recorded in llvm.module.flags applied.
Definition: Function.cpp:336
const Constant * getAliasee() const
Definition: GlobalAlias.h:84
static GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
Definition: Globals.cpp:506
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalObject.
Definition: Globals.cpp:128
void copyMetadata(const GlobalObject *Src, unsigned Offset)
Copy metadata from Src, adjusting offsets by Offset.
Definition: Metadata.cpp:1650
void setComdat(Comdat *C)
Definition: Globals.cpp:196
void setSection(StringRef S)
Change the section for this global.
Definition: Globals.cpp:250
VisibilityTypes getVisibility() const
Definition: GlobalValue.h:244
void setUnnamedAddr(UnnamedAddr Val)
Definition: GlobalValue.h:227
bool hasLocalLinkage() const
Definition: GlobalValue.h:523
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1',...
Definition: GlobalValue.h:562
ThreadLocalMode getThreadLocalMode() const
Definition: GlobalValue.h:267
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:652
@ HiddenVisibility
The GV is hidden.
Definition: GlobalValue.h:64
void setVisibility(VisibilityTypes V)
Definition: GlobalValue.h:250
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:47
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:56
@ CommonLinkage
Tentative definitions.
Definition: GlobalValue.h:58
@ InternalLinkage
Rename collisions when linking (static functions).
Definition: GlobalValue.h:55
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition: GlobalValue.h:49
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition: GlobalValue.h:57
DLLStorageClassTypes getDLLStorageClass() const
Definition: GlobalValue.h:271
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
void copyAttributesFrom(const GlobalVariable *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a GlobalVariable) fro...
Definition: Globals.cpp:481
Analysis pass providing a never-invalidated alias analysis result.
This instruction compares its operands according to the predicate given to the constructor.
Common base class shared among various IRBuilders.
Definition: IRBuilder.h:94
AllocaInst * CreateAlloca(Type *Ty, unsigned AddrSpace, Value *ArraySize=nullptr, const Twine &Name="")
Definition: IRBuilder.h:1702
IntegerType * getInt1Ty()
Fetch the type representing a single bit.
Definition: IRBuilder.h:497
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition: IRBuilder.h:2355
Value * CreatePointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2068
Value * CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2164
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition: IRBuilder.cpp:1134
BasicBlock::iterator GetInsertPoint() const
Definition: IRBuilder.h:175
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2017
Value * CreateTypeSize(Type *DstType, TypeSize Size)
Create an expression which evaluates to the number of units in Size at runtime.
Definition: IRBuilder.cpp:113
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1366
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition: IRBuilder.h:512
BasicBlock * GetInsertBlock() const
Definition: IRBuilder.h:174
IntegerType * getInt64Ty()
Fetch the type representing a 64-bit integer.
Definition: IRBuilder.h:517
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2140
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition: IRBuilder.h:472
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Definition: IRBuilder.h:2292
Value * CreateNot(Value *V, const Twine &Name="")
Definition: IRBuilder.h:1678
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2136
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1273
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2022
ConstantInt * getIntN(unsigned N, uint64_t C)
Get a constant N-bit value, zero extended or truncated from a 64-bit value.
Definition: IRBuilder.h:483
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Definition: IRBuilder.h:1719
PointerType * getInt8PtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer to an 8-bit integer value.
Definition: IRBuilder.h:560
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1404
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition: IRBuilder.h:1732
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1256
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2012
Value * CreateIsNotNull(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg != 0.
Definition: IRBuilder.h:2444
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1426
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
Definition: IRBuilder.h:2091
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition: IRBuilder.h:180
Type * getVoidTy()
Fetch the type representing void.
Definition: IRBuilder.h:550
StoreInst * CreateAlignedStore(Value *Val, Value *Ptr, MaybeAlign Align, bool isVolatile=false)
Definition: IRBuilder.h:1755
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args=std::nullopt, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2307
Value * CreateGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="", bool IsInBounds=false)
Definition: IRBuilder.h:1795
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
Definition: IRBuilder.h:502
CallInst * CreateMemCpy(Value *Dst, MaybeAlign DstAlign, Value *Src, MaybeAlign SrcAlign, uint64_t Size, bool isVolatile=false, MDNode *TBAATag=nullptr, MDNode *TBAAStructTag=nullptr, MDNode *ScopeTag=nullptr, MDNode *NoAliasTag=nullptr)
Create and insert a memcpy between the specified pointers.
Definition: IRBuilder.h:634
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1290
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2564
static InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT, bool canThrow=false)
InlineAsm::get - Return the specified uniqued inline asm string.
Definition: InlineAsm.cpp:43
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...
Definition: PassManager.h:933
Base class for instruction visitors.
Definition: InstVisitor.h:78
RetTy visitCallBase(CallBase &I)
Definition: InstVisitor.h:267
RetTy visitCleanupReturnInst(CleanupReturnInst &I)
Definition: InstVisitor.h:244
RetTy visitIntrinsicInst(IntrinsicInst &I)
Definition: InstVisitor.h:219
void visit(Iterator Start, Iterator End)
Definition: InstVisitor.h:87
RetTy visitReturnInst(ReturnInst &I)
Definition: InstVisitor.h:226
RetTy visitAllocaInst(AllocaInst &I)
Definition: InstVisitor.h:168
RetTy visitResumeInst(ResumeInst &I)
Definition: InstVisitor.h:238
bool isLifetimeStartOrEnd() const LLVM_READONLY
Return true if the instruction is a llvm.lifetime.start or llvm.lifetime.end marker.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:365
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:70
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
Definition: Instruction.h:257
const BasicBlock * getParent() const
Definition: Instruction.h:90
BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
const Instruction * getNextNonDebugInstruction(bool SkipPseudoOp=false) const
Return a pointer to the next non-debug instruction in the same basic block as 'this',...
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Definition: Instruction.cpp:82
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Definition: Instruction.h:362
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition: Type.cpp:339
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:47
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
Definition: IntrinsicInst.h:54
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
An instruction for reading from memory.
Definition: Instructions.h:177
static Error ParseSectionSpecifier(StringRef Spec, StringRef &Segment, StringRef &Section, unsigned &TAA, bool &TAAParsed, unsigned &StubSize)
Parse the section specifier indicated by "Spec".
MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight)
Return metadata containing two branch weights.
Definition: MDBuilder.cpp:37
Metadata node.
Definition: Metadata.h:950
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1416
This is the common base class for memset/memcpy/memmove.
Root of the metadata hierarchy.
Definition: Metadata.h:61
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.cpp:398
Evaluate the size and offset of an object pointed to by a Value* statically.
static bool bothKnown(const SizeOffsetType &SizeOffset)
SizeOffsetType compute(Value *V)
Pass interface - Implemented by all 'passes'.
Definition: Pass.h:94
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:152
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: PassManager.h:155
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:158
void abandon()
Mark an analysis as abandoned.
Definition: PassManager.h:206
Resume the propagation of an exception.
Return a value (possibly void), from a function.
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, Instruction *InsertBefore=nullptr)
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:383
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:365
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:450
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:577
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:941
void reserve(size_type N)
Definition: SmallVector.h:667
void resize(size_type N)
Definition: SmallVector.h:642
void push_back(const T &Elt)
Definition: SmallVector.h:416
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
This pass performs the global (interprocedural) stack safety analysis (new pass manager).
bool stackAccessIsSafe(const Instruction &I) const
bool isSafe(const AllocaInst &AI) const
An instruction for storing to memory.
Definition: Instructions.h:301
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
bool startswith(StringRef Prefix) const
Definition: StringRef.h:261
const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:131
Class to represent struct types.
Definition: DerivedTypes.h:213
static StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition: Type.cpp:434
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
AttributeList getAttrList(LLVMContext *C, ArrayRef< unsigned > ArgNos, bool Signed, bool Ret=false, AttributeList AL=AttributeList()) const
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
bool isAndroidVersionLT(unsigned Major) const
Definition: Triple.h:727
bool isThumb() const
Tests whether the target is Thumb (little and big endian).
Definition: Triple.h:784
bool isDriverKit() const
Is this an Apple DriverKit triple.
Definition: Triple.h:514
bool isOSNetBSD() const
Definition: Triple.h:537
bool isAndroid() const
Tests whether the target is Android.
Definition: Triple.h:725
bool isMIPS64() const
Tests whether the target is MIPS 64-bit (little and big endian).
Definition: Triple.h:871
@ loongarch64
Definition: Triple.h:62
ArchType getArch() const
Get the parsed architecture type of this triple.
Definition: Triple.h:356
EnvironmentType getEnvironment() const
Get the parsed environment type of this triple.
Definition: Triple.h:373
bool isMIPS32() const
Tests whether the target is MIPS 32-bit (little and big endian).
Definition: Triple.h:866
bool isOSWindows() const
Tests whether the OS is Windows.
Definition: Triple.h:584
@ DXContainer
Definition: Triple.h:284
@ UnknownObjectFormat
Definition: Triple.h:281
bool isARM() const
Tests whether the target is ARM (little and big endian).
Definition: Triple.h:789
bool isOSLinux() const
Tests whether the OS is Linux.
Definition: Triple.h:638
bool isAMDGPU() const
Definition: Triple.h:779
bool isMacOSX() const
Is this a Mac OS X triple.
Definition: Triple.h:486
bool isOSFreeBSD() const
Definition: Triple.h:545
bool isOSEmscripten() const
Tests whether the OS is Emscripten.
Definition: Triple.h:658
bool isWatchOS() const
Is this an Apple watchOS triple.
Definition: Triple.h:505
bool isiOS() const
Is this an iOS triple.
Definition: Triple.h:495
bool isPS() const
Tests whether the target is the PS4 or PS5 platform.
Definition: Triple.h:722
bool isOSFuchsia() const
Definition: Triple.h:549
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
static Type * getVoidTy(LLVMContext &C)
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:302
static IntegerType * getInt8Ty(LLVMContext &C)
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
static IntegerType * getInt32Ty(LLVMContext &C)
This function has undefined behavior.
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
op_range operands()
Definition: User.h:242
Value * getOperand(unsigned i) const
Definition: User.h:169
static ValueAsMetadata * get(Value *V)
Definition: Metadata.cpp:394
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:535
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:384
constexpr ScalarTy getFixedValue() const
Definition: TypeSize.h:182
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition: TypeSize.h:166
An efficient, type-erasing, non-owning reference to a callable.
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition: ilist_node.h:289
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
Definition: BitmaskEnum.h:119
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
const uint64_t Version
Definition: InstrProf.h:1073
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=std::nullopt)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:1465
@ S_CSTRING_LITERALS
S_CSTRING_LITERALS - Section with literal C strings.
Definition: MachO.h:131
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
Definition: CommandLine.h:703
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:445
uint64_t getAllocaSizeInBytes(const AllocaInst &AI)
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
void ReplaceInstWithInst(BasicBlock *BB, BasicBlock::iterator &BI, Instruction *I)
Replace the instruction specified by BI with the instruction specified by I.
@ Offset
Definition: DWP.cpp:406
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1819
SmallVector< uint8_t, 64 > GetShadowBytesAfterScope(const SmallVectorImpl< ASanStackVariableDescription > &Vars, const ASanStackFrameLayout &Layout)
std::string demangle(const std::string &MangledName)
Attempt to demangle a string using different demangling schemes.
Definition: Demangle.cpp:29
std::pair< APInt, APInt > SizeOffsetType
AllocaInst * findAllocaForValue(Value *V, bool OffsetZero=false)
Returns unique alloca where the value comes from, or nullptr.
@ Done
Definition: Threading.h:61
Function * createSanitizerCtor(Module &M, StringRef CtorName)
Creates sanitizer constructor function.
AsanDetectStackUseAfterReturnMode
Mode of ASan detect stack use after return.
@ Always
Always detect stack use after return.
@ Never
Never detect stack use after return.
@ Runtime
Detect stack use after return if not disabled runtime with (ASAN_OPTIONS=detect_stack_use_after_retur...
Instruction * SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
GlobalVariable * createPrivateGlobalForString(Module &M, StringRef Str, bool AllowMerging, const char *NamePrefix="")
const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=6)
This method strips off any GEP address adjustments and pointer casts from the specified value,...
void SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore, Instruction **ThenTerm, Instruction **ElseTerm, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr)
SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen, but also creates the ElseBlock...
bool isAllocaPromotable(const AllocaInst *AI)
Return true if this alloca is legal for promotion.
SmallString< 64 > ComputeASanStackFrameDescription(const SmallVectorImpl< ASanStackVariableDescription > &Vars)
SmallVector< uint8_t, 64 > GetShadowBytes(const SmallVectorImpl< ASanStackVariableDescription > &Vars, const ASanStackFrameLayout &Layout)
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition: bit.h:179
FunctionCallee declareSanitizerInitFunction(Module &M, StringRef InitName, ArrayRef< Type * > InitArgTypes, bool Weak=false)
std::string getUniqueModuleId(Module *M)
Produce a unique identifier for this module by taking the MD5 sum of the names of the module's strong...
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition: MathExtras.h:292
std::pair< Function *, FunctionCallee > createSanitizerCtorAndInitFunctions(Module &M, StringRef CtorName, StringRef InitName, ArrayRef< Type * > InitArgTypes, ArrayRef< Value * > InitArgs, StringRef VersionCheckName=StringRef(), bool Weak=false)
Creates sanitizer constructor function, and calls sanitizer's init function from it.
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void SplitBlockAndInsertForEachLane(ElementCount EC, Type *IndexTy, Instruction *InsertBefore, std::function< void(IRBuilderBase &, Value *)> Func)
Utility function for performing a given action on each lane of a vector with EC elements.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:145
AsanDtorKind
Types of ASan module destructors supported.
@ None
Do not emit any destructors for ASan.
ASanStackFrameLayout ComputeASanStackFrameLayout(SmallVectorImpl< ASanStackVariableDescription > &Vars, uint64_t Granularity, uint64_t MinHeaderSize)
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition: Error.h:745
void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
static const int kAsanStackUseAfterReturnMagic
@ Dynamic
Denotes mode unknown at compile time.
void appendToGlobalCtors(Module &M, Function *F, int Priority, Constant *Data=nullptr)
Append F to the list of global ctors of module M with the given Priority.
Definition: ModuleUtils.cpp:71
Align assumeAligned(uint64_t Value)
Treats the value 0 as a 1, so Align is always at least 1.
Definition: Alignment.h:111
iterator_range< df_iterator< T > > depth_first(const T &G)
AsanCtorKind
Types of ASan module constructors supported.
void maybeMarkSanitizerLibraryCallNoBuiltin(CallInst *CI, const TargetLibraryInfo *TLI)
Given a CallInst, check if it calls a string function known to CodeGen, and mark it with NoBuiltin if...
Definition: Local.cpp:3452
void appendToUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.used list.
void appendToGlobalDtors(Module &M, Function *F, int Priority, Constant *Data=nullptr)
Same as appendToGlobalCtors(), but for global dtors.
Definition: ModuleUtils.cpp:75
void getAddressSanitizerParams(const Triple &TargetTriple, int LongSize, bool IsKasan, uint64_t *ShadowBase, int *MappingScale, bool *OrShadowOffset)
bool replaceDbgDeclare(Value *Address, Value *NewAddress, DIBuilder &Builder, uint8_t DIExprFlags, int Offset)
Replaces llvm.dbg.declare instruction when the address it describes is replaced with a new value.
Definition: Local.cpp:1760
#define N
#define OP(n)
Definition: regex2.h:73
ASanAccessInfo(int32_t Packed)