1 //===-- SanitizerCoverage.cpp - coverage instrumentation for sanitizers ---===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // Coverage instrumentation done on LLVM IR level, works with Sanitizers.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/Analysis/EHPersonalities.h"
17 #include "llvm/Analysis/PostDominators.h"
18 #include "llvm/IR/CFG.h"
19 #include "llvm/IR/Constant.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/DebugInfo.h"
22 #include "llvm/IR/Dominators.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/GlobalVariable.h"
25 #include "llvm/IR/IRBuilder.h"
26 #include "llvm/IR/InlineAsm.h"
27 #include "llvm/IR/IntrinsicInst.h"
28 #include "llvm/IR/Intrinsics.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/MDBuilder.h"
31 #include "llvm/IR/Mangler.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/Type.h"
34 #include "llvm/InitializePasses.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/SpecialCaseList.h"
38 #include "llvm/Support/VirtualFileSystem.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Transforms/Instrumentation.h"
41 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
42 #include "llvm/Transforms/Utils/ModuleUtils.h"
46 #define DEBUG_TYPE "sancov"
48 static const char *const SanCovTracePCIndirName =
49 "__sanitizer_cov_trace_pc_indir";
50 static const char *const SanCovTracePCName = "__sanitizer_cov_trace_pc";
51 static const char *const SanCovTraceCmp1 = "__sanitizer_cov_trace_cmp1";
52 static const char *const SanCovTraceCmp2 = "__sanitizer_cov_trace_cmp2";
53 static const char *const SanCovTraceCmp4 = "__sanitizer_cov_trace_cmp4";
54 static const char *const SanCovTraceCmp8 = "__sanitizer_cov_trace_cmp8";
55 static const char *const SanCovTraceConstCmp1 =
56 "__sanitizer_cov_trace_const_cmp1";
57 static const char *const SanCovTraceConstCmp2 =
58 "__sanitizer_cov_trace_const_cmp2";
59 static const char *const SanCovTraceConstCmp4 =
60 "__sanitizer_cov_trace_const_cmp4";
61 static const char *const SanCovTraceConstCmp8 =
62 "__sanitizer_cov_trace_const_cmp8";
63 static const char *const SanCovTraceDiv4 = "__sanitizer_cov_trace_div4";
64 static const char *const SanCovTraceDiv8 = "__sanitizer_cov_trace_div8";
65 static const char *const SanCovTraceGep = "__sanitizer_cov_trace_gep";
66 static const char *const SanCovTraceSwitchName = "__sanitizer_cov_trace_switch";
67 static const char *const SanCovModuleCtorTracePcGuardName =
68 "sancov.module_ctor_trace_pc_guard";
69 static const char *const SanCovModuleCtor8bitCountersName =
70 "sancov.module_ctor_8bit_counters";
71 static const char *const SanCovModuleCtorBoolFlagName =
72 "sancov.module_ctor_bool_flag";
73 static const uint64_t SanCtorAndDtorPriority = 2;
75 static const char *const SanCovTracePCGuardName =
76 "__sanitizer_cov_trace_pc_guard";
77 static const char *const SanCovTracePCGuardInitName =
78 "__sanitizer_cov_trace_pc_guard_init";
79 static const char *const SanCov8bitCountersInitName =
80 "__sanitizer_cov_8bit_counters_init";
81 static const char *const SanCovBoolFlagInitName =
82 "__sanitizer_cov_bool_flag_init";
83 static const char *const SanCovPCsInitName = "__sanitizer_cov_pcs_init";
85 static const char *const SanCovGuardsSectionName = "sancov_guards";
86 static const char *const SanCovCountersSectionName = "sancov_cntrs";
87 static const char *const SanCovBoolFlagSectionName = "sancov_bools";
88 static const char *const SanCovPCsSectionName = "sancov_pcs";
90 static const char *const SanCovLowestStackName = "__sancov_lowest_stack";
92 static cl::opt<int> ClCoverageLevel(
93 "sanitizer-coverage-level",
94 cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
95 "3: all blocks and critical edges"),
96 cl::Hidden, cl::init(0));
98 static cl::opt<bool> ClTracePC("sanitizer-coverage-trace-pc",
99 cl::desc("Experimental pc tracing"), cl::Hidden,
102 static cl::opt<bool> ClTracePCGuard("sanitizer-coverage-trace-pc-guard",
103 cl::desc("pc tracing with a guard"),
104 cl::Hidden, cl::init(false));
106 // If true, we create a global variable that contains PCs of all instrumented
107 // BBs, put this global into a named section, and pass this section's bounds
108 // to __sanitizer_cov_pcs_init.
109 // This way the coverage instrumentation does not need to acquire the PCs
110 // at run-time. Works with trace-pc-guard, inline-8bit-counters, and
112 static cl::opt<bool> ClCreatePCTable("sanitizer-coverage-pc-table",
113 cl::desc("create a static PC table"),
114 cl::Hidden, cl::init(false));
117 ClInline8bitCounters("sanitizer-coverage-inline-8bit-counters",
118 cl::desc("increments 8-bit counter for every edge"),
119 cl::Hidden, cl::init(false));
122 ClInlineBoolFlag("sanitizer-coverage-inline-bool-flag",
123 cl::desc("sets a boolean flag for every edge"), cl::Hidden,
127 ClCMPTracing("sanitizer-coverage-trace-compares",
128 cl::desc("Tracing of CMP and similar instructions"),
129 cl::Hidden, cl::init(false));
131 static cl::opt<bool> ClDIVTracing("sanitizer-coverage-trace-divs",
132 cl::desc("Tracing of DIV instructions"),
133 cl::Hidden, cl::init(false));
135 static cl::opt<bool> ClGEPTracing("sanitizer-coverage-trace-geps",
136 cl::desc("Tracing of GEP instructions"),
137 cl::Hidden, cl::init(false));
140 ClPruneBlocks("sanitizer-coverage-prune-blocks",
141 cl::desc("Reduce the number of instrumented blocks"),
142 cl::Hidden, cl::init(true));
144 static cl::opt<bool> ClStackDepth("sanitizer-coverage-stack-depth",
145 cl::desc("max stack depth tracing"),
146 cl::Hidden, cl::init(false));
150 SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
151 SanitizerCoverageOptions Res;
152 switch (LegacyCoverageLevel) {
154 Res.CoverageType = SanitizerCoverageOptions::SCK_None;
157 Res.CoverageType = SanitizerCoverageOptions::SCK_Function;
160 Res.CoverageType = SanitizerCoverageOptions::SCK_BB;
163 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
166 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
167 Res.IndirectCalls = true;
173 SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
174 // Sets CoverageType and IndirectCalls.
175 SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
176 Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
177 Options.IndirectCalls |= CLOpts.IndirectCalls;
178 Options.TraceCmp |= ClCMPTracing;
179 Options.TraceDiv |= ClDIVTracing;
180 Options.TraceGep |= ClGEPTracing;
181 Options.TracePC |= ClTracePC;
182 Options.TracePCGuard |= ClTracePCGuard;
183 Options.Inline8bitCounters |= ClInline8bitCounters;
184 Options.InlineBoolFlag |= ClInlineBoolFlag;
185 Options.PCTable |= ClCreatePCTable;
186 Options.NoPrune |= !ClPruneBlocks;
187 Options.StackDepth |= ClStackDepth;
188 if (!Options.TracePCGuard && !Options.TracePC &&
189 !Options.Inline8bitCounters && !Options.StackDepth &&
190 !Options.InlineBoolFlag)
191 Options.TracePCGuard = true; // TracePCGuard is default.
195 using DomTreeCallback = function_ref<const DominatorTree *(Function &F)>;
196 using PostDomTreeCallback =
197 function_ref<const PostDominatorTree *(Function &F)>;
199 class ModuleSanitizerCoverage {
201 ModuleSanitizerCoverage(
202 const SanitizerCoverageOptions &Options = SanitizerCoverageOptions(),
203 const SpecialCaseList *Allowlist = nullptr,
204 const SpecialCaseList *Blocklist = nullptr)
205 : Options(OverrideFromCL(Options)), Allowlist(Allowlist),
206 Blocklist(Blocklist) {}
207 bool instrumentModule(Module &M, DomTreeCallback DTCallback,
208 PostDomTreeCallback PDTCallback);
211 void instrumentFunction(Function &F, DomTreeCallback DTCallback,
212 PostDomTreeCallback PDTCallback);
213 void InjectCoverageForIndirectCalls(Function &F,
214 ArrayRef<Instruction *> IndirCalls);
215 void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
216 void InjectTraceForDiv(Function &F,
217 ArrayRef<BinaryOperator *> DivTraceTargets);
218 void InjectTraceForGep(Function &F,
219 ArrayRef<GetElementPtrInst *> GepTraceTargets);
220 void InjectTraceForSwitch(Function &F,
221 ArrayRef<Instruction *> SwitchTraceTargets);
222 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks,
223 bool IsLeafFunc = true);
224 GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
225 Function &F, Type *Ty,
226 const char *Section);
227 GlobalVariable *CreatePCArray(Function &F, ArrayRef<BasicBlock *> AllBlocks);
228 void CreateFunctionLocalArrays(Function &F, ArrayRef<BasicBlock *> AllBlocks);
229 void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx,
230 bool IsLeafFunc = true);
231 Function *CreateInitCallsForSections(Module &M, const char *CtorName,
232 const char *InitFunctionName, Type *Ty,
233 const char *Section);
234 std::pair<Value *, Value *> CreateSecStartEnd(Module &M, const char *Section,
237 void SetNoSanitizeMetadata(Instruction *I) {
238 I->setMetadata(I->getModule()->getMDKindID("nosanitize"),
239 MDNode::get(*C, None));
242 std::string getSectionName(const std::string &Section) const;
243 std::string getSectionStart(const std::string &Section) const;
244 std::string getSectionEnd(const std::string &Section) const;
245 FunctionCallee SanCovTracePCIndir;
246 FunctionCallee SanCovTracePC, SanCovTracePCGuard;
247 FunctionCallee SanCovTraceCmpFunction[4];
248 FunctionCallee SanCovTraceConstCmpFunction[4];
249 FunctionCallee SanCovTraceDivFunction[2];
250 FunctionCallee SanCovTraceGepFunction;
251 FunctionCallee SanCovTraceSwitchFunction;
252 GlobalVariable *SanCovLowestStack;
253 Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty, *Int32PtrTy,
254 *Int16Ty, *Int8Ty, *Int8PtrTy, *Int1Ty, *Int1PtrTy;
256 std::string CurModuleUniqueId;
259 const DataLayout *DL;
261 GlobalVariable *FunctionGuardArray; // for trace-pc-guard.
262 GlobalVariable *Function8bitCounterArray; // for inline-8bit-counters.
263 GlobalVariable *FunctionBoolArray; // for inline-bool-flag.
264 GlobalVariable *FunctionPCsArray; // for pc-table.
265 SmallVector<GlobalValue *, 20> GlobalsToAppendToUsed;
266 SmallVector<GlobalValue *, 20> GlobalsToAppendToCompilerUsed;
268 SanitizerCoverageOptions Options;
270 const SpecialCaseList *Allowlist;
271 const SpecialCaseList *Blocklist;
274 class ModuleSanitizerCoverageLegacyPass : public ModulePass {
276 ModuleSanitizerCoverageLegacyPass(
277 const SanitizerCoverageOptions &Options = SanitizerCoverageOptions(),
278 const std::vector<std::string> &AllowlistFiles =
279 std::vector<std::string>(),
280 const std::vector<std::string> &BlocklistFiles =
281 std::vector<std::string>())
282 : ModulePass(ID), Options(Options) {
283 if (AllowlistFiles.size() > 0)
284 Allowlist = SpecialCaseList::createOrDie(AllowlistFiles,
285 *vfs::getRealFileSystem());
286 if (BlocklistFiles.size() > 0)
287 Blocklist = SpecialCaseList::createOrDie(BlocklistFiles,
288 *vfs::getRealFileSystem());
289 initializeModuleSanitizerCoverageLegacyPassPass(
290 *PassRegistry::getPassRegistry());
292 bool runOnModule(Module &M) override {
293 ModuleSanitizerCoverage ModuleSancov(Options, Allowlist.get(),
295 auto DTCallback = [this](Function &F) -> const DominatorTree * {
296 return &this->getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
298 auto PDTCallback = [this](Function &F) -> const PostDominatorTree * {
299 return &this->getAnalysis<PostDominatorTreeWrapperPass>(F)
302 return ModuleSancov.instrumentModule(M, DTCallback, PDTCallback);
305 static char ID; // Pass identification, replacement for typeid
306 StringRef getPassName() const override { return "ModuleSanitizerCoverage"; }
308 void getAnalysisUsage(AnalysisUsage &AU) const override {
309 AU.addRequired<DominatorTreeWrapperPass>();
310 AU.addRequired<PostDominatorTreeWrapperPass>();
314 SanitizerCoverageOptions Options;
316 std::unique_ptr<SpecialCaseList> Allowlist;
317 std::unique_ptr<SpecialCaseList> Blocklist;
322 PreservedAnalyses ModuleSanitizerCoveragePass::run(Module &M,
323 ModuleAnalysisManager &MAM) {
324 ModuleSanitizerCoverage ModuleSancov(Options, Allowlist.get(),
326 auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
327 auto DTCallback = [&FAM](Function &F) -> const DominatorTree * {
328 return &FAM.getResult<DominatorTreeAnalysis>(F);
330 auto PDTCallback = [&FAM](Function &F) -> const PostDominatorTree * {
331 return &FAM.getResult<PostDominatorTreeAnalysis>(F);
333 if (ModuleSancov.instrumentModule(M, DTCallback, PDTCallback))
334 return PreservedAnalyses::none();
335 return PreservedAnalyses::all();
338 std::pair<Value *, Value *>
339 ModuleSanitizerCoverage::CreateSecStartEnd(Module &M, const char *Section,
341 GlobalVariable *SecStart =
342 new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage, nullptr,
343 getSectionStart(Section));
344 SecStart->setVisibility(GlobalValue::HiddenVisibility);
345 GlobalVariable *SecEnd =
346 new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage,
347 nullptr, getSectionEnd(Section));
348 SecEnd->setVisibility(GlobalValue::HiddenVisibility);
349 IRBuilder<> IRB(M.getContext());
350 Value *SecEndPtr = IRB.CreatePointerCast(SecEnd, Ty);
351 if (!TargetTriple.isOSBinFormatCOFF())
352 return std::make_pair(IRB.CreatePointerCast(SecStart, Ty), SecEndPtr);
354 // Account for the fact that on windows-msvc __start_* symbols actually
355 // point to a uint64_t before the start of the array.
356 auto SecStartI8Ptr = IRB.CreatePointerCast(SecStart, Int8PtrTy);
357 auto GEP = IRB.CreateGEP(Int8Ty, SecStartI8Ptr,
358 ConstantInt::get(IntptrTy, sizeof(uint64_t)));
359 return std::make_pair(IRB.CreatePointerCast(GEP, Ty), SecEndPtr);
362 Function *ModuleSanitizerCoverage::CreateInitCallsForSections(
363 Module &M, const char *CtorName, const char *InitFunctionName, Type *Ty,
364 const char *Section) {
365 auto SecStartEnd = CreateSecStartEnd(M, Section, Ty);
366 auto SecStart = SecStartEnd.first;
367 auto SecEnd = SecStartEnd.second;
369 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
370 M, CtorName, InitFunctionName, {Ty, Ty}, {SecStart, SecEnd});
371 assert(CtorFunc->getName() == CtorName);
373 if (TargetTriple.supportsCOMDAT()) {
374 // Use comdat to dedup CtorFunc.
375 CtorFunc->setComdat(M.getOrInsertComdat(CtorName));
376 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
378 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
381 if (TargetTriple.isOSBinFormatCOFF()) {
382 // In COFF files, if the contructors are set as COMDAT (they are because
383 // COFF supports COMDAT) and the linker flag /OPT:REF (strip unreferenced
384 // functions and data) is used, the constructors get stripped. To prevent
385 // this, give the constructors weak ODR linkage and ensure the linker knows
386 // to include the sancov constructor. This way the linker can deduplicate
387 // the constructors but always leave one copy.
388 CtorFunc->setLinkage(GlobalValue::WeakODRLinkage);
389 appendToUsed(M, CtorFunc);
394 bool ModuleSanitizerCoverage::instrumentModule(
395 Module &M, DomTreeCallback DTCallback, PostDomTreeCallback PDTCallback) {
396 if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
399 !Allowlist->inSection("coverage", "src", M.getSourceFileName()))
402 Blocklist->inSection("coverage", "src", M.getSourceFileName()))
404 C = &(M.getContext());
405 DL = &M.getDataLayout();
407 CurModuleUniqueId = getUniqueModuleId(CurModule);
408 TargetTriple = Triple(M.getTargetTriple());
409 FunctionGuardArray = nullptr;
410 Function8bitCounterArray = nullptr;
411 FunctionBoolArray = nullptr;
412 FunctionPCsArray = nullptr;
413 IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
414 IntptrPtrTy = PointerType::getUnqual(IntptrTy);
415 Type *VoidTy = Type::getVoidTy(*C);
417 Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
418 Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
419 Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
420 Int1PtrTy = PointerType::getUnqual(IRB.getInt1Ty());
421 Int64Ty = IRB.getInt64Ty();
422 Int32Ty = IRB.getInt32Ty();
423 Int16Ty = IRB.getInt16Ty();
424 Int8Ty = IRB.getInt8Ty();
425 Int1Ty = IRB.getInt1Ty();
428 M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy);
429 // Make sure smaller parameters are zero-extended to i64 as required by the
431 AttributeList SanCovTraceCmpZeroExtAL;
432 if (TargetTriple.getArch() == Triple::x86_64) {
433 SanCovTraceCmpZeroExtAL =
434 SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 0, Attribute::ZExt);
435 SanCovTraceCmpZeroExtAL =
436 SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 1, Attribute::ZExt);
439 SanCovTraceCmpFunction[0] =
440 M.getOrInsertFunction(SanCovTraceCmp1, SanCovTraceCmpZeroExtAL, VoidTy,
441 IRB.getInt8Ty(), IRB.getInt8Ty());
442 SanCovTraceCmpFunction[1] =
443 M.getOrInsertFunction(SanCovTraceCmp2, SanCovTraceCmpZeroExtAL, VoidTy,
444 IRB.getInt16Ty(), IRB.getInt16Ty());
445 SanCovTraceCmpFunction[2] =
446 M.getOrInsertFunction(SanCovTraceCmp4, SanCovTraceCmpZeroExtAL, VoidTy,
447 IRB.getInt32Ty(), IRB.getInt32Ty());
448 SanCovTraceCmpFunction[3] =
449 M.getOrInsertFunction(SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty);
451 SanCovTraceConstCmpFunction[0] = M.getOrInsertFunction(
452 SanCovTraceConstCmp1, SanCovTraceCmpZeroExtAL, VoidTy, Int8Ty, Int8Ty);
453 SanCovTraceConstCmpFunction[1] = M.getOrInsertFunction(
454 SanCovTraceConstCmp2, SanCovTraceCmpZeroExtAL, VoidTy, Int16Ty, Int16Ty);
455 SanCovTraceConstCmpFunction[2] = M.getOrInsertFunction(
456 SanCovTraceConstCmp4, SanCovTraceCmpZeroExtAL, VoidTy, Int32Ty, Int32Ty);
457 SanCovTraceConstCmpFunction[3] =
458 M.getOrInsertFunction(SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty);
462 if (TargetTriple.getArch() == Triple::x86_64)
463 AL = AL.addParamAttribute(*C, 0, Attribute::ZExt);
464 SanCovTraceDivFunction[0] =
465 M.getOrInsertFunction(SanCovTraceDiv4, AL, VoidTy, IRB.getInt32Ty());
467 SanCovTraceDivFunction[1] =
468 M.getOrInsertFunction(SanCovTraceDiv8, VoidTy, Int64Ty);
469 SanCovTraceGepFunction =
470 M.getOrInsertFunction(SanCovTraceGep, VoidTy, IntptrTy);
471 SanCovTraceSwitchFunction =
472 M.getOrInsertFunction(SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy);
474 Constant *SanCovLowestStackConstant =
475 M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy);
476 SanCovLowestStack = dyn_cast<GlobalVariable>(SanCovLowestStackConstant);
477 if (!SanCovLowestStack) {
478 C->emitError(StringRef("'") + SanCovLowestStackName +
479 "' should not be declared by the user");
482 SanCovLowestStack->setThreadLocalMode(
483 GlobalValue::ThreadLocalMode::InitialExecTLSModel);
484 if (Options.StackDepth && !SanCovLowestStack->isDeclaration())
485 SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy));
487 SanCovTracePC = M.getOrInsertFunction(SanCovTracePCName, VoidTy);
489 M.getOrInsertFunction(SanCovTracePCGuardName, VoidTy, Int32PtrTy);
492 instrumentFunction(F, DTCallback, PDTCallback);
494 Function *Ctor = nullptr;
496 if (FunctionGuardArray)
497 Ctor = CreateInitCallsForSections(M, SanCovModuleCtorTracePcGuardName,
498 SanCovTracePCGuardInitName, Int32PtrTy,
499 SanCovGuardsSectionName);
500 if (Function8bitCounterArray)
501 Ctor = CreateInitCallsForSections(M, SanCovModuleCtor8bitCountersName,
502 SanCov8bitCountersInitName, Int8PtrTy,
503 SanCovCountersSectionName);
504 if (FunctionBoolArray) {
505 Ctor = CreateInitCallsForSections(M, SanCovModuleCtorBoolFlagName,
506 SanCovBoolFlagInitName, Int1PtrTy,
507 SanCovBoolFlagSectionName);
509 if (Ctor && Options.PCTable) {
510 auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, IntptrPtrTy);
511 FunctionCallee InitFunction = declareSanitizerInitFunction(
512 M, SanCovPCsInitName, {IntptrPtrTy, IntptrPtrTy});
513 IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
514 IRBCtor.CreateCall(InitFunction, {SecStartEnd.first, SecStartEnd.second});
516 // We don't reference these arrays directly in any of our runtime functions,
517 // so we need to prevent them from being dead stripped.
518 if (TargetTriple.isOSBinFormatMachO())
519 appendToUsed(M, GlobalsToAppendToUsed);
520 appendToCompilerUsed(M, GlobalsToAppendToCompilerUsed);
524 // True if block has successors and it dominates all of them.
525 static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
526 if (succ_begin(BB) == succ_end(BB))
529 for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
530 if (!DT->dominates(BB, SUCC))
537 // True if block has predecessors and it postdominates all of them.
538 static bool isFullPostDominator(const BasicBlock *BB,
539 const PostDominatorTree *PDT) {
540 if (pred_begin(BB) == pred_end(BB))
543 for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) {
544 if (!PDT->dominates(BB, PRED))
551 static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
552 const DominatorTree *DT,
553 const PostDominatorTree *PDT,
554 const SanitizerCoverageOptions &Options) {
555 // Don't insert coverage for blocks containing nothing but unreachable: we
556 // will never call __sanitizer_cov() for them, so counting them in
557 // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
558 // percentage. Also, unreachable instructions frequently have no debug
560 if (isa<UnreachableInst>(BB->getFirstNonPHIOrDbgOrLifetime()))
563 // Don't insert coverage into blocks without a valid insertion point
564 // (catchswitch blocks).
565 if (BB->getFirstInsertionPt() == BB->end())
568 if (Options.NoPrune || &F.getEntryBlock() == BB)
571 if (Options.CoverageType == SanitizerCoverageOptions::SCK_Function &&
572 &F.getEntryBlock() != BB)
575 // Do not instrument full dominators, or full post-dominators with multiple
577 return !isFullDominator(BB, DT)
578 && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
582 // Returns true iff From->To is a backedge.
583 // A twist here is that we treat From->To as a backedge if
584 // * To dominates From or
585 // * To->UniqueSuccessor dominates From
586 static bool IsBackEdge(BasicBlock *From, BasicBlock *To,
587 const DominatorTree *DT) {
588 if (DT->dominates(To, From))
590 if (auto Next = To->getUniqueSuccessor())
591 if (DT->dominates(Next, From))
596 // Prunes uninteresting Cmp instrumentation:
597 // * CMP instructions that feed into loop backedge branch.
599 // Note that Cmp pruning is controlled by the same flag as the
601 static bool IsInterestingCmp(ICmpInst *CMP, const DominatorTree *DT,
602 const SanitizerCoverageOptions &Options) {
603 if (!Options.NoPrune)
604 if (CMP->hasOneUse())
605 if (auto BR = dyn_cast<BranchInst>(CMP->user_back()))
606 for (BasicBlock *B : BR->successors())
607 if (IsBackEdge(BR->getParent(), B, DT))
612 void ModuleSanitizerCoverage::instrumentFunction(
613 Function &F, DomTreeCallback DTCallback, PostDomTreeCallback PDTCallback) {
616 if (F.getName().find(".module_ctor") != std::string::npos)
617 return; // Should not instrument sanitizer init functions.
618 if (F.getName().startswith("__sanitizer_"))
619 return; // Don't instrument __sanitizer_* callbacks.
620 // Don't touch available_externally functions, their actual body is elewhere.
621 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage)
623 // Don't instrument MSVC CRT configuration helpers. They may run before normal
625 if (F.getName() == "__local_stdio_printf_options" ||
626 F.getName() == "__local_stdio_scanf_options")
628 if (isa<UnreachableInst>(F.getEntryBlock().getTerminator()))
630 // Don't instrument functions using SEH for now. Splitting basic blocks like
631 // we do for coverage breaks WinEHPrepare.
632 // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
633 if (F.hasPersonalityFn() &&
634 isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
636 if (Allowlist && !Allowlist->inSection("coverage", "fun", F.getName()))
638 if (Blocklist && Blocklist->inSection("coverage", "fun", F.getName()))
640 if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
641 SplitAllCriticalEdges(F, CriticalEdgeSplittingOptions().setIgnoreUnreachableDests());
642 SmallVector<Instruction *, 8> IndirCalls;
643 SmallVector<BasicBlock *, 16> BlocksToInstrument;
644 SmallVector<Instruction *, 8> CmpTraceTargets;
645 SmallVector<Instruction *, 8> SwitchTraceTargets;
646 SmallVector<BinaryOperator *, 8> DivTraceTargets;
647 SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
649 const DominatorTree *DT = DTCallback(F);
650 const PostDominatorTree *PDT = PDTCallback(F);
651 bool IsLeafFunc = true;
654 if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
655 BlocksToInstrument.push_back(&BB);
656 for (auto &Inst : BB) {
657 if (Options.IndirectCalls) {
658 CallBase *CB = dyn_cast<CallBase>(&Inst);
659 if (CB && !CB->getCalledFunction())
660 IndirCalls.push_back(&Inst);
662 if (Options.TraceCmp) {
663 if (ICmpInst *CMP = dyn_cast<ICmpInst>(&Inst))
664 if (IsInterestingCmp(CMP, DT, Options))
665 CmpTraceTargets.push_back(&Inst);
666 if (isa<SwitchInst>(&Inst))
667 SwitchTraceTargets.push_back(&Inst);
669 if (Options.TraceDiv)
670 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
671 if (BO->getOpcode() == Instruction::SDiv ||
672 BO->getOpcode() == Instruction::UDiv)
673 DivTraceTargets.push_back(BO);
674 if (Options.TraceGep)
675 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
676 GepTraceTargets.push_back(GEP);
677 if (Options.StackDepth)
678 if (isa<InvokeInst>(Inst) ||
679 (isa<CallInst>(Inst) && !isa<IntrinsicInst>(Inst)))
684 InjectCoverage(F, BlocksToInstrument, IsLeafFunc);
685 InjectCoverageForIndirectCalls(F, IndirCalls);
686 InjectTraceForCmp(F, CmpTraceTargets);
687 InjectTraceForSwitch(F, SwitchTraceTargets);
688 InjectTraceForDiv(F, DivTraceTargets);
689 InjectTraceForGep(F, GepTraceTargets);
692 GlobalVariable *ModuleSanitizerCoverage::CreateFunctionLocalArrayInSection(
693 size_t NumElements, Function &F, Type *Ty, const char *Section) {
694 ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
695 auto Array = new GlobalVariable(
696 *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
697 Constant::getNullValue(ArrayTy), "__sancov_gen_");
699 if (TargetTriple.supportsCOMDAT() && !F.isInterposable())
701 GetOrCreateFunctionComdat(F, TargetTriple, CurModuleUniqueId))
702 Array->setComdat(Comdat);
703 Array->setSection(getSectionName(Section));
704 Array->setAlignment(Align(DL->getTypeStoreSize(Ty).getFixedSize()));
705 GlobalsToAppendToUsed.push_back(Array);
706 GlobalsToAppendToCompilerUsed.push_back(Array);
707 MDNode *MD = MDNode::get(F.getContext(), ValueAsMetadata::get(&F));
708 Array->addMetadata(LLVMContext::MD_associated, *MD);
714 ModuleSanitizerCoverage::CreatePCArray(Function &F,
715 ArrayRef<BasicBlock *> AllBlocks) {
716 size_t N = AllBlocks.size();
718 SmallVector<Constant *, 32> PCs;
719 IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
720 for (size_t i = 0; i < N; i++) {
721 if (&F.getEntryBlock() == AllBlocks[i]) {
722 PCs.push_back((Constant *)IRB.CreatePointerCast(&F, IntptrPtrTy));
723 PCs.push_back((Constant *)IRB.CreateIntToPtr(
724 ConstantInt::get(IntptrTy, 1), IntptrPtrTy));
726 PCs.push_back((Constant *)IRB.CreatePointerCast(
727 BlockAddress::get(AllBlocks[i]), IntptrPtrTy));
728 PCs.push_back((Constant *)IRB.CreateIntToPtr(
729 ConstantInt::get(IntptrTy, 0), IntptrPtrTy));
732 auto *PCArray = CreateFunctionLocalArrayInSection(N * 2, F, IntptrPtrTy,
733 SanCovPCsSectionName);
734 PCArray->setInitializer(
735 ConstantArray::get(ArrayType::get(IntptrPtrTy, N * 2), PCs));
736 PCArray->setConstant(true);
741 void ModuleSanitizerCoverage::CreateFunctionLocalArrays(
742 Function &F, ArrayRef<BasicBlock *> AllBlocks) {
743 if (Options.TracePCGuard)
744 FunctionGuardArray = CreateFunctionLocalArrayInSection(
745 AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName);
747 if (Options.Inline8bitCounters)
748 Function8bitCounterArray = CreateFunctionLocalArrayInSection(
749 AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName);
750 if (Options.InlineBoolFlag)
751 FunctionBoolArray = CreateFunctionLocalArrayInSection(
752 AllBlocks.size(), F, Int1Ty, SanCovBoolFlagSectionName);
755 FunctionPCsArray = CreatePCArray(F, AllBlocks);
758 bool ModuleSanitizerCoverage::InjectCoverage(Function &F,
759 ArrayRef<BasicBlock *> AllBlocks,
761 if (AllBlocks.empty()) return false;
762 CreateFunctionLocalArrays(F, AllBlocks);
763 for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
764 InjectCoverageAtBlock(F, *AllBlocks[i], i, IsLeafFunc);
768 // On every indirect call we call a run-time function
769 // __sanitizer_cov_indir_call* with two parameters:
771 // - global cache array that contains CacheSize pointers (zero-initialized).
772 // The cache is used to speed up recording the caller-callee pairs.
773 // The address of the caller is passed implicitly via caller PC.
774 // CacheSize is encoded in the name of the run-time function.
775 void ModuleSanitizerCoverage::InjectCoverageForIndirectCalls(
776 Function &F, ArrayRef<Instruction *> IndirCalls) {
777 if (IndirCalls.empty())
779 assert(Options.TracePC || Options.TracePCGuard ||
780 Options.Inline8bitCounters || Options.InlineBoolFlag);
781 for (auto I : IndirCalls) {
783 CallBase &CB = cast<CallBase>(*I);
784 Value *Callee = CB.getCalledOperand();
785 if (isa<InlineAsm>(Callee))
787 IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
791 // For every switch statement we insert a call:
792 // __sanitizer_cov_trace_switch(CondValue,
793 // {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
795 void ModuleSanitizerCoverage::InjectTraceForSwitch(
796 Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
797 for (auto I : SwitchTraceTargets) {
798 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
800 SmallVector<Constant *, 16> Initializers;
801 Value *Cond = SI->getCondition();
802 if (Cond->getType()->getScalarSizeInBits() >
803 Int64Ty->getScalarSizeInBits())
805 Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
806 Initializers.push_back(
807 ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
808 if (Cond->getType()->getScalarSizeInBits() <
809 Int64Ty->getScalarSizeInBits())
810 Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
811 for (auto It : SI->cases()) {
812 Constant *C = It.getCaseValue();
813 if (C->getType()->getScalarSizeInBits() <
814 Int64Ty->getScalarSizeInBits())
815 C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
816 Initializers.push_back(C);
818 llvm::sort(Initializers.begin() + 2, Initializers.end(),
819 [](const Constant *A, const Constant *B) {
820 return cast<ConstantInt>(A)->getLimitedValue() <
821 cast<ConstantInt>(B)->getLimitedValue();
823 ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
824 GlobalVariable *GV = new GlobalVariable(
825 *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
826 ConstantArray::get(ArrayOfInt64Ty, Initializers),
827 "__sancov_gen_cov_switch_values");
828 IRB.CreateCall(SanCovTraceSwitchFunction,
829 {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
834 void ModuleSanitizerCoverage::InjectTraceForDiv(
835 Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
836 for (auto BO : DivTraceTargets) {
838 Value *A1 = BO->getOperand(1);
839 if (isa<ConstantInt>(A1)) continue;
840 if (!A1->getType()->isIntegerTy())
842 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
843 int CallbackIdx = TypeSize == 32 ? 0 :
844 TypeSize == 64 ? 1 : -1;
845 if (CallbackIdx < 0) continue;
846 auto Ty = Type::getIntNTy(*C, TypeSize);
847 IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
848 {IRB.CreateIntCast(A1, Ty, true)});
852 void ModuleSanitizerCoverage::InjectTraceForGep(
853 Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
854 for (auto GEP : GepTraceTargets) {
855 IRBuilder<> IRB(GEP);
856 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
857 if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy())
858 IRB.CreateCall(SanCovTraceGepFunction,
859 {IRB.CreateIntCast(*I, IntptrTy, true)});
863 void ModuleSanitizerCoverage::InjectTraceForCmp(
864 Function &, ArrayRef<Instruction *> CmpTraceTargets) {
865 for (auto I : CmpTraceTargets) {
866 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
867 IRBuilder<> IRB(ICMP);
868 Value *A0 = ICMP->getOperand(0);
869 Value *A1 = ICMP->getOperand(1);
870 if (!A0->getType()->isIntegerTy())
872 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
873 int CallbackIdx = TypeSize == 8 ? 0 :
876 TypeSize == 64 ? 3 : -1;
877 if (CallbackIdx < 0) continue;
878 // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
879 auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx];
880 bool FirstIsConst = isa<ConstantInt>(A0);
881 bool SecondIsConst = isa<ConstantInt>(A1);
882 // If both are const, then we don't need such a comparison.
883 if (FirstIsConst && SecondIsConst) continue;
884 // If only one is const, then make it the first callback argument.
885 if (FirstIsConst || SecondIsConst) {
886 CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx];
891 auto Ty = Type::getIntNTy(*C, TypeSize);
892 IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true),
893 IRB.CreateIntCast(A1, Ty, true)});
898 void ModuleSanitizerCoverage::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
901 BasicBlock::iterator IP = BB.getFirstInsertionPt();
902 bool IsEntryBB = &BB == &F.getEntryBlock();
905 if (auto SP = F.getSubprogram())
906 EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
907 // Keep static allocas and llvm.localescape calls in the entry block. Even
908 // if we aren't splitting the block, it's nice for allocas to be before
910 IP = PrepareToSplitEntryBlock(BB, IP);
912 EntryLoc = IP->getDebugLoc();
915 IRBuilder<> IRB(&*IP);
916 IRB.SetCurrentDebugLocation(EntryLoc);
917 if (Options.TracePC) {
918 IRB.CreateCall(SanCovTracePC)
919 ->setCannotMerge(); // gets the PC using GET_CALLER_PC.
921 if (Options.TracePCGuard) {
922 auto GuardPtr = IRB.CreateIntToPtr(
923 IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
924 ConstantInt::get(IntptrTy, Idx * 4)),
926 IRB.CreateCall(SanCovTracePCGuard, GuardPtr)->setCannotMerge();
928 if (Options.Inline8bitCounters) {
929 auto CounterPtr = IRB.CreateGEP(
930 Function8bitCounterArray->getValueType(), Function8bitCounterArray,
931 {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
932 auto Load = IRB.CreateLoad(Int8Ty, CounterPtr);
933 auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
934 auto Store = IRB.CreateStore(Inc, CounterPtr);
935 SetNoSanitizeMetadata(Load);
936 SetNoSanitizeMetadata(Store);
938 if (Options.InlineBoolFlag) {
939 auto FlagPtr = IRB.CreateGEP(
940 FunctionBoolArray->getValueType(), FunctionBoolArray,
941 {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
942 auto Load = IRB.CreateLoad(Int1Ty, FlagPtr);
944 SplitBlockAndInsertIfThen(IRB.CreateIsNull(Load), &*IP, false);
945 IRBuilder<> ThenIRB(ThenTerm);
946 auto Store = ThenIRB.CreateStore(ConstantInt::getTrue(Int1Ty), FlagPtr);
947 SetNoSanitizeMetadata(Load);
948 SetNoSanitizeMetadata(Store);
950 if (Options.StackDepth && IsEntryBB && !IsLeafFunc) {
951 // Check stack depth. If it's the deepest so far, record it.
952 Module *M = F.getParent();
953 Function *GetFrameAddr = Intrinsic::getDeclaration(
954 M, Intrinsic::frameaddress,
955 IRB.getInt8PtrTy(M->getDataLayout().getAllocaAddrSpace()));
957 IRB.CreateCall(GetFrameAddr, {Constant::getNullValue(Int32Ty)});
958 auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy);
959 auto LowestStack = IRB.CreateLoad(IntptrTy, SanCovLowestStack);
960 auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack);
961 auto ThenTerm = SplitBlockAndInsertIfThen(IsStackLower, &*IP, false);
962 IRBuilder<> ThenIRB(ThenTerm);
963 auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack);
964 SetNoSanitizeMetadata(LowestStack);
965 SetNoSanitizeMetadata(Store);
970 ModuleSanitizerCoverage::getSectionName(const std::string &Section) const {
971 if (TargetTriple.isOSBinFormatCOFF()) {
972 if (Section == SanCovCountersSectionName)
974 if (Section == SanCovBoolFlagSectionName)
976 if (Section == SanCovPCsSectionName)
978 return ".SCOV$GM"; // For SanCovGuardsSectionName.
980 if (TargetTriple.isOSBinFormatMachO())
981 return "__DATA,__" + Section;
982 return "__" + Section;
986 ModuleSanitizerCoverage::getSectionStart(const std::string &Section) const {
987 if (TargetTriple.isOSBinFormatMachO())
988 return "\1section$start$__DATA$__" + Section;
989 return "__start___" + Section;
993 ModuleSanitizerCoverage::getSectionEnd(const std::string &Section) const {
994 if (TargetTriple.isOSBinFormatMachO())
995 return "\1section$end$__DATA$__" + Section;
996 return "__stop___" + Section;
999 char ModuleSanitizerCoverageLegacyPass::ID = 0;
1000 INITIALIZE_PASS_BEGIN(ModuleSanitizerCoverageLegacyPass, "sancov",
1001 "Pass for instrumenting coverage on functions", false,
1003 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1004 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
1005 INITIALIZE_PASS_END(ModuleSanitizerCoverageLegacyPass, "sancov",
1006 "Pass for instrumenting coverage on functions", false,
1008 ModulePass *llvm::createModuleSanitizerCoverageLegacyPassPass(
1009 const SanitizerCoverageOptions &Options,
1010 const std::vector<std::string> &AllowlistFiles,
1011 const std::vector<std::string> &BlocklistFiles) {
1012 return new ModuleSanitizerCoverageLegacyPass(Options, AllowlistFiles,