SanitizerCoverage.cpp 45 KB

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