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