45 #include "llvm/Support/DataTypes.h"
64 #include <system_error>
68 #define DEBUG_TYPE "asan"
102 "__asan_unregister_globals";
104 "__asan_register_image_globals";
106 "__asan_unregister_image_globals";
108 "__asan_register_elf_globals";
110 "__asan_unregister_elf_globals";
115 "__asan_version_mismatch_check_v8";
127 "__asan_poison_stack_memory";
129 "__asan_unpoison_stack_memory";
134 "___asan_globals_registered";
137 "__asan_option_detect_stack_use_after_return";
140 "__asan_shadow_memory_dynamic_address";
152 "asan-kernel",
cl::desc(
"Enable KernelAddressSanitizer instrumentation"),
156 cl::desc(
"Enable recovery mode (continue-after-error)."),
161 cl::desc(
"instrument read instructions"),
164 "asan-instrument-writes",
cl::desc(
"instrument write instructions"),
167 "asan-instrument-atomics",
171 "asan-always-slow-path",
175 "asan-force-dynamic-shadow",
176 cl::desc(
"Load shadow address into a local variable for each function"),
184 "asan-max-ins-per-bb",
cl::init(10000),
185 cl::desc(
"maximal number of instructions to instrument in any given BB"),
191 "asan-max-inline-poisoning-size",
193 "Inline shadow poisoning for blocks up to the given size in bytes."),
196 cl::desc(
"Check stack-use-after-return"),
199 cl::desc(
"Create redzones for byval "
200 "arguments (extra copy "
204 cl::desc(
"Check stack-use-after-scope"),
211 cl::desc(
"Handle C++ initializer order"),
214 "asan-detect-invalid-pointer-pair",
218 "asan-realign-stack",
219 cl::desc(
"Realign stack to the value of this flag (power of two)"),
222 "asan-instrumentation-with-call-threshold",
224 "If the function being instrumented contains more than "
225 "this number of memory accesses, use callbacks instead of "
226 "inline checks (-1 means never use callbacks)."),
229 "asan-memory-access-callback-prefix",
234 cl::desc(
"instrument dynamic allocas"),
237 "asan-skip-promotable-allocas",
245 cl::desc(
"scale of asan shadow mapping"),
248 "asan-mapping-offset",
257 "asan-opt-same-temp",
cl::desc(
"Instrument the same temp just once"),
260 cl::desc(
"Don't instrument scalar globals"),
263 "asan-opt-stack",
cl::desc(
"Don't instrument scalar stack variables"),
267 "asan-stack-dynamic-alloca",
272 "asan-force-experiment",
278 cl::desc(
"Use private aliases for global"
284 cl::desc(
"Use linker features to support dead "
285 "code stripping of globals"),
292 cl::desc(
"Place ASan constructors in comdat sections"),
307 STATISTIC(NumInstrumentedReads,
"Number of instrumented reads");
308 STATISTIC(NumInstrumentedWrites,
"Number of instrumented writes");
309 STATISTIC(NumOptimizedAccessesToGlobalVar,
310 "Number of optimized accesses to global vars");
311 STATISTIC(NumOptimizedAccessesToStackVar,
312 "Number of optimized accesses to stack vars");
316 struct LocationMetadata {
321 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
323 bool empty()
const {
return Filename.empty(); }
330 mdconst::extract<ConstantInt>(MDN->
getOperand(1))->getLimitedValue();
332 mdconst::extract<ConstantInt>(MDN->
getOperand(2))->getLimitedValue();
337 class GlobalsMetadata {
340 Entry() : SourceLoc(),
Name(), IsDynInit(
false), IsBlacklisted(
false) {}
341 LocationMetadata SourceLoc;
347 GlobalsMetadata() : inited_(
false) {}
358 if (!Globals)
return;
359 for (
auto MDN : Globals->
operands()) {
362 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->
getOperand(0));
367 Entry &
E = Entries[GV];
368 if (
auto *Loc = cast_or_null<MDNode>(MDN->
getOperand(1)))
369 E.SourceLoc.parse(Loc);
371 E.Name =
Name->getString();
373 mdconst::extract<ConstantInt>(MDN->
getOperand(3));
374 E.IsDynInit |= IsDynInit->
isOne();
376 mdconst::extract<ConstantInt>(MDN->
getOperand(4));
377 E.IsBlacklisted |= IsBlacklisted->
isOne();
383 auto Pos = Entries.find(
G);
384 return (Pos != Entries.end()) ? Pos->second : Entry();
394 struct ShadowMapping {
400 static ShadowMapping getShadowMapping(
Triple &TargetTriple,
int LongSize,
402 bool IsAndroid = TargetTriple.
isAndroid();
405 bool IsPS4CPU = TargetTriple.
isPS4CPU();
420 ShadowMapping Mapping;
422 if (LongSize == 32) {
451 else if (IsLinux && IsX86_64) {
456 }
else if (IsWindows && IsX86_64) {
489 Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64 && !IsSystemZ && !IsPS4CPU &&
490 !(Mapping.Offset & (Mapping.Offset - 1)) &&
496 static size_t RedzoneSizeForScale(
int MappingScale) {
499 return std::max(32U, 1U << MappingScale);
504 explicit AddressSanitizer(
bool CompileKernel =
false,
bool Recover =
false,
505 bool UseAfterScope =
false)
509 LocalDynamicShadow(nullptr) {
513 return "AddressSanitizerFunctionPass";
519 uint64_t getAllocaSizeInBytes(
const AllocaInst &AI)
const {
520 uint64_t ArraySize = 1;
523 assert(CI &&
"non-constant array size");
527 uint64_t SizeInBytes =
529 return SizeInBytes * ArraySize;
532 bool isInterestingAlloca(
const AllocaInst &AI);
539 uint64_t *TypeSize,
unsigned *Alignment,
540 Value **MaybeMask =
nullptr);
543 void instrumentPointerComparisonOrSubtraction(
Instruction *
I);
550 Value *SizeArgument,
bool UseCalls,
555 bool IsWrite,
size_t AccessSizeIndex,
559 bool runOnFunction(
Function &
F)
override;
560 bool maybeInsertAsanInitAtFunctionEntry(
Function &
F);
561 void maybeInsertDynamicShadowAtFunctionEntry(
Function &
F);
562 void markEscapedLocalAllocas(
Function &
F);
563 bool doInitialization(
Module &M)
override;
564 bool doFinalization(
Module &M)
override;
570 void initializeCallbacks(
Module &M);
575 uint64_t TypeSize)
const;
578 struct FunctionStateRAII {
579 AddressSanitizer *
Pass;
580 FunctionStateRAII(AddressSanitizer *
Pass) : Pass(Pass) {
581 assert(Pass->ProcessedAllocas.empty() &&
582 "last pass forgot to clear cache");
583 assert(!Pass->LocalDynamicShadow);
585 ~FunctionStateRAII() {
586 Pass->LocalDynamicShadow =
nullptr;
587 Pass->ProcessedAllocas.clear();
598 ShadowMapping Mapping;
601 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
606 Function *AsanErrorCallbackSized[2][2];
607 Function *AsanMemoryAccessCallbackSized[2][2];
608 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
610 Value *LocalDynamicShadow;
611 GlobalsMetadata GlobalsMD;
614 friend struct FunctionStackPoisoner;
617 class AddressSanitizerModule :
public ModulePass {
619 explicit AddressSanitizerModule(
bool CompileKernel =
false,
620 bool Recover =
false,
621 bool UseGlobalsGC =
true)
633 bool runOnModule(
Module &M)
override;
635 StringRef getPassName()
const override {
return "AddressSanitizerModule"; }
638 void initializeCallbacks(
Module &M);
647 const std::string &UniqueModuleId);
663 bool ShouldUseMachOGlobalsSection()
const;
664 StringRef getGlobalMetadataSection()
const;
667 size_t MinRedzoneSizeForGlobal()
const {
668 return RedzoneSizeForScale(Mapping.Scale);
671 GlobalsMetadata GlobalsMD;
679 ShadowMapping Mapping;
685 Function *AsanUnregisterImageGlobals;
689 Function *AsanCtorFunction =
nullptr;
690 Function *AsanDtorFunction =
nullptr;
702 struct FunctionStackPoisoner :
public InstVisitor<FunctionStackPoisoner> {
704 AddressSanitizer &ASan;
709 ShadowMapping Mapping;
714 unsigned StackAlignment;
718 Function *AsanSetShadowFunc[0x100] = {};
719 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
720 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
723 struct AllocaPoisonCall {
739 AllocaForValueMapTy AllocaForValue;
741 bool HasNonEmptyInlineAsm =
false;
742 bool HasReturnsTwiceCall =
false;
743 std::unique_ptr<CallInst> EmptyInlineAsm;
745 FunctionStackPoisoner(
Function &
F, AddressSanitizer &ASan)
750 IntptrTy(ASan.IntptrTy),
752 Mapping(ASan.Mapping),
753 StackAlignment(1 << Mapping.Scale),
754 EmptyInlineAsm(
CallInst::Create(ASan.EmptyAsm)) {}
756 bool runOnFunction() {
760 copyArgsPassedByValToAllocas();
765 if (AllocaVec.empty() && DynamicAllocaVec.empty())
return false;
767 initializeCallbacks(*
F.getParent());
769 processDynamicAllocas();
770 processStaticAllocas();
781 void copyArgsPassedByValToAllocas();
786 void processStaticAllocas();
787 void processDynamicAllocas();
789 void createDynamicAllocasInitStorage();
793 void visitReturnInst(
ReturnInst &RI) { RetVec.push_back(&RI); }
796 void visitResumeInst(
ResumeInst &RI) { RetVec.push_back(&RI); }
801 void unpoisonDynamicAllocasBeforeInst(
Instruction *InstBefore,
804 Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
809 if (!isa<ReturnInst>(InstBefore)) {
811 InstBefore->
getModule(), Intrinsic::get_dynamic_area_offset,
814 Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
816 DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
820 IRB.CreateCall(AsanAllocasUnpoisonFunc,
821 {IRB.CreateLoad(DynamicAllocaLayout), DynamicAreaPtr});
825 void unpoisonDynamicAllocas() {
826 for (
auto &
Ret : RetVec)
827 unpoisonDynamicAllocasBeforeInst(
Ret, DynamicAllocaLayout);
829 for (
auto &StackRestoreInst : StackRestoreVec)
830 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
831 StackRestoreInst->getOperand(0));
848 if (!ASan.isInterestingAlloca(AI)) {
852 if (AllocaVec.empty())
855 StaticAllocasToMoveUp.push_back(&AI);
862 DynamicAllocaVec.push_back(&AI);
864 AllocaVec.push_back(&AI);
871 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
872 if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
873 if (!ASan.UseAfterScope)
875 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
884 if (SizeValue == ~0ULL ||
889 if (!AI || !ASan.isInterestingAlloca(*AI))
891 bool DoPoison = (ID == Intrinsic::lifetime_end);
892 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
894 StaticAllocaPoisonCallVec.push_back(APC);
896 DynamicAllocaPoisonCallVec.push_back(APC);
901 if (
CallInst *CI = dyn_cast<CallInst>(I)) {
902 HasNonEmptyInlineAsm |=
903 CI->isInlineAsm() && !CI->isIdenticalTo(EmptyInlineAsm.get());
904 HasReturnsTwiceCall |= CI->canReturnTwice();
909 void initializeCallbacks(
Module &M);
911 bool doesDominateAllExits(
const Instruction *I)
const {
912 for (
auto Ret : RetVec) {
913 if (!ASan.getDominatorTree().dominates(I,
Ret))
return false;
933 void poisonAlloca(
Value *V, uint64_t Size,
IRBuilder<> &IRB,
bool DoPoison);
945 AddressSanitizer,
"asan",
946 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
false,
952 "AddressSanitizer: detects
use-after-free and out-of-bounds bugs.",
false,
956 bool UseAfterScope) {
957 assert(!CompileKernel || Recover);
958 return new AddressSanitizer(CompileKernel, Recover, UseAfterScope);
963 AddressSanitizerModule,
"asan-module",
964 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
970 assert(!CompileKernel || Recover);
971 return new AddressSanitizerModule(CompileKernel, Recover, UseGlobalsGC);
996 LocationMetadata MD) {
1019 if (G->
getName() ==
"__llvm_gcov_ctr")
1027 Shadow = IRB.
CreateLShr(Shadow, Mapping.Scale);
1028 if (Mapping.Offset == 0)
return Shadow;
1031 if (LocalDynamicShadow)
1032 ShadowBase = LocalDynamicShadow;
1035 if (Mapping.OrShadowOffset)
1036 return IRB.
CreateOr(Shadow, ShadowBase);
1038 return IRB.
CreateAdd(Shadow, ShadowBase);
1042 void AddressSanitizer::instrumentMemIntrinsic(
MemIntrinsic *
MI) {
1044 if (isa<MemTransferInst>(MI)) {
1046 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
1050 }
else if (isa<MemSetInst>(MI)) {
1061 bool AddressSanitizer::isInterestingAlloca(
const AllocaInst &AI) {
1062 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
1064 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
1065 return PreviouslySeenAllocaInfo->getSecond();
1067 bool IsInteresting =
1080 ProcessedAllocas[&AI] = IsInteresting;
1081 return IsInteresting;
1087 unsigned *Alignment,
1088 Value **MaybeMask) {
1093 if (LocalDynamicShadow == I)
1096 Value *PtrOperand =
nullptr;
1098 if (
LoadInst *LI = dyn_cast<LoadInst>(I)) {
1102 *Alignment = LI->getAlignment();
1103 PtrOperand = LI->getPointerOperand();
1104 }
else if (
StoreInst *SI = dyn_cast<StoreInst>(I)) {
1108 *Alignment =
SI->getAlignment();
1109 PtrOperand =
SI->getPointerOperand();
1110 }
else if (
AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
1115 PtrOperand = RMW->getPointerOperand();
1121 PtrOperand = XCHG->getPointerOperand();
1122 }
else if (
auto CI = dyn_cast<CallInst>(I)) {
1124 if (
F && (
F->getName().startswith(
"llvm.masked.load.") ||
1125 F->getName().startswith(
"llvm.masked.store."))) {
1126 unsigned OpOffset = 0;
1127 if (
F->getName().startswith(
"llvm.masked.store.")) {
1140 auto Ty = cast<PointerType>(BasePtr->getType())->getElementType();
1142 if (
auto AlignmentConstant =
1143 dyn_cast<ConstantInt>(CI->
getOperand(1 + OpOffset)))
1144 *Alignment = (
unsigned)AlignmentConstant->getZExtValue();
1149 PtrOperand = BasePtr;
1172 if (
auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
1173 return isInterestingAlloca(*AI) ? AI :
nullptr;
1186 if (
ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
1187 if (!Cmp->isRelational())
return false;
1189 if (BO->getOpcode() != Instruction::Sub)
return false;
1204 void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
1207 Function *
F = isa<ICmpInst>(
I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
1209 for (
Value *&i : Param) {
1210 if (i->getType()->isPointerTy())
1218 unsigned Alignment,
unsigned Granularity,
1220 Value *SizeArgument,
bool UseCalls,
1224 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1226 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
1227 return Pass->instrumentAddress(I, InsertBefore, Addr, TypeSize, IsWrite,
1228 nullptr, UseCalls, Exp);
1229 Pass->instrumentUnusualSizeOrAlignment(I, InsertBefore, Addr, TypeSize,
1230 IsWrite,
nullptr, UseCalls, Exp);
1236 Value *Addr,
unsigned Alignment,
1237 unsigned Granularity,
uint32_t TypeSize,
1238 bool IsWrite,
Value *SizeArgument,
1240 auto *VTy = cast<PointerType>(Addr->
getType())->getElementType();
1242 unsigned Num = VTy->getVectorNumElements();
1244 for (
unsigned Idx = 0; Idx < Num; ++Idx) {
1245 Value *InstrumentedAddress =
nullptr;
1247 if (
auto *Vector = dyn_cast<ConstantVector>(Mask)) {
1249 if (
auto *Masked = dyn_cast<ConstantInt>(Vector->getOperand(Idx))) {
1250 if (Masked->isZero())
1260 InsertBefore = ThenTerm;
1264 InstrumentedAddress =
1267 Granularity, ElemTypeSize, IsWrite, SizeArgument,
1275 bool IsWrite =
false;
1276 unsigned Alignment = 0;
1277 uint64_t TypeSize = 0;
1278 Value *MaybeMask =
nullptr;
1280 isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment, &MaybeMask);
1301 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1302 NumOptimizedAccessesToGlobalVar++;
1310 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1311 NumOptimizedAccessesToStackVar++;
1317 NumInstrumentedWrites++;
1319 NumInstrumentedReads++;
1321 unsigned Granularity = 1 << Mapping.Scale;
1324 Alignment, Granularity, TypeSize, IsWrite,
1325 nullptr, UseCalls, Exp);
1328 IsWrite,
nullptr, UseCalls, Exp);
1333 Value *Addr,
bool IsWrite,
1334 size_t AccessSizeIndex,
1335 Value *SizeArgument,
1342 Call = IRB.
CreateCall(AsanErrorCallbackSized[IsWrite][0],
1343 {Addr, SizeArgument});
1345 Call = IRB.
CreateCall(AsanErrorCallbackSized[IsWrite][1],
1346 {Addr, SizeArgument, ExpVal});
1350 IRB.
CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1352 Call = IRB.
CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1366 size_t Granularity =
static_cast<size_t>(1) << Mapping.Scale;
1368 Value *LastAccessedByte =
1371 if (TypeSize / 8 > 1)
1381 void AddressSanitizer::instrumentAddress(
Instruction *OrigIns,
1384 Value *SizeArgument,
bool UseCalls,
1392 IRB.
CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1395 IRB.
CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1403 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1405 Value *ShadowValue =
1409 size_t Granularity = 1ULL << Mapping.Scale;
1417 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
1420 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
1434 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
1435 AccessSizeIndex, SizeArgument, Exp);
1443 void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1445 bool IsWrite,
Value *SizeArgument,
bool UseCalls,
uint32_t Exp) {
1451 IRB.
CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1454 IRB.
CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1460 instrumentAddress(I, InsertBefore, Addr, 8, IsWrite, Size,
false, Exp);
1461 instrumentAddress(I, InsertBefore, LastByte, 8, IsWrite, Size,
false, Exp);
1465 void AddressSanitizerModule::poisonOneInitializer(
Function &GlobalInit,
1473 IRB.
CreateCall(AsanPoisonGlobals, ModuleNameAddr);
1477 if (
ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
1481 void AddressSanitizerModule::createInitializerPoisonCalls(
1492 if (isa<ConstantAggregateZero>(
OP))
continue;
1501 poisonOneInitializer(*F, ModuleName);
1506 bool AddressSanitizerModule::ShouldInstrumentGlobal(
GlobalVariable *G) {
1508 DEBUG(
dbgs() <<
"GLOBAL: " << *G <<
"\n");
1510 if (GlobalsMD.get(G).IsBlacklisted)
return false;
1511 if (!Ty->
isSized())
return false;
1527 if (G->
getAlignment() > MinRedzoneSizeForGlobal())
return false;
1533 if (Section ==
"llvm.metadata")
return false;
1550 DEBUG(
dbgs() <<
"Ignoring a global initializer callback: " << *G <<
"\n");
1556 unsigned TAA = 0, StubSize = 0;
1559 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
1560 assert(ErrorCode.empty() &&
"Invalid section specifier.");
1565 if (ParsedSegment ==
"__OBJC" ||
1566 (ParsedSegment ==
"__DATA" && ParsedSection.
startswith(
"__objc_"))) {
1567 DEBUG(
dbgs() <<
"Ignoring ObjC runtime global: " << *G <<
"\n");
1578 if (ParsedSegment ==
"__DATA" && ParsedSection ==
"__cfstring") {
1579 DEBUG(
dbgs() <<
"Ignoring CFString: " << *G <<
"\n");
1585 DEBUG(
dbgs() <<
"Ignoring a cstring literal: " << *G <<
"\n");
1597 bool AddressSanitizerModule::ShouldUseMachOGlobalsSection()
const {
1611 StringRef AddressSanitizerModule::getGlobalMetadataSection()
const {
1621 void AddressSanitizerModule::initializeCallbacks(
Module &M) {
1638 IntptrTy, IntptrTy));
1643 AsanRegisterImageGlobals =
1648 AsanUnregisterImageGlobals =
1655 IntptrTy, IntptrTy, IntptrTy));
1660 IntptrTy, IntptrTy, IntptrTy));
1666 void AddressSanitizerModule::SetComdatForGlobalMetadata(
1680 Name += InternalSuffix;
1699 AddressSanitizerModule::CreateMetadataGlobal(
Module &M,
Constant *Initializer,
1705 M, Initializer->
getType(),
false, Linkage, Initializer,
1707 Metadata->
setSection(getGlobalMetadataSection());
1720 void AddressSanitizerModule::InstrumentGlobalsCOFF(
1726 for (
size_t i = 0; i < ExtendedGlobals.
size(); i++) {
1727 Constant *Initializer = MetadataInitializers[i];
1730 CreateMetadataGlobal(M, Initializer, G->
getName());
1735 unsigned SizeOfGlobalStruct = DL.getTypeAllocSize(Initializer->
getType());
1737 "global metadata will not be padded appropriately");
1740 SetComdatForGlobalMetadata(G, Metadata,
"");
1744 void AddressSanitizerModule::InstrumentGlobalsELF(
1747 const std::string &UniqueModuleId) {
1751 for (
size_t i = 0; i < ExtendedGlobals.
size(); i++) {
1754 CreateMetadataGlobal(M, MetadataInitializers[i], G->
getName());
1757 MetadataGlobals[i] = Metadata;
1759 SetComdatForGlobalMetadata(G, Metadata, UniqueModuleId);
1764 if (!MetadataGlobals.empty())
1781 "__start_" + getGlobalMetadataSection());
1785 "__stop_" + getGlobalMetadataSection());
1797 IRB_Dtor.
CreateCall(AsanUnregisterElfGlobals,
1803 void AddressSanitizerModule::InstrumentGlobalsMachO(
1814 for (
size_t i = 0; i < ExtendedGlobals.
size(); i++) {
1815 Constant *Initializer = MetadataInitializers[i];
1818 CreateMetadataGlobal(M, Initializer, G->
getName());
1822 auto LivenessBinder =
1828 Liveness->
setSection(
"__DATA,__asan_liveness,regular,live_support");
1829 LivenessGlobals[i] = Liveness;
1836 if (!LivenessGlobals.empty())
1856 IRB_Dtor.
CreateCall(AsanUnregisterImageGlobals,
1860 void AddressSanitizerModule::InstrumentGlobalsWithMetadataArray(
1864 unsigned N = ExtendedGlobals.
size();
1892 bool AddressSanitizerModule::InstrumentGlobals(
IRBuilder<> &IRB,
Module &M,
bool *CtorComdat) {
1893 *CtorComdat =
false;
1899 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.
push_back(&G);
1902 size_t n = GlobalsToChange.
size();
1922 IntptrTy, IntptrTy, IntptrTy);
1926 bool HasDynamicallyInitializedGlobals =
false;
1933 for (
size_t i = 0; i < n; i++) {
1934 static const uint64_t kMaxGlobalRedzone = 1 << 18;
1937 auto MD = GlobalsMD.get(G);
1942 M, MD.Name.
empty() ? NameForGlobal : MD.Name,
1946 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
1947 uint64_t MinRZ = MinRedzoneSizeForGlobal();
1951 MinRZ,
std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
1952 uint64_t RightRedzoneSize =
RZ;
1954 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
1955 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
1968 "",
G, G->getThreadLocalMode());
1976 if (Seq && Seq->isCString())
1977 NewGlobal->
setSection(
"__TEXT,__asan_cstring,regular");
1983 G->getDebugInfo(GVs);
1984 for (
auto *GV : GVs)
1994 G->eraseFromParent();
1995 NewGlobals[i] = NewGlobal;
1998 if (!MD.SourceLoc.empty()) {
2008 bool CanUsePrivateAliases =
2015 NameForGlobal + M.
getName(), NewGlobal);
2019 auto *ODRIndicatorSym =
2028 ODRIndicatorSym->setAlignment(1);
2029 ODRIndicator = ODRIndicatorSym;
2030 InstrumentedGlobal = GA;
2043 if (
ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals =
true;
2045 DEBUG(
dbgs() <<
"NEW GLOBAL: " << *NewGlobal <<
"\n");
2047 Initializers[i] = Initializer;
2050 std::string ELFUniqueModuleId =
2054 if (!ELFUniqueModuleId.empty()) {
2055 InstrumentGlobalsELF(IRB, M, NewGlobals, Initializers, ELFUniqueModuleId);
2058 InstrumentGlobalsCOFF(IRB, M, NewGlobals, Initializers);
2059 }
else if (UseGlobalsGC && ShouldUseMachOGlobalsSection()) {
2060 InstrumentGlobalsMachO(IRB, M, NewGlobals, Initializers);
2062 InstrumentGlobalsWithMetadataArray(IRB, M, NewGlobals, Initializers);
2066 if (HasDynamicallyInitializedGlobals)
2067 createInitializerPoisonCalls(M, ModuleName);
2073 bool AddressSanitizerModule::runOnModule(
Module &M) {
2078 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
2079 initializeCallbacks(M);
2090 bool CtorComdat =
true;
2091 bool Changed =
false;
2094 IRBuilder<> IRB(AsanCtorFunction->getEntryBlock().getTerminator());
2095 Changed |= InstrumentGlobals(IRB, M, &CtorComdat);
2105 if (AsanDtorFunction) {
2112 if (AsanDtorFunction)
2119 void AddressSanitizer::initializeCallbacks(
Module &M) {
2123 for (
int Exp = 0; Exp < 2; Exp++) {
2124 for (
size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
2125 const std::string TypeStr = AccessIsWrite ?
"store" :
"load";
2126 const std::string ExpStr = Exp ?
"exp_" :
"";
2127 const std::string SuffixStr = CompileKernel ?
"N" :
"_n";
2128 const std::string EndingStr = Recover ?
"_noabort" :
"";
2135 Args1.push_back(ExpType);
2137 AsanErrorCallbackSized[AccessIsWrite][Exp] =
2143 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
2149 AccessSizeIndex++) {
2150 const std::string Suffix = TypeStr +
itostr(1ULL << AccessSizeIndex);
2151 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2156 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2164 const std::string MemIntrinCallbackPrefix =
2167 MemIntrinCallbackPrefix +
"memmove", IRB.
getInt8PtrTy(),
2170 MemIntrinCallbackPrefix +
"memcpy", IRB.
getInt8PtrTy(),
2173 MemIntrinCallbackPrefix +
"memset", IRB.
getInt8PtrTy(),
2190 bool AddressSanitizer::doInitialization(
Module &M) {
2199 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
2203 bool AddressSanitizer::doFinalization(
Module &M) {
2208 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(
Function &F) {
2216 if (F.
getName().
find(
" load]") != std::string::npos) {
2226 void AddressSanitizer::maybeInsertDynamicShadowAtFunctionEntry(
Function &F) {
2234 LocalDynamicShadow = IRB.
CreateLoad(GlobalDynamicAddress);
2237 void AddressSanitizer::markEscapedLocalAllocas(
Function &F) {
2242 assert(ProcessedAllocas.empty() &&
"must process localescape before allocas");
2257 "non-static alloca arg to localescape");
2258 ProcessedAllocas[AI] =
false;
2265 bool AddressSanitizer::runOnFunction(
Function &F) {
2270 bool FunctionModified =
false;
2275 if (maybeInsertAsanInitAtFunctionEntry(F))
2276 FunctionModified =
true;
2279 if (!F.
hasFnAttribute(Attribute::SanitizeAddress))
return FunctionModified;
2281 DEBUG(
dbgs() <<
"ASAN instrumenting:\n" << F <<
"\n");
2284 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2286 FunctionStateRAII CleanupObj(
this);
2288 maybeInsertDynamicShadowAtFunctionEntry(F);
2292 markEscapedLocalAllocas(F);
2306 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
2309 for (
auto &BB : F) {
2311 TempsToInstrument.
clear();
2312 int NumInsnsPerBB = 0;
2313 for (
auto &Inst : BB) {
2314 if (LooksLikeCodeInBug11395(&Inst))
return false;
2315 Value *MaybeMask =
nullptr;
2316 if (
Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
2317 &Alignment, &MaybeMask)) {
2323 if (TempsToInstrument.
count(Addr))
2326 if (!TempsToInstrument.
insert(Addr).second)
2332 PointerComparisonsOrSubtracts.
push_back(&Inst);
2334 }
else if (isa<MemIntrinsic>(Inst)) {
2337 if (isa<AllocaInst>(Inst)) NumAllocas++;
2341 TempsToInstrument.
clear();
2342 if (CS.doesNotReturn()) NoReturnCalls.
push_back(CS.getInstruction());
2344 if (
CallInst *CI = dyn_cast<CallInst>(&Inst))
2358 const DataLayout &DL = F.getParent()->getDataLayout();
2364 int NumInstrumented = 0;
2365 for (
auto Inst : ToInstrument) {
2368 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
2369 instrumentMop(ObjSizeVis, Inst, UseCalls,
2370 F.getParent()->getDataLayout());
2372 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
2377 FunctionStackPoisoner FSP(F, *
this);
2378 bool ChangedStack = FSP.runOnFunction();
2382 for (
auto CI : NoReturnCalls) {
2387 for (
auto Inst : PointerComparisonsOrSubtracts) {
2388 instrumentPointerComparisonOrSubtraction(Inst);
2392 if (NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty())
2393 FunctionModified =
true;
2395 DEBUG(
dbgs() <<
"ASAN done instrumenting: " << FunctionModified <<
" "
2398 return FunctionModified;
2404 bool AddressSanitizer::LooksLikeCodeInBug11395(
Instruction *I) {
2405 if (LongSize != 32)
return false;
2413 void FunctionStackPoisoner::initializeCallbacks(
Module &M) {
2416 std::string Suffix =
itostr(i);
2424 if (ASan.UseAfterScope) {
2427 IntptrTy, IntptrTy));
2430 IntptrTy, IntptrTy));
2433 for (
size_t Val : {0x00, 0xf1, 0xf2, 0xf3, 0xf5, 0xf8}) {
2434 std::ostringstream
Name;
2436 Name << std::setw(2) << std::setfill(
'0') << std::hex << Val;
2437 AsanSetShadowFunc[Val] =
2439 Name.str(), IRB.
getVoidTy(), IntptrTy, IntptrTy));
2444 AsanAllocasUnpoisonFunc =
2451 size_t Begin,
size_t End,
2453 Value *ShadowBase) {
2457 const size_t LargestStoreSizeInBytes =
2458 std::min<size_t>(
sizeof(uint64_t), ASan.LongSize / 8);
2460 const bool IsLittleEndian = F.getParent()->getDataLayout().isLittleEndian();
2466 for (
size_t i = Begin; i <
End;) {
2467 if (!ShadowMask[i]) {
2473 size_t StoreSizeInBytes = LargestStoreSizeInBytes;
2475 while (StoreSizeInBytes > End - i)
2476 StoreSizeInBytes /= 2;
2479 for (
size_t j = StoreSizeInBytes - 1; j && !ShadowMask[i + j]; --j) {
2480 while (j <= StoreSizeInBytes / 2)
2481 StoreSizeInBytes /= 2;
2485 for (
size_t j = 0; j < StoreSizeInBytes; j++) {
2487 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
2489 Val = (Val << 8) | ShadowBytes[i + j];
2493 Value *Poison = IRB.
getIntN(StoreSizeInBytes * 8, Val);
2497 i += StoreSizeInBytes;
2504 copyToShadow(ShadowMask, ShadowBytes, 0, ShadowMask.
size(), IRB, ShadowBase);
2509 size_t Begin,
size_t End,
2512 size_t Done = Begin;
2513 for (
size_t i = Begin, j = Begin + 1; i <
End; i = j++) {
2514 if (!ShadowMask[i]) {
2518 uint8_t Val = ShadowBytes[i];
2519 if (!AsanSetShadowFunc[Val])
2523 for (; j < End && ShadowMask[j] && Val == ShadowBytes[j]; ++j) {
2527 copyToShadowInline(ShadowMask, ShadowBytes, Done, i, IRB, ShadowBase);
2535 copyToShadowInline(ShadowMask, ShadowBytes, Done, End, IRB, ShadowBase);
2543 for (
int i = 0;; i++, MaxSize *= 2)
2544 if (LocalStackSize <= MaxSize)
return i;
2548 void FunctionStackPoisoner::copyArgsPassedByValToAllocas() {
2551 const DataLayout &DL = F.getParent()->getDataLayout();
2553 if (Arg.hasByValAttr()) {
2555 unsigned Align = Arg.getParamAlignment();
2556 if (Align == 0) Align = DL.getABITypeAlignment(Ty);
2558 const std::string &Name = Arg.
hasName() ? Arg.getName().str() :
2562 Arg.replaceAllUsesWith(AI);
2564 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
2573 Value *ValueIfFalse) {
2582 Value *FunctionStackPoisoner::createAllocaForLayout(
2591 nullptr,
"MyAlloca");
2600 void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
2603 DynamicAllocaLayout = IRB.
CreateAlloca(IntptrTy,
nullptr);
2608 void FunctionStackPoisoner::processDynamicAllocas() {
2610 assert(DynamicAllocaPoisonCallVec.empty());
2615 for (
const auto &APC : DynamicAllocaPoisonCallVec) {
2618 assert(ASan.isInterestingAlloca(*APC.AI));
2619 assert(!APC.AI->isStaticAlloca());
2622 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
2629 createDynamicAllocasInitStorage();
2630 for (
auto &AI : DynamicAllocaVec)
2631 handleDynamicAllocaCall(AI);
2632 unpoisonDynamicAllocas();
2635 void FunctionStackPoisoner::processStaticAllocas() {
2636 if (AllocaVec.empty()) {
2637 assert(StaticAllocaPoisonCallVec.empty());
2641 int StackMallocIdx = -1;
2643 if (
auto SP = F.getSubprogram())
2653 auto InsBeforeB = InsBefore->
getParent();
2654 assert(InsBeforeB == &F.getEntryBlock());
2655 for (
auto *AI : StaticAllocasToMoveUp)
2656 if (AI->getParent() == InsBeforeB)
2657 AI->moveBefore(InsBefore);
2660 if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
2663 SVD.
reserve(AllocaVec.size());
2666 ASan.getAllocaSizeInBytes(*AI),
2677 size_t MinHeaderSize = ASan.LongSize / 2;
2683 for (
auto &
Desc : SVD)
2687 for (
const auto &APC : StaticAllocaPoisonCallVec) {
2690 assert(ASan.isInterestingAlloca(*APC.AI));
2691 assert(APC.AI->isStaticAlloca());
2694 Desc.LifetimeSize = Desc.Size;
2696 if (
const DILocation *LifetimeLoc = APC.InsBefore->getDebugLoc().get()) {
2697 if (LifetimeLoc->getFile() == FnLoc->getFile())
2698 if (
unsigned Line = LifetimeLoc->getLine())
2699 Desc.Line =
std::min(Desc.Line ? Desc.Line : Line, Line);
2716 DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2717 DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2719 Value *StaticAlloca =
2720 DoDynamicAlloca ?
nullptr : createAllocaForLayout(IRB, L,
false);
2723 Value *LocalStackBase;
2725 if (DoStackMalloc) {
2730 Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
2732 Value *UseAfterReturnIsEnabled =
2738 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2741 Value *FakeStackValue =
2742 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
2746 FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
2749 Value *NoFakeStack =
2752 IRBIf.SetInsertPoint(Term);
2753 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2754 Value *AllocaValue =
2755 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L,
true) : StaticAlloca;
2758 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
2764 DoDynamicAlloca ? createAllocaForLayout(IRB, L,
true) : StaticAlloca;
2768 for (
const auto &Desc : SVD) {
2802 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
2805 copyToShadow(ShadowAfterScope, ShadowAfterScope, IRB, ShadowBase);
2807 if (!StaticAllocaPoisonCallVec.empty()) {
2811 for (
const auto &APC : StaticAllocaPoisonCallVec) {
2818 copyToShadow(ShadowAfterScope,
2819 APC.DoPoison ? ShadowAfterScope : ShadowInScope, Begin, End,
2828 for (
auto Ret : RetVec) {
2833 if (DoStackMalloc) {
2834 assert(StackMallocIdx >= 0);
2851 if (StackMallocIdx <= 4) {
2855 copyToShadow(ShadowAfterReturn, ShadowAfterReturn, IRBPoison,
2857 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
2860 Value *SavedFlagPtr = IRBPoison.CreateLoad(
2861 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
2862 IRBPoison.CreateStore(
2864 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
2867 IRBPoison.CreateCall(
2868 AsanStackFreeFunc[StackMallocIdx],
2873 copyToShadow(ShadowAfterScope, ShadowClean, IRBElse, ShadowBase);
2875 copyToShadow(ShadowAfterScope, ShadowClean, IRBRet, ShadowBase);
2883 void FunctionStackPoisoner::poisonAlloca(
Value *V, uint64_t Size,
2889 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
2890 {AddrArg, SizeArg});
2903 if (
AllocaInst *AI = dyn_cast<AllocaInst>(V))
2905 return ASan.isInterestingAlloca(*AI) ? AI :
nullptr;
2908 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
2909 if (I != AllocaForValue.end())
return I->second;
2912 AllocaForValue[V] =
nullptr;
2916 else if (
PHINode *PN = dyn_cast<PHINode>(V)) {
2917 for (
Value *IncValue : PN->incoming_values()) {
2919 if (IncValue == PN)
continue;
2920 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
2922 if (IncValueAI ==
nullptr || (Res !=
nullptr && IncValueAI != Res))
2927 Res = findAllocaForValue(EP->getPointerOperand());
2929 DEBUG(
dbgs() <<
"Alloca search canceled on unknown instruction: " << *V <<
"\n");
2931 if (Res) AllocaForValue[V] = Res;
2935 void FunctionStackPoisoner::handleDynamicAllocaCall(
AllocaInst *AI) {
2949 const unsigned ElementSize =
2982 IRB.
CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
3001 Value *Addr, uint64_t TypeSize)
const {
3003 if (!ObjSizeVis.
bothKnown(SizeOffset))
return false;
3004 uint64_t Size = SizeOffset.first.getZExtValue();
3005 int64_t
Offset = SizeOffset.second.getSExtValue();
3010 return Offset >= 0 && Size >= uint64_t(Offset) &&
3011 Size - uint64_t(Offset) >= TypeSize / 8;
void setVisibility(VisibilityTypes V)
Pass interface - Implemented by all 'passes'.
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...
Return a value (possibly void), from a function.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
static const char *const kAsanSetShadowPrefix
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. ...
LinkageTypes getLinkage() const
bool replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress, DIBuilder &Builder, bool Deref, int Offset=0)
Replaces llvm.dbg.declare instruction when the alloca it describes is replaced with a new value...
void ReplaceInstWithInst(BasicBlock::InstListType &BIL, BasicBlock::iterator &BI, Instruction *I)
Replace the instruction specified by BI with the instruction specified by I.
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.
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))
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...
VisibilityTypes getVisibility() const
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.
bool isOSBinFormatMachO() const
Tests whether the environment is MachO.
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))
Function * checkSanitizerInterfaceFunction(Constant *FuncOrBitcast)
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
STATISTIC(NumFunctions,"Total number of functions")
void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
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. ...
void setAlignment(unsigned Align)
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
an instruction that atomically checks whether a specified value is in a memory location, and, if it is, stores a new value there.
Maximum length of the test input libFuzzer tries to guess a good value based on the corpus and reports it always prefer smaller inputs during the corpus shuffle When libFuzzer itself reports a bug this exit code will be used If indicates the maximal total time in seconds to run the fuzzer minimizes the provided crash input Use with tries to cleanse the provided crash input to make it contain fewer original bytes Use with exact_artifact_path to specify the output Experimental Use value profile to guide fuzzing Number of jobs to run If min(jobs, NumberOfCpuCores()/2)\" is used.") FUZZER_FLAG_INT(reload
static Constant * getAnon(ArrayRef< Constant * > V, bool Packed=false)
Return an anonymous struct that has the specified elements.
Available for inspection, not emission.
unsigned getNumOperands() const
Return number of MDNode operands.
static const char *const kAsanUnregisterElfGlobalsName
MachineInstrBuilder MachineInstrBuilder &DefMI const MCInstrDesc & Desc
bool isMacOSXVersionLT(unsigned Major, unsigned Minor=0, unsigned Micro=0) const
isMacOSXVersionLT - Comparison function for checking OS X version compatibility, which handles suppor...
Type * getValueType() const
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
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, bool InBounds=false, Optional< unsigned > InRangeIndex=None, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
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))
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
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))
const Function * getParent() const
Return the enclosing method, or null if none.
SmallString< 64 > ComputeASanStackFrameDescription(const SmallVectorImpl< ASanStackVariableDescription > &Vars)
const Instruction & front() const
static cl::opt< bool > ClUseAfterScope("asan-use-after-scope", cl::desc("Check stack-use-after-scope"), cl::Hidden, cl::init(false))
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.
static cl::opt< bool > ClUsePrivateAliasForGlobals("asan-use-private-alias", cl::desc("Use private aliases for global"" variables"), cl::Hidden, cl::init(false))
void reserve(size_type N)
void setAlignment(unsigned Align)
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
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))
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
bool isAllocaPromotable(const AllocaInst *AI)
Return true if this alloca is legal for promotion.
Type * getPointerElementType() const
bool isAndroid() const
Tests whether the target is Android.
bool isOSWindows() const
Tests whether the OS is Windows.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
StringRef getName() const
Return a constant reference to the value's name.
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.
bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1...
static const uint64_t kDefaultShadowScale
bool isMacOSX() const
isMacOSX - Is this a Mac OS X triple.
static const char *const kAsanShadowMemoryDynamicAddress
static const int kAsanStackUseAfterReturnMagic
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
DILocation * get() const
Get the underlying DILocation.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
StringRef getName() const
Get a short "name" for the module.
IntegerType * getInt64Ty()
Fetch the type representing a 64-bit integer.
This is the base class for all instructions that perform data casts.
const APInt & getValue() const
Return the constant as an APInt value reference.
Class to represent struct types.
static const uint64_t kLinuxKasan_ShadowOffset64
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...
A Use represents the edge between a Value definition and its users.
unsigned getNumArgOperands() const
Return the number of call arguments.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
static const char *const kAsanAllocasUnpoison
ObjectFormatType getObjectFormat() const
getFormat - Get the object format for this triple.
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
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
static const uint64_t kIOSSimShadowOffset64
Type * getVoidTy()
Fetch the type representing void.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
bool isOSLinux() const
Tests whether the OS is Linux.
static const char *const kAsanPoisonStackMemoryName
static const uint64_t kSmallX86_64ShadowOffset
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
SmallVector< uint8_t, 64 > GetShadowBytesAfterScope(const SmallVectorImpl< ASanStackVariableDescription > &Vars, const ASanStackFrameLayout &Layout)
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
static const char *const kSanCovGenPrefix
unsigned getAlignment() const
Class to represent array types.
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))
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
getLimitedValue - If the value is smaller than the specified limit, return it, otherwise return the l...
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)
StringRef getSection() const
Get the custom section of this global if it has one.
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static cl::opt< bool > ClOpt("asan-opt", cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true))
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
static const uint64_t kWindowsShadowOffset64
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
ArchType getArch() const
getArch - Get the parsed architecture type of this triple.
An instruction for storing to memory.
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
std::pair< APInt, APInt > SizeOffsetType
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()
size_t size() const
size - Get the array size.
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
static const uint64_t kDefaultShadowOffset32
ConstantInt * getIntN(unsigned N, uint64_t C)
Get a constant N-bit value, zero extended or truncated from a 64-bit value.
Class to represent pointers.
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="")
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
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 cl::opt< bool > ClInstrumentWrites("asan-instrument-writes", cl::desc("instrument write instructions"), cl::Hidden, cl::init(true))
bool hasSection() const
Check if this global has a custom object file section.
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
ExternalWeak linkage description.
Function * declareSanitizerInitFunction(Module &M, StringRef InitName, ArrayRef< Type * > InitArgTypes)
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
bool isiOS() const
Is this an iOS triple.
LoadInst * CreateLoad(Value *Ptr, const char *Name)
static const size_t kNumberOfAccessSizes
static const char *const kAsanGlobalsRegisteredFlagName
initializer< Ty > init(const Ty &Val)
No other Module may specify this COMDAT.
static const char *const kAsanPtrCmp
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.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
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...
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.
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...
This is an important class for using LLVM in a threaded context.
uint64_t getTypeStoreSizeInBits(Type *Ty) const
Returns the maximum number of bits that may be overwritten by storing the specified type; always a mu...
bool isOSBinFormatWasm() const
Tests whether the OS uses the Wasm binary format.
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
This function has undefined behavior.
const Comdat * getComdat() const
This is an important base class in LLVM.
PointerType * getType() const
Overload to return most specific pointer type.
Resume the propagation of an exception.
static const char *const kAsanInitName
static const char *const kAsanStackFreeNameTemplate
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
static const uint64_t kMIPS32_ShadowOffset32
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
static const char *const kAsanOptionDetectUseAfterReturn
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
unsigned getAlignment() const
Return the alignment of the memory that is being allocated by the instruction.
static const uint64_t kFreeBSD_ShadowOffset32
static const uint64_t kAArch64_ShadowOffset64
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
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 isWatchOS() const
Is this an Apple watchOS triple.
bool isUsedWithInAlloca() const
Return true if this alloca is used as an inalloca argument to a call.
This instruction compares its operands according to the predicate given to the constructor.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
static const unsigned End
Value * CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name="")
FunctionPass class - This class is used to implement most global optimizations.
Value * getOperand(unsigned i) const
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)
static cl::opt< bool > ClOptGlobals("asan-opt-globals", cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true))
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
static const uintptr_t kRetiredStackFrameMagic
static Constant * get(StructType *T, ArrayRef< Constant * > V)
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
bool isOSBinFormatCOFF() const
Tests whether the OS uses the COFF binary format.
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
static const char *const kAsanGenPrefix
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
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 > ClRedzoneByvalArgs("asan-redzone-byval-args", cl::desc("Create redzones for byval ""arguments (extra copy ""required)"), cl::Hidden, cl::init(true))
bool isPointerTy() const
True if this is an instance of PointerType.
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
static std::string itostr(int64_t X)
static cl::opt< bool > ClGlobals("asan-globals", cl::desc("Handle global objects"), cl::Hidden, cl::init(true))
static wasm::ValType getType(const TargetRegisterClass *RC)
PointerType * getInt8PtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer to an 8-bit integer value.
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...
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))
Triple - Helper class for working with autoconf configuration names.
static const char *const kAsanRegisterGlobalsName
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
static Constant * getPointerCast(Constant *C, Type *Ty)
Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant expression.
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.
StringRef getString() const
static const uint64_t kDynamicShadowSentinel
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
const MDOperand & getOperand(unsigned I) const
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.
const BasicBlockListType & getBasicBlockList() const
Get the underlying elements of the Function...
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
This is the shared class of boolean and integer constants.
void setSelectionKind(SelectionKind Val)
static const char *const kAsanStackMallocNameTemplate
InstrTy * getInstruction() const
static const char *const kAsanUnpoisonStackMemoryName
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
INITIALIZE_PASS(AddressSanitizerModule,"asan-module","AddressSanitizer: detects use-after-free and out-of-bounds bugs.""ModulePass", false, false) ModulePass *llvm
static StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Evaluate the size and offset of an object pointed to by a Value* statically.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
static CallInst * Create(Value *Func, ArrayRef< Value * > Args, ArrayRef< OperandBundleDef > Bundles=None, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
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)
bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size...
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
Provides information about what library functions are available for the current target.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
INITIALIZE_PASS_BEGIN(AddressSanitizer,"asan","AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false, false) INITIALIZE_PASS_END(AddressSanitizer
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
bool isSwiftError() const
Return true if this value is a swifterror value.
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 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.
const BasicBlock & getEntryBlock() const
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)
BasicBlock * getSuccessor(unsigned idx) const
Return the specified successor.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
SizeOffsetType compute(Value *V)
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
Value * CreateGEP(Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="")
ConstantArray - Constant Array Declarations.
bool hasInitializer() const
Definitions have initializers, declarations don't.
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.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
bool isInlineAsm() const
Check if this call is an inline asm statement.
Value * CreatePointerCast(Value *V, Type *DestTy, const Twine &Name="")
void setMetadata(unsigned KindID, MDNode *MD)
Set a particular kind of metadata attachment.
bool isOSVersionLT(unsigned Major, unsigned Minor=0, unsigned Micro=0) const
isOSVersionLT - Helper function for doing comparisons against version numbers included in the target ...
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
llvm_unreachable("Unknown RegBank!")
static cl::opt< bool > ClSkipPromotableAllocas("asan-skip-promotable-allocas", cl::desc("Do not instrument promotable allocas"), cl::Hidden, cl::init(true))
ThreadLocalMode getThreadLocalMode() const
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
static cl::opt< int > ClDebugMin("asan-debug-min", cl::desc("Debug min inst"), cl::Hidden, cl::init(-1))
NamedMDNode * getNamedMetadata(const Twine &Name) const
Return the first NamedMDNode in the module with the specified name.
static cl::opt< std::string > ClMemoryAccessCallbackPrefix("asan-memory-access-callback-prefix", cl::desc("Prefix for memory access callbacks"), cl::Hidden, cl::init("__asan_"))
bool isOSBinFormatELF() const
Tests whether the OS uses the ELF binary format.
static const uint64_t kMIPS64_ShadowOffset64
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
CallInst * CreateMemCpy(Value *Dst, Value *Src, uint64_t Size, unsigned Align, bool isVolatile=false, MDNode *TBAATag=nullptr, MDNode *TBAAStructTag=nullptr, MDNode *ScopeTag=nullptr, MDNode *NoAliasTag=nullptr)
Create and insert a memcpy between the specified pointers.
void setUnnamedAddr(UnnamedAddr Val)
static IntegerType * getInt32Ty(LLVMContext &C)
static int StackMallocSizeClass(uint64_t LocalStackSize)
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
void copyAttributesFrom(const GlobalVariable *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a GlobalVariable) fro...
static cl::opt< bool > ClDynamicAllocaStack("asan-stack-dynamic-alloca", cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden, cl::init(true))
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
unsigned getPointerSizeInBits(unsigned AS=0) const
Layout pointer size, in bits FIXME: The defaults need to be removed once all of the backends/clients ...
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
CallInst * CreateCall(Value *Callee, ArrayRef< Value * > Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
bool isPS4CPU() const
Tests whether the target is the PS4 CPU.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
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="")
bool hasLocalLinkage() const
const std::string to_string(const T &Value)
static const char *const kAsanUnregisterGlobalsName
iterator_range< df_iterator< T > > depth_first(const T &G)
static const char *const kAsanUnpoisonGlobalsName
iterator_range< op_iterator > arg_operands()
Iteration adapter for range-for loops.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static bool bothKnown(const SizeOffsetType &SizeOffset)
const BasicBlock & front() const
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)
static const char *const kAsanVersionCheckName
static const uint64_t kPPC64_ShadowOffset64
static const unsigned kAllocaRzSize
static cl::opt< bool > ClInstrumentAtomics("asan-instrument-atomics", cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden, cl::init(true))
const Value * getArraySize() const
Get the number of elements allocated.
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)
static const char *const kAsanRegisterImageGlobalsName
DLLStorageClassTypes getDLLStorageClass() const
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
void addDebugInfo(DIGlobalVariableExpression *GV)
Attach a DIGlobalVariableExpression.
FunctionPass * createAddressSanitizerFunctionPass(bool CompileKernel=false, bool Recover=false, bool UseAfterScope=false)
static const char *const kAsanAllocaPoison
static const char *const kAsanHandleNoReturnName
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
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 cl::opt< uint32_t > ClMaxInlinePoisoningSize("asan-max-inline-poisoning-size", cl::desc("Inline shadow poisoning for blocks up to the given size in bytes."), cl::Hidden, cl::init(64))
static 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))
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))
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
ModulePass * createAddressSanitizerModulePass(bool CompileKernel=false, bool Recover=false, bool UseGlobalsGC=true)
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
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.
const BasicBlock * getParent() const
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 isOne() const
This is just a convenience method to make client code smaller for a common case.
GlobalVariable * getGlobalVariable(StringRef Name) const
Look up the specified global variable in the module symbol table.
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))
A wrapper class for inspecting calls to intrinsic functions.
LLVMContext & getContext() const
Get the global data context.
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