90 #define DEBUG_TYPE "asan" 136 "__asan_unregister_globals";
138 "__asan_register_image_globals";
140 "__asan_unregister_image_globals";
142 "__asan_register_elf_globals";
144 "__asan_unregister_elf_globals";
149 "__asan_version_mismatch_check_v";
161 "__asan_poison_stack_memory";
163 "__asan_unpoison_stack_memory";
168 "___asan_globals_registered";
171 "__asan_option_detect_stack_use_after_return";
174 "__asan_shadow_memory_dynamic_address";
187 "asan-kernel",
cl::desc(
"Enable KernelAddressSanitizer instrumentation"),
192 cl::desc(
"Enable recovery mode (continue-after-error)."),
197 cl::desc(
"instrument read instructions"),
201 "asan-instrument-writes",
cl::desc(
"instrument write instructions"),
205 "asan-instrument-atomics",
210 "asan-always-slow-path",
215 "asan-force-dynamic-shadow",
216 cl::desc(
"Load shadow address into a local variable for each function"),
221 cl::desc(
"Access dynamic shadow through an ifunc global on " 222 "platforms that support this"),
226 "asan-with-ifunc-suppress-remat",
227 cl::desc(
"Suppress rematerialization of dynamic shadow address by passing " 228 "it through inline asm in prologue."),
236 "asan-max-ins-per-bb",
cl::init(10000),
237 cl::desc(
"maximal number of instructions to instrument in any given BB"),
244 "asan-max-inline-poisoning-size",
246 "Inline shadow poisoning for blocks up to the given size in bytes."),
250 cl::desc(
"Check stack-use-after-return"),
254 cl::desc(
"Create redzones for byval " 255 "arguments (extra copy " 260 cl::desc(
"Check stack-use-after-scope"),
269 cl::desc(
"Handle C++ initializer order"),
273 "asan-detect-invalid-pointer-pair",
278 "asan-realign-stack",
279 cl::desc(
"Realign stack to the value of this flag (power of two)"),
283 "asan-instrumentation-with-call-threshold",
285 "If the function being instrumented contains more than " 286 "this number of memory accesses, use callbacks instead of " 287 "inline checks (-1 means never use callbacks)."),
291 "asan-memory-access-callback-prefix",
297 cl::desc(
"instrument dynamic allocas"),
301 "asan-skip-promotable-allocas",
310 cl::desc(
"scale of asan shadow mapping"),
314 "asan-mapping-offset",
325 "asan-opt-same-temp",
cl::desc(
"Instrument the same temp just once"),
329 cl::desc(
"Don't instrument scalar globals"),
333 "asan-opt-stack",
cl::desc(
"Don't instrument scalar stack variables"),
337 "asan-stack-dynamic-alloca",
342 "asan-force-experiment",
348 cl::desc(
"Use private aliases for global" 354 cl::desc(
"Use linker features to support dead " 355 "code stripping of globals"),
362 cl::desc(
"Place ASan constructors in comdat sections"),
382 STATISTIC(NumInstrumentedReads,
"Number of instrumented reads");
383 STATISTIC(NumInstrumentedWrites,
"Number of instrumented writes");
384 STATISTIC(NumOptimizedAccessesToGlobalVar,
385 "Number of optimized accesses to global vars");
386 STATISTIC(NumOptimizedAccessesToStackVar,
387 "Number of optimized accesses to stack vars");
392 struct LocationMetadata {
397 LocationMetadata() =
default;
399 bool empty()
const {
return Filename.
empty(); }
404 Filename = DIFilename->getString();
406 mdconst::extract<ConstantInt>(MDN->
getOperand(1))->getLimitedValue();
408 mdconst::extract<ConstantInt>(MDN->
getOperand(2))->getLimitedValue();
413 class GlobalsMetadata {
416 LocationMetadata SourceLoc;
418 bool IsDynInit =
false;
419 bool IsBlacklisted =
false;
424 GlobalsMetadata() =
default;
435 if (!Globals)
return;
436 for (
auto MDN : Globals->
operands()) {
439 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->
getOperand(0));
444 Entry &
E = Entries[GV];
445 if (
auto *Loc = cast_or_null<MDNode>(MDN->
getOperand(1)))
446 E.SourceLoc.parse(Loc);
448 E.Name =
Name->getString();
450 mdconst::extract<ConstantInt>(MDN->
getOperand(3));
451 E.IsDynInit |= IsDynInit->
isOne();
453 mdconst::extract<ConstantInt>(MDN->
getOperand(4));
454 E.IsBlacklisted |= IsBlacklisted->
isOne();
460 auto Pos = Entries.find(
G);
461 return (Pos != Entries.end()) ? Pos->second : Entry();
465 bool inited_ =
false;
474 struct ShadowMapping {
485 bool IsAndroid = TargetTriple.
isAndroid();
489 bool IsPS4CPU = TargetTriple.
isPS4CPU();
496 bool IsMIPS32 = TargetTriple.
isMIPS32();
497 bool IsMIPS64 = TargetTriple.
isMIPS64();
498 bool IsArmOrThumb = TargetTriple.
isARM() || TargetTriple.
isThumb();
504 ShadowMapping Mapping;
511 if (LongSize == 32) {
547 else if (IsLinux && IsX86_64) {
553 }
else if (IsWindows && IsX86_64) {
581 Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64 && !IsSystemZ && !IsPS4CPU &&
582 !(Mapping.Offset & (Mapping.Offset - 1)) &&
584 bool IsAndroidWithIfuncSupport =
586 Mapping.InGlobal =
ClWithIfunc && IsAndroidWithIfuncSupport && IsArmOrThumb;
594 return std::max(32U, 1U << MappingScale);
604 explicit AddressSanitizer(
bool CompileKernel =
false,
bool Recover =
false,
605 bool UseAfterScope =
false)
608 this->CompileKernel =
ClEnableKasan.getNumOccurrences() > 0 ?
614 return "AddressSanitizerFunctionPass";
623 uint64_t ArraySize = 1;
626 assert(CI &&
"non-constant array size");
630 uint64_t SizeInBytes =
632 return SizeInBytes * ArraySize;
636 bool isInterestingAlloca(
const AllocaInst &AI);
643 uint64_t *TypeSize,
unsigned *Alignment,
644 Value **MaybeMask =
nullptr);
648 void instrumentPointerComparisonOrSubtraction(
Instruction *I);
652 void instrumentUnusualSizeOrAlignment(
Instruction *I,
655 Value *SizeArgument,
bool UseCalls,
660 bool IsWrite,
size_t AccessSizeIndex,
665 bool maybeInsertAsanInitAtFunctionEntry(
Function &F);
666 void maybeInsertDynamicShadowAtFunctionEntry(
Function &F);
667 void markEscapedLocalAllocas(
Function &F);
668 bool doInitialization(
Module &M)
override;
669 bool doFinalization(
Module &M)
override;
674 friend struct FunctionStackPoisoner;
676 void initializeCallbacks(
Module &M);
681 uint64_t TypeSize)
const;
684 struct FunctionStateRAII {
685 AddressSanitizer *
Pass;
687 FunctionStateRAII(AddressSanitizer *Pass) :
Pass(Pass) {
688 assert(Pass->ProcessedAllocas.empty() &&
689 "last pass forgot to clear cache");
690 assert(!Pass->LocalDynamicShadow);
693 ~FunctionStateRAII() {
694 Pass->LocalDynamicShadow =
nullptr;
695 Pass->ProcessedAllocas.clear();
706 ShadowMapping Mapping;
709 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
717 Function *AsanErrorCallbackSized[2][2];
718 Function *AsanMemoryAccessCallbackSized[2][2];
720 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
722 Value *LocalDynamicShadow =
nullptr;
723 GlobalsMetadata GlobalsMD;
727 class AddressSanitizerModule :
public ModulePass {
732 explicit AddressSanitizerModule(
bool CompileKernel =
false,
733 bool Recover =
false,
734 bool UseGlobalsGC =
true)
745 this->Recover =
ClRecover.getNumOccurrences() > 0 ?
747 this->CompileKernel =
ClEnableKasan.getNumOccurrences() > 0 ?
751 bool runOnModule(
Module &M)
override;
752 StringRef getPassName()
const override {
return "AddressSanitizerModule"; }
755 void initializeCallbacks(
Module &M);
764 const std::string &UniqueModuleId);
780 bool ShouldUseMachOGlobalsSection()
const;
781 StringRef getGlobalMetadataSection()
const;
784 size_t MinRedzoneSizeForGlobal()
const {
787 int GetAsanVersion(
const Module &M)
const;
789 GlobalsMetadata GlobalsMD;
797 ShadowMapping Mapping;
803 Function *AsanUnregisterImageGlobals;
807 Function *AsanCtorFunction =
nullptr;
808 Function *AsanDtorFunction =
nullptr;
820 struct FunctionStackPoisoner :
public InstVisitor<FunctionStackPoisoner> {
822 AddressSanitizer &ASan;
827 ShadowMapping Mapping;
832 unsigned StackAlignment;
836 Function *AsanSetShadowFunc[0x100] = {};
837 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
838 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
841 struct AllocaPoisonCall {
857 AllocaForValueMapTy AllocaForValue;
859 bool HasNonEmptyInlineAsm =
false;
860 bool HasReturnsTwiceCall =
false;
861 std::unique_ptr<CallInst> EmptyInlineAsm;
863 FunctionStackPoisoner(
Function &F, AddressSanitizer &ASan)
868 IntptrTy(ASan.IntptrTy),
870 Mapping(ASan.Mapping),
871 StackAlignment(1 << Mapping.Scale),
878 copyArgsPassedByValToAllocas();
883 if (AllocaVec.
empty() && DynamicAllocaVec.
empty())
return false;
887 processDynamicAllocas();
888 processStaticAllocas();
899 void copyArgsPassedByValToAllocas();
904 void processStaticAllocas();
905 void processDynamicAllocas();
907 void createDynamicAllocasInitStorage();
919 void unpoisonDynamicAllocasBeforeInst(
Instruction *InstBefore,
927 if (!isa<ReturnInst>(InstBefore)) {
929 InstBefore->
getModule(), Intrinsic::get_dynamic_area_offset,
939 {IRB.
CreateLoad(DynamicAllocaLayout), DynamicAreaPtr});
943 void unpoisonDynamicAllocas() {
944 for (
auto &
Ret : RetVec)
945 unpoisonDynamicAllocasBeforeInst(
Ret, DynamicAllocaLayout);
947 for (
auto &StackRestoreInst : StackRestoreVec)
948 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
949 StackRestoreInst->getOperand(0));
966 if (!ASan.isInterestingAlloca(AI)) {
970 if (AllocaVec.
empty())
989 if (ID == Intrinsic::stackrestore) StackRestoreVec.
push_back(&II);
990 if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
991 if (!ASan.UseAfterScope)
993 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
1002 if (SizeValue == ~0ULL ||
1007 if (!AI || !ASan.isInterestingAlloca(*AI))
1009 bool DoPoison = (ID == Intrinsic::lifetime_end);
1010 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
1012 StaticAllocaPoisonCallVec.
push_back(APC);
1014 DynamicAllocaPoisonCallVec.
push_back(APC);
1019 if (
CallInst *CI = dyn_cast<CallInst>(I)) {
1020 HasNonEmptyInlineAsm |= CI->isInlineAsm() &&
1021 !CI->isIdenticalTo(EmptyInlineAsm.get()) &&
1022 I != ASan.LocalDynamicShadow;
1023 HasReturnsTwiceCall |= CI->canReturnTwice();
1028 void initializeCallbacks(
Module &M);
1030 bool doesDominateAllExits(
const Instruction *
I)
const {
1031 for (
auto Ret : RetVec) {
1032 if (!ASan.getDominatorTree().dominates(I,
Ret))
return false;
1065 AddressSanitizer,
"asan",
1066 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
false,
1071 AddressSanitizer,
"asan",
1072 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
false,
1077 bool UseAfterScope) {
1078 assert(!CompileKernel || Recover);
1079 return new AddressSanitizer(CompileKernel, Recover, UseAfterScope);
1085 AddressSanitizerModule,
"asan-module",
1086 "AddressSanitizer: detects use-after-free and out-of-bounds bugs." 1092 bool UseGlobalsGC) {
1093 assert(!CompileKernel || Recover);
1094 return new AddressSanitizerModule(CompileKernel, Recover, UseGlobalsGC);
1105 bool AllowMerging) {
1113 GV->setAlignment(1);
1119 LocationMetadata MD) {
1142 if (G->
getName() ==
"__llvm_gcov_ctr")
1150 Shadow = IRB.
CreateLShr(Shadow, Mapping.Scale);
1151 if (Mapping.Offset == 0)
return Shadow;
1154 if (LocalDynamicShadow)
1155 ShadowBase = LocalDynamicShadow;
1158 if (Mapping.OrShadowOffset)
1159 return IRB.
CreateOr(Shadow, ShadowBase);
1161 return IRB.
CreateAdd(Shadow, ShadowBase);
1165 void AddressSanitizer::instrumentMemIntrinsic(
MemIntrinsic *
MI) {
1167 if (isa<MemTransferInst>(MI)) {
1169 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
1173 }
else if (isa<MemSetInst>(MI)) {
1184 bool AddressSanitizer::isInterestingAlloca(
const AllocaInst &AI) {
1185 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
1187 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
1188 return PreviouslySeenAllocaInfo->getSecond();
1190 bool IsInteresting =
1203 ProcessedAllocas[&AI] = IsInteresting;
1204 return IsInteresting;
1210 unsigned *Alignment,
1211 Value **MaybeMask) {
1216 if (LocalDynamicShadow == I)
1219 Value *PtrOperand =
nullptr;
1221 if (
LoadInst *LI = dyn_cast<LoadInst>(I)) {
1225 *Alignment = LI->getAlignment();
1226 PtrOperand = LI->getPointerOperand();
1227 }
else if (
StoreInst *
SI = dyn_cast<StoreInst>(I)) {
1231 *Alignment =
SI->getAlignment();
1232 PtrOperand =
SI->getPointerOperand();
1233 }
else if (
AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
1238 PtrOperand = RMW->getPointerOperand();
1244 PtrOperand = XCHG->getPointerOperand();
1245 }
else if (
auto CI = dyn_cast<CallInst>(I)) {
1247 if (
F && (
F->getName().startswith(
"llvm.masked.load.") ||
1248 F->getName().startswith(
"llvm.masked.store."))) {
1249 unsigned OpOffset = 0;
1250 if (
F->getName().startswith(
"llvm.masked.store.")) {
1262 auto BasePtr = CI->getOperand(0 + OpOffset);
1263 auto Ty = cast<PointerType>(BasePtr->getType())->getElementType();
1265 if (
auto AlignmentConstant =
1266 dyn_cast<ConstantInt>(CI->getOperand(1 + OpOffset)))
1267 *Alignment = (
unsigned)AlignmentConstant->getZExtValue();
1271 *MaybeMask = CI->getOperand(2 + OpOffset);
1272 PtrOperand = BasePtr;
1295 if (
auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
1296 return isInterestingAlloca(*AI) ? AI :
nullptr;
1309 if (
ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
1310 if (!Cmp->isRelational())
return false;
1312 if (BO->getOpcode() != Instruction::Sub)
return false;
1327 void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
1330 Function *
F = isa<ICmpInst>(
I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
1332 for (
Value *&i : Param) {
1333 if (i->getType()->isPointerTy())
1341 unsigned Alignment,
unsigned Granularity,
1343 Value *SizeArgument,
bool UseCalls,
1347 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1349 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
1350 return Pass->instrumentAddress(I, InsertBefore, Addr, TypeSize, IsWrite,
1351 nullptr, UseCalls, Exp);
1352 Pass->instrumentUnusualSizeOrAlignment(I, InsertBefore, Addr, TypeSize,
1353 IsWrite,
nullptr, UseCalls, Exp);
1359 Value *Addr,
unsigned Alignment,
1360 unsigned Granularity,
uint32_t TypeSize,
1361 bool IsWrite,
Value *SizeArgument,
1363 auto *VTy = cast<PointerType>(Addr->
getType())->getElementType();
1365 unsigned Num = VTy->getVectorNumElements();
1367 for (
unsigned Idx = 0; Idx < Num; ++Idx) {
1368 Value *InstrumentedAddress =
nullptr;
1370 if (
auto *Vector = dyn_cast<ConstantVector>(Mask)) {
1372 if (
auto *Masked = dyn_cast<ConstantInt>(Vector->getOperand(Idx))) {
1373 if (Masked->isZero())
1383 InsertBefore = ThenTerm;
1387 InstrumentedAddress =
1390 Granularity, ElemTypeSize, IsWrite, SizeArgument,
1398 bool IsWrite =
false;
1399 unsigned Alignment = 0;
1400 uint64_t TypeSize = 0;
1401 Value *MaybeMask =
nullptr;
1403 isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment, &MaybeMask);
1424 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1425 NumOptimizedAccessesToGlobalVar++;
1433 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1434 NumOptimizedAccessesToStackVar++;
1440 NumInstrumentedWrites++;
1442 NumInstrumentedReads++;
1444 unsigned Granularity = 1 << Mapping.Scale;
1447 Alignment, Granularity, TypeSize, IsWrite,
1448 nullptr, UseCalls, Exp);
1451 IsWrite,
nullptr, UseCalls, Exp);
1456 Value *Addr,
bool IsWrite,
1457 size_t AccessSizeIndex,
1458 Value *SizeArgument,
1465 Call = IRB.
CreateCall(AsanErrorCallbackSized[IsWrite][0],
1466 {Addr, SizeArgument});
1468 Call = IRB.
CreateCall(AsanErrorCallbackSized[IsWrite][1],
1469 {Addr, SizeArgument, ExpVal});
1473 IRB.
CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1475 Call = IRB.
CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1489 size_t Granularity =
static_cast<size_t>(1) << Mapping.Scale;
1491 Value *LastAccessedByte =
1494 if (TypeSize / 8 > 1)
1504 void AddressSanitizer::instrumentAddress(
Instruction *OrigIns,
1507 Value *SizeArgument,
bool UseCalls,
1517 IRB.
CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1520 IRB.
CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1537 assert(cast<BranchInst>(TagCheckTerm)->isUnconditional());
1539 InsertBefore = TagCheckTerm;
1545 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1547 Value *ShadowValue =
1551 size_t Granularity = 1ULL << Mapping.Scale;
1559 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
1562 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
1576 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
1577 AccessSizeIndex, SizeArgument, Exp);
1585 void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1587 bool IsWrite,
Value *SizeArgument,
bool UseCalls,
uint32_t Exp) {
1593 IRB.
CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1596 IRB.
CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1602 instrumentAddress(I, InsertBefore, Addr, 8, IsWrite, Size,
false, Exp);
1603 instrumentAddress(I, InsertBefore, LastByte, 8, IsWrite, Size,
false, Exp);
1607 void AddressSanitizerModule::poisonOneInitializer(
Function &GlobalInit,
1615 IRB.
CreateCall(AsanPoisonGlobals, ModuleNameAddr);
1619 if (
ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
1623 void AddressSanitizerModule::createInitializerPoisonCalls(
1634 if (isa<ConstantAggregateZero>(
OP))
continue;
1643 poisonOneInitializer(*
F, ModuleName);
1648 bool AddressSanitizerModule::ShouldInstrumentGlobal(
GlobalVariable *G) {
1652 if (GlobalsMD.get(G).IsBlacklisted)
return false;
1653 if (!Ty->
isSized())
return false;
1669 if (G->
getAlignment() > MinRedzoneSizeForGlobal())
return false;
1675 if (Section ==
"llvm.metadata")
return false;
1695 if (TargetTriple.isOSBinFormatCOFF() && Section.
contains(
'$')) {
1696 LLVM_DEBUG(
dbgs() <<
"Ignoring global in sorted section (contains '$'): " 1701 if (TargetTriple.isOSBinFormatMachO()) {
1703 unsigned TAA = 0, StubSize = 0;
1706 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
1707 assert(ErrorCode.empty() &&
"Invalid section specifier.");
1712 if (ParsedSegment ==
"__OBJC" ||
1713 (ParsedSegment ==
"__DATA" && ParsedSection.
startswith(
"__objc_"))) {
1714 LLVM_DEBUG(
dbgs() <<
"Ignoring ObjC runtime global: " << *G <<
"\n");
1725 if (ParsedSegment ==
"__DATA" && ParsedSection ==
"__cfstring") {
1732 LLVM_DEBUG(
dbgs() <<
"Ignoring a cstring literal: " << *G <<
"\n");
1744 bool AddressSanitizerModule::ShouldUseMachOGlobalsSection()
const {
1745 if (!TargetTriple.isOSBinFormatMachO())
1748 if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
1750 if (TargetTriple.isiOS() && !TargetTriple.isOSVersionLT(9))
1752 if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
1758 StringRef AddressSanitizerModule::getGlobalMetadataSection()
const {
1759 switch (TargetTriple.getObjectFormat()) {
1768 void AddressSanitizerModule::initializeCallbacks(
Module &M) {
1773 kAsanPoisonGlobalsName, IRB.
getVoidTy(), IntptrTy));
1776 kAsanUnpoisonGlobalsName, IRB.
getVoidTy()));
1781 kAsanRegisterGlobalsName, IRB.
getVoidTy(), IntptrTy, IntptrTy));
1785 IntptrTy, IntptrTy));
1790 AsanRegisterImageGlobals =
1792 kAsanRegisterImageGlobalsName, IRB.
getVoidTy(), IntptrTy));
1795 AsanUnregisterImageGlobals =
1797 kAsanUnregisterImageGlobalsName, IRB.
getVoidTy(), IntptrTy));
1802 IntptrTy, IntptrTy, IntptrTy));
1807 IntptrTy, IntptrTy, IntptrTy));
1813 void AddressSanitizerModule::SetComdatForGlobalMetadata(
1827 Name += InternalSuffix;
1836 if (TargetTriple.isOSBinFormatCOFF()) {
1851 AddressSanitizerModule::CreateMetadataGlobal(
Module &M,
Constant *Initializer,
1853 auto Linkage = TargetTriple.isOSBinFormatMachO()
1857 M, Initializer->
getType(),
false, Linkage, Initializer,
1859 Metadata->
setSection(getGlobalMetadataSection());
1872 void AddressSanitizerModule::InstrumentGlobalsCOFF(
1878 for (
size_t i = 0; i < ExtendedGlobals.
size(); i++) {
1879 Constant *Initializer = MetadataInitializers[i];
1882 CreateMetadataGlobal(M, Initializer, G->
getName());
1887 unsigned SizeOfGlobalStruct = DL.getTypeAllocSize(Initializer->
getType());
1889 "global metadata will not be padded appropriately");
1892 SetComdatForGlobalMetadata(G, Metadata,
"");
1896 void AddressSanitizerModule::InstrumentGlobalsELF(
1899 const std::string &UniqueModuleId) {
1903 for (
size_t i = 0; i < ExtendedGlobals.
size(); i++) {
1906 CreateMetadataGlobal(M, MetadataInitializers[i], G->
getName());
1911 SetComdatForGlobalMetadata(G, Metadata, UniqueModuleId);
1916 if (!MetadataGlobals.empty())
1933 "__start_" + getGlobalMetadataSection());
1937 "__stop_" + getGlobalMetadataSection());
1949 IRB_Dtor.
CreateCall(AsanUnregisterElfGlobals,
1955 void AddressSanitizerModule::InstrumentGlobalsMachO(
1966 for (
size_t i = 0; i < ExtendedGlobals.
size(); i++) {
1967 Constant *Initializer = MetadataInitializers[i];
1970 CreateMetadataGlobal(M, Initializer, G->
getName());
1974 auto LivenessBinder =
1980 Liveness->
setSection(
"__DATA,__asan_liveness,regular,live_support");
1981 LivenessGlobals[i] = Liveness;
1988 if (!LivenessGlobals.empty())
2008 IRB_Dtor.
CreateCall(AsanUnregisterImageGlobals,
2012 void AddressSanitizerModule::InstrumentGlobalsWithMetadataArray(
2016 unsigned N = ExtendedGlobals.
size();
2026 if (Mapping.Scale > 3)
2027 AllGlobals->setAlignment(1ULL << Mapping.Scale);
2046 bool AddressSanitizerModule::InstrumentGlobals(
IRBuilder<> &IRB,
Module &M,
bool *CtorComdat) {
2047 *CtorComdat =
false;
2053 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.
push_back(&G);
2056 size_t n = GlobalsToChange.
size();
2076 IntptrTy, IntptrTy, IntptrTy);
2080 bool HasDynamicallyInitializedGlobals =
false;
2087 for (
size_t i = 0; i < n; i++) {
2088 static const uint64_t kMaxGlobalRedzone = 1 << 18;
2091 auto MD = GlobalsMD.get(G);
2096 M, MD.Name.
empty() ? NameForGlobal : MD.Name,
2101 uint64_t MinRZ = MinRedzoneSizeForGlobal();
2105 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
2106 uint64_t RightRedzoneSize =
RZ;
2108 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
2109 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
2122 "",
G, G->getThreadLocalMode());
2127 if (TargetTriple.isOSBinFormatMachO() && !G->hasSection() &&
2130 if (Seq && Seq->isCString())
2131 NewGlobal->
setSection(
"__TEXT,__asan_cstring,regular");
2137 G->getDebugInfo(GVs);
2138 for (
auto *GV : GVs)
2148 G->eraseFromParent();
2149 NewGlobals[i] = NewGlobal;
2152 if (!MD.SourceLoc.empty()) {
2162 bool CanUsePrivateAliases =
2163 TargetTriple.isOSBinFormatELF() || TargetTriple.isOSBinFormatMachO() ||
2164 TargetTriple.isOSBinFormatWasm();
2169 NameForGlobal + M.
getName(), NewGlobal);
2173 auto *ODRIndicatorSym =
2176 kODRGenPrefix + NameForGlobal,
nullptr,
2182 ODRIndicatorSym->setAlignment(1);
2183 ODRIndicator = ODRIndicatorSym;
2184 InstrumentedGlobal = GA;
2197 if (
ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals =
true;
2201 Initializers[i] = Initializer;
2207 for (
size_t i = 0; i < n; i++) {
2214 std::string ELFUniqueModuleId =
2218 if (!ELFUniqueModuleId.empty()) {
2219 InstrumentGlobalsELF(IRB, M, NewGlobals, Initializers, ELFUniqueModuleId);
2221 }
else if (UseGlobalsGC && TargetTriple.isOSBinFormatCOFF()) {
2222 InstrumentGlobalsCOFF(IRB, M, NewGlobals, Initializers);
2223 }
else if (UseGlobalsGC && ShouldUseMachOGlobalsSection()) {
2224 InstrumentGlobalsMachO(IRB, M, NewGlobals, Initializers);
2226 InstrumentGlobalsWithMetadataArray(IRB, M, NewGlobals, Initializers);
2230 if (HasDynamicallyInitializedGlobals)
2231 createInitializerPoisonCalls(M, ModuleName);
2237 int AddressSanitizerModule::GetAsanVersion(
const Module &M)
const {
2243 Version += (LongSize == 32 && isAndroid);
2247 bool AddressSanitizerModule::runOnModule(
Module &M) {
2253 initializeCallbacks(M);
2260 std::string VersionCheckName =
2263 M, kAsanModuleCtorName, kAsanInitName, {},
2264 {}, VersionCheckName);
2266 bool CtorComdat =
true;
2267 bool Changed =
false;
2270 IRBuilder<> IRB(AsanCtorFunction->getEntryBlock().getTerminator());
2271 Changed |= InstrumentGlobals(IRB, M, &CtorComdat);
2277 if (UseCtorComdat && TargetTriple.isOSBinFormatELF() && CtorComdat) {
2281 if (AsanDtorFunction) {
2288 if (AsanDtorFunction)
2295 void AddressSanitizer::initializeCallbacks(
Module &M) {
2299 for (
int Exp = 0; Exp < 2; Exp++) {
2300 for (
size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
2301 const std::string TypeStr = AccessIsWrite ?
"store" :
"load";
2302 const std::string ExpStr = Exp ?
"exp_" :
"";
2303 const std::string EndingStr = Recover ?
"_noabort" :
"";
2310 Args1.push_back(ExpType);
2312 AsanErrorCallbackSized[AccessIsWrite][Exp] =
2314 kAsanReportErrorTemplate + ExpStr + TypeStr +
"_n" + EndingStr,
2317 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
2323 AccessSizeIndex++) {
2324 const std::string Suffix = TypeStr +
itostr(1ULL << AccessSizeIndex);
2325 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2327 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
2330 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2338 const std::string MemIntrinCallbackPrefix =
2341 MemIntrinCallbackPrefix +
"memmove", IRB.
getInt8PtrTy(),
2344 MemIntrinCallbackPrefix +
"memcpy", IRB.
getInt8PtrTy(),
2347 MemIntrinCallbackPrefix +
"memset", IRB.
getInt8PtrTy(),
2354 kAsanPtrCmp, IRB.
getVoidTy(), IntptrTy, IntptrTy));
2356 kAsanPtrSub, IRB.
getVoidTy(), IntptrTy, IntptrTy));
2361 if (Mapping.InGlobal)
2367 bool AddressSanitizer::doInitialization(
Module &M) {
2380 bool AddressSanitizer::doFinalization(
Module &M) {
2385 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(
Function &
F) {
2393 if (F.
getName().
find(
" load]") != std::string::npos) {
2403 void AddressSanitizer::maybeInsertDynamicShadowAtFunctionEntry(
Function &F) {
2409 if (Mapping.InGlobal) {
2417 LocalDynamicShadow =
2418 IRB.
CreateCall(Asm, {AsanShadowGlobal},
".asan.shadow");
2420 LocalDynamicShadow =
2425 kAsanShadowMemoryDynamicAddress, IntptrTy);
2426 LocalDynamicShadow = IRB.
CreateLoad(GlobalDynamicAddress);
2430 void AddressSanitizer::markEscapedLocalAllocas(
Function &F) {
2435 assert(ProcessedAllocas.empty() &&
"must process localescape before allocas");
2450 "non-static alloca arg to localescape");
2451 ProcessedAllocas[AI] =
false;
2463 bool FunctionModified =
false;
2468 if (maybeInsertAsanInitAtFunctionEntry(F))
2469 FunctionModified =
true;
2472 if (!F.
hasFnAttribute(Attribute::SanitizeAddress))
return FunctionModified;
2477 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2479 FunctionStateRAII CleanupObj(
this);
2481 maybeInsertDynamicShadowAtFunctionEntry(F);
2485 markEscapedLocalAllocas(F);
2499 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
2502 for (
auto &BB : F) {
2504 TempsToInstrument.
clear();
2505 int NumInsnsPerBB = 0;
2506 for (
auto &Inst : BB) {
2507 if (LooksLikeCodeInBug11395(&Inst))
return false;
2508 Value *MaybeMask =
nullptr;
2509 if (
Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
2510 &Alignment, &MaybeMask)) {
2516 if (TempsToInstrument.
count(Addr))
2519 if (!TempsToInstrument.
insert(Addr).second)
2525 PointerComparisonsOrSubtracts.
push_back(&Inst);
2527 }
else if (isa<MemIntrinsic>(Inst)) {
2530 if (isa<AllocaInst>(Inst)) NumAllocas++;
2534 TempsToInstrument.
clear();
2537 if (
CallInst *CI = dyn_cast<CallInst>(&Inst))
2550 const DataLayout &DL = F.getParent()->getDataLayout();
2556 int NumInstrumented = 0;
2557 for (
auto Inst : ToInstrument) {
2560 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
2561 instrumentMop(ObjSizeVis, Inst, UseCalls,
2562 F.getParent()->getDataLayout());
2564 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
2569 FunctionStackPoisoner FSP(F, *
this);
2570 bool ChangedStack = FSP.runOnFunction();
2574 for (
auto CI : NoReturnCalls) {
2579 for (
auto Inst : PointerComparisonsOrSubtracts) {
2580 instrumentPointerComparisonOrSubtraction(Inst);
2584 if (NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty())
2585 FunctionModified =
true;
2587 LLVM_DEBUG(
dbgs() <<
"ASAN done instrumenting: " << FunctionModified <<
" " 2590 return FunctionModified;
2596 bool AddressSanitizer::LooksLikeCodeInBug11395(
Instruction *I) {
2597 if (LongSize != 32)
return false;
2605 void FunctionStackPoisoner::initializeCallbacks(
Module &M) {
2608 std::string Suffix =
itostr(i);
2616 if (ASan.UseAfterScope) {
2619 IntptrTy, IntptrTy));
2622 IntptrTy, IntptrTy));
2625 for (
size_t Val : {0x00, 0xf1, 0xf2, 0xf3, 0xf5, 0xf8}) {
2626 std::ostringstream
Name;
2628 Name << std::setw(2) << std::setfill(
'0') << std::hex << Val;
2629 AsanSetShadowFunc[Val] =
2631 Name.str(), IRB.
getVoidTy(), IntptrTy, IntptrTy));
2635 kAsanAllocaPoison, IRB.
getVoidTy(), IntptrTy, IntptrTy));
2636 AsanAllocasUnpoisonFunc =
2638 kAsanAllocasUnpoison, IRB.
getVoidTy(), IntptrTy, IntptrTy));
2643 size_t Begin,
size_t End,
2645 Value *ShadowBase) {
2649 const size_t LargestStoreSizeInBytes =
2650 std::min<size_t>(
sizeof(uint64_t), ASan.LongSize / 8);
2658 for (
size_t i = Begin; i < End;) {
2659 if (!ShadowMask[i]) {
2665 size_t StoreSizeInBytes = LargestStoreSizeInBytes;
2667 while (StoreSizeInBytes > End - i)
2668 StoreSizeInBytes /= 2;
2671 for (
size_t j = StoreSizeInBytes - 1; j && !ShadowMask[i + j]; --j) {
2672 while (j <= StoreSizeInBytes / 2)
2673 StoreSizeInBytes /= 2;
2677 for (
size_t j = 0; j < StoreSizeInBytes; j++) {
2679 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
2681 Val = (Val << 8) | ShadowBytes[i + j];
2685 Value *Poison = IRB.
getIntN(StoreSizeInBytes * 8, Val);
2689 i += StoreSizeInBytes;
2696 copyToShadow(ShadowMask, ShadowBytes, 0, ShadowMask.
size(), IRB, ShadowBase);
2701 size_t Begin,
size_t End,
2704 size_t Done = Begin;
2705 for (
size_t i = Begin, j = Begin + 1; i < End; i = j++) {
2706 if (!ShadowMask[i]) {
2710 uint8_t Val = ShadowBytes[i];
2711 if (!AsanSetShadowFunc[Val])
2715 for (; j < End && ShadowMask[j] && Val == ShadowBytes[j]; ++j) {
2719 copyToShadowInline(ShadowMask, ShadowBytes, Done, i, IRB, ShadowBase);
2727 copyToShadowInline(ShadowMask, ShadowBytes, Done, End, IRB, ShadowBase);
2735 for (
int i = 0;; i++, MaxSize *= 2)
2736 if (LocalStackSize <= MaxSize)
return i;
2740 void FunctionStackPoisoner::copyArgsPassedByValToAllocas() {
2742 if (CopyInsertPoint == ASan.LocalDynamicShadow) {
2750 if (
Arg.hasByValAttr()) {
2752 unsigned Align =
Arg.getParamAlignment();
2771 Value *ValueIfFalse) {
2780 Value *FunctionStackPoisoner::createAllocaForLayout(
2789 nullptr,
"MyAlloca");
2798 void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
2801 DynamicAllocaLayout = IRB.
CreateAlloca(IntptrTy,
nullptr);
2806 void FunctionStackPoisoner::processDynamicAllocas() {
2808 assert(DynamicAllocaPoisonCallVec.empty());
2813 for (
const auto &APC : DynamicAllocaPoisonCallVec) {
2816 assert(ASan.isInterestingAlloca(*APC.AI));
2817 assert(!APC.AI->isStaticAlloca());
2820 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
2827 createDynamicAllocasInitStorage();
2828 for (
auto &AI : DynamicAllocaVec)
2829 handleDynamicAllocaCall(AI);
2830 unpoisonDynamicAllocas();
2833 void FunctionStackPoisoner::processStaticAllocas() {
2834 if (AllocaVec.empty()) {
2835 assert(StaticAllocaPoisonCallVec.empty());
2839 int StackMallocIdx = -1;
2851 auto InsBeforeB = InsBefore->
getParent();
2853 for (
auto *AI : StaticAllocasToMoveUp)
2858 if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
2861 SVD.
reserve(AllocaVec.size());
2864 ASan.getAllocaSizeInBytes(*AI),
2875 size_t Granularity = 1ULL << Mapping.Scale;
2876 size_t MinHeaderSize =
std::max((
size_t)ASan.LongSize / 2, Granularity);
2882 for (
auto &Desc : SVD)
2883 AllocaToSVDMap[Desc.AI] = &Desc;
2886 for (
const auto &APC : StaticAllocaPoisonCallVec) {
2889 assert(ASan.isInterestingAlloca(*APC.AI));
2890 assert(APC.AI->isStaticAlloca());
2893 Desc.LifetimeSize = Desc.Size;
2895 if (
const DILocation *LifetimeLoc = APC.InsBefore->getDebugLoc().
get()) {
2896 if (LifetimeLoc->getFile() == FnLoc->getFile())
2897 if (
unsigned Line = LifetimeLoc->getLine())
2898 Desc.Line = std::min(Desc.Line ? Desc.Line : Line, Line);
2915 DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2916 DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2918 Value *StaticAlloca =
2919 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L,
false);
2922 Value *LocalStackBase;
2923 Value *LocalStackBaseAlloca;
2926 if (DoStackMalloc) {
2927 LocalStackBaseAlloca =
2928 IRB.
CreateAlloca(IntptrTy,
nullptr,
"asan_local_stack_base");
2934 kAsanOptionDetectUseAfterReturn, IRB.
getInt32Ty());
2935 Value *UseAfterReturnIsEnabled =
2944 Value *FakeStackValue =
2945 IRBIf.
CreateCall(AsanStackMallocFunc[StackMallocIdx],
2949 FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
2952 Value *NoFakeStack =
2957 Value *AllocaValue =
2958 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L,
true) : StaticAlloca;
2962 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
2964 IRB.
CreateStore(LocalStackBase, LocalStackBaseAlloca);
2971 DoDynamicAlloca ? createAllocaForLayout(IRB, L,
true) : StaticAlloca;
2972 LocalStackBaseAlloca = LocalStackBase;
2977 for (
const auto &Desc : SVD) {
3012 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
3015 copyToShadow(ShadowAfterScope, ShadowAfterScope, IRB, ShadowBase);
3017 if (!StaticAllocaPoisonCallVec.empty()) {
3021 for (
const auto &APC : StaticAllocaPoisonCallVec) {
3028 copyToShadow(ShadowAfterScope,
3029 APC.DoPoison ? ShadowAfterScope : ShadowInScope, Begin, End,
3038 for (
auto Ret : RetVec) {
3043 if (DoStackMalloc) {
3044 assert(StackMallocIdx >= 0);
3061 if (StackMallocIdx <= 4) {
3065 copyToShadow(ShadowAfterReturn, ShadowAfterReturn, IRBPoison,
3078 AsanStackFreeFunc[StackMallocIdx],
3083 copyToShadow(ShadowAfterScope, ShadowClean, IRBElse, ShadowBase);
3085 copyToShadow(ShadowAfterScope, ShadowClean, IRBRet, ShadowBase);
3093 void FunctionStackPoisoner::poisonAlloca(
Value *V, uint64_t
Size,
3099 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
3100 {AddrArg, SizeArg});
3113 if (
AllocaInst *AI = dyn_cast<AllocaInst>(V))
3115 return ASan.isInterestingAlloca(*AI) ? AI :
nullptr;
3118 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
3119 if (I != AllocaForValue.end())
return I->second;
3122 AllocaForValue[V] =
nullptr;
3125 Res = findAllocaForValue(CI->getOperand(0));
3126 else if (
PHINode *PN = dyn_cast<PHINode>(V)) {
3127 for (
Value *IncValue : PN->incoming_values()) {
3129 if (IncValue == PN)
continue;
3130 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
3132 if (IncValueAI ==
nullptr || (Res !=
nullptr && IncValueAI != Res))
3137 Res = findAllocaForValue(EP->getPointerOperand());
3139 LLVM_DEBUG(
dbgs() <<
"Alloca search canceled on unknown instruction: " << *V
3142 if (Res) AllocaForValue[V] = Res;
3146 void FunctionStackPoisoner::handleDynamicAllocaCall(
AllocaInst *AI) {
3150 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
3160 const unsigned ElementSize =
3193 IRB.
CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
3212 Value *Addr, uint64_t TypeSize)
const {
3214 if (!ObjSizeVis.
bothKnown(SizeOffset))
return false;
3215 uint64_t Size = SizeOffset.first.getZExtValue();
3216 int64_t
Offset = SizeOffset.second.getSExtValue();
3221 return Offset >= 0 && Size >= uint64_t(Offset) &&
3222 Size - uint64_t(Offset) >= TypeSize / 8;
void setVisibility(VisibilityTypes V)
Pass interface - Implemented by all 'passes'.
static const uint64_t kMyriadCacheBitMask32
static cl::opt< std::string > ClDebugFunc("asan-debug-func", cl::Hidden, cl::desc("Debug func"))
static bool isValueValidForType(Type *Ty, uint64_t V)
This static method returns true if the type Ty is big enough to represent the value V...
void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue *> Values)
Adds global values to the llvm.compiler.used list.
Return a value (possibly void), from a function.
StringRef getSection() const
Get the custom section of this global if it has one.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
static const char *const kAsanSetShadowPrefix
unsigned getAlignment() const
void push_back(const T &Elt)
static const uint64_t kIOSShadowOffset32
static cl::opt< bool > ClStack("asan-stack", cl::desc("Handle stack memory"), cl::Hidden, cl::init(true))
A parsed version of the target data layout string in and methods for querying it. ...
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
uint64_t getTypeStoreSizeInBits(Type *Ty) const
Returns the maximum number of bits that may be overwritten by storing the specified type; always a mu...
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
ThreadLocalMode getThreadLocalMode() const
void ReplaceInstWithInst(BasicBlock::InstListType &BIL, BasicBlock::iterator &BI, Instruction *I)
Replace the instruction specified by BI with the instruction specified by I.
Function * declareSanitizerInitFunction(Module &M, StringRef InitName, ArrayRef< Type *> InitArgTypes)
static Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
void appendToGlobalDtors(Module &M, Function *F, int Priority, Constant *Data=nullptr)
Same as appendToGlobalCtors(), but for global dtors.
bool hasLocalLinkage() const
static const uint64_t kFreeBSD_ShadowOffset64
static cl::opt< bool > ClInitializers("asan-initialization-order", cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(true))
DILocation * get() const
Get the underlying DILocation.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
bool isMIPS64() const
Tests whether the target is MIPS 64-bit (little and big endian).
static bool GlobalWasGeneratedByCompiler(GlobalVariable *G)
Check if G has been created by a trusted compiler pass.
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
void SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore, TerminatorInst **ThenTerm, TerminatorInst **ElseTerm, MDNode *BranchWeights=nullptr)
SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen, but also creates the ElseBlock...
This class represents an incoming formal argument to a Function.
AllocaInst * CreateAlloca(Type *Ty, unsigned AddrSpace, Value *ArraySize=nullptr, const Twine &Name="")
Base class for instruction visitors.
static cl::opt< int > ClMappingScale("asan-mapping-scale", cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0))
bool replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress, DIBuilder &Builder, bool DerefBefore, int Offset, bool DerefAfter)
Replaces llvm.dbg.declare instruction when the alloca it describes is replaced with a new value...
Function * checkSanitizerInterfaceFunction(Constant *FuncOrBitcast)
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
bool hasPrivateLinkage() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
Compute iterated dominance frontiers using a linear time algorithm.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool contains(StringRef Other) const
Return true if the given string is a substring of *this, and false otherwise.
static size_t RedzoneSizeForScale(int MappingScale)
static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize, bool IsKasan)
Constant * getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
A Module instance is used to store all the information related to an LLVM module. ...
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant *> IdxList, bool InBounds=false, Optional< unsigned > InRangeIndex=None, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
bool isSized(SmallPtrSetImpl< Type *> *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
BasicBlock * getSuccessor(unsigned idx) const
Return the specified successor.
void setAlignment(unsigned Align)
an instruction that atomically checks whether a specified value is in a memory location, and, if it is, stores a new value there.
Available for inspection, not emission.
static const char *const kAsanUnregisterElfGlobalsName
static const uintptr_t kCurrentStackFrameMagic
This class represents a function call, abstracting a target machine's calling convention.
static cl::opt< bool > ClUseAfterReturn("asan-use-after-return", cl::desc("Check stack-use-after-return"), cl::Hidden, cl::init(true))
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space...
static bool isInterestingPointerComparisonOrSubtraction(Instruction *I)
static const char *const kODRGenPrefix
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM...
static cl::opt< bool > ClWithIfunc("asan-with-ifunc", cl::desc("Access dynamic shadow through an ifunc global on " "platforms that support this"), cl::Hidden, cl::init(true))
bool isWatchOS() const
Is this an Apple watchOS triple.
Like Internal, but omit from symbol table.
bool RoundToAlign
Whether to round the result up to the alignment of allocas, byval arguments, and global variables...
Externally visible function.
static cl::opt< bool > ClForceDynamicShadow("asan-force-dynamic-shadow", cl::desc("Load shadow address into a local variable for each function"), cl::Hidden, cl::init(false))
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
static cl::opt< int > ClDebug("asan-debug", cl::desc("debug"), cl::Hidden, cl::init(0))
static cl::opt< bool > ClRecover("asan-recover", cl::desc("Enable recovery mode (continue-after-error)."), cl::Hidden, cl::init(false))
GlobalVariable * getGlobalVariable(StringRef Name) const
Look up the specified global variable in the module symbol table.
INITIALIZE_PASS_BEGIN(AddressSanitizer, "asan", "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false, false) INITIALIZE_PASS_END(AddressSanitizer
unsigned getPointerSizeInBits(unsigned AS=0) const
Layout pointer size, in bits FIXME: The defaults need to be removed once all of the backends/clients ...
STATISTIC(NumFunctions, "Total number of functions")
SmallString< 64 > ComputeASanStackFrameDescription(const SmallVectorImpl< ASanStackVariableDescription > &Vars)
StringRef getName() const
Get a short "name" for the module.
static cl::opt< bool > ClUseAfterScope("asan-use-after-scope", cl::desc("Check stack-use-after-scope"), cl::Hidden, cl::init(false))
static CallInst * Create(Value *Func, ArrayRef< Value *> Args, ArrayRef< OperandBundleDef > Bundles=None, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
const MDOperand & getOperand(unsigned I) const
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
An instruction for reading from memory.
an instruction that atomically reads a memory location, combines it with another value, and then stores the result back.
This defines the Use class.
void reserve(size_type N)
void setAlignment(unsigned Align)
static GlobalVariable * createPrivateGlobalForString(Module &M, StringRef Str, bool AllowMerging)
static cl::opt< unsigned long long > ClMappingOffset("asan-mapping-offset", cl::desc("offset of asan shadow mapping [EXPERIMENTAL]"), cl::Hidden, cl::init(0))
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
static Constant * get(ArrayType *T, ArrayRef< Constant *> V)
static const uint64_t kMyriadDDRTag
bool isAllocaPromotable(const AllocaInst *AI)
Return true if this alloca is legal for promotion.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
StoreInst * CreateAlignedStore(Value *Val, Value *Ptr, unsigned Align, bool isVolatile=false)
iterator begin()
Instruction iterator methods.
static void doInstrumentAddress(AddressSanitizer *Pass, Instruction *I, Instruction *InsertBefore, Value *Addr, unsigned Alignment, unsigned Granularity, uint32_t TypeSize, bool IsWrite, Value *SizeArgument, bool UseCalls, uint32_t Exp)
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, Instruction *InsertBefore=nullptr)
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
static const uint64_t kDefaultShadowScale
static const char *const kAsanShadowMemoryDynamicAddress
static const int kAsanStackUseAfterReturnMagic
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
bool doesNotReturn() const
Determine if the call cannot return.
Type * getPointerElementType() const
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
unsigned getAlignment() const
Return the alignment of the memory that is being allocated by the instruction.
IntegerType * getInt64Ty()
Fetch the type representing a 64-bit integer.
This is the base class for all instructions that perform data casts.
PointerType * getType() const
Overload to return most specific pointer type.
Class to represent struct types.
LLVMContext & getContext() const
Get the global data context.
static const uint64_t kSmallX86_64ShadowOffsetBase
static const uint64_t kLinuxKasan_ShadowOffset64
A Use represents the edge between a Value definition and its users.
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
This file contains the simple types necessary to represent the attributes associated with functions a...
InstrTy * getInstruction() const
static const char *const kAsanAllocasUnpoison
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
void setName(const Twine &Name)
Change the name of the value.
static const char *const kAsanModuleCtorName
static const uint64_t kIOSSimShadowOffset64
static const uint64_t kMyriadMemoryOffset32
static StructType * get(LLVMContext &Context, ArrayRef< Type *> Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Type * getVoidTy()
Fetch the type representing void.
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
static const uint64_t kSmallX86_64ShadowOffsetAlignMask
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
static const char *const kAsanPoisonStackMemoryName
Type * getType() const
All values are typed, get the type of this value.
SmallVector< uint8_t, 64 > GetShadowBytesAfterScope(const SmallVectorImpl< ASanStackVariableDescription > &Vars, const ASanStackFrameLayout &Layout)
std::string itostr(int64_t X)
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
static const char *const kSanCovGenPrefix
bool isSwiftError() const
Return true if this value is a swifterror value.
ArchType getArch() const
getArch - Get the parsed architecture type of this triple.
Class to represent array types.
bool isUsedWithInAlloca() const
Return true if this alloca is used as an inalloca argument to a call.
static const int kMaxAsanStackMallocSizeClass
static const uint64_t kIOSSimShadowOffset32
static cl::opt< bool > ClOptSameTemp("asan-opt-same-temp", cl::desc("Instrument the same temp just once"), cl::Hidden, cl::init(true))
static cl::opt< bool > ClEnableKasan("asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"), cl::Hidden, cl::init(false))
static const uint64_t kAsanCtorAndDtorPriority
void setComdat(Comdat *C)
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
NamedMDNode * getNamedMetadata(const Twine &Name) const
Return the first NamedMDNode in the module with the specified name.
static cl::opt< bool > ClOpt("asan-opt", cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true))
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
const APInt & getValue() const
Return the constant as an APInt value reference.
bool isLittleEndian() const
Layout endianness...
static const uint64_t kWindowsShadowOffset64
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
bool isiOS() const
Is this an iOS triple.
An instruction for storing to memory.
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
static const uint64_t kMyriadTagShift
LinkageTypes getLinkage() const
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
void takeName(Value *V)
Transfer the name from V to this value.
static cl::opt< bool > ClAlwaysSlowPath("asan-always-slow-path", cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden, cl::init(false))
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
iterator_range< op_iterator > operands()
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
static const uint64_t kDefaultShadowOffset32
Value * getOperand(unsigned i) const
ConstantInt * getIntN(unsigned N, uint64_t C)
Get a constant N-bit value, zero extended or truncated from a 64-bit value.
static void instrumentMaskedLoadOrStore(AddressSanitizer *Pass, const DataLayout &DL, Type *IntptrTy, Value *Mask, Instruction *I, Value *Addr, unsigned Alignment, unsigned Granularity, uint32_t TypeSize, bool IsWrite, Value *SizeArgument, bool UseCalls, uint32_t Exp)
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="")
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Value * getOperand(unsigned i_nocapture) const
static cl::opt< bool > ClInstrumentWrites("asan-instrument-writes", cl::desc("instrument write instructions"), cl::Hidden, cl::init(true))
bool isOSWindows() const
Tests whether the OS is Windows.
ExternalWeak linkage description.
const BasicBlock & getEntryBlock() const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
LoadInst * CreateLoad(Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ptr, "...")' correctly, instead of converting the string to 'bool' fo...
static const size_t kNumberOfAccessSizes
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
static bool runOnFunction(Function &F, bool PostInlining)
static const char *const kAsanGlobalsRegisteredFlagName
initializer< Ty > init(const Ty &Val)
No other Module may specify this COMDAT.
static const char *const kAsanPtrCmp
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
static std::string ParseSectionSpecifier(StringRef Spec, StringRef &Segment, StringRef &Section, unsigned &TAA, bool &TAAParsed, unsigned &StubSize)
Parse the section specifier indicated by "Spec".
Subclasses of this class are all able to terminate a basic block.
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
DLLStorageClassTypes getDLLStorageClass() const
std::size_t countTrailingZeros(T Val, ZeroBehavior ZB=ZB_Width)
Count number of 0's from the least significant bit to the most stopping at the first 1...
VisibilityTypes getVisibility() const
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
std::pair< Function *, Function * > createSanitizerCtorAndInitFunctions(Module &M, StringRef CtorName, StringRef InitName, ArrayRef< Type *> InitArgTypes, ArrayRef< Value *> InitArgs, StringRef VersionCheckName=StringRef())
Creates sanitizer constructor function, and calls sanitizer's init function from it.
VendorType getVendor() const
getVendor - Get the parsed vendor type of this triple.
This is an important class for using LLVM in a threaded context.
DISubprogram * getSubprogram() const
Get the attached subprogram.
Constant * getOrInsertGlobal(StringRef Name, Type *Ty)
Look up the specified global in the module symbol table.
Conditional or Unconditional Branch instruction.
static const size_t kMinStackMallocSize
size_t size() const
size - Get the array size.
This function has undefined behavior.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Resume the propagation of an exception.
static const char *const kAsanInitName
static const char *const kAsanStackFreeNameTemplate
static const uint64_t kNetBSD_ShadowOffset32
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
bool isPointerTy() const
True if this is an instance of PointerType.
static const uint64_t kMIPS32_ShadowOffset32
const Instruction & front() const
static const char *const kAsanOptionDetectUseAfterReturn
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
static const uint64_t kFreeBSD_ShadowOffset32
static const uint64_t kAArch64_ShadowOffset64
static cl::opt< bool > ClInstrumentReads("asan-instrument-reads", cl::desc("instrument read instructions"), cl::Hidden, cl::init(true))
Represent the analysis usage information of a pass.
static Type * getVoidTy(LLVMContext &C)
bool isAndroidVersionLT(unsigned Major) const
bool isPS4CPU() const
Tests whether the target is the PS4 CPU.
This instruction compares its operands according to the predicate given to the constructor.
Value * CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name="")
FunctionPass class - This class is used to implement most global optimizations.
static FunctionType * get(Type *Result, ArrayRef< Type *> Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Constant * get(StructType *T, ArrayRef< Constant *> V)
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
ASanStackFrameLayout ComputeASanStackFrameLayout(SmallVectorImpl< ASanStackVariableDescription > &Vars, size_t Granularity, size_t MinHeaderSize)
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
static cl::opt< bool > ClOptGlobals("asan-opt-globals", cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true))
static cl::opt< bool > ClUseGlobalsGC("asan-globals-live-support", cl::desc("Use linker features to support dead " "code stripping of globals"), cl::Hidden, cl::init(true))
static const uintptr_t kRetiredStackFrameMagic
llvm::Expected< Value > parse(llvm::StringRef JSON)
Parses the provided JSON source, or returns a ParseError.
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
static const uint64_t kMyriadShadowScale
static cl::opt< bool > ClUsePrivateAliasForGlobals("asan-use-private-alias", cl::desc("Use private aliases for global" " variables"), cl::Hidden, cl::init(false))
static const char *const kAsanGenPrefix
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...
static const char *const kAsanPtrSub
static cl::opt< int > ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb", cl::init(10000), cl::desc("maximal number of instructions to instrument in any given BB"), cl::Hidden)
S_CSTRING_LITERALS - Section with literal C strings.
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs, and aliases.
iterator_range< User::op_iterator > arg_operands()
Iteration adapter for range-for loops.
static cl::opt< bool > ClGlobals("asan-globals", cl::desc("Handle global objects"), cl::Hidden, cl::init(true))
static cl::opt< uint32_t > ClMaxInlinePoisoningSize("asan-max-inline-poisoning-size", cl::desc("Inline shadow poisoning for blocks up to the given size in bytes."), cl::Hidden, cl::init(64))
const Value * getArraySize() const
Get the number of elements allocated.
std::pair< APInt, APInt > SizeOffsetType
static wasm::ValType getType(const TargetRegisterClass *RC)
PointerType * getInt8PtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer to an 8-bit integer value.
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight)
Return metadata containing two branch weights.
static const uint64_t kWindowsShadowOffset32
Value * GetUnderlyingObject(Value *V, const DataLayout &DL, unsigned MaxLookup=6)
This method strips off any GEP address adjustments and pointer casts from the specified value...
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void initializeAddressSanitizerPass(PassRegistry &)
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
static cl::opt< bool > ClWithComdat("asan-with-comdat", cl::desc("Place ASan constructors in comdat sections"), cl::Hidden, cl::init(true))
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
Triple - Helper class for working with autoconf configuration names.
static const char *const kAsanRegisterGlobalsName
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Value * CreateGEP(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &Name="")
static Constant * getPointerCast(Constant *C, Type *Ty)
Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant expression.
static const uint64_t kDynamicShadowSentinel
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
static cl::opt< int > ClDebugMax("asan-debug-max", cl::desc("Debug max inst"), cl::Hidden, cl::init(-1))
print lazy value Lazy Value Info Printer Pass
This is the common base class for memset/memcpy/memmove.
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
getLimitedValue - If the value is smaller than the specified limit, return it, otherwise return the l...
This is the shared class of boolean and integer constants.
void setSelectionKind(SelectionKind Val)
static const char *const kAsanStackMallocNameTemplate
static const char *const kAsanUnpoisonStackMemoryName
Evaluate the size and offset of an object pointed to by a Value* statically.
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
bool hasSection() const
Check if this global has a custom object file section.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
static size_t TypeSizeToSizeIndex(uint32_t TypeSize)
Module.h This file contains the declarations for the Module class.
Provides information about what library functions are available for the current target.
unsigned getABITypeAlignment(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
bool isOSLinux() const
Tests whether the OS is Linux.
TerminatorInst * SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
static const uint64_t kDefaultShadowOffset64
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
static cl::opt< int > ClDebugStack("asan-debug-stack", cl::desc("debug stack"), cl::Hidden, cl::init(0))
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
CallInst * CreateMemCpy(Value *Dst, unsigned DstAlign, Value *Src, unsigned SrcAlign, uint64_t Size, bool isVolatile=false, MDNode *TBAATag=nullptr, MDNode *TBAAStructTag=nullptr, MDNode *ScopeTag=nullptr, MDNode *NoAliasTag=nullptr)
Create and insert a memcpy between the specified pointers.
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
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.
static cl::opt< bool > ClInvalidPointerPairs("asan-detect-invalid-pointer-pair", cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden, cl::init(false))
static bool isPointerOperand(Value *V)
static cl::opt< int > ClInstrumentationWithCallsThreshold("asan-instrumentation-with-call-threshold", cl::desc("If the function being instrumented contains more than " "this number of memory accesses, use callbacks instead of " "inline checks (-1 means never use callbacks)."), cl::Hidden, cl::init(7000))
void setLinkage(LinkageTypes LT)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
SizeOffsetType compute(Value *V)
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
ConstantArray - Constant Array Declarations.
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1', drop it.
static const uint64_t kSystemZ_ShadowOffset64
static GlobalVariable * createPrivateGlobalForSourceLoc(Module &M, LocationMetadata MD)
Create a global describing a source location.
LinkageTypes
An enumeration for the kinds of linkage for global values.
static cl::opt< bool > ClWithIfuncSuppressRemat("asan-with-ifunc-suppress-remat", cl::desc("Suppress rematerialization of dynamic shadow address by passing " "it through inline asm in prologue."), cl::Hidden, cl::init(true))
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
Value * CreatePointerCast(Value *V, Type *DestTy, const Twine &Name="")
void setMetadata(unsigned KindID, MDNode *MD)
Set a particular kind of metadata attachment.
amdgpu Simplify well known AMD library false Value Value * Arg
static cl::opt< bool > ClSkipPromotableAllocas("asan-skip-promotable-allocas", cl::desc("Do not instrument promotable allocas"), cl::Hidden, cl::init(true))
const Comdat * getComdat() const
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
bool isMIPS32() const
Tests whether the target is MIPS 32-bit (little and big endian).
static const uint64_t kMyriadMemorySize32
static cl::opt< int > ClDebugMin("asan-debug-min", cl::desc("Debug min inst"), cl::Hidden, cl::init(-1))
static cl::opt< std::string > ClMemoryAccessCallbackPrefix("asan-memory-access-callback-prefix", cl::desc("Prefix for memory access callbacks"), cl::Hidden, cl::init("__asan_"))
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
bool isInlineAsm() const
Check if this call is an inline asm statement.
static const uint64_t kMIPS64_ShadowOffset64
void setUnnamedAddr(UnnamedAddr Val)
static IntegerType * getInt32Ty(LLVMContext &C)
bool isThumb() const
Tests whether the target is Thumb (little and big endian).
static int StackMallocSizeClass(uint64_t LocalStackSize)
LLVM_NODISCARD bool empty() const
unsigned getNumArgOperands() const
Return the number of call arguments.
static cl::opt< uint32_t > ClForceExperiment("asan-force-experiment", cl::desc("Force optimization experiment (for testing)"), cl::Hidden, cl::init(0))
static const char *const kAsanRegisterElfGlobalsName
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value...
StringRef getName() const
Return a constant reference to the value's name.
void copyAttributesFrom(const GlobalVariable *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a GlobalVariable) fro...
const Function * getParent() const
Return the enclosing method, or null if none.
static cl::opt< bool > ClDynamicAllocaStack("asan-stack-dynamic-alloca", cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden, cl::init(true))
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Type * getValueType() const
const BasicBlockListType & getBasicBlockList() const
Get the underlying elements of the Function...
static const uint64_t kNetBSD_ShadowOffset64
Rename collisions when linking (static functions).
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...
static InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT)
InlineAsm::get - Return the specified uniqued inline asm string.
static const uint64_t kPS4CPU_ShadowOffset64
static const char *const kAsanModuleDtorName
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
const std::string to_string(const T &Value)
static uint64_t getAllocaSizeInBytes(const AllocaInst &AI)
static const char *const kAsanUnregisterGlobalsName
iterator_range< df_iterator< T > > depth_first(const T &G)
static const char *const kAsanUnpoisonGlobalsName
bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
const BasicBlock & front() const
static bool bothKnown(const SizeOffsetType &SizeOffset)
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
static const char *const kAsanPoisonGlobalsName
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
void setAlignment(unsigned Align)
INITIALIZE_PASS(AddressSanitizerModule, "asan-module", "AddressSanitizer: detects use-after-free and out-of-bounds bugs." "ModulePass", false, false) ModulePass *llvm
static const uint64_t kPPC64_ShadowOffset64
static const unsigned kAllocaRzSize
bool hasInitializer() const
Definitions have initializers, declarations don't.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
static cl::opt< bool > ClRedzoneByvalArgs("asan-redzone-byval-args", cl::desc("Create redzones for byval " "arguments (extra copy " "required)"), cl::Hidden, cl::init(true))
static cl::opt< bool > ClInstrumentAtomics("asan-instrument-atomics", cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden, cl::init(true))
static const char *const kAsanUnregisterImageGlobalsName
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
static const Function * getParent(const Value *V)
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
bool isAndroid() const
Tests whether the target is Android.
static const char *const kAsanRegisterImageGlobalsName
static Constant * getAnon(ArrayRef< Constant *> V, bool Packed=false)
Return an anonymous struct that has the specified elements.
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
void addDebugInfo(DIGlobalVariableExpression *GV)
Attach a DIGlobalVariableExpression.
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
FunctionPass * createAddressSanitizerFunctionPass(bool CompileKernel=false, bool Recover=false, bool UseAfterScope=false)
static const char *const kAsanAllocaPoison
static const char *const kAsanHandleNoReturnName
iterator_range< global_iterator > globals()
static const size_t kMaxStackMallocSize
StringRef - Represent a constant reference to a string, i.e.
Various options to control the behavior of getObjectSize.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, const Twine &N="", Module *M=nullptr)
Legacy analysis pass which computes a DominatorTree.
static cl::opt< bool > ClOptStack("asan-opt-stack", cl::desc("Don't instrument scalar stack variables"), cl::Hidden, cl::init(false))
bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size...
static const char *const kAsanVersionCheckNamePrefix
static cl::opt< unsigned > ClRealignStack("asan-realign-stack", cl::desc("Realign stack to the value of this flag (power of two)"), cl::Hidden, cl::init(32))
unsigned getNumOperands() const
Return number of MDNode operands.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t find(char C, size_t From=0) const
Search for the first character C in the string.
ModulePass * createAddressSanitizerModulePass(bool CompileKernel=false, bool Recover=false, bool UseGlobalsGC=true)
static cl::opt< bool > ClInstrumentDynamicAllocas("asan-instrument-dynamic-allocas", cl::desc("instrument dynamic allocas"), cl::Hidden, cl::init(true))
void setSection(StringRef S)
Change the section for this global.
static GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
bool isARM() const
Tests whether the target is ARM (little and big endian).
std::vector< uint32_t > Metadata
PAL metadata represented as a vector.
iterator_range< arg_iterator > args()
A wrapper class for inspecting calls to intrinsic functions.
const BasicBlock * getParent() const
an instruction to allocate memory on the stack
SmallVector< uint8_t, 64 > GetShadowBytes(const SmallVectorImpl< ASanStackVariableDescription > &Vars, const ASanStackFrameLayout &Layout)
static const char *const kAsanReportErrorTemplate
CallInst * CreateCall(Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)