91 #define DEBUG_TYPE "asan" 138 "__asan_unregister_globals";
140 "__asan_register_image_globals";
142 "__asan_unregister_image_globals";
144 "__asan_register_elf_globals";
146 "__asan_unregister_elf_globals";
151 "__asan_version_mismatch_check_v";
163 "__asan_poison_stack_memory";
165 "__asan_unpoison_stack_memory";
170 "___asan_globals_registered";
173 "__asan_option_detect_stack_use_after_return";
176 "__asan_shadow_memory_dynamic_address";
189 "asan-kernel",
cl::desc(
"Enable KernelAddressSanitizer instrumentation"),
194 cl::desc(
"Enable recovery mode (continue-after-error)."),
198 "asan-guard-against-version-mismatch",
199 cl::desc(
"Guard against compiler/runtime version mismatch."),
204 cl::desc(
"instrument read instructions"),
208 "asan-instrument-writes",
cl::desc(
"instrument write instructions"),
212 "asan-instrument-atomics",
217 "asan-always-slow-path",
222 "asan-force-dynamic-shadow",
223 cl::desc(
"Load shadow address into a local variable for each function"),
228 cl::desc(
"Access dynamic shadow through an ifunc global on " 229 "platforms that support this"),
233 "asan-with-ifunc-suppress-remat",
234 cl::desc(
"Suppress rematerialization of dynamic shadow address by passing " 235 "it through inline asm in prologue."),
243 "asan-max-ins-per-bb",
cl::init(10000),
244 cl::desc(
"maximal number of instructions to instrument in any given BB"),
251 "asan-max-inline-poisoning-size",
253 "Inline shadow poisoning for blocks up to the given size in bytes."),
257 cl::desc(
"Check stack-use-after-return"),
261 cl::desc(
"Create redzones for byval " 262 "arguments (extra copy " 267 cl::desc(
"Check stack-use-after-scope"),
276 cl::desc(
"Handle C++ initializer order"),
280 "asan-detect-invalid-pointer-pair",
285 "asan-detect-invalid-pointer-cmp",
290 "asan-detect-invalid-pointer-sub",
295 "asan-realign-stack",
296 cl::desc(
"Realign stack to the value of this flag (power of two)"),
300 "asan-instrumentation-with-call-threshold",
302 "If the function being instrumented contains more than " 303 "this number of memory accesses, use callbacks instead of " 304 "inline checks (-1 means never use callbacks)."),
308 "asan-memory-access-callback-prefix",
314 cl::desc(
"instrument dynamic allocas"),
318 "asan-skip-promotable-allocas",
327 cl::desc(
"scale of asan shadow mapping"),
332 cl::desc(
"offset of asan shadow mapping [EXPERIMENTAL]"),
342 "asan-opt-same-temp",
cl::desc(
"Instrument the same temp just once"),
346 cl::desc(
"Don't instrument scalar globals"),
350 "asan-opt-stack",
cl::desc(
"Don't instrument scalar stack variables"),
354 "asan-stack-dynamic-alloca",
359 "asan-force-experiment",
365 cl::desc(
"Use private aliases for global variables"),
370 cl::desc(
"Use odr indicators to improve ODR reporting"),
375 cl::desc(
"Use linker features to support dead " 376 "code stripping of globals"),
383 cl::desc(
"Place ASan constructors in comdat sections"),
403 STATISTIC(NumInstrumentedReads,
"Number of instrumented reads");
404 STATISTIC(NumInstrumentedWrites,
"Number of instrumented writes");
405 STATISTIC(NumOptimizedAccessesToGlobalVar,
406 "Number of optimized accesses to global vars");
407 STATISTIC(NumOptimizedAccessesToStackVar,
408 "Number of optimized accesses to stack vars");
417 struct ShadowMapping {
428 bool IsAndroid = TargetTriple.
isAndroid();
432 bool IsPS4CPU = TargetTriple.
isPS4CPU();
438 bool IsMIPS32 = TargetTriple.
isMIPS32();
439 bool IsMIPS64 = TargetTriple.
isMIPS64();
440 bool IsArmOrThumb = TargetTriple.
isARM() || TargetTriple.
isThumb();
447 ShadowMapping Mapping;
454 if (LongSize == 32) {
467 else if (IsEmscripten)
485 else if (IsFreeBSD && !IsMIPS64)
494 else if (IsLinux && IsX86_64) {
500 }
else if (IsWindows && IsX86_64) {
525 Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64 && !IsSystemZ && !IsPS4CPU &&
526 !(Mapping.Offset & (Mapping.Offset - 1)) &&
528 bool IsAndroidWithIfuncSupport =
530 Mapping.InGlobal =
ClWithIfunc && IsAndroidWithIfuncSupport && IsArmOrThumb;
538 return std::max(32U, 1U << MappingScale);
552 class ASanGlobalsMetadataWrapperPass :
public ModulePass {
556 ASanGlobalsMetadataWrapperPass() :
ModulePass(ID) {
561 bool runOnModule(
Module &M)
override {
567 return "ASanGlobalsMetadataWrapperPass";
585 bool CompileKernel =
false,
bool Recover =
false,
586 bool UseAfterScope =
false)
587 : UseAfterScope(UseAfterScope ||
ClUseAfterScope), GlobalsMD(*GlobalsMD) {
589 this->CompileKernel =
601 uint64_t ArraySize = 1;
604 assert(CI &&
"non-constant array size");
608 uint64_t SizeInBytes =
610 return SizeInBytes * ArraySize;
614 bool isInterestingAlloca(
const AllocaInst &AI);
621 uint64_t *
TypeSize,
unsigned *Alignment,
622 Value **MaybeMask =
nullptr);
626 void instrumentPointerComparisonOrSubtraction(
Instruction *I);
630 void instrumentUnusualSizeOrAlignment(
Instruction *I,
633 Value *SizeArgument,
bool UseCalls,
638 bool IsWrite,
size_t AccessSizeIndex,
643 bool maybeInsertAsanInitAtFunctionEntry(
Function &F);
644 void maybeInsertDynamicShadowAtFunctionEntry(
Function &F);
645 void markEscapedLocalAllocas(
Function &F);
648 friend struct FunctionStackPoisoner;
650 void initializeCallbacks(
Module &M);
655 uint64_t TypeSize)
const;
658 struct FunctionStateRAII {
662 assert(Pass->ProcessedAllocas.empty() &&
663 "last pass forgot to clear cache");
664 assert(!Pass->LocalDynamicShadow);
667 ~FunctionStateRAII() {
668 Pass->LocalDynamicShadow =
nullptr;
669 Pass->ProcessedAllocas.clear();
680 ShadowMapping Mapping;
695 Value *LocalDynamicShadow =
nullptr;
700 class AddressSanitizerLegacyPass :
public FunctionPass {
704 explicit AddressSanitizerLegacyPass(
bool CompileKernel =
false,
705 bool Recover =
false,
706 bool UseAfterScope =
false)
707 :
FunctionPass(ID), CompileKernel(CompileKernel), Recover(Recover),
708 UseAfterScope(UseAfterScope) {
713 return "AddressSanitizerFunctionPass";
723 getAnalysis<ASanGlobalsMetadataWrapperPass>().getGlobalsMD();
725 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
728 return ASan.instrumentFunction(F, TLI);
737 class ModuleAddressSanitizer {
740 bool CompileKernel =
false,
bool Recover =
false,
741 bool UseGlobalsGC =
true,
bool UseOdrIndicator =
false)
742 : GlobalsMD(*GlobalsMD), UseGlobalsGC(UseGlobalsGC &&
ClUseGlobalsGC),
755 this->CompileKernel =
765 bool instrumentModule(
Module &);
768 void initializeCallbacks(
Module &M);
777 const std::string &UniqueModuleId);
793 bool ShouldUseMachOGlobalsSection()
const;
794 StringRef getGlobalMetadataSection()
const;
797 size_t MinRedzoneSizeForGlobal()
const {
800 int GetAsanVersion(
const Module &M)
const;
806 bool UsePrivateAlias;
807 bool UseOdrIndicator;
812 ShadowMapping Mapping;
822 Function *AsanCtorFunction =
nullptr;
823 Function *AsanDtorFunction =
nullptr;
826 class ModuleAddressSanitizerLegacyPass :
public ModulePass {
830 explicit ModuleAddressSanitizerLegacyPass(
bool CompileKernel =
false,
831 bool Recover =
false,
832 bool UseGlobalGC =
true,
833 bool UseOdrIndicator =
false)
834 :
ModulePass(ID), CompileKernel(CompileKernel), Recover(Recover),
835 UseGlobalGC(UseGlobalGC), UseOdrIndicator(UseOdrIndicator) {
840 StringRef getPassName()
const override {
return "ModuleAddressSanitizer"; }
846 bool runOnModule(
Module &M)
override {
848 getAnalysis<ASanGlobalsMetadataWrapperPass>().getGlobalsMD();
849 ModuleAddressSanitizer ASanModule(M, &GlobalsMD, CompileKernel, Recover,
850 UseGlobalGC, UseOdrIndicator);
851 return ASanModule.instrumentModule(M);
858 bool UseOdrIndicator;
870 struct FunctionStackPoisoner :
public InstVisitor<FunctionStackPoisoner> {
877 ShadowMapping Mapping;
882 unsigned StackAlignment;
887 FunctionCallee AsanPoisonStackMemoryFunc, AsanUnpoisonStackMemoryFunc;
891 struct AllocaPoisonCall {
899 bool HasUntracedLifetimeIntrinsic =
false;
910 bool HasNonEmptyInlineAsm =
false;
911 bool HasReturnsTwiceCall =
false;
912 std::unique_ptr<CallInst> EmptyInlineAsm;
915 :
F(F), ASan(ASan), DIB(*F.
getParent(),
false),
916 C(ASan.C), IntptrTy(ASan.IntptrTy),
918 StackAlignment(1 << Mapping.Scale),
925 copyArgsPassedByValToAllocas();
930 if (AllocaVec.
empty() && DynamicAllocaVec.
empty())
return false;
934 if (HasUntracedLifetimeIntrinsic) {
938 StaticAllocaPoisonCallVec.
clear();
939 DynamicAllocaPoisonCallVec.
clear();
942 processDynamicAllocas();
943 processStaticAllocas();
954 void copyArgsPassedByValToAllocas();
959 void processStaticAllocas();
960 void processDynamicAllocas();
962 void createDynamicAllocasInitStorage();
974 void unpoisonDynamicAllocasBeforeInst(
Instruction *InstBefore,
982 if (!isa<ReturnInst>(InstBefore)) {
984 InstBefore->
getModule(), Intrinsic::get_dynamic_area_offset,
994 AsanAllocasUnpoisonFunc,
995 {IRB.
CreateLoad(IntptrTy, DynamicAllocaLayout), DynamicAreaPtr});
999 void unpoisonDynamicAllocas() {
1000 for (
auto &
Ret : RetVec)
1001 unpoisonDynamicAllocasBeforeInst(
Ret, DynamicAllocaLayout);
1003 for (
auto &StackRestoreInst : StackRestoreVec)
1004 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
1005 StackRestoreInst->getOperand(0));
1018 void handleDynamicAllocaCall(
AllocaInst *AI);
1022 if (!ASan.isInterestingAlloca(AI)) {
1026 if (AllocaVec.
empty())
1045 if (ID == Intrinsic::stackrestore) StackRestoreVec.
push_back(&II);
1046 if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
1047 if (!ASan.UseAfterScope)
1054 if (
Size->isMinusOne())
return;
1057 const uint64_t SizeValue =
Size->getValue().getLimitedValue();
1058 if (SizeValue == ~0ULL ||
1065 HasUntracedLifetimeIntrinsic =
true;
1069 if (!ASan.isInterestingAlloca(*AI))
1071 bool DoPoison = (ID == Intrinsic::lifetime_end);
1072 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
1074 StaticAllocaPoisonCallVec.
push_back(APC);
1076 DynamicAllocaPoisonCallVec.
push_back(APC);
1081 if (
CallInst *CI = dyn_cast<CallInst>(I)) {
1082 HasNonEmptyInlineAsm |= CI->isInlineAsm() &&
1083 !CI->isIdenticalTo(EmptyInlineAsm.get()) &&
1084 I != ASan.LocalDynamicShadow;
1085 HasReturnsTwiceCall |= CI->canReturnTwice();
1090 void initializeCallbacks(
Module &M);
1118 LineNo = mdconst::extract<ConstantInt>(MDN->
getOperand(1))->getLimitedValue();
1120 mdconst::extract<ConstantInt>(MDN->
getOperand(2))->getLimitedValue();
1130 for (
auto MDN : Globals->
operands()) {
1132 assert(MDN->getNumOperands() == 5);
1133 auto *V = mdconst::extract_or_null<Constant>(MDN->getOperand(0));
1137 auto *StrippedV = V->stripPointerCasts();
1144 if (
auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
1146 if (
auto *
Name = cast_or_null<MDString>(MDN->getOperand(2)))
1148 ConstantInt *IsDynInit = mdconst::extract<ConstantInt>(MDN->getOperand(3));
1151 mdconst::extract<ConstantInt>(MDN->getOperand(4));
1165 : CompileKernel(CompileKernel), Recover(Recover),
1166 UseAfterScope(UseAfterScope) {}
1171 auto &MAM = MAMProxy.getManager();
1176 if (Sanitizer.instrumentFunction(F, TLI))
1182 "The ASanGlobalsMetadataAnalysis is required to run before " 1183 "AddressSanitizer can run");
1190 bool UseOdrIndicator)
1191 : CompileKernel(CompileKernel), Recover(Recover), UseGlobalGC(UseGlobalGC),
1192 UseOdrIndicator(UseOdrIndicator) {}
1197 ModuleAddressSanitizer Sanitizer(M, &GlobalsMD, CompileKernel, Recover,
1198 UseGlobalGC, UseOdrIndicator);
1199 if (Sanitizer.instrumentModule(M))
1205 "Read metadata to mark which globals should be instrumented " 1206 "when running ASan.",
1212 AddressSanitizerLegacyPass,
"asan",
1213 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
false,
1218 AddressSanitizerLegacyPass,
"asan",
1219 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
false,
1224 bool UseAfterScope) {
1225 assert(!CompileKernel || Recover);
1226 return new AddressSanitizerLegacyPass(CompileKernel, Recover, UseAfterScope);
1232 ModuleAddressSanitizerLegacyPass,
"asan-module",
1233 "AddressSanitizer: detects use-after-free and out-of-bounds bugs." 1238 bool CompileKernel,
bool Recover,
bool UseGlobalsGC,
bool UseOdrIndicator) {
1239 assert(!CompileKernel || Recover);
1240 return new ModuleAddressSanitizerLegacyPass(CompileKernel, Recover,
1241 UseGlobalsGC, UseOdrIndicator);
1279 if (G->
getName() ==
"__llvm_gcov_ctr")
1287 Shadow = IRB.
CreateLShr(Shadow, Mapping.Scale);
1288 if (Mapping.Offset == 0)
return Shadow;
1291 if (LocalDynamicShadow)
1292 ShadowBase = LocalDynamicShadow;
1295 if (Mapping.OrShadowOffset)
1296 return IRB.
CreateOr(Shadow, ShadowBase);
1298 return IRB.
CreateAdd(Shadow, ShadowBase);
1302 void AddressSanitizer::instrumentMemIntrinsic(
MemIntrinsic *
MI) {
1304 if (isa<MemTransferInst>(MI)) {
1306 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
1310 }
else if (isa<MemSetInst>(MI)) {
1321 bool AddressSanitizer::isInterestingAlloca(
const AllocaInst &AI) {
1322 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
1324 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
1325 return PreviouslySeenAllocaInfo->getSecond();
1327 bool IsInteresting =
1340 ProcessedAllocas[&AI] = IsInteresting;
1341 return IsInteresting;
1347 unsigned *Alignment,
1348 Value **MaybeMask) {
1353 if (LocalDynamicShadow == I)
1356 Value *PtrOperand =
nullptr;
1358 if (
LoadInst *LI = dyn_cast<LoadInst>(I)) {
1362 *Alignment = LI->getAlignment();
1363 PtrOperand = LI->getPointerOperand();
1364 }
else if (
StoreInst *
SI = dyn_cast<StoreInst>(I)) {
1368 *Alignment =
SI->getAlignment();
1369 PtrOperand =
SI->getPointerOperand();
1370 }
else if (
AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
1375 PtrOperand = RMW->getPointerOperand();
1381 PtrOperand = XCHG->getPointerOperand();
1382 }
else if (
auto CI = dyn_cast<CallInst>(I)) {
1384 if (
F && (
F->getName().startswith(
"llvm.masked.load.") ||
1385 F->getName().startswith(
"llvm.masked.store."))) {
1386 unsigned OpOffset = 0;
1387 if (
F->getName().startswith(
"llvm.masked.store.")) {
1399 auto BasePtr = CI->getOperand(0 + OpOffset);
1400 auto Ty = cast<PointerType>(BasePtr->getType())->getElementType();
1402 if (
auto AlignmentConstant =
1403 dyn_cast<ConstantInt>(CI->getOperand(1 + OpOffset)))
1404 *Alignment = (
unsigned)AlignmentConstant->getZExtValue();
1408 *MaybeMask = CI->getOperand(2 + OpOffset);
1409 PtrOperand = BasePtr;
1432 if (
auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
1433 return isInterestingAlloca(*AI) ? AI :
nullptr;
1446 if (
ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
1447 if (!Cmp->isRelational())
1461 if (BO->getOpcode() != Instruction::Sub)
1480 void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
1483 FunctionCallee F = isa<ICmpInst>(
I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
1485 for (
Value *&i : Param) {
1486 if (i->getType()->isPointerTy())
1494 unsigned Alignment,
unsigned Granularity,
1496 Value *SizeArgument,
bool UseCalls,
1500 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1502 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
1503 return Pass->instrumentAddress(I, InsertBefore, Addr, TypeSize, IsWrite,
1504 nullptr, UseCalls, Exp);
1505 Pass->instrumentUnusualSizeOrAlignment(I, InsertBefore, Addr, TypeSize,
1506 IsWrite,
nullptr, UseCalls, Exp);
1512 Value *Addr,
unsigned Alignment,
1513 unsigned Granularity,
uint32_t TypeSize,
1514 bool IsWrite,
Value *SizeArgument,
1516 auto *VTy = cast<PointerType>(Addr->
getType())->getElementType();
1518 unsigned Num = VTy->getVectorNumElements();
1520 for (
unsigned Idx = 0; Idx < Num; ++Idx) {
1521 Value *InstrumentedAddress =
nullptr;
1523 if (
auto *
Vector = dyn_cast<ConstantVector>(Mask)) {
1525 if (
auto *Masked = dyn_cast<ConstantInt>(
Vector->getOperand(Idx))) {
1526 if (Masked->isZero())
1536 InsertBefore = ThenTerm;
1540 InstrumentedAddress =
1543 Granularity, ElemTypeSize, IsWrite, SizeArgument,
1551 bool IsWrite =
false;
1552 unsigned Alignment = 0;
1553 uint64_t TypeSize = 0;
1554 Value *MaybeMask =
nullptr;
1556 isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment, &MaybeMask);
1577 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1578 NumOptimizedAccessesToGlobalVar++;
1586 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1587 NumOptimizedAccessesToStackVar++;
1593 NumInstrumentedWrites++;
1595 NumInstrumentedReads++;
1597 unsigned Granularity = 1 << Mapping.Scale;
1600 Alignment, Granularity, TypeSize, IsWrite,
1601 nullptr, UseCalls, Exp);
1604 IsWrite,
nullptr, UseCalls, Exp);
1609 Value *Addr,
bool IsWrite,
1610 size_t AccessSizeIndex,
1611 Value *SizeArgument,
1618 Call = IRB.
CreateCall(AsanErrorCallbackSized[IsWrite][0],
1619 {Addr, SizeArgument});
1621 Call = IRB.
CreateCall(AsanErrorCallbackSized[IsWrite][1],
1622 {Addr, SizeArgument, ExpVal});
1626 IRB.
CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1628 Call = IRB.
CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1642 size_t Granularity =
static_cast<size_t>(1) << Mapping.Scale;
1644 Value *LastAccessedByte =
1647 if (TypeSize / 8 > 1)
1657 void AddressSanitizer::instrumentAddress(
Instruction *OrigIns,
1660 Value *SizeArgument,
bool UseCalls,
1670 IRB.
CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1673 IRB.
CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1691 assert(cast<BranchInst>(TagCheckTerm)->isUnconditional());
1693 InsertBefore = TagCheckTerm;
1699 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1701 Value *ShadowValue =
1705 size_t Granularity = 1ULL << Mapping.Scale;
1713 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
1716 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
1730 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
1731 AccessSizeIndex, SizeArgument, Exp);
1739 void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1741 bool IsWrite,
Value *SizeArgument,
bool UseCalls,
uint32_t Exp) {
1747 IRB.
CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1750 IRB.
CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1756 instrumentAddress(I, InsertBefore, Addr, 8, IsWrite, Size,
false, Exp);
1757 instrumentAddress(I, InsertBefore, LastByte, 8, IsWrite, Size,
false, Exp);
1761 void ModuleAddressSanitizer::poisonOneInitializer(
Function &GlobalInit,
1769 IRB.
CreateCall(AsanPoisonGlobals, ModuleNameAddr);
1773 if (
ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
1777 void ModuleAddressSanitizer::createInitializerPoisonCalls(
1788 if (isa<ConstantAggregateZero>(
OP))
continue;
1794 auto *Priority = cast<ConstantInt>(CS->
getOperand(0));
1798 poisonOneInitializer(*
F, ModuleName);
1803 bool ModuleAddressSanitizer::ShouldInstrumentGlobal(
GlobalVariable *G) {
1809 if (GlobalsMD.get(G).IsBlacklisted)
return false;
1810 if (!Ty->
isSized())
return false;
1820 if (G->
getAlignment() > MinRedzoneSizeForGlobal())
return false;
1826 if (!TargetTriple.isOSBinFormatCOFF()) {
1838 switch (
C->getSelectionKind()) {
1853 if (Section ==
"llvm.metadata")
return false;
1873 if (TargetTriple.isOSBinFormatCOFF() && Section.
contains(
'$')) {
1874 LLVM_DEBUG(
dbgs() <<
"Ignoring global in sorted section (contains '$'): " 1879 if (TargetTriple.isOSBinFormatMachO()) {
1881 unsigned TAA = 0, StubSize = 0;
1884 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
1885 assert(ErrorCode.empty() &&
"Invalid section specifier.");
1890 if (ParsedSegment ==
"__OBJC" ||
1891 (ParsedSegment ==
"__DATA" && ParsedSection.
startswith(
"__objc_"))) {
1892 LLVM_DEBUG(
dbgs() <<
"Ignoring ObjC runtime global: " << *G <<
"\n");
1903 if (ParsedSegment ==
"__DATA" && ParsedSection ==
"__cfstring") {
1910 LLVM_DEBUG(
dbgs() <<
"Ignoring a cstring literal: " << *G <<
"\n");
1922 bool ModuleAddressSanitizer::ShouldUseMachOGlobalsSection()
const {
1923 if (!TargetTriple.isOSBinFormatMachO())
1926 if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
1928 if (TargetTriple.isiOS() && !TargetTriple.isOSVersionLT(9))
1930 if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
1936 StringRef ModuleAddressSanitizer::getGlobalMetadataSection()
const {
1937 switch (TargetTriple.getObjectFormat()) {
1944 "ModuleAddressSanitizer not implemented for object file format.");
1951 void ModuleAddressSanitizer::initializeCallbacks(
Module &M) {
1957 AsanUnpoisonGlobals =
1962 kAsanRegisterGlobalsName, IRB.
getVoidTy(), IntptrTy, IntptrTy);
1964 kAsanUnregisterGlobalsName, IRB.
getVoidTy(), IntptrTy, IntptrTy);
1969 kAsanRegisterImageGlobalsName, IRB.
getVoidTy(), IntptrTy);
1971 kAsanUnregisterImageGlobalsName, IRB.
getVoidTy(), IntptrTy);
1973 AsanRegisterElfGlobals =
1975 IntptrTy, IntptrTy, IntptrTy);
1976 AsanUnregisterElfGlobals =
1978 IntptrTy, IntptrTy, IntptrTy);
1983 void ModuleAddressSanitizer::SetComdatForGlobalMetadata(
1997 Name += InternalSuffix;
2006 if (TargetTriple.isOSBinFormatCOFF()) {
2021 ModuleAddressSanitizer::CreateMetadataGlobal(
Module &M,
Constant *Initializer,
2023 auto Linkage = TargetTriple.isOSBinFormatMachO()
2029 Metadata->
setSection(getGlobalMetadataSection());
2042 void ModuleAddressSanitizer::InstrumentGlobalsCOFF(
2048 for (
size_t i = 0; i < ExtendedGlobals.
size(); i++) {
2049 Constant *Initializer = MetadataInitializers[i];
2052 CreateMetadataGlobal(M, Initializer, G->
getName());
2057 unsigned SizeOfGlobalStruct = DL.getTypeAllocSize(Initializer->
getType());
2059 "global metadata will not be padded appropriately");
2062 SetComdatForGlobalMetadata(G, Metadata,
"");
2066 void ModuleAddressSanitizer::InstrumentGlobalsELF(
2069 const std::string &UniqueModuleId) {
2073 for (
size_t i = 0; i < ExtendedGlobals.
size(); i++) {
2076 CreateMetadataGlobal(M, MetadataInitializers[i], G->
getName());
2078 Metadata->
setMetadata(LLVMContext::MD_associated, MD);
2079 MetadataGlobals[i] = Metadata;
2081 SetComdatForGlobalMetadata(G, Metadata, UniqueModuleId);
2086 if (!MetadataGlobals.empty())
2103 "__start_" + getGlobalMetadataSection());
2107 "__stop_" + getGlobalMetadataSection());
2119 IRB_Dtor.
CreateCall(AsanUnregisterElfGlobals,
2125 void ModuleAddressSanitizer::InstrumentGlobalsMachO(
2136 for (
size_t i = 0; i < ExtendedGlobals.
size(); i++) {
2137 Constant *Initializer = MetadataInitializers[i];
2140 CreateMetadataGlobal(M, Initializer, G->
getName());
2144 auto LivenessBinder =
2150 Liveness->
setSection(
"__DATA,__asan_liveness,regular,live_support");
2151 LivenessGlobals[i] = Liveness;
2158 if (!LivenessGlobals.empty())
2178 IRB_Dtor.
CreateCall(AsanUnregisterImageGlobals,
2182 void ModuleAddressSanitizer::InstrumentGlobalsWithMetadataArray(
2186 unsigned N = ExtendedGlobals.
size();
2196 if (Mapping.Scale > 3)
2197 AllGlobals->setAlignment(
Align(1ULL << Mapping.Scale));
2218 *CtorComdat =
false;
2223 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.
push_back(&G);
2226 size_t n = GlobalsToChange.
size();
2246 IntptrTy, IntptrTy, IntptrTy);
2250 bool HasDynamicallyInitializedGlobals =
false;
2257 for (
size_t i = 0; i < n; i++) {
2258 static const uint64_t kMaxGlobalRedzone = 1 << 18;
2263 auto MD = GlobalsMD.get(G);
2268 M, MD.Name.
empty() ? NameForGlobal : MD.Name,
2273 uint64_t MinRZ = MinRedzoneSizeForGlobal();
2277 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
2278 uint64_t RightRedzoneSize =
RZ;
2280 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
2281 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
2294 "",
G, G->getThreadLocalMode());
2304 if (TargetTriple.isOSBinFormatMachO() && !G->hasSection() &&
2307 if (Seq && Seq->isCString())
2308 NewGlobal->
setSection(
"__TEXT,__asan_cstring,regular");
2314 G->getDebugInfo(GVs);
2315 for (
auto *GV : GVs)
2325 G->eraseFromParent();
2326 NewGlobals[i] = NewGlobal;
2329 if (!MD.SourceLoc.empty()) {
2339 bool CanUsePrivateAliases =
2340 TargetTriple.isOSBinFormatELF() || TargetTriple.isOSBinFormatMachO() ||
2341 TargetTriple.isOSBinFormatWasm();
2342 if (CanUsePrivateAliases && UsePrivateAlias) {
2345 InstrumentedGlobal =
2353 }
else if (UseOdrIndicator) {
2356 auto *ODRIndicatorSym =
2359 kODRGenPrefix + NameForGlobal,
nullptr,
2366 ODRIndicator = ODRIndicatorSym;
2379 if (
ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals =
true;
2383 Initializers[i] = Initializer;
2389 for (
size_t i = 0; i < n; i++) {
2396 std::string ELFUniqueModuleId =
2400 if (!ELFUniqueModuleId.empty()) {
2401 InstrumentGlobalsELF(IRB, M, NewGlobals, Initializers, ELFUniqueModuleId);
2403 }
else if (UseGlobalsGC && TargetTriple.isOSBinFormatCOFF()) {
2404 InstrumentGlobalsCOFF(IRB, M, NewGlobals, Initializers);
2405 }
else if (UseGlobalsGC && ShouldUseMachOGlobalsSection()) {
2406 InstrumentGlobalsMachO(IRB, M, NewGlobals, Initializers);
2408 InstrumentGlobalsWithMetadataArray(IRB, M, NewGlobals, Initializers);
2412 if (HasDynamicallyInitializedGlobals)
2413 createInitializerPoisonCalls(M, ModuleName);
2419 int ModuleAddressSanitizer::GetAsanVersion(
const Module &M)
const {
2425 Version += (LongSize == 32 && isAndroid);
2429 bool ModuleAddressSanitizer::instrumentModule(
Module &M) {
2430 initializeCallbacks(M);
2438 std::string VersionCheckName =
2441 M, kAsanModuleCtorName, kAsanInitName, {},
2442 {}, VersionCheckName);
2444 bool CtorComdat =
true;
2447 IRBuilder<> IRB(AsanCtorFunction->getEntryBlock().getTerminator());
2448 InstrumentGlobals(IRB, M, &CtorComdat);
2456 if (UseCtorComdat && TargetTriple.isOSBinFormatELF() && CtorComdat) {
2459 if (AsanDtorFunction) {
2465 if (AsanDtorFunction)
2472 void AddressSanitizer::initializeCallbacks(
Module &M) {
2476 for (
int Exp = 0; Exp < 2; Exp++) {
2477 for (
size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
2478 const std::string TypeStr = AccessIsWrite ?
"store" :
"load";
2479 const std::string ExpStr = Exp ?
"exp_" :
"";
2480 const std::string EndingStr = Recover ?
"_noabort" :
"";
2487 Args1.push_back(ExpType);
2490 kAsanReportErrorTemplate + ExpStr + TypeStr +
"_n" + EndingStr,
2498 AccessSizeIndex++) {
2499 const std::string Suffix = TypeStr +
itostr(1ULL << AccessSizeIndex);
2500 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2502 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
2505 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2513 const std::string MemIntrinCallbackPrefix =
2525 AsanHandleNoReturnFunc =
2528 AsanPtrCmpFunction =
2530 AsanPtrSubFunction =
2536 if (Mapping.InGlobal)
2541 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(
Function &
F) {
2549 if (F.
getName().
find(
" load]") != std::string::npos) {
2559 void AddressSanitizer::maybeInsertDynamicShadowAtFunctionEntry(
Function &F) {
2565 if (Mapping.InGlobal) {
2573 LocalDynamicShadow =
2574 IRB.
CreateCall(Asm, {AsanShadowGlobal},
".asan.shadow");
2576 LocalDynamicShadow =
2581 kAsanShadowMemoryDynamicAddress, IntptrTy);
2582 LocalDynamicShadow = IRB.
CreateLoad(IntptrTy, GlobalDynamicAddress);
2586 void AddressSanitizer::markEscapedLocalAllocas(
Function &F) {
2591 assert(ProcessedAllocas.empty() &&
"must process localescape before allocas");
2606 "non-static alloca arg to localescape");
2607 ProcessedAllocas[AI] =
false;
2614 bool AddressSanitizer::instrumentFunction(
Function &F,
2620 bool FunctionModified =
false;
2625 if (maybeInsertAsanInitAtFunctionEntry(F))
2626 FunctionModified =
true;
2629 if (!F.
hasFnAttribute(Attribute::SanitizeAddress))
return FunctionModified;
2635 FunctionStateRAII CleanupObj(
this);
2637 maybeInsertDynamicShadowAtFunctionEntry(F);
2641 markEscapedLocalAllocas(F);
2656 for (
auto &BB : F) {
2658 TempsToInstrument.
clear();
2659 int NumInsnsPerBB = 0;
2660 for (
auto &Inst : BB) {
2661 if (LooksLikeCodeInBug11395(&Inst))
return false;
2662 Value *MaybeMask =
nullptr;
2663 if (
Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
2664 &Alignment, &MaybeMask)) {
2670 if (TempsToInstrument.
count(Addr))
2673 if (!TempsToInstrument.
insert(Addr).second)
2681 PointerComparisonsOrSubtracts.
push_back(&Inst);
2683 }
else if (isa<MemIntrinsic>(Inst)) {
2686 if (isa<AllocaInst>(Inst)) NumAllocas++;
2690 TempsToInstrument.
clear();
2694 if (
CallInst *CI = dyn_cast<CallInst>(&Inst))
2707 const DataLayout &DL = F.getParent()->getDataLayout();
2713 int NumInstrumented = 0;
2714 for (
auto Inst : ToInstrument) {
2717 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
2718 instrumentMop(ObjSizeVis, Inst, UseCalls,
2719 F.getParent()->getDataLayout());
2721 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
2726 FunctionStackPoisoner FSP(F, *
this);
2727 bool ChangedStack = FSP.runOnFunction();
2731 for (
auto CI : NoReturnCalls) {
2736 for (
auto Inst : PointerComparisonsOrSubtracts) {
2737 instrumentPointerComparisonOrSubtraction(Inst);
2741 if (NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty())
2742 FunctionModified =
true;
2744 LLVM_DEBUG(
dbgs() <<
"ASAN done instrumenting: " << FunctionModified <<
" " 2747 return FunctionModified;
2753 bool AddressSanitizer::LooksLikeCodeInBug11395(
Instruction *I) {
2754 if (LongSize != 32)
return false;
2762 void FunctionStackPoisoner::initializeCallbacks(
Module &M) {
2765 std::string Suffix =
itostr(i);
2767 kAsanStackMallocNameTemplate + Suffix, IntptrTy, IntptrTy);
2768 AsanStackFreeFunc[i] =
2772 if (ASan.UseAfterScope) {
2774 kAsanPoisonStackMemoryName, IRB.
getVoidTy(), IntptrTy, IntptrTy);
2776 kAsanUnpoisonStackMemoryName, IRB.
getVoidTy(), IntptrTy, IntptrTy);
2779 for (
size_t Val : {0x00, 0xf1, 0xf2, 0xf3, 0xf5, 0xf8}) {
2780 std::ostringstream
Name;
2782 Name << std::setw(2) << std::setfill(
'0') << std::hex << Val;
2783 AsanSetShadowFunc[Val] =
2788 kAsanAllocaPoison, IRB.
getVoidTy(), IntptrTy, IntptrTy);
2790 kAsanAllocasUnpoison, IRB.
getVoidTy(), IntptrTy, IntptrTy);
2795 size_t Begin,
size_t End,
2797 Value *ShadowBase) {
2801 const size_t LargestStoreSizeInBytes =
2802 std::min<size_t>(
sizeof(uint64_t), ASan.LongSize / 8);
2810 for (
size_t i = Begin; i < End;) {
2811 if (!ShadowMask[i]) {
2817 size_t StoreSizeInBytes = LargestStoreSizeInBytes;
2819 while (StoreSizeInBytes > End - i)
2820 StoreSizeInBytes /= 2;
2823 for (
size_t j = StoreSizeInBytes - 1; j && !ShadowMask[i + j]; --j) {
2824 while (j <= StoreSizeInBytes / 2)
2825 StoreSizeInBytes /= 2;
2829 for (
size_t j = 0; j < StoreSizeInBytes; j++) {
2831 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
2833 Val = (Val << 8) | ShadowBytes[i + j];
2837 Value *Poison = IRB.
getIntN(StoreSizeInBytes * 8, Val);
2841 i += StoreSizeInBytes;
2848 copyToShadow(ShadowMask, ShadowBytes, 0, ShadowMask.
size(), IRB, ShadowBase);
2853 size_t Begin,
size_t End,
2856 size_t Done = Begin;
2857 for (
size_t i = Begin, j = Begin + 1; i < End; i = j++) {
2858 if (!ShadowMask[i]) {
2862 uint8_t Val = ShadowBytes[i];
2863 if (!AsanSetShadowFunc[Val])
2867 for (; j < End && ShadowMask[j] && Val == ShadowBytes[j]; ++j) {
2871 copyToShadowInline(ShadowMask, ShadowBytes, Done, i, IRB, ShadowBase);
2879 copyToShadowInline(ShadowMask, ShadowBytes, Done, End, IRB, ShadowBase);
2887 for (
int i = 0;; i++, MaxSize *= 2)
2888 if (LocalStackSize <= MaxSize)
return i;
2892 void FunctionStackPoisoner::copyArgsPassedByValToAllocas() {
2894 if (CopyInsertPoint == ASan.LocalDynamicShadow) {
2902 if (
Arg.hasByValAttr()) {
2903 Type *Ty =
Arg.getType()->getPointerElementType();
2904 const Align Alignment =
2909 (
Arg.hasName() ?
Arg.getName() :
"Arg" +
Twine(
Arg.getArgNo())) +
2912 Arg.replaceAllUsesWith(AI);
2923 Value *ValueIfFalse) {
2932 Value *FunctionStackPoisoner::createAllocaForLayout(
2941 nullptr,
"MyAlloca");
2950 void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
2953 DynamicAllocaLayout = IRB.
CreateAlloca(IntptrTy,
nullptr);
2958 void FunctionStackPoisoner::processDynamicAllocas() {
2960 assert(DynamicAllocaPoisonCallVec.empty());
2965 for (
const auto &APC : DynamicAllocaPoisonCallVec) {
2968 assert(ASan.isInterestingAlloca(*APC.AI));
2969 assert(!APC.AI->isStaticAlloca());
2972 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
2979 createDynamicAllocasInitStorage();
2980 for (
auto &AI : DynamicAllocaVec)
2981 handleDynamicAllocaCall(AI);
2982 unpoisonDynamicAllocas();
2985 void FunctionStackPoisoner::processStaticAllocas() {
2986 if (AllocaVec.empty()) {
2987 assert(StaticAllocaPoisonCallVec.empty());
2991 int StackMallocIdx = -1;
3002 auto InsBeforeB = InsBefore->
getParent();
3004 for (
auto *AI : StaticAllocasToMoveUp)
3009 if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
3012 SVD.
reserve(AllocaVec.size());
3015 ASan.getAllocaSizeInBytes(*AI),
3026 size_t Granularity = 1ULL << Mapping.Scale;
3027 size_t MinHeaderSize =
std::max((
size_t)ASan.LongSize / 2, Granularity);
3033 for (
auto &Desc : SVD)
3034 AllocaToSVDMap[Desc.AI] = &Desc;
3037 for (
const auto &APC : StaticAllocaPoisonCallVec) {
3040 assert(ASan.isInterestingAlloca(*APC.AI));
3041 assert(APC.AI->isStaticAlloca());
3044 Desc.LifetimeSize = Desc.Size;
3046 if (
const DILocation *LifetimeLoc = APC.InsBefore->getDebugLoc().
get()) {
3047 if (LifetimeLoc->getFile() == FnLoc->getFile())
3048 if (
unsigned Line = LifetimeLoc->getLine())
3049 Desc.Line = std::min(Desc.Line ? Desc.Line : Line, Line);
3066 DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
3067 DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
3069 Value *StaticAlloca =
3070 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L,
false);
3073 Value *LocalStackBase;
3074 Value *LocalStackBaseAlloca;
3077 if (DoStackMalloc) {
3078 LocalStackBaseAlloca =
3079 IRB.
CreateAlloca(IntptrTy,
nullptr,
"asan_local_stack_base");
3085 kAsanOptionDetectUseAfterReturn, IRB.
getInt32Ty());
3094 Value *FakeStackValue =
3095 IRBIf.
CreateCall(AsanStackMallocFunc[StackMallocIdx],
3098 FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
3101 Value *NoFakeStack =
3105 Value *AllocaValue =
3106 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L,
true) : StaticAlloca;
3109 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
3110 IRB.
CreateStore(LocalStackBase, LocalStackBaseAlloca);
3117 DoDynamicAlloca ? createAllocaForLayout(IRB, L,
true) : StaticAlloca;
3118 LocalStackBaseAlloca = LocalStackBase;
3122 for (
const auto &Desc : SVD) {
3157 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
3160 copyToShadow(ShadowAfterScope, ShadowAfterScope, IRB, ShadowBase);
3162 if (!StaticAllocaPoisonCallVec.empty()) {
3166 for (
const auto &APC : StaticAllocaPoisonCallVec) {
3173 copyToShadow(ShadowAfterScope,
3174 APC.DoPoison ? ShadowAfterScope : ShadowInScope, Begin, End,
3183 for (
auto Ret : RetVec) {
3188 if (DoStackMalloc) {
3189 assert(StackMallocIdx >= 0);
3206 if (StackMallocIdx <= 4) {
3210 copyToShadow(ShadowAfterReturn, ShadowAfterReturn, IRBPoison,
3216 IntptrTy, IRBPoison.
CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
3223 AsanStackFreeFunc[StackMallocIdx],
3228 copyToShadow(ShadowAfterScope, ShadowClean, IRBElse, ShadowBase);
3230 copyToShadow(ShadowAfterScope, ShadowClean, IRBRet, ShadowBase);
3238 void FunctionStackPoisoner::poisonAlloca(
Value *V, uint64_t
Size,
3244 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
3245 {AddrArg, SizeArg});
3256 void FunctionStackPoisoner::handleDynamicAllocaCall(
AllocaInst *AI) {
3260 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
3270 const unsigned ElementSize =
3303 IRB.
CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
3322 Value *Addr, uint64_t TypeSize)
const {
3324 if (!ObjSizeVis.
bothKnown(SizeOffset))
return false;
3325 uint64_t Size = SizeOffset.first.getZExtValue();
3326 int64_t
Offset = SizeOffset.second.getSExtValue();
3331 return Offset >= 0 && Size >= uint64_t(Offset) &&
3332 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
static cl::opt< bool > ClStack("asan-stack", cl::desc("Handle stack memory"), cl::Hidden, cl::init(true))
bool isOSEmscripten() const
Tests whether the OS is Emscripten.
A parsed version of the target data layout string in and methods for querying it. ...
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
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.
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.
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))
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
bool hasPrivateLinkage() const
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
This class represents lattice values for constants.
static size_t RedzoneSizeForScale(int MappingScale)
static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize, bool IsKasan)
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
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. This instruction must be a terminator.
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
An instruction that atomically checks whether a specified value is in a memory location, and, if it is, stores a new value there.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
LLVM_NODISCARD bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Available for inspection, not emission.
void push_back(const T &Elt)
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 > ClUsePrivateAlias("asan-use-private-alias", cl::desc("Use private aliases for global variables"), cl::Hidden, cl::init(false))
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 const char *const kODRGenPrefix
static Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
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...
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
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 isInterposable() const
Return true if this global's definition can be substituted with an arbitrary definition at link time...
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
The data referenced by the COMDAT must be the same size.
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.
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)
static cl::opt< bool > ClUseAfterScope("asan-use-after-scope", cl::desc("Check stack-use-after-scope"), cl::Hidden, cl::init(false))
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)
TypeSize getTypeStoreSizeInBits(Type *Ty) const
Returns the maximum number of bits that may be overwritten by storing the specified type; always a mu...
static Constant * get(ArrayType *T, ArrayRef< Constant *> V)
static cl::opt< bool > ClInsertVersionCheck("asan-guard-against-version-mismatch", cl::desc("Guard against compiler/runtime version mismatch."), cl::Hidden, cl::init(true))
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.
Value * getArgOperand(unsigned i) const
static const uint64_t kDefaultShadowScale
unsigned 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...
static const char *const kAsanShadowMemoryDynamicAddress
static const int kAsanStackUseAfterReturnMagic
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
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.
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 file contains the simple types necessary to represent the attributes associated with functions a...
The linker may choose any COMDAT.
ModuleAddressSanitizerPass(bool CompileKernel=false, bool Recover=false, bool UseGlobalGC=true, bool UseOdrIndicator=false)
static const char *const kAsanAllocasUnpoison
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
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
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
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="")
InstrTy * getInstruction() const
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
static uint64_t GetCtorAndDtorPriority(Triple &TargetTriple)
static const uint64_t kSmallX86_64ShadowOffsetAlignMask
static const char *const kAsanPoisonStackMemoryName
Type * getType() const
All values are typed, get the type of this value.
CallInst * CreateMemCpy(Value *Dst, MaybeAlign DstAlign, Value *Src, MaybeAlign SrcAlign, uint64_t Size, bool isVolatile=false, MDNode *TBAATag=nullptr, MDNode *TBAAStructTag=nullptr, MDNode *ScopeTag=nullptr, MDNode *NoAliasTag=nullptr)
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.
static cl::opt< bool > ClUseOdrIndicator("asan-use-odr-indicator", cl::desc("Use odr indicators to improve ODR reporting"), cl::Hidden, cl::init(false))
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
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
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)
static cl::opt< bool > ClInvalidPointerSub("asan-detect-invalid-pointer-sub", cl::desc("Instrument - operations with pointer operands"), cl::Hidden, cl::init(false))
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))
AddressSanitizerPass(bool CompileKernel=false, bool Recover=false, bool UseAfterScope=false)
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
bool isLittleEndian() const
Layout endianness...
static const uint64_t kWindowsShadowOffset64
iterator_range< User::op_iterator > arg_operands()
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.
static const uint64_t kMyriadTagShift
LinkageTypes getLinkage() const
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Align getValueOrABITypeAlignment(MaybeAlign Alignment, Type *Ty) const
Helper function to return Alignment if it's set or the result of getABITypeAlignment(Ty), in any case the result is a valid alignment.
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))
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)
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
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'.
StringRef getString() 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
static const size_t kNumberOfAccessSizes
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
static bool runOnFunction(Function &F, bool PostInlining)
void initializeModuleAddressSanitizerLegacyPassPass(PassRegistry &)
static const char *const kAsanGlobalsRegisteredFlagName
initializer< Ty > init(const Ty &Val)
No other Module may specify this COMDAT.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
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".
A set of analyses that are preserved following a run of a transformation pass.
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
VisibilityTypes getVisibility() const
static const uint64_t kEmscriptenShadowOffset
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...
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.
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.
bool isInlineAsm() const
Check if this call is an inline asm statement.
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
TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
static bool isInterestingPointerSubtraction(Instruction *I)
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
LLVM_NODISCARD size_t find(char C, size_t From=0) const
Search for the first character C in the string.
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.
bool isLifetimeStartOrEnd() const
Return true if the instruction is a llvm.lifetime.start or llvm.lifetime.end marker.
static Type * getVoidTy(LLVMContext &C)
AllocaInst * findAllocaForValue(Value *V, DenseMap< Value *, AllocaInst *> &AllocaForValue)
Finds alloca where the value comes from.
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.
unsigned getAddressSpace() const
Value * CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name="")
FunctionPass class - This class is used to implement most global optimizations.
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
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))
LLVM_NODISCARD bool contains(StringRef Other) const
Return true if the given string is a substring of *this, and false otherwise.
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
The data referenced by the COMDAT must be the same.
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
static const uint64_t kMyriadShadowScale
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.
static cl::opt< bool > ClInvalidPointerCmp("asan-detect-invalid-pointer-cmp", cl::desc("Instrument <, <=, >, >= with pointer operands"), cl::Hidden, cl::init(false))
static constexpr const Align None()
Returns a default constructed Align which corresponds to no alignment.
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
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.
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
This struct is a compact representation of a valid (non-zero power of two) alignment.
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.
This is the shared class of boolean and integer constants.
void setSelectionKind(SelectionKind Val)
static const char *const kAsanStackMallocNameTemplate
Align max(MaybeAlign Lhs, Align Rhs)
static const char *const kAsanUnpoisonStackMemoryName
Evaluate the size and offset of an object pointed to by a Value* statically.
An analysis over an "inner" IR unit that provides access to an analysis manager over a "outer" IR uni...
This struct is a compact representation of a valid (power of two) or undefined (0) alignment...
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...
INITIALIZE_PASS(ASanGlobalsMetadataWrapperPass, "asan-globals-md", "Read metadata to mark which globals should be instrumented " "when running ASan.", false, true) char AddressSanitizerLegacyPass INITIALIZE_PASS_BEGIN(AddressSanitizerLegacyPass, "asan", "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false, false) INITIALIZE_PASS_END(AddressSanitizerLegacyPass
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.
void setAlignment(MaybeAlign Alignment)
bool isOSLinux() const
Tests whether the OS is Linux.
static const uint64_t kDefaultShadowOffset64
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
FunctionPass * createAddressSanitizerFunctionPass(bool CompileKernel=false, bool Recover=false, bool UseAfterScope=false)
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")
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)
The linker will choose the largest COMDAT.
GlobalVariable * createPrivateGlobalForString(Module &M, StringRef Str, bool AllowMerging, const char *NamePrefix="")
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.
FunctionCallee getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
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 setAlignment(MaybeAlign Align)
void setLinkage(LinkageTypes LT)
INITIALIZE_PASS(ASanGlobalsMetadataWrapperPass, "asan-globals-md", "Read metadata to mark which globals should be instrumented " "when running ASan.", false, true) char AddressSanitizerLegacyPass AddressSanitizer
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))
void setPreservesAll()
Set by analyses that do not transform their input at all.
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
static const uint64_t kAsanEmscriptenCtorAndDtorPriority
Value * CreatePointerCast(Value *V, Type *DestTy, const Twine &Name="")
void initializeAddressSanitizerLegacyPassPass(PassRegistry &)
void setMetadata(unsigned KindID, MDNode *MD)
Set a particular kind of metadata attachment.
FunctionCallee declareSanitizerInitFunction(Module &M, StringRef InitName, ArrayRef< Type *> InitArgTypes)
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
void SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore, Instruction **ThenTerm, Instruction **ElseTerm, MDNode *BranchWeights=nullptr)
SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen, but also creates the ElseBlock...
ModulePass * createModuleAddressSanitizerLegacyPassPass(bool CompileKernel=false, bool Recover=false, bool UseGlobalsGC=true, bool UseOdrIndicator=true)
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))
unsigned getNumArgOperands() const
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.
void setAlignment(MaybeAlign Align)
static const uint64_t kMIPS64_ShadowOffset64
Constant * getOrInsertGlobal(StringRef Name, Type *Ty, function_ref< GlobalVariable *()> CreateGlobalCallback)
Look up the specified global in the module symbol table.
void setUnnamedAddr(UnnamedAddr Val)
static IntegerType * getInt32Ty(LLVMContext &C)
bool isThumb() const
Tests whether the target is Thumb (little and big endian).
INITIALIZE_PASS(ModuleAddressSanitizerLegacyPass, "asan-module", "AddressSanitizer: detects use-after-free and out-of-bounds bugs." "ModulePass", false, false) ModulePass *llvm
static int StackMallocSizeClass(uint64_t LocalStackSize)
Linkage
Describes symbol linkage.
LLVM_NODISCARD bool empty() const
void initializeASanGlobalsMetadataWrapperPassPass(PassRegistry &)
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
StringRef getName() const
Return a constant reference to the value's name.
bool hasExactDefinition() const
Return true if this global has an exact defintion.
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
static const uint64_t kNetBSDKasan_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...
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
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 bool isInterestingPointerComparison(Instruction *I)
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
Analysis pass providing the TargetLibraryInfo.
iterator_range< df_iterator< T > > depth_first(const T &G)
static const char *const kAsanUnpoisonGlobalsName
LLVM_NODISCARD const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1...
bool replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress, DIBuilder &Builder, uint8_t DIExprFlags, int Offset)
Replaces llvm.dbg.declare instruction when the alloca it describes is replaced with a new value...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
const BasicBlock & front() const
static bool bothKnown(const SizeOffsetType &SizeOffset)
static const char *const kAsanPoisonGlobalsName
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
static const uint64_t kPPC64_ShadowOffset64
static const unsigned kAllocaRzSize
bool doesNotReturn() const
Determine if the call cannot return.
LocationMetadata SourceLoc
bool hasInitializer() const
Definitions have initializers, declarations don't.
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.
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.
A container for analyses that lazily runs them and caches their results.
static cl::opt< bool > ClOptStack("asan-opt-stack", cl::desc("Don't instrument scalar stack variables"), cl::Hidden, cl::init(false))
std::pair< Function *, FunctionCallee > 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.
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.
static cl::opt< uint64_t > ClMappingOffset("asan-mapping-offset", cl::desc("offset of asan shadow mapping [EXPERIMENTAL]"), cl::Hidden, cl::init(0))
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.
A special type used by analysis passes to provide an address that identifies that particular analysis...
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...
Instruction * SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
Align assumeAligned(uint64_t Value)
Treats the value 0 as a 1, so Align is always at least 1.
bool isARM() const
Tests whether the target is ARM (little and big endian).
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