SanitizerCoverage.cpp 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105
  1. //===-- SanitizerCoverage.cpp - coverage instrumentation for sanitizers ---===//
  2. //
  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
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // Coverage instrumentation done on LLVM IR level, works with Sanitizers.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
  13. #include "llvm/ADT/ArrayRef.h"
  14. #include "llvm/ADT/SmallVector.h"
  15. #include "llvm/Analysis/EHPersonalities.h"
  16. #include "llvm/Analysis/PostDominators.h"
  17. #include "llvm/IR/CFG.h"
  18. #include "llvm/IR/Constant.h"
  19. #include "llvm/IR/DataLayout.h"
  20. #include "llvm/IR/DebugInfo.h"
  21. #include "llvm/IR/Dominators.h"
  22. #include "llvm/IR/Function.h"
  23. #include "llvm/IR/GlobalVariable.h"
  24. #include "llvm/IR/IRBuilder.h"
  25. #include "llvm/IR/InlineAsm.h"
  26. #include "llvm/IR/IntrinsicInst.h"
  27. #include "llvm/IR/Intrinsics.h"
  28. #include "llvm/IR/LLVMContext.h"
  29. #include "llvm/IR/MDBuilder.h"
  30. #include "llvm/IR/Mangler.h"
  31. #include "llvm/IR/Module.h"
  32. #include "llvm/IR/Type.h"
  33. #include "llvm/InitializePasses.h"
  34. #include "llvm/Support/CommandLine.h"
  35. #include "llvm/Support/Debug.h"
  36. #include "llvm/Support/SpecialCaseList.h"
  37. #include "llvm/Support/VirtualFileSystem.h"
  38. #include "llvm/Support/raw_ostream.h"
  39. #include "llvm/Transforms/Instrumentation.h"
  40. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  41. #include "llvm/Transforms/Utils/ModuleUtils.h"
  42. using namespace llvm;
  43. #define DEBUG_TYPE "sancov"
  44. const char SanCovTracePCIndirName[] = "__sanitizer_cov_trace_pc_indir";
  45. const char SanCovTracePCName[] = "__sanitizer_cov_trace_pc";
  46. const char SanCovTraceCmp1[] = "__sanitizer_cov_trace_cmp1";
  47. const char SanCovTraceCmp2[] = "__sanitizer_cov_trace_cmp2";
  48. const char SanCovTraceCmp4[] = "__sanitizer_cov_trace_cmp4";
  49. const char SanCovTraceCmp8[] = "__sanitizer_cov_trace_cmp8";
  50. const char SanCovTraceConstCmp1[] = "__sanitizer_cov_trace_const_cmp1";
  51. const char SanCovTraceConstCmp2[] = "__sanitizer_cov_trace_const_cmp2";
  52. const char SanCovTraceConstCmp4[] = "__sanitizer_cov_trace_const_cmp4";
  53. const char SanCovTraceConstCmp8[] = "__sanitizer_cov_trace_const_cmp8";
  54. const char SanCovLoad1[] = "__sanitizer_cov_load1";
  55. const char SanCovLoad2[] = "__sanitizer_cov_load2";
  56. const char SanCovLoad4[] = "__sanitizer_cov_load4";
  57. const char SanCovLoad8[] = "__sanitizer_cov_load8";
  58. const char SanCovLoad16[] = "__sanitizer_cov_load16";
  59. const char SanCovStore1[] = "__sanitizer_cov_store1";
  60. const char SanCovStore2[] = "__sanitizer_cov_store2";
  61. const char SanCovStore4[] = "__sanitizer_cov_store4";
  62. const char SanCovStore8[] = "__sanitizer_cov_store8";
  63. const char SanCovStore16[] = "__sanitizer_cov_store16";
  64. const char SanCovTraceDiv4[] = "__sanitizer_cov_trace_div4";
  65. const char SanCovTraceDiv8[] = "__sanitizer_cov_trace_div8";
  66. const char SanCovTraceGep[] = "__sanitizer_cov_trace_gep";
  67. const char SanCovTraceSwitchName[] = "__sanitizer_cov_trace_switch";
  68. const char SanCovModuleCtorTracePcGuardName[] =
  69. "sancov.module_ctor_trace_pc_guard";
  70. const char SanCovModuleCtor8bitCountersName[] =
  71. "sancov.module_ctor_8bit_counters";
  72. const char SanCovModuleCtorBoolFlagName[] = "sancov.module_ctor_bool_flag";
  73. static const uint64_t SanCtorAndDtorPriority = 2;
  74. const char SanCovTracePCGuardName[] = "__sanitizer_cov_trace_pc_guard";
  75. const char SanCovTracePCGuardInitName[] = "__sanitizer_cov_trace_pc_guard_init";
  76. const char SanCov8bitCountersInitName[] = "__sanitizer_cov_8bit_counters_init";
  77. const char SanCovBoolFlagInitName[] = "__sanitizer_cov_bool_flag_init";
  78. const char SanCovPCsInitName[] = "__sanitizer_cov_pcs_init";
  79. const char SanCovGuardsSectionName[] = "sancov_guards";
  80. const char SanCovCountersSectionName[] = "sancov_cntrs";
  81. const char SanCovBoolFlagSectionName[] = "sancov_bools";
  82. const char SanCovPCsSectionName[] = "sancov_pcs";
  83. const char SanCovLowestStackName[] = "__sancov_lowest_stack";
  84. static cl::opt<int> ClCoverageLevel(
  85. "sanitizer-coverage-level",
  86. cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
  87. "3: all blocks and critical edges"),
  88. cl::Hidden, cl::init(0));
  89. static cl::opt<bool> ClTracePC("sanitizer-coverage-trace-pc",
  90. cl::desc("Experimental pc tracing"), cl::Hidden,
  91. cl::init(false));
  92. static cl::opt<bool> ClTracePCGuard("sanitizer-coverage-trace-pc-guard",
  93. cl::desc("pc tracing with a guard"),
  94. cl::Hidden, cl::init(false));
  95. // If true, we create a global variable that contains PCs of all instrumented
  96. // BBs, put this global into a named section, and pass this section's bounds
  97. // to __sanitizer_cov_pcs_init.
  98. // This way the coverage instrumentation does not need to acquire the PCs
  99. // at run-time. Works with trace-pc-guard, inline-8bit-counters, and
  100. // inline-bool-flag.
  101. static cl::opt<bool> ClCreatePCTable("sanitizer-coverage-pc-table",
  102. cl::desc("create a static PC table"),
  103. cl::Hidden, cl::init(false));
  104. static cl::opt<bool>
  105. ClInline8bitCounters("sanitizer-coverage-inline-8bit-counters",
  106. cl::desc("increments 8-bit counter for every edge"),
  107. cl::Hidden, cl::init(false));
  108. static cl::opt<bool>
  109. ClInlineBoolFlag("sanitizer-coverage-inline-bool-flag",
  110. cl::desc("sets a boolean flag for every edge"), cl::Hidden,
  111. cl::init(false));
  112. static cl::opt<bool>
  113. ClCMPTracing("sanitizer-coverage-trace-compares",
  114. cl::desc("Tracing of CMP and similar instructions"),
  115. cl::Hidden, cl::init(false));
  116. static cl::opt<bool> ClDIVTracing("sanitizer-coverage-trace-divs",
  117. cl::desc("Tracing of DIV instructions"),
  118. cl::Hidden, cl::init(false));
  119. static cl::opt<bool> ClLoadTracing("sanitizer-coverage-trace-loads",
  120. cl::desc("Tracing of load instructions"),
  121. cl::Hidden, cl::init(false));
  122. static cl::opt<bool> ClStoreTracing("sanitizer-coverage-trace-stores",
  123. cl::desc("Tracing of store instructions"),
  124. cl::Hidden, cl::init(false));
  125. static cl::opt<bool> ClGEPTracing("sanitizer-coverage-trace-geps",
  126. cl::desc("Tracing of GEP instructions"),
  127. cl::Hidden, cl::init(false));
  128. static cl::opt<bool>
  129. ClPruneBlocks("sanitizer-coverage-prune-blocks",
  130. cl::desc("Reduce the number of instrumented blocks"),
  131. cl::Hidden, cl::init(true));
  132. static cl::opt<bool> ClStackDepth("sanitizer-coverage-stack-depth",
  133. cl::desc("max stack depth tracing"),
  134. cl::Hidden, cl::init(false));
  135. namespace {
  136. SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
  137. SanitizerCoverageOptions Res;
  138. switch (LegacyCoverageLevel) {
  139. case 0:
  140. Res.CoverageType = SanitizerCoverageOptions::SCK_None;
  141. break;
  142. case 1:
  143. Res.CoverageType = SanitizerCoverageOptions::SCK_Function;
  144. break;
  145. case 2:
  146. Res.CoverageType = SanitizerCoverageOptions::SCK_BB;
  147. break;
  148. case 3:
  149. Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
  150. break;
  151. case 4:
  152. Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
  153. Res.IndirectCalls = true;
  154. break;
  155. }
  156. return Res;
  157. }
  158. SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
  159. // Sets CoverageType and IndirectCalls.
  160. SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
  161. Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
  162. Options.IndirectCalls |= CLOpts.IndirectCalls;
  163. Options.TraceCmp |= ClCMPTracing;
  164. Options.TraceDiv |= ClDIVTracing;
  165. Options.TraceGep |= ClGEPTracing;
  166. Options.TracePC |= ClTracePC;
  167. Options.TracePCGuard |= ClTracePCGuard;
  168. Options.Inline8bitCounters |= ClInline8bitCounters;
  169. Options.InlineBoolFlag |= ClInlineBoolFlag;
  170. Options.PCTable |= ClCreatePCTable;
  171. Options.NoPrune |= !ClPruneBlocks;
  172. Options.StackDepth |= ClStackDepth;
  173. Options.TraceLoads |= ClLoadTracing;
  174. Options.TraceStores |= ClStoreTracing;
  175. if (!Options.TracePCGuard && !Options.TracePC &&
  176. !Options.Inline8bitCounters && !Options.StackDepth &&
  177. !Options.InlineBoolFlag && !Options.TraceLoads && !Options.TraceStores)
  178. Options.TracePCGuard = true; // TracePCGuard is default.
  179. return Options;
  180. }
  181. using DomTreeCallback = function_ref<const DominatorTree *(Function &F)>;
  182. using PostDomTreeCallback =
  183. function_ref<const PostDominatorTree *(Function &F)>;
  184. class ModuleSanitizerCoverage {
  185. public:
  186. ModuleSanitizerCoverage(
  187. const SanitizerCoverageOptions &Options = SanitizerCoverageOptions(),
  188. const SpecialCaseList *Allowlist = nullptr,
  189. const SpecialCaseList *Blocklist = nullptr)
  190. : Options(OverrideFromCL(Options)), Allowlist(Allowlist),
  191. Blocklist(Blocklist) {}
  192. bool instrumentModule(Module &M, DomTreeCallback DTCallback,
  193. PostDomTreeCallback PDTCallback);
  194. private:
  195. void instrumentFunction(Function &F, DomTreeCallback DTCallback,
  196. PostDomTreeCallback PDTCallback);
  197. void InjectCoverageForIndirectCalls(Function &F,
  198. ArrayRef<Instruction *> IndirCalls);
  199. void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
  200. void InjectTraceForDiv(Function &F,
  201. ArrayRef<BinaryOperator *> DivTraceTargets);
  202. void InjectTraceForGep(Function &F,
  203. ArrayRef<GetElementPtrInst *> GepTraceTargets);
  204. void InjectTraceForLoadsAndStores(Function &F, ArrayRef<LoadInst *> Loads,
  205. ArrayRef<StoreInst *> Stores);
  206. void InjectTraceForSwitch(Function &F,
  207. ArrayRef<Instruction *> SwitchTraceTargets);
  208. bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks,
  209. bool IsLeafFunc = true);
  210. GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
  211. Function &F, Type *Ty,
  212. const char *Section);
  213. GlobalVariable *CreatePCArray(Function &F, ArrayRef<BasicBlock *> AllBlocks);
  214. void CreateFunctionLocalArrays(Function &F, ArrayRef<BasicBlock *> AllBlocks);
  215. void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx,
  216. bool IsLeafFunc = true);
  217. Function *CreateInitCallsForSections(Module &M, const char *CtorName,
  218. const char *InitFunctionName, Type *Ty,
  219. const char *Section);
  220. std::pair<Value *, Value *> CreateSecStartEnd(Module &M, const char *Section,
  221. Type *Ty);
  222. void SetNoSanitizeMetadata(Instruction *I) {
  223. I->setMetadata(I->getModule()->getMDKindID("nosanitize"),
  224. MDNode::get(*C, None));
  225. }
  226. std::string getSectionName(const std::string &Section) const;
  227. std::string getSectionStart(const std::string &Section) const;
  228. std::string getSectionEnd(const std::string &Section) const;
  229. FunctionCallee SanCovTracePCIndir;
  230. FunctionCallee SanCovTracePC, SanCovTracePCGuard;
  231. std::array<FunctionCallee, 4> SanCovTraceCmpFunction;
  232. std::array<FunctionCallee, 4> SanCovTraceConstCmpFunction;
  233. std::array<FunctionCallee, 5> SanCovLoadFunction;
  234. std::array<FunctionCallee, 5> SanCovStoreFunction;
  235. std::array<FunctionCallee, 2> SanCovTraceDivFunction;
  236. FunctionCallee SanCovTraceGepFunction;
  237. FunctionCallee SanCovTraceSwitchFunction;
  238. GlobalVariable *SanCovLowestStack;
  239. Type *Int128PtrTy, *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty,
  240. *Int32PtrTy, *Int16PtrTy, *Int16Ty, *Int8Ty, *Int8PtrTy, *Int1Ty,
  241. *Int1PtrTy;
  242. Module *CurModule;
  243. std::string CurModuleUniqueId;
  244. Triple TargetTriple;
  245. LLVMContext *C;
  246. const DataLayout *DL;
  247. GlobalVariable *FunctionGuardArray; // for trace-pc-guard.
  248. GlobalVariable *Function8bitCounterArray; // for inline-8bit-counters.
  249. GlobalVariable *FunctionBoolArray; // for inline-bool-flag.
  250. GlobalVariable *FunctionPCsArray; // for pc-table.
  251. SmallVector<GlobalValue *, 20> GlobalsToAppendToUsed;
  252. SmallVector<GlobalValue *, 20> GlobalsToAppendToCompilerUsed;
  253. SanitizerCoverageOptions Options;
  254. const SpecialCaseList *Allowlist;
  255. const SpecialCaseList *Blocklist;
  256. };
  257. class ModuleSanitizerCoverageLegacyPass : public ModulePass {
  258. public:
  259. ModuleSanitizerCoverageLegacyPass(
  260. const SanitizerCoverageOptions &Options = SanitizerCoverageOptions(),
  261. const std::vector<std::string> &AllowlistFiles =
  262. std::vector<std::string>(),
  263. const std::vector<std::string> &BlocklistFiles =
  264. std::vector<std::string>())
  265. : ModulePass(ID), Options(Options) {
  266. if (AllowlistFiles.size() > 0)
  267. Allowlist = SpecialCaseList::createOrDie(AllowlistFiles,
  268. *vfs::getRealFileSystem());
  269. if (BlocklistFiles.size() > 0)
  270. Blocklist = SpecialCaseList::createOrDie(BlocklistFiles,
  271. *vfs::getRealFileSystem());
  272. initializeModuleSanitizerCoverageLegacyPassPass(
  273. *PassRegistry::getPassRegistry());
  274. }
  275. bool runOnModule(Module &M) override {
  276. ModuleSanitizerCoverage ModuleSancov(Options, Allowlist.get(),
  277. Blocklist.get());
  278. auto DTCallback = [this](Function &F) -> const DominatorTree * {
  279. return &this->getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
  280. };
  281. auto PDTCallback = [this](Function &F) -> const PostDominatorTree * {
  282. return &this->getAnalysis<PostDominatorTreeWrapperPass>(F)
  283. .getPostDomTree();
  284. };
  285. return ModuleSancov.instrumentModule(M, DTCallback, PDTCallback);
  286. }
  287. static char ID; // Pass identification, replacement for typeid
  288. StringRef getPassName() const override { return "ModuleSanitizerCoverage"; }
  289. void getAnalysisUsage(AnalysisUsage &AU) const override {
  290. AU.addRequired<DominatorTreeWrapperPass>();
  291. AU.addRequired<PostDominatorTreeWrapperPass>();
  292. }
  293. private:
  294. SanitizerCoverageOptions Options;
  295. std::unique_ptr<SpecialCaseList> Allowlist;
  296. std::unique_ptr<SpecialCaseList> Blocklist;
  297. };
  298. } // namespace
  299. PreservedAnalyses ModuleSanitizerCoveragePass::run(Module &M,
  300. ModuleAnalysisManager &MAM) {
  301. ModuleSanitizerCoverage ModuleSancov(Options, Allowlist.get(),
  302. Blocklist.get());
  303. auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
  304. auto DTCallback = [&FAM](Function &F) -> const DominatorTree * {
  305. return &FAM.getResult<DominatorTreeAnalysis>(F);
  306. };
  307. auto PDTCallback = [&FAM](Function &F) -> const PostDominatorTree * {
  308. return &FAM.getResult<PostDominatorTreeAnalysis>(F);
  309. };
  310. if (ModuleSancov.instrumentModule(M, DTCallback, PDTCallback))
  311. return PreservedAnalyses::none();
  312. return PreservedAnalyses::all();
  313. }
  314. std::pair<Value *, Value *>
  315. ModuleSanitizerCoverage::CreateSecStartEnd(Module &M, const char *Section,
  316. Type *Ty) {
  317. // Use ExternalWeak so that if all sections are discarded due to section
  318. // garbage collection, the linker will not report undefined symbol errors.
  319. // Windows defines the start/stop symbols in compiler-rt so no need for
  320. // ExternalWeak.
  321. GlobalValue::LinkageTypes Linkage = TargetTriple.isOSBinFormatCOFF()
  322. ? GlobalVariable::ExternalLinkage
  323. : GlobalVariable::ExternalWeakLinkage;
  324. GlobalVariable *SecStart =
  325. new GlobalVariable(M, Ty, false, Linkage, nullptr,
  326. getSectionStart(Section));
  327. SecStart->setVisibility(GlobalValue::HiddenVisibility);
  328. GlobalVariable *SecEnd =
  329. new GlobalVariable(M, Ty, false, Linkage, nullptr,
  330. getSectionEnd(Section));
  331. SecEnd->setVisibility(GlobalValue::HiddenVisibility);
  332. IRBuilder<> IRB(M.getContext());
  333. if (!TargetTriple.isOSBinFormatCOFF())
  334. return std::make_pair(SecStart, SecEnd);
  335. // Account for the fact that on windows-msvc __start_* symbols actually
  336. // point to a uint64_t before the start of the array.
  337. auto SecStartI8Ptr = IRB.CreatePointerCast(SecStart, Int8PtrTy);
  338. auto GEP = IRB.CreateGEP(Int8Ty, SecStartI8Ptr,
  339. ConstantInt::get(IntptrTy, sizeof(uint64_t)));
  340. return std::make_pair(IRB.CreatePointerCast(GEP, PointerType::getUnqual(Ty)),
  341. SecEnd);
  342. }
  343. Function *ModuleSanitizerCoverage::CreateInitCallsForSections(
  344. Module &M, const char *CtorName, const char *InitFunctionName, Type *Ty,
  345. const char *Section) {
  346. auto SecStartEnd = CreateSecStartEnd(M, Section, Ty);
  347. auto SecStart = SecStartEnd.first;
  348. auto SecEnd = SecStartEnd.second;
  349. Function *CtorFunc;
  350. Type *PtrTy = PointerType::getUnqual(Ty);
  351. std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
  352. M, CtorName, InitFunctionName, {PtrTy, PtrTy}, {SecStart, SecEnd});
  353. assert(CtorFunc->getName() == CtorName);
  354. if (TargetTriple.supportsCOMDAT()) {
  355. // Use comdat to dedup CtorFunc.
  356. CtorFunc->setComdat(M.getOrInsertComdat(CtorName));
  357. appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
  358. } else {
  359. appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
  360. }
  361. if (TargetTriple.isOSBinFormatCOFF()) {
  362. // In COFF files, if the contructors are set as COMDAT (they are because
  363. // COFF supports COMDAT) and the linker flag /OPT:REF (strip unreferenced
  364. // functions and data) is used, the constructors get stripped. To prevent
  365. // this, give the constructors weak ODR linkage and ensure the linker knows
  366. // to include the sancov constructor. This way the linker can deduplicate
  367. // the constructors but always leave one copy.
  368. CtorFunc->setLinkage(GlobalValue::WeakODRLinkage);
  369. }
  370. return CtorFunc;
  371. }
  372. bool ModuleSanitizerCoverage::instrumentModule(
  373. Module &M, DomTreeCallback DTCallback, PostDomTreeCallback PDTCallback) {
  374. if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
  375. return false;
  376. if (Allowlist &&
  377. !Allowlist->inSection("coverage", "src", M.getSourceFileName()))
  378. return false;
  379. if (Blocklist &&
  380. Blocklist->inSection("coverage", "src", M.getSourceFileName()))
  381. return false;
  382. C = &(M.getContext());
  383. DL = &M.getDataLayout();
  384. CurModule = &M;
  385. CurModuleUniqueId = getUniqueModuleId(CurModule);
  386. TargetTriple = Triple(M.getTargetTriple());
  387. FunctionGuardArray = nullptr;
  388. Function8bitCounterArray = nullptr;
  389. FunctionBoolArray = nullptr;
  390. FunctionPCsArray = nullptr;
  391. IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
  392. IntptrPtrTy = PointerType::getUnqual(IntptrTy);
  393. Type *VoidTy = Type::getVoidTy(*C);
  394. IRBuilder<> IRB(*C);
  395. Int128PtrTy = PointerType::getUnqual(IRB.getInt128Ty());
  396. Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
  397. Int16PtrTy = PointerType::getUnqual(IRB.getInt16Ty());
  398. Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
  399. Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
  400. Int1PtrTy = PointerType::getUnqual(IRB.getInt1Ty());
  401. Int64Ty = IRB.getInt64Ty();
  402. Int32Ty = IRB.getInt32Ty();
  403. Int16Ty = IRB.getInt16Ty();
  404. Int8Ty = IRB.getInt8Ty();
  405. Int1Ty = IRB.getInt1Ty();
  406. SanCovTracePCIndir =
  407. M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy);
  408. // Make sure smaller parameters are zero-extended to i64 if required by the
  409. // target ABI.
  410. AttributeList SanCovTraceCmpZeroExtAL;
  411. SanCovTraceCmpZeroExtAL =
  412. SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 0, Attribute::ZExt);
  413. SanCovTraceCmpZeroExtAL =
  414. SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 1, Attribute::ZExt);
  415. SanCovTraceCmpFunction[0] =
  416. M.getOrInsertFunction(SanCovTraceCmp1, SanCovTraceCmpZeroExtAL, VoidTy,
  417. IRB.getInt8Ty(), IRB.getInt8Ty());
  418. SanCovTraceCmpFunction[1] =
  419. M.getOrInsertFunction(SanCovTraceCmp2, SanCovTraceCmpZeroExtAL, VoidTy,
  420. IRB.getInt16Ty(), IRB.getInt16Ty());
  421. SanCovTraceCmpFunction[2] =
  422. M.getOrInsertFunction(SanCovTraceCmp4, SanCovTraceCmpZeroExtAL, VoidTy,
  423. IRB.getInt32Ty(), IRB.getInt32Ty());
  424. SanCovTraceCmpFunction[3] =
  425. M.getOrInsertFunction(SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty);
  426. SanCovTraceConstCmpFunction[0] = M.getOrInsertFunction(
  427. SanCovTraceConstCmp1, SanCovTraceCmpZeroExtAL, VoidTy, Int8Ty, Int8Ty);
  428. SanCovTraceConstCmpFunction[1] = M.getOrInsertFunction(
  429. SanCovTraceConstCmp2, SanCovTraceCmpZeroExtAL, VoidTy, Int16Ty, Int16Ty);
  430. SanCovTraceConstCmpFunction[2] = M.getOrInsertFunction(
  431. SanCovTraceConstCmp4, SanCovTraceCmpZeroExtAL, VoidTy, Int32Ty, Int32Ty);
  432. SanCovTraceConstCmpFunction[3] =
  433. M.getOrInsertFunction(SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty);
  434. // Loads.
  435. SanCovLoadFunction[0] = M.getOrInsertFunction(SanCovLoad1, VoidTy, Int8PtrTy);
  436. SanCovLoadFunction[1] =
  437. M.getOrInsertFunction(SanCovLoad2, VoidTy, Int16PtrTy);
  438. SanCovLoadFunction[2] =
  439. M.getOrInsertFunction(SanCovLoad4, VoidTy, Int32PtrTy);
  440. SanCovLoadFunction[3] =
  441. M.getOrInsertFunction(SanCovLoad8, VoidTy, Int64PtrTy);
  442. SanCovLoadFunction[4] =
  443. M.getOrInsertFunction(SanCovLoad16, VoidTy, Int128PtrTy);
  444. // Stores.
  445. SanCovStoreFunction[0] =
  446. M.getOrInsertFunction(SanCovStore1, VoidTy, Int8PtrTy);
  447. SanCovStoreFunction[1] =
  448. M.getOrInsertFunction(SanCovStore2, VoidTy, Int16PtrTy);
  449. SanCovStoreFunction[2] =
  450. M.getOrInsertFunction(SanCovStore4, VoidTy, Int32PtrTy);
  451. SanCovStoreFunction[3] =
  452. M.getOrInsertFunction(SanCovStore8, VoidTy, Int64PtrTy);
  453. SanCovStoreFunction[4] =
  454. M.getOrInsertFunction(SanCovStore16, VoidTy, Int128PtrTy);
  455. {
  456. AttributeList AL;
  457. AL = AL.addParamAttribute(*C, 0, Attribute::ZExt);
  458. SanCovTraceDivFunction[0] =
  459. M.getOrInsertFunction(SanCovTraceDiv4, AL, VoidTy, IRB.getInt32Ty());
  460. }
  461. SanCovTraceDivFunction[1] =
  462. M.getOrInsertFunction(SanCovTraceDiv8, VoidTy, Int64Ty);
  463. SanCovTraceGepFunction =
  464. M.getOrInsertFunction(SanCovTraceGep, VoidTy, IntptrTy);
  465. SanCovTraceSwitchFunction =
  466. M.getOrInsertFunction(SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy);
  467. Constant *SanCovLowestStackConstant =
  468. M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy);
  469. SanCovLowestStack = dyn_cast<GlobalVariable>(SanCovLowestStackConstant);
  470. if (!SanCovLowestStack || SanCovLowestStack->getValueType() != IntptrTy) {
  471. C->emitError(StringRef("'") + SanCovLowestStackName +
  472. "' should not be declared by the user");
  473. return true;
  474. }
  475. SanCovLowestStack->setThreadLocalMode(
  476. GlobalValue::ThreadLocalMode::InitialExecTLSModel);
  477. if (Options.StackDepth && !SanCovLowestStack->isDeclaration())
  478. SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy));
  479. SanCovTracePC = M.getOrInsertFunction(SanCovTracePCName, VoidTy);
  480. SanCovTracePCGuard =
  481. M.getOrInsertFunction(SanCovTracePCGuardName, VoidTy, Int32PtrTy);
  482. for (auto &F : M)
  483. instrumentFunction(F, DTCallback, PDTCallback);
  484. Function *Ctor = nullptr;
  485. if (FunctionGuardArray)
  486. Ctor = CreateInitCallsForSections(M, SanCovModuleCtorTracePcGuardName,
  487. SanCovTracePCGuardInitName, Int32Ty,
  488. SanCovGuardsSectionName);
  489. if (Function8bitCounterArray)
  490. Ctor = CreateInitCallsForSections(M, SanCovModuleCtor8bitCountersName,
  491. SanCov8bitCountersInitName, Int8Ty,
  492. SanCovCountersSectionName);
  493. if (FunctionBoolArray) {
  494. Ctor = CreateInitCallsForSections(M, SanCovModuleCtorBoolFlagName,
  495. SanCovBoolFlagInitName, Int1Ty,
  496. SanCovBoolFlagSectionName);
  497. }
  498. if (Ctor && Options.PCTable) {
  499. auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, IntptrTy);
  500. FunctionCallee InitFunction = declareSanitizerInitFunction(
  501. M, SanCovPCsInitName, {IntptrPtrTy, IntptrPtrTy});
  502. IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
  503. IRBCtor.CreateCall(InitFunction, {SecStartEnd.first, SecStartEnd.second});
  504. }
  505. appendToUsed(M, GlobalsToAppendToUsed);
  506. appendToCompilerUsed(M, GlobalsToAppendToCompilerUsed);
  507. return true;
  508. }
  509. // True if block has successors and it dominates all of them.
  510. static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
  511. if (succ_empty(BB))
  512. return false;
  513. return llvm::all_of(successors(BB), [&](const BasicBlock *SUCC) {
  514. return DT->dominates(BB, SUCC);
  515. });
  516. }
  517. // True if block has predecessors and it postdominates all of them.
  518. static bool isFullPostDominator(const BasicBlock *BB,
  519. const PostDominatorTree *PDT) {
  520. if (pred_empty(BB))
  521. return false;
  522. return llvm::all_of(predecessors(BB), [&](const BasicBlock *PRED) {
  523. return PDT->dominates(BB, PRED);
  524. });
  525. }
  526. static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
  527. const DominatorTree *DT,
  528. const PostDominatorTree *PDT,
  529. const SanitizerCoverageOptions &Options) {
  530. // Don't insert coverage for blocks containing nothing but unreachable: we
  531. // will never call __sanitizer_cov() for them, so counting them in
  532. // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
  533. // percentage. Also, unreachable instructions frequently have no debug
  534. // locations.
  535. if (isa<UnreachableInst>(BB->getFirstNonPHIOrDbgOrLifetime()))
  536. return false;
  537. // Don't insert coverage into blocks without a valid insertion point
  538. // (catchswitch blocks).
  539. if (BB->getFirstInsertionPt() == BB->end())
  540. return false;
  541. if (Options.NoPrune || &F.getEntryBlock() == BB)
  542. return true;
  543. if (Options.CoverageType == SanitizerCoverageOptions::SCK_Function &&
  544. &F.getEntryBlock() != BB)
  545. return false;
  546. // Do not instrument full dominators, or full post-dominators with multiple
  547. // predecessors.
  548. return !isFullDominator(BB, DT)
  549. && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
  550. }
  551. // Returns true iff From->To is a backedge.
  552. // A twist here is that we treat From->To as a backedge if
  553. // * To dominates From or
  554. // * To->UniqueSuccessor dominates From
  555. static bool IsBackEdge(BasicBlock *From, BasicBlock *To,
  556. const DominatorTree *DT) {
  557. if (DT->dominates(To, From))
  558. return true;
  559. if (auto Next = To->getUniqueSuccessor())
  560. if (DT->dominates(Next, From))
  561. return true;
  562. return false;
  563. }
  564. // Prunes uninteresting Cmp instrumentation:
  565. // * CMP instructions that feed into loop backedge branch.
  566. //
  567. // Note that Cmp pruning is controlled by the same flag as the
  568. // BB pruning.
  569. static bool IsInterestingCmp(ICmpInst *CMP, const DominatorTree *DT,
  570. const SanitizerCoverageOptions &Options) {
  571. if (!Options.NoPrune)
  572. if (CMP->hasOneUse())
  573. if (auto BR = dyn_cast<BranchInst>(CMP->user_back()))
  574. for (BasicBlock *B : BR->successors())
  575. if (IsBackEdge(BR->getParent(), B, DT))
  576. return false;
  577. return true;
  578. }
  579. void ModuleSanitizerCoverage::instrumentFunction(
  580. Function &F, DomTreeCallback DTCallback, PostDomTreeCallback PDTCallback) {
  581. if (F.empty())
  582. return;
  583. if (F.getName().find(".module_ctor") != std::string::npos)
  584. return; // Should not instrument sanitizer init functions.
  585. if (F.getName().startswith("__sanitizer_"))
  586. return; // Don't instrument __sanitizer_* callbacks.
  587. // Don't touch available_externally functions, their actual body is elewhere.
  588. if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage)
  589. return;
  590. // Don't instrument MSVC CRT configuration helpers. They may run before normal
  591. // initialization.
  592. if (F.getName() == "__local_stdio_printf_options" ||
  593. F.getName() == "__local_stdio_scanf_options")
  594. return;
  595. if (isa<UnreachableInst>(F.getEntryBlock().getTerminator()))
  596. return;
  597. // Don't instrument functions using SEH for now. Splitting basic blocks like
  598. // we do for coverage breaks WinEHPrepare.
  599. // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
  600. if (F.hasPersonalityFn() &&
  601. isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
  602. return;
  603. if (Allowlist && !Allowlist->inSection("coverage", "fun", F.getName()))
  604. return;
  605. if (Blocklist && Blocklist->inSection("coverage", "fun", F.getName()))
  606. return;
  607. if (F.hasFnAttribute(Attribute::NoSanitizeCoverage))
  608. return;
  609. if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
  610. SplitAllCriticalEdges(F, CriticalEdgeSplittingOptions().setIgnoreUnreachableDests());
  611. SmallVector<Instruction *, 8> IndirCalls;
  612. SmallVector<BasicBlock *, 16> BlocksToInstrument;
  613. SmallVector<Instruction *, 8> CmpTraceTargets;
  614. SmallVector<Instruction *, 8> SwitchTraceTargets;
  615. SmallVector<BinaryOperator *, 8> DivTraceTargets;
  616. SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
  617. SmallVector<LoadInst *, 8> Loads;
  618. SmallVector<StoreInst *, 8> Stores;
  619. const DominatorTree *DT = DTCallback(F);
  620. const PostDominatorTree *PDT = PDTCallback(F);
  621. bool IsLeafFunc = true;
  622. for (auto &BB : F) {
  623. if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
  624. BlocksToInstrument.push_back(&BB);
  625. for (auto &Inst : BB) {
  626. if (Options.IndirectCalls) {
  627. CallBase *CB = dyn_cast<CallBase>(&Inst);
  628. if (CB && !CB->getCalledFunction())
  629. IndirCalls.push_back(&Inst);
  630. }
  631. if (Options.TraceCmp) {
  632. if (ICmpInst *CMP = dyn_cast<ICmpInst>(&Inst))
  633. if (IsInterestingCmp(CMP, DT, Options))
  634. CmpTraceTargets.push_back(&Inst);
  635. if (isa<SwitchInst>(&Inst))
  636. SwitchTraceTargets.push_back(&Inst);
  637. }
  638. if (Options.TraceDiv)
  639. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
  640. if (BO->getOpcode() == Instruction::SDiv ||
  641. BO->getOpcode() == Instruction::UDiv)
  642. DivTraceTargets.push_back(BO);
  643. if (Options.TraceGep)
  644. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
  645. GepTraceTargets.push_back(GEP);
  646. if (Options.TraceLoads)
  647. if (LoadInst *LI = dyn_cast<LoadInst>(&Inst))
  648. Loads.push_back(LI);
  649. if (Options.TraceStores)
  650. if (StoreInst *SI = dyn_cast<StoreInst>(&Inst))
  651. Stores.push_back(SI);
  652. if (Options.StackDepth)
  653. if (isa<InvokeInst>(Inst) ||
  654. (isa<CallInst>(Inst) && !isa<IntrinsicInst>(Inst)))
  655. IsLeafFunc = false;
  656. }
  657. }
  658. InjectCoverage(F, BlocksToInstrument, IsLeafFunc);
  659. InjectCoverageForIndirectCalls(F, IndirCalls);
  660. InjectTraceForCmp(F, CmpTraceTargets);
  661. InjectTraceForSwitch(F, SwitchTraceTargets);
  662. InjectTraceForDiv(F, DivTraceTargets);
  663. InjectTraceForGep(F, GepTraceTargets);
  664. InjectTraceForLoadsAndStores(F, Loads, Stores);
  665. }
  666. GlobalVariable *ModuleSanitizerCoverage::CreateFunctionLocalArrayInSection(
  667. size_t NumElements, Function &F, Type *Ty, const char *Section) {
  668. ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
  669. auto Array = new GlobalVariable(
  670. *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
  671. Constant::getNullValue(ArrayTy), "__sancov_gen_");
  672. if (TargetTriple.supportsCOMDAT() &&
  673. (TargetTriple.isOSBinFormatELF() || !F.isInterposable()))
  674. if (auto Comdat = getOrCreateFunctionComdat(F, TargetTriple))
  675. Array->setComdat(Comdat);
  676. Array->setSection(getSectionName(Section));
  677. Array->setAlignment(Align(DL->getTypeStoreSize(Ty).getFixedSize()));
  678. // sancov_pcs parallels the other metadata section(s). Optimizers (e.g.
  679. // GlobalOpt/ConstantMerge) may not discard sancov_pcs and the other
  680. // section(s) as a unit, so we conservatively retain all unconditionally in
  681. // the compiler.
  682. //
  683. // With comdat (COFF/ELF), the linker can guarantee the associated sections
  684. // will be retained or discarded as a unit, so llvm.compiler.used is
  685. // sufficient. Otherwise, conservatively make all of them retained by the
  686. // linker.
  687. if (Array->hasComdat())
  688. GlobalsToAppendToCompilerUsed.push_back(Array);
  689. else
  690. GlobalsToAppendToUsed.push_back(Array);
  691. return Array;
  692. }
  693. GlobalVariable *
  694. ModuleSanitizerCoverage::CreatePCArray(Function &F,
  695. ArrayRef<BasicBlock *> AllBlocks) {
  696. size_t N = AllBlocks.size();
  697. assert(N);
  698. SmallVector<Constant *, 32> PCs;
  699. IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
  700. for (size_t i = 0; i < N; i++) {
  701. if (&F.getEntryBlock() == AllBlocks[i]) {
  702. PCs.push_back((Constant *)IRB.CreatePointerCast(&F, IntptrPtrTy));
  703. PCs.push_back((Constant *)IRB.CreateIntToPtr(
  704. ConstantInt::get(IntptrTy, 1), IntptrPtrTy));
  705. } else {
  706. PCs.push_back((Constant *)IRB.CreatePointerCast(
  707. BlockAddress::get(AllBlocks[i]), IntptrPtrTy));
  708. PCs.push_back((Constant *)IRB.CreateIntToPtr(
  709. ConstantInt::get(IntptrTy, 0), IntptrPtrTy));
  710. }
  711. }
  712. auto *PCArray = CreateFunctionLocalArrayInSection(N * 2, F, IntptrPtrTy,
  713. SanCovPCsSectionName);
  714. PCArray->setInitializer(
  715. ConstantArray::get(ArrayType::get(IntptrPtrTy, N * 2), PCs));
  716. PCArray->setConstant(true);
  717. return PCArray;
  718. }
  719. void ModuleSanitizerCoverage::CreateFunctionLocalArrays(
  720. Function &F, ArrayRef<BasicBlock *> AllBlocks) {
  721. if (Options.TracePCGuard)
  722. FunctionGuardArray = CreateFunctionLocalArrayInSection(
  723. AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName);
  724. if (Options.Inline8bitCounters)
  725. Function8bitCounterArray = CreateFunctionLocalArrayInSection(
  726. AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName);
  727. if (Options.InlineBoolFlag)
  728. FunctionBoolArray = CreateFunctionLocalArrayInSection(
  729. AllBlocks.size(), F, Int1Ty, SanCovBoolFlagSectionName);
  730. if (Options.PCTable)
  731. FunctionPCsArray = CreatePCArray(F, AllBlocks);
  732. }
  733. bool ModuleSanitizerCoverage::InjectCoverage(Function &F,
  734. ArrayRef<BasicBlock *> AllBlocks,
  735. bool IsLeafFunc) {
  736. if (AllBlocks.empty()) return false;
  737. CreateFunctionLocalArrays(F, AllBlocks);
  738. for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
  739. InjectCoverageAtBlock(F, *AllBlocks[i], i, IsLeafFunc);
  740. return true;
  741. }
  742. // On every indirect call we call a run-time function
  743. // __sanitizer_cov_indir_call* with two parameters:
  744. // - callee address,
  745. // - global cache array that contains CacheSize pointers (zero-initialized).
  746. // The cache is used to speed up recording the caller-callee pairs.
  747. // The address of the caller is passed implicitly via caller PC.
  748. // CacheSize is encoded in the name of the run-time function.
  749. void ModuleSanitizerCoverage::InjectCoverageForIndirectCalls(
  750. Function &F, ArrayRef<Instruction *> IndirCalls) {
  751. if (IndirCalls.empty())
  752. return;
  753. assert(Options.TracePC || Options.TracePCGuard ||
  754. Options.Inline8bitCounters || Options.InlineBoolFlag);
  755. for (auto I : IndirCalls) {
  756. IRBuilder<> IRB(I);
  757. CallBase &CB = cast<CallBase>(*I);
  758. Value *Callee = CB.getCalledOperand();
  759. if (isa<InlineAsm>(Callee))
  760. continue;
  761. IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
  762. }
  763. }
  764. // For every switch statement we insert a call:
  765. // __sanitizer_cov_trace_switch(CondValue,
  766. // {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
  767. void ModuleSanitizerCoverage::InjectTraceForSwitch(
  768. Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
  769. for (auto I : SwitchTraceTargets) {
  770. if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
  771. IRBuilder<> IRB(I);
  772. SmallVector<Constant *, 16> Initializers;
  773. Value *Cond = SI->getCondition();
  774. if (Cond->getType()->getScalarSizeInBits() >
  775. Int64Ty->getScalarSizeInBits())
  776. continue;
  777. Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
  778. Initializers.push_back(
  779. ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
  780. if (Cond->getType()->getScalarSizeInBits() <
  781. Int64Ty->getScalarSizeInBits())
  782. Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
  783. for (auto It : SI->cases()) {
  784. Constant *C = It.getCaseValue();
  785. if (C->getType()->getScalarSizeInBits() <
  786. Int64Ty->getScalarSizeInBits())
  787. C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
  788. Initializers.push_back(C);
  789. }
  790. llvm::sort(drop_begin(Initializers, 2),
  791. [](const Constant *A, const Constant *B) {
  792. return cast<ConstantInt>(A)->getLimitedValue() <
  793. cast<ConstantInt>(B)->getLimitedValue();
  794. });
  795. ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
  796. GlobalVariable *GV = new GlobalVariable(
  797. *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
  798. ConstantArray::get(ArrayOfInt64Ty, Initializers),
  799. "__sancov_gen_cov_switch_values");
  800. IRB.CreateCall(SanCovTraceSwitchFunction,
  801. {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
  802. }
  803. }
  804. }
  805. void ModuleSanitizerCoverage::InjectTraceForDiv(
  806. Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
  807. for (auto BO : DivTraceTargets) {
  808. IRBuilder<> IRB(BO);
  809. Value *A1 = BO->getOperand(1);
  810. if (isa<ConstantInt>(A1)) continue;
  811. if (!A1->getType()->isIntegerTy())
  812. continue;
  813. uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
  814. int CallbackIdx = TypeSize == 32 ? 0 :
  815. TypeSize == 64 ? 1 : -1;
  816. if (CallbackIdx < 0) continue;
  817. auto Ty = Type::getIntNTy(*C, TypeSize);
  818. IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
  819. {IRB.CreateIntCast(A1, Ty, true)});
  820. }
  821. }
  822. void ModuleSanitizerCoverage::InjectTraceForGep(
  823. Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
  824. for (auto GEP : GepTraceTargets) {
  825. IRBuilder<> IRB(GEP);
  826. for (Use &Idx : GEP->indices())
  827. if (!isa<ConstantInt>(Idx) && Idx->getType()->isIntegerTy())
  828. IRB.CreateCall(SanCovTraceGepFunction,
  829. {IRB.CreateIntCast(Idx, IntptrTy, true)});
  830. }
  831. }
  832. void ModuleSanitizerCoverage::InjectTraceForLoadsAndStores(
  833. Function &, ArrayRef<LoadInst *> Loads, ArrayRef<StoreInst *> Stores) {
  834. auto CallbackIdx = [&](Type *ElementTy) -> int {
  835. uint64_t TypeSize = DL->getTypeStoreSizeInBits(ElementTy);
  836. return TypeSize == 8 ? 0
  837. : TypeSize == 16 ? 1
  838. : TypeSize == 32 ? 2
  839. : TypeSize == 64 ? 3
  840. : TypeSize == 128 ? 4
  841. : -1;
  842. };
  843. Type *PointerType[5] = {Int8PtrTy, Int16PtrTy, Int32PtrTy, Int64PtrTy,
  844. Int128PtrTy};
  845. for (auto LI : Loads) {
  846. IRBuilder<> IRB(LI);
  847. auto Ptr = LI->getPointerOperand();
  848. int Idx = CallbackIdx(LI->getType());
  849. if (Idx < 0)
  850. continue;
  851. IRB.CreateCall(SanCovLoadFunction[Idx],
  852. IRB.CreatePointerCast(Ptr, PointerType[Idx]));
  853. }
  854. for (auto SI : Stores) {
  855. IRBuilder<> IRB(SI);
  856. auto Ptr = SI->getPointerOperand();
  857. int Idx = CallbackIdx(SI->getValueOperand()->getType());
  858. if (Idx < 0)
  859. continue;
  860. IRB.CreateCall(SanCovStoreFunction[Idx],
  861. IRB.CreatePointerCast(Ptr, PointerType[Idx]));
  862. }
  863. }
  864. void ModuleSanitizerCoverage::InjectTraceForCmp(
  865. Function &, ArrayRef<Instruction *> CmpTraceTargets) {
  866. for (auto I : CmpTraceTargets) {
  867. if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
  868. IRBuilder<> IRB(ICMP);
  869. Value *A0 = ICMP->getOperand(0);
  870. Value *A1 = ICMP->getOperand(1);
  871. if (!A0->getType()->isIntegerTy())
  872. continue;
  873. uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
  874. int CallbackIdx = TypeSize == 8 ? 0 :
  875. TypeSize == 16 ? 1 :
  876. TypeSize == 32 ? 2 :
  877. TypeSize == 64 ? 3 : -1;
  878. if (CallbackIdx < 0) continue;
  879. // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
  880. auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx];
  881. bool FirstIsConst = isa<ConstantInt>(A0);
  882. bool SecondIsConst = isa<ConstantInt>(A1);
  883. // If both are const, then we don't need such a comparison.
  884. if (FirstIsConst && SecondIsConst) continue;
  885. // If only one is const, then make it the first callback argument.
  886. if (FirstIsConst || SecondIsConst) {
  887. CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx];
  888. if (SecondIsConst)
  889. std::swap(A0, A1);
  890. }
  891. auto Ty = Type::getIntNTy(*C, TypeSize);
  892. IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true),
  893. IRB.CreateIntCast(A1, Ty, true)});
  894. }
  895. }
  896. }
  897. void ModuleSanitizerCoverage::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
  898. size_t Idx,
  899. bool IsLeafFunc) {
  900. BasicBlock::iterator IP = BB.getFirstInsertionPt();
  901. bool IsEntryBB = &BB == &F.getEntryBlock();
  902. DebugLoc EntryLoc;
  903. if (IsEntryBB) {
  904. if (auto SP = F.getSubprogram())
  905. EntryLoc = DILocation::get(SP->getContext(), SP->getScopeLine(), 0, SP);
  906. // Keep static allocas and llvm.localescape calls in the entry block. Even
  907. // if we aren't splitting the block, it's nice for allocas to be before
  908. // calls.
  909. IP = PrepareToSplitEntryBlock(BB, IP);
  910. } else {
  911. EntryLoc = IP->getDebugLoc();
  912. if (!EntryLoc)
  913. if (auto *SP = F.getSubprogram())
  914. EntryLoc = DILocation::get(SP->getContext(), 0, 0, SP);
  915. }
  916. IRBuilder<> IRB(&*IP);
  917. IRB.SetCurrentDebugLocation(EntryLoc);
  918. if (Options.TracePC) {
  919. IRB.CreateCall(SanCovTracePC)
  920. ->setCannotMerge(); // gets the PC using GET_CALLER_PC.
  921. }
  922. if (Options.TracePCGuard) {
  923. auto GuardPtr = IRB.CreateIntToPtr(
  924. IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
  925. ConstantInt::get(IntptrTy, Idx * 4)),
  926. Int32PtrTy);
  927. IRB.CreateCall(SanCovTracePCGuard, GuardPtr)->setCannotMerge();
  928. }
  929. if (Options.Inline8bitCounters) {
  930. auto CounterPtr = IRB.CreateGEP(
  931. Function8bitCounterArray->getValueType(), Function8bitCounterArray,
  932. {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
  933. auto Load = IRB.CreateLoad(Int8Ty, CounterPtr);
  934. auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
  935. auto Store = IRB.CreateStore(Inc, CounterPtr);
  936. SetNoSanitizeMetadata(Load);
  937. SetNoSanitizeMetadata(Store);
  938. }
  939. if (Options.InlineBoolFlag) {
  940. auto FlagPtr = IRB.CreateGEP(
  941. FunctionBoolArray->getValueType(), FunctionBoolArray,
  942. {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
  943. auto Load = IRB.CreateLoad(Int1Ty, FlagPtr);
  944. auto ThenTerm =
  945. SplitBlockAndInsertIfThen(IRB.CreateIsNull(Load), &*IP, false);
  946. IRBuilder<> ThenIRB(ThenTerm);
  947. auto Store = ThenIRB.CreateStore(ConstantInt::getTrue(Int1Ty), FlagPtr);
  948. SetNoSanitizeMetadata(Load);
  949. SetNoSanitizeMetadata(Store);
  950. }
  951. if (Options.StackDepth && IsEntryBB && !IsLeafFunc) {
  952. // Check stack depth. If it's the deepest so far, record it.
  953. Module *M = F.getParent();
  954. Function *GetFrameAddr = Intrinsic::getDeclaration(
  955. M, Intrinsic::frameaddress,
  956. IRB.getInt8PtrTy(M->getDataLayout().getAllocaAddrSpace()));
  957. auto FrameAddrPtr =
  958. IRB.CreateCall(GetFrameAddr, {Constant::getNullValue(Int32Ty)});
  959. auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy);
  960. auto LowestStack = IRB.CreateLoad(IntptrTy, SanCovLowestStack);
  961. auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack);
  962. auto ThenTerm = SplitBlockAndInsertIfThen(IsStackLower, &*IP, false);
  963. IRBuilder<> ThenIRB(ThenTerm);
  964. auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack);
  965. SetNoSanitizeMetadata(LowestStack);
  966. SetNoSanitizeMetadata(Store);
  967. }
  968. }
  969. std::string
  970. ModuleSanitizerCoverage::getSectionName(const std::string &Section) const {
  971. if (TargetTriple.isOSBinFormatCOFF()) {
  972. if (Section == SanCovCountersSectionName)
  973. return ".SCOV$CM";
  974. if (Section == SanCovBoolFlagSectionName)
  975. return ".SCOV$BM";
  976. if (Section == SanCovPCsSectionName)
  977. return ".SCOVP$M";
  978. return ".SCOV$GM"; // For SanCovGuardsSectionName.
  979. }
  980. if (TargetTriple.isOSBinFormatMachO())
  981. return "__DATA,__" + Section;
  982. return "__" + Section;
  983. }
  984. std::string
  985. ModuleSanitizerCoverage::getSectionStart(const std::string &Section) const {
  986. if (TargetTriple.isOSBinFormatMachO())
  987. return "\1section$start$__DATA$__" + Section;
  988. return "__start___" + Section;
  989. }
  990. std::string
  991. ModuleSanitizerCoverage::getSectionEnd(const std::string &Section) const {
  992. if (TargetTriple.isOSBinFormatMachO())
  993. return "\1section$end$__DATA$__" + Section;
  994. return "__stop___" + Section;
  995. }
  996. char ModuleSanitizerCoverageLegacyPass::ID = 0;
  997. INITIALIZE_PASS_BEGIN(ModuleSanitizerCoverageLegacyPass, "sancov",
  998. "Pass for instrumenting coverage on functions", false,
  999. false)
  1000. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  1001. INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
  1002. INITIALIZE_PASS_END(ModuleSanitizerCoverageLegacyPass, "sancov",
  1003. "Pass for instrumenting coverage on functions", false,
  1004. false)
  1005. ModulePass *llvm::createModuleSanitizerCoverageLegacyPassPass(
  1006. const SanitizerCoverageOptions &Options,
  1007. const std::vector<std::string> &AllowlistFiles,
  1008. const std::vector<std::string> &BlocklistFiles) {
  1009. return new ModuleSanitizerCoverageLegacyPass(Options, AllowlistFiles,
  1010. BlocklistFiles);
  1011. }