40 #define DEBUG_TYPE "sancov"
43 "__sanitizer_cov_trace_pc_indir";
57 "__sanitizer_cov_trace_pc_guard";
59 "__sanitizer_cov_trace_pc_guard_init";
61 "__sanitizer_cov_8bit_counters_init";
67 "sanitizer-coverage-level",
68 cl::desc(
"Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
69 "3: all blocks and critical edges"),
81 cl::desc(
"increments 8-bit counter for every edge"),
86 cl::desc(
"Tracing of CMP and similar instructions"),
90 cl::desc(
"Tracing of DIV instructions"),
94 cl::desc(
"Tracing of GEP instructions"),
99 cl::desc(
"Reduce the number of instrumented blocks"),
106 switch (LegacyCoverageLevel) {
144 class SanitizerCoverageModule :
public ModulePass {
146 SanitizerCoverageModule(
151 bool runOnModule(
Module &M)
override;
154 StringRef getPassName()
const override {
return "SanitizerCoverageModule"; }
162 void InjectCoverageForIndirectCalls(
Function &
F,
172 GlobalVariable *CreateFunctionLocalArrayInSection(
size_t NumElements,
175 void CreateFunctionLocalArrays(
size_t NumGuards,
Function &
F);
177 void CreateInitCallForSection(
Module &M,
const char *InitFunctionName,
185 std::string getSectionName(
const std::string &
Section)
const;
186 std::string getSectionStart(
const std::string &
Section)
const;
187 std::string getSectionEnd(
const std::string &
Section)
const;
189 Function *SanCovTracePC, *SanCovTracePCGuard;
190 Function *SanCovTraceCmpFunction[4];
191 Function *SanCovTraceDivFunction[2];
193 Function *SanCovTraceSwitchFunction;
195 Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *
Int32Ty, *Int32PtrTy,
210 void SanitizerCoverageModule::CreateInitCallForSection(
211 Module &M,
const char *InitFunctionName,
Type *Ty,
217 getSectionStart(Section));
221 nullptr, getSectionEnd(Section));
226 {IRB.CreatePointerCast(SecStart, Ty), IRB.CreatePointerCast(SecEnd, Ty)});
228 if (TargetTriple.supportsCOMDAT()) {
237 bool SanitizerCoverageModule::runOnModule(
Module &M) {
244 FunctionGuardArray =
nullptr;
245 Function8bitCounterArray =
nullptr;
259 SanCovTraceCmpFunction[0] =
268 SanCovTraceCmpFunction[3] =
272 SanCovTraceDivFunction[0] =
275 SanCovTraceDivFunction[1] =
278 SanCovTraceGepFunction =
281 SanCovTraceSwitchFunction =
287 for (
int i = 0; i < 3; i++) {
288 SanCovTraceCmpFunction[i]->
addParamAttr(0, Attribute::ZExt);
289 SanCovTraceCmpFunction[i]->addParamAttr(1, Attribute::ZExt);
291 SanCovTraceDivFunction[0]->addParamAttr(0, Attribute::ZExt);
308 if (FunctionGuardArray)
311 if (Function8bitCounterArray)
371 bool SanitizerCoverageModule::runOnFunction(
Function &
F) {
374 if (F.
getName().
find(
".module_ctor") != std::string::npos)
380 if (F.
getName() ==
"__local_stdio_printf_options" ||
381 F.
getName() ==
"__local_stdio_scanf_options")
399 &getAnalysis<DominatorTreeWrapperPass>(
F).getDomTree();
401 &getAnalysis<PostDominatorTreeWrapperPass>(
F).getPostDomTree();
406 for (
auto &Inst : BB) {
409 if (CS && !
CS.getCalledFunction())
413 if (isa<ICmpInst>(&Inst))
415 if (isa<SwitchInst>(&Inst))
420 if (BO->getOpcode() == Instruction::SDiv ||
421 BO->getOpcode() == Instruction::UDiv)
429 InjectCoverage(F, BlocksToInstrument);
430 InjectCoverageForIndirectCalls(F, IndirCalls);
431 InjectTraceForCmp(F, CmpTraceTargets);
432 InjectTraceForSwitch(F, SwitchTraceTargets);
433 InjectTraceForDiv(F, DivTraceTargets);
434 InjectTraceForGep(F, GepTraceTargets);
438 GlobalVariable *SanitizerCoverageModule::CreateFunctionLocalArrayInSection(
439 size_t NumElements,
Function &F,
Type *Ty,
const char *Section) {
446 Array->setSection(getSectionName(Section));
449 void SanitizerCoverageModule::CreateFunctionLocalArrays(
size_t NumGuards,
452 FunctionGuardArray = CreateFunctionLocalArrayInSection(
455 Function8bitCounterArray = CreateFunctionLocalArrayInSection(
459 bool SanitizerCoverageModule::InjectCoverage(
Function &F,
461 if (AllBlocks.
empty())
return false;
466 CreateFunctionLocalArrays(1, F);
470 CreateFunctionLocalArrays(AllBlocks.
size(),
F);
471 for (
size_t i = 0,
N = AllBlocks.
size(); i <
N; i++)
472 InjectCoverageAtBlock(F, *AllBlocks[i], i);
485 void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
487 if (IndirCalls.
empty())
490 for (
auto I : IndirCalls) {
493 Value *Callee =
CS.getCalledValue();
494 if (isa<InlineAsm>(Callee))
496 IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
504 void SanitizerCoverageModule::InjectTraceForSwitch(
506 for (
auto I : SwitchTraceTargets) {
510 Value *Cond =
SI->getCondition();
512 Int64Ty->getScalarSizeInBits())
518 Int64Ty->getScalarSizeInBits())
519 Cond = IRB.CreateIntCast(Cond, Int64Ty,
false);
520 for (
auto It :
SI->cases()) {
523 Int64Ty->getScalarSizeInBits())
529 return cast<ConstantInt>(
A)->getLimitedValue() <
530 cast<ConstantInt>(
B)->getLimitedValue();
536 "__sancov_gen_cov_switch_values");
537 IRB.CreateCall(SanCovTraceSwitchFunction,
538 {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
543 void SanitizerCoverageModule::InjectTraceForDiv(
545 for (
auto BO : DivTraceTargets) {
547 Value *A1 = BO->getOperand(1);
548 if (isa<ConstantInt>(A1))
continue;
552 int CallbackIdx = TypeSize == 32 ? 0 :
553 TypeSize == 64 ? 1 : -1;
554 if (CallbackIdx < 0)
continue;
556 IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
557 {IRB.CreateIntCast(A1, Ty,
true)});
561 void SanitizerCoverageModule::InjectTraceForGep(
563 for (
auto GEP : GepTraceTargets) {
565 for (
auto I =
GEP->idx_begin();
I !=
GEP->idx_end(); ++
I)
566 if (!isa<ConstantInt>(*
I) && (*I)->getType()->isIntegerTy())
567 IRB.CreateCall(SanCovTraceGepFunction,
568 {IRB.CreateIntCast(*
I, IntptrTy,
true)});
572 void SanitizerCoverageModule::InjectTraceForCmp(
574 for (
auto I : CmpTraceTargets) {
582 int CallbackIdx = TypeSize == 8 ? 0 :
585 TypeSize == 64 ? 3 : -1;
586 if (CallbackIdx < 0)
continue;
588 auto Ty = Type::getIntNTy(*C, TypeSize);
590 SanCovTraceCmpFunction[CallbackIdx],
591 {IRB.CreateIntCast(A0, Ty,
true), IRB.CreateIntCast(A1, Ty,
true)});
603 EntryLoc = DebugLoc::get(
SP->getScopeLine(), 0,
SP);
609 EntryLoc = IP->getDebugLoc();
613 IRB.SetCurrentDebugLocation(EntryLoc);
615 IRB.CreateCall(SanCovTracePC);
616 IRB.CreateCall(EmptyAsm, {});
619 auto GuardPtr = IRB.CreateIntToPtr(
620 IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
621 ConstantInt::get(IntptrTy, Idx * 4)),
623 IRB.CreateCall(SanCovTracePCGuard, GuardPtr);
624 IRB.CreateCall(EmptyAsm, {});
627 auto CounterPtr = IRB.CreateGEP(
628 Function8bitCounterArray,
629 {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
630 auto Load = IRB.CreateLoad(CounterPtr);
631 auto Inc = IRB.CreateAdd(
Load, ConstantInt::get(Int8Ty, 1));
632 auto Store = IRB.CreateStore(Inc, CounterPtr);
633 SetNoSanitizeMetadata(
Load);
634 SetNoSanitizeMetadata(
Store);
639 SanitizerCoverageModule::getSectionName(
const std::string &Section)
const {
640 if (TargetTriple.getObjectFormat() == Triple::COFF)
642 if (TargetTriple.isOSBinFormatMachO())
643 return "__DATA,__" + Section;
648 SanitizerCoverageModule::getSectionStart(
const std::string &Section)
const {
649 if (TargetTriple.isOSBinFormatMachO())
650 return "\1section$start$__DATA$__" + Section;
655 SanitizerCoverageModule::getSectionEnd(
const std::string &Section)
const {
656 if (TargetTriple.isOSBinFormatMachO())
657 return "\1section$end$__DATA$__" + Section;
664 "SanitizerCoverage: TODO."
670 "SanitizerCoverage: TODO."
675 return new SanitizerCoverageModule(Options);
void setVisibility(VisibilityTypes V)
void push_back(const T &Elt)
A parsed version of the target data layout string in and methods for querying it. ...
static const uint64_t SanCtorAndDtorPriority
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
Function * checkSanitizerInterfaceFunction(Constant *FuncOrBitcast)
Constant * getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
adds the attribute to the list of attributes for the given arg.
A Module instance is used to store all the information related to an LLVM module. ...
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
static bool isFullPostDominator(const BasicBlock *BB, const PostDominatorTree *PDT)
static const char *const SanCovGuardsSectionName
Like Internal, but omit from symbol table.
Externally visible function.
static IntegerType * getInt64Ty(LLVMContext &C)
unsigned SplitAllCriticalEdges(Function &F, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions())
Loop over all of the edges in the CFG, breaking critical edges as they are found. ...
static const char *const SanCovTracePCName
static IntegerType * getInt16Ty(LLVMContext &C)
static const char *const SanCovTraceSwitchName
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
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.
static const char *const SanCov8bitCountersInitName
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
static cl::opt< int > ClCoverageLevel("sanitizer-coverage-level", cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, ""3: all blocks and critical edges"), cl::Hidden, cl::init(0))
static const char *const SanCovTraceCmp2
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Constant * getPersonalityFn() const
Get the personality function associated with this function.
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
static const char *const SanCovTraceGep
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
static cl::opt< bool > ClDIVTracing("sanitizer-coverage-trace-divs", cl::desc("Tracing of DIV instructions"), cl::Hidden, cl::init(false))
Class to represent array types.
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
static cl::opt< bool > ClCMPTracing("sanitizer-coverage-trace-compares", cl::desc("Tracing of CMP and similar instructions"), cl::Hidden, cl::init(false))
static const char *const SanCovTracePCGuardName
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
size_t size() const
size - Get the array size.
Interval::succ_iterator succ_end(Interval *I)
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
static const char *const SanCovTracePCIndirName
initializer< Ty > init(const Ty &Val)
static const char *const SanCovTraceCmp1
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.
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...
static const char *const SanCovTraceDiv4
const Comdat * getComdat() const
This is an important base class in LLVM.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
bool hasPersonalityFn() const
Check whether this function has a personality function.
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
Represent the analysis usage information of a pass.
static Type * getVoidTy(LLVMContext &C)
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
Interval::pred_iterator pred_end(Interval *I)
static cl::opt< bool > ClPruneBlocks("sanitizer-coverage-prune-blocks", cl::desc("Reduce the number of instrumented blocks"), cl::Hidden, cl::init(true))
static cl::opt< bool > ClTracePCGuard("sanitizer-coverage-trace-pc-guard", cl::desc("pc tracing with a guard"), cl::Hidden, cl::init(false))
static const char *const SanCovTraceCmp4
bool empty() const
empty - Check if the array is empty.
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
static const char *const SanCovTraceCmp8
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Triple - Helper class for working with autoconf configuration names.
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
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.
Iterator for intrusive lists based on ilist_node.
static const char *const SanCovModuleCtorName
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the generic address space (address sp...
static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT)
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
static const char *const SanCovCountersSectionName
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
enum llvm::SanitizerCoverageOptions::Type CoverageType
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.
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 bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB, const DominatorTree *DT, const PostDominatorTree *PDT, const SanitizerCoverageOptions &Options)
BasicBlock::iterator PrepareToSplitEntryBlock(BasicBlock &BB, BasicBlock::iterator IP)
Instrumentation passes often insert conditional checks into entry blocks.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
DISubprogram * getSubprogram() const
Get the attached subprogram.
bool isIntegerTy() const
True if this is an instance of IntegerType.
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
static cl::opt< bool > ClTracePC("sanitizer-coverage-trace-pc", cl::desc("Experimental pc tracing"), cl::Hidden, cl::init(false))
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
static IntegerType * getInt32Ty(LLVMContext &C)
static cl::opt< bool > ClGEPTracing("sanitizer-coverage-trace-geps", cl::desc("Tracing of GEP instructions"), cl::Hidden, cl::init(false))
static const char *const SanCovTraceDiv8
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 ...
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
ModulePass * createSanitizerCoverageModulePass(const SanitizerCoverageOptions &Options=SanitizerCoverageOptions())
Rename collisions when linking (static functions).
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.
INITIALIZE_PASS_BEGIN(SanitizerCoverageModule,"sancov","SanitizerCoverage: TODO.""ModulePass", false, false) INITIALIZE_PASS_END(SanitizerCoverageModule
static cl::opt< bool > ClInline8bitCounters("sanitizer-coverage-inline-8bit-counters", cl::desc("increments 8-bit counter for every edge"), cl::Hidden, cl::init(false))
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool isAsynchronousEHPersonality(EHPersonality Pers)
Returns true if this personality function catches asynchronous exceptions.
static const char *const SanCovTracePCGuardInitName
LLVM Value Representation.
void initializeSanitizerCoverageModulePass(PassRegistry &)
StringRef - Represent a constant reference to a string, i.e.
Legacy analysis pass which computes a DominatorTree.
void sort(Policy policy, RandomAccessIterator Start, RandomAccessIterator End, const Comparator &Comp=Comparator())
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
unsigned getMDKindID(StringRef Name) const
Return a unique non-zero ID for the specified metadata kind.
static IntegerType * getInt8Ty(LLVMContext &C)
LLVMContext & getContext() const
Get the global data context.