FuzzerTracePC.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  1. //===- FuzzerTracePC.cpp - PC tracing--------------------------------------===//
  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. // Trace PCs.
  9. // This module implements __sanitizer_cov_trace_pc_guard[_init],
  10. // the callback required for -fsanitize-coverage=trace-pc-guard instrumentation.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "FuzzerTracePC.h"
  14. #include "FuzzerBuiltins.h"
  15. #include "FuzzerBuiltinsMsvc.h"
  16. #include "FuzzerCorpus.h"
  17. #include "FuzzerDefs.h"
  18. #include "FuzzerDictionary.h"
  19. #include "FuzzerExtFunctions.h"
  20. #include "FuzzerIO.h"
  21. #include "FuzzerPlatform.h"
  22. #include "FuzzerUtil.h"
  23. #include "FuzzerValueBitMap.h"
  24. #include <set>
  25. // Used by -fsanitize-coverage=stack-depth to track stack depth
  26. ATTRIBUTES_INTERFACE_TLS_INITIAL_EXEC uintptr_t __sancov_lowest_stack;
  27. namespace fuzzer {
  28. TracePC TPC;
  29. size_t TracePC::GetTotalPCCoverage() {
  30. return ObservedPCs.size();
  31. }
  32. void TracePC::HandleInline8bitCountersInit(uint8_t *Start, uint8_t *Stop) {
  33. if (Start == Stop) return;
  34. if (NumModules &&
  35. Modules[NumModules - 1].Start() == Start)
  36. return;
  37. assert(NumModules <
  38. sizeof(Modules) / sizeof(Modules[0]));
  39. auto &M = Modules[NumModules++];
  40. uint8_t *AlignedStart = RoundUpByPage(Start);
  41. uint8_t *AlignedStop = RoundDownByPage(Stop);
  42. size_t NumFullPages = AlignedStop > AlignedStart ?
  43. (AlignedStop - AlignedStart) / PageSize() : 0;
  44. bool NeedFirst = Start < AlignedStart || !NumFullPages;
  45. bool NeedLast = Stop > AlignedStop && AlignedStop >= AlignedStart;
  46. M.NumRegions = NumFullPages + NeedFirst + NeedLast;;
  47. assert(M.NumRegions > 0);
  48. M.Regions = new Module::Region[M.NumRegions];
  49. assert(M.Regions);
  50. size_t R = 0;
  51. if (NeedFirst)
  52. M.Regions[R++] = {Start, std::min(Stop, AlignedStart), true, false};
  53. for (uint8_t *P = AlignedStart; P < AlignedStop; P += PageSize())
  54. M.Regions[R++] = {P, P + PageSize(), true, true};
  55. if (NeedLast)
  56. M.Regions[R++] = {AlignedStop, Stop, true, false};
  57. assert(R == M.NumRegions);
  58. assert(M.Size() == (size_t)(Stop - Start));
  59. assert(M.Stop() == Stop);
  60. assert(M.Start() == Start);
  61. NumInline8bitCounters += M.Size();
  62. }
  63. void TracePC::HandlePCsInit(const uintptr_t *Start, const uintptr_t *Stop) {
  64. const PCTableEntry *B = reinterpret_cast<const PCTableEntry *>(Start);
  65. const PCTableEntry *E = reinterpret_cast<const PCTableEntry *>(Stop);
  66. if (NumPCTables && ModulePCTable[NumPCTables - 1].Start == B) return;
  67. assert(NumPCTables < sizeof(ModulePCTable) / sizeof(ModulePCTable[0]));
  68. ModulePCTable[NumPCTables++] = {B, E};
  69. NumPCsInPCTables += E - B;
  70. }
  71. void TracePC::PrintModuleInfo() {
  72. if (NumModules) {
  73. Printf("INFO: Loaded %zd modules (%zd inline 8-bit counters): ",
  74. NumModules, NumInline8bitCounters);
  75. for (size_t i = 0; i < NumModules; i++)
  76. Printf("%zd [%p, %p), ", Modules[i].Size(), Modules[i].Start(),
  77. Modules[i].Stop());
  78. Printf("\n");
  79. }
  80. if (NumPCTables) {
  81. Printf("INFO: Loaded %zd PC tables (%zd PCs): ", NumPCTables,
  82. NumPCsInPCTables);
  83. for (size_t i = 0; i < NumPCTables; i++) {
  84. Printf("%zd [%p,%p), ", ModulePCTable[i].Stop - ModulePCTable[i].Start,
  85. ModulePCTable[i].Start, ModulePCTable[i].Stop);
  86. }
  87. Printf("\n");
  88. if (NumInline8bitCounters && NumInline8bitCounters != NumPCsInPCTables) {
  89. Printf("ERROR: The size of coverage PC tables does not match the\n"
  90. "number of instrumented PCs. This might be a compiler bug,\n"
  91. "please contact the libFuzzer developers.\n"
  92. "Also check https://bugs.llvm.org/show_bug.cgi?id=34636\n"
  93. "for possible workarounds (tl;dr: don't use the old GNU ld)\n");
  94. _Exit(1);
  95. }
  96. }
  97. if (size_t NumExtraCounters = ExtraCountersEnd() - ExtraCountersBegin())
  98. Printf("INFO: %zd Extra Counters\n", NumExtraCounters);
  99. size_t MaxFeatures = CollectFeatures([](uint32_t) {});
  100. if (MaxFeatures > std::numeric_limits<uint32_t>::max())
  101. Printf("WARNING: The coverage PC tables may produce up to %zu features.\n"
  102. "This exceeds the maximum 32-bit value. Some features may be\n"
  103. "ignored, and fuzzing may become less precise. If possible,\n"
  104. "consider refactoring the fuzzer into several smaller fuzzers\n"
  105. "linked against only a portion of the current target.\n",
  106. MaxFeatures);
  107. }
  108. ATTRIBUTE_NO_SANITIZE_ALL
  109. void TracePC::HandleCallerCallee(uintptr_t Caller, uintptr_t Callee) {
  110. const uintptr_t kBits = 12;
  111. const uintptr_t kMask = (1 << kBits) - 1;
  112. uintptr_t Idx = (Caller & kMask) | ((Callee & kMask) << kBits);
  113. ValueProfileMap.AddValueModPrime(Idx);
  114. }
  115. /// \return the address of the previous instruction.
  116. /// Note: the logic is copied from `sanitizer_common/sanitizer_stacktrace.h`
  117. inline ALWAYS_INLINE uintptr_t GetPreviousInstructionPc(uintptr_t PC) {
  118. #if defined(__arm__)
  119. // T32 (Thumb) branch instructions might be 16 or 32 bit long,
  120. // so we return (pc-2) in that case in order to be safe.
  121. // For A32 mode we return (pc-4) because all instructions are 32 bit long.
  122. return (PC - 3) & (~1);
  123. #elif defined(__sparc__) || defined(__mips__)
  124. return PC - 8;
  125. #elif defined(__riscv__)
  126. return PC - 2;
  127. #elif defined(__i386__) || defined(__x86_64__) || defined(_M_IX86) || defined(_M_X64)
  128. return PC - 1;
  129. #else
  130. return PC - 4;
  131. #endif
  132. }
  133. /// \return the address of the next instruction.
  134. /// Note: the logic is copied from `sanitizer_common/sanitizer_stacktrace.cpp`
  135. ALWAYS_INLINE uintptr_t TracePC::GetNextInstructionPc(uintptr_t PC) {
  136. #if defined(__mips__)
  137. return PC + 8;
  138. #elif defined(__powerpc__) || defined(__sparc__) || defined(__arm__) || \
  139. defined(__aarch64__)
  140. return PC + 4;
  141. #else
  142. return PC + 1;
  143. #endif
  144. }
  145. void TracePC::UpdateObservedPCs() {
  146. std::vector<uintptr_t> CoveredFuncs;
  147. auto ObservePC = [&](const PCTableEntry *TE) {
  148. if (ObservedPCs.insert(TE).second && DoPrintNewPCs) {
  149. PrintPC("\tNEW_PC: %p %F %L", "\tNEW_PC: %p",
  150. GetNextInstructionPc(TE->PC));
  151. Printf("\n");
  152. }
  153. };
  154. auto Observe = [&](const PCTableEntry *TE) {
  155. if (PcIsFuncEntry(TE))
  156. if (++ObservedFuncs[TE->PC] == 1 && NumPrintNewFuncs)
  157. CoveredFuncs.push_back(TE->PC);
  158. ObservePC(TE);
  159. };
  160. if (NumPCsInPCTables) {
  161. if (NumInline8bitCounters == NumPCsInPCTables) {
  162. for (size_t i = 0; i < NumModules; i++) {
  163. auto &M = Modules[i];
  164. assert(M.Size() ==
  165. (size_t)(ModulePCTable[i].Stop - ModulePCTable[i].Start));
  166. for (size_t r = 0; r < M.NumRegions; r++) {
  167. auto &R = M.Regions[r];
  168. if (!R.Enabled) continue;
  169. for (uint8_t *P = R.Start; P < R.Stop; P++)
  170. if (*P)
  171. Observe(&ModulePCTable[i].Start[M.Idx(P)]);
  172. }
  173. }
  174. }
  175. }
  176. for (size_t i = 0, N = Min(CoveredFuncs.size(), NumPrintNewFuncs); i < N;
  177. i++) {
  178. Printf("\tNEW_FUNC[%zd/%zd]: ", i + 1, CoveredFuncs.size());
  179. PrintPC("%p %F %L", "%p", GetNextInstructionPc(CoveredFuncs[i]));
  180. Printf("\n");
  181. }
  182. }
  183. uintptr_t TracePC::PCTableEntryIdx(const PCTableEntry *TE) {
  184. size_t TotalTEs = 0;
  185. for (size_t i = 0; i < NumPCTables; i++) {
  186. auto &M = ModulePCTable[i];
  187. if (TE >= M.Start && TE < M.Stop)
  188. return TotalTEs + TE - M.Start;
  189. TotalTEs += M.Stop - M.Start;
  190. }
  191. assert(0);
  192. return 0;
  193. }
  194. const TracePC::PCTableEntry *TracePC::PCTableEntryByIdx(uintptr_t Idx) {
  195. for (size_t i = 0; i < NumPCTables; i++) {
  196. auto &M = ModulePCTable[i];
  197. size_t Size = M.Stop - M.Start;
  198. if (Idx < Size) return &M.Start[Idx];
  199. Idx -= Size;
  200. }
  201. return nullptr;
  202. }
  203. static std::string GetModuleName(uintptr_t PC) {
  204. char ModulePathRaw[4096] = ""; // What's PATH_MAX in portable C++?
  205. void *OffsetRaw = nullptr;
  206. if (!EF->__sanitizer_get_module_and_offset_for_pc(
  207. reinterpret_cast<void *>(PC), ModulePathRaw,
  208. sizeof(ModulePathRaw), &OffsetRaw))
  209. return "";
  210. return ModulePathRaw;
  211. }
  212. template<class CallBack>
  213. void TracePC::IterateCoveredFunctions(CallBack CB) {
  214. for (size_t i = 0; i < NumPCTables; i++) {
  215. auto &M = ModulePCTable[i];
  216. assert(M.Start < M.Stop);
  217. auto ModuleName = GetModuleName(M.Start->PC);
  218. for (auto NextFE = M.Start; NextFE < M.Stop; ) {
  219. auto FE = NextFE;
  220. assert(PcIsFuncEntry(FE) && "Not a function entry point");
  221. do {
  222. NextFE++;
  223. } while (NextFE < M.Stop && !(PcIsFuncEntry(NextFE)));
  224. CB(FE, NextFE, ObservedFuncs[FE->PC]);
  225. }
  226. }
  227. }
  228. void TracePC::SetFocusFunction(const std::string &FuncName) {
  229. // This function should be called once.
  230. assert(!FocusFunctionCounterPtr);
  231. // "auto" is not a valid function name. If this function is called with "auto"
  232. // that means the auto focus functionality failed.
  233. if (FuncName.empty() || FuncName == "auto")
  234. return;
  235. for (size_t M = 0; M < NumModules; M++) {
  236. auto &PCTE = ModulePCTable[M];
  237. size_t N = PCTE.Stop - PCTE.Start;
  238. for (size_t I = 0; I < N; I++) {
  239. if (!(PcIsFuncEntry(&PCTE.Start[I]))) continue; // not a function entry.
  240. auto Name = DescribePC("%F", GetNextInstructionPc(PCTE.Start[I].PC));
  241. if (Name[0] == 'i' && Name[1] == 'n' && Name[2] == ' ')
  242. Name = Name.substr(3, std::string::npos);
  243. if (FuncName != Name) continue;
  244. Printf("INFO: Focus function is set to '%s'\n", Name.c_str());
  245. FocusFunctionCounterPtr = Modules[M].Start() + I;
  246. return;
  247. }
  248. }
  249. Printf("ERROR: Failed to set focus function. Make sure the function name is "
  250. "valid (%s) and symbolization is enabled.\n", FuncName.c_str());
  251. exit(1);
  252. }
  253. bool TracePC::ObservedFocusFunction() {
  254. return FocusFunctionCounterPtr && *FocusFunctionCounterPtr;
  255. }
  256. void TracePC::PrintCoverage(bool PrintAllCounters) {
  257. if (!EF->__sanitizer_symbolize_pc ||
  258. !EF->__sanitizer_get_module_and_offset_for_pc) {
  259. Printf("INFO: __sanitizer_symbolize_pc or "
  260. "__sanitizer_get_module_and_offset_for_pc is not available,"
  261. " not printing coverage\n");
  262. return;
  263. }
  264. Printf(PrintAllCounters ? "FULL COVERAGE:\n" : "COVERAGE:\n");
  265. auto CoveredFunctionCallback = [&](const PCTableEntry *First,
  266. const PCTableEntry *Last,
  267. uintptr_t Counter) {
  268. assert(First < Last);
  269. auto VisualizePC = GetNextInstructionPc(First->PC);
  270. std::string FileStr = DescribePC("%s", VisualizePC);
  271. if (!IsInterestingCoverageFile(FileStr))
  272. return;
  273. std::string FunctionStr = DescribePC("%F", VisualizePC);
  274. if (FunctionStr.find("in ") == 0)
  275. FunctionStr = FunctionStr.substr(3);
  276. std::string LineStr = DescribePC("%l", VisualizePC);
  277. size_t NumEdges = Last - First;
  278. std::vector<uintptr_t> UncoveredPCs;
  279. std::vector<uintptr_t> CoveredPCs;
  280. for (auto TE = First; TE < Last; TE++)
  281. if (!ObservedPCs.count(TE))
  282. UncoveredPCs.push_back(TE->PC);
  283. else
  284. CoveredPCs.push_back(TE->PC);
  285. if (PrintAllCounters) {
  286. Printf("U");
  287. for (auto PC : UncoveredPCs)
  288. Printf(DescribePC(" %l", GetNextInstructionPc(PC)).c_str());
  289. Printf("\n");
  290. Printf("C");
  291. for (auto PC : CoveredPCs)
  292. Printf(DescribePC(" %l", GetNextInstructionPc(PC)).c_str());
  293. Printf("\n");
  294. } else {
  295. Printf("%sCOVERED_FUNC: hits: %zd", Counter ? "" : "UN", Counter);
  296. Printf(" edges: %zd/%zd", NumEdges - UncoveredPCs.size(), NumEdges);
  297. Printf(" %s %s:%s\n", FunctionStr.c_str(), FileStr.c_str(),
  298. LineStr.c_str());
  299. if (Counter)
  300. for (auto PC : UncoveredPCs)
  301. Printf(" UNCOVERED_PC: %s\n",
  302. DescribePC("%s:%l", GetNextInstructionPc(PC)).c_str());
  303. }
  304. };
  305. IterateCoveredFunctions(CoveredFunctionCallback);
  306. }
  307. // Value profile.
  308. // We keep track of various values that affect control flow.
  309. // These values are inserted into a bit-set-based hash map.
  310. // Every new bit in the map is treated as a new coverage.
  311. //
  312. // For memcmp/strcmp/etc the interesting value is the length of the common
  313. // prefix of the parameters.
  314. // For cmp instructions the interesting value is a XOR of the parameters.
  315. // The interesting value is mixed up with the PC and is then added to the map.
  316. ATTRIBUTE_NO_SANITIZE_ALL
  317. void TracePC::AddValueForMemcmp(void *caller_pc, const void *s1, const void *s2,
  318. size_t n, bool StopAtZero) {
  319. if (!n) return;
  320. size_t Len = std::min(n, Word::GetMaxSize());
  321. const uint8_t *A1 = reinterpret_cast<const uint8_t *>(s1);
  322. const uint8_t *A2 = reinterpret_cast<const uint8_t *>(s2);
  323. uint8_t B1[Word::kMaxSize];
  324. uint8_t B2[Word::kMaxSize];
  325. // Copy the data into locals in this non-msan-instrumented function
  326. // to avoid msan complaining further.
  327. size_t Hash = 0; // Compute some simple hash of both strings.
  328. for (size_t i = 0; i < Len; i++) {
  329. B1[i] = A1[i];
  330. B2[i] = A2[i];
  331. size_t T = B1[i];
  332. Hash ^= (T << 8) | B2[i];
  333. }
  334. size_t I = 0;
  335. uint8_t HammingDistance = 0;
  336. for (; I < Len; I++) {
  337. if (B1[I] != B2[I] || (StopAtZero && B1[I] == 0)) {
  338. HammingDistance = static_cast<uint8_t>(Popcountll(B1[I] ^ B2[I]));
  339. break;
  340. }
  341. }
  342. size_t PC = reinterpret_cast<size_t>(caller_pc);
  343. size_t Idx = (PC & 4095) | (I << 12);
  344. Idx += HammingDistance;
  345. ValueProfileMap.AddValue(Idx);
  346. TORCW.Insert(Idx ^ Hash, Word(B1, Len), Word(B2, Len));
  347. }
  348. template <class T>
  349. ATTRIBUTE_TARGET_POPCNT ALWAYS_INLINE
  350. ATTRIBUTE_NO_SANITIZE_ALL
  351. void TracePC::HandleCmp(uintptr_t PC, T Arg1, T Arg2) {
  352. uint64_t ArgXor = Arg1 ^ Arg2;
  353. if (sizeof(T) == 4)
  354. TORC4.Insert(ArgXor, Arg1, Arg2);
  355. else if (sizeof(T) == 8)
  356. TORC8.Insert(ArgXor, Arg1, Arg2);
  357. uint64_t HammingDistance = Popcountll(ArgXor); // [0,64]
  358. uint64_t AbsoluteDistance = (Arg1 == Arg2 ? 0 : Clzll(Arg1 - Arg2) + 1);
  359. ValueProfileMap.AddValue(PC * 128 + HammingDistance);
  360. ValueProfileMap.AddValue(PC * 128 + 64 + AbsoluteDistance);
  361. }
  362. ATTRIBUTE_NO_SANITIZE_MEMORY
  363. static size_t InternalStrnlen(const char *S, size_t MaxLen) {
  364. size_t Len = 0;
  365. for (; Len < MaxLen && S[Len]; Len++) {}
  366. return Len;
  367. }
  368. // Finds min of (strlen(S1), strlen(S2)).
  369. // Needed because one of these strings may actually be non-zero terminated.
  370. ATTRIBUTE_NO_SANITIZE_MEMORY
  371. static size_t InternalStrnlen2(const char *S1, const char *S2) {
  372. size_t Len = 0;
  373. for (; S1[Len] && S2[Len]; Len++) {}
  374. return Len;
  375. }
  376. void TracePC::ClearInlineCounters() {
  377. IterateCounterRegions([](const Module::Region &R){
  378. if (R.Enabled)
  379. memset(R.Start, 0, R.Stop - R.Start);
  380. });
  381. }
  382. ATTRIBUTE_NO_SANITIZE_ALL
  383. void TracePC::RecordInitialStack() {
  384. int stack;
  385. __sancov_lowest_stack = InitialStack = reinterpret_cast<uintptr_t>(&stack);
  386. }
  387. uintptr_t TracePC::GetMaxStackOffset() const {
  388. return InitialStack - __sancov_lowest_stack; // Stack grows down
  389. }
  390. void WarnAboutDeprecatedInstrumentation(const char *flag) {
  391. // Use RawPrint because Printf cannot be used on Windows before OutputFile is
  392. // initialized.
  393. RawPrint(flag);
  394. RawPrint(
  395. " is no longer supported by libFuzzer.\n"
  396. "Please either migrate to a compiler that supports -fsanitize=fuzzer\n"
  397. "or use an older version of libFuzzer\n");
  398. exit(1);
  399. }
  400. } // namespace fuzzer
  401. extern "C" {
  402. ATTRIBUTE_INTERFACE
  403. ATTRIBUTE_NO_SANITIZE_ALL
  404. void __sanitizer_cov_trace_pc_guard(uint32_t *Guard) {
  405. fuzzer::WarnAboutDeprecatedInstrumentation(
  406. "-fsanitize-coverage=trace-pc-guard");
  407. }
  408. // Best-effort support for -fsanitize-coverage=trace-pc, which is available
  409. // in both Clang and GCC.
  410. ATTRIBUTE_INTERFACE
  411. ATTRIBUTE_NO_SANITIZE_ALL
  412. void __sanitizer_cov_trace_pc() {
  413. fuzzer::WarnAboutDeprecatedInstrumentation("-fsanitize-coverage=trace-pc");
  414. }
  415. ATTRIBUTE_INTERFACE
  416. void __sanitizer_cov_trace_pc_guard_init(uint32_t *Start, uint32_t *Stop) {
  417. fuzzer::WarnAboutDeprecatedInstrumentation(
  418. "-fsanitize-coverage=trace-pc-guard");
  419. }
  420. ATTRIBUTE_INTERFACE
  421. void __sanitizer_cov_8bit_counters_init(uint8_t *Start, uint8_t *Stop) {
  422. fuzzer::TPC.HandleInline8bitCountersInit(Start, Stop);
  423. }
  424. ATTRIBUTE_INTERFACE
  425. void __sanitizer_cov_pcs_init(const uintptr_t *pcs_beg,
  426. const uintptr_t *pcs_end) {
  427. fuzzer::TPC.HandlePCsInit(pcs_beg, pcs_end);
  428. }
  429. ATTRIBUTE_INTERFACE
  430. ATTRIBUTE_NO_SANITIZE_ALL
  431. void __sanitizer_cov_trace_pc_indir(uintptr_t Callee) {
  432. uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC());
  433. fuzzer::TPC.HandleCallerCallee(PC, Callee);
  434. }
  435. ATTRIBUTE_INTERFACE
  436. ATTRIBUTE_NO_SANITIZE_ALL
  437. ATTRIBUTE_TARGET_POPCNT
  438. void __sanitizer_cov_trace_cmp8(uint64_t Arg1, uint64_t Arg2) {
  439. uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC());
  440. fuzzer::TPC.HandleCmp(PC, Arg1, Arg2);
  441. }
  442. ATTRIBUTE_INTERFACE
  443. ATTRIBUTE_NO_SANITIZE_ALL
  444. ATTRIBUTE_TARGET_POPCNT
  445. // Now the __sanitizer_cov_trace_const_cmp[1248] callbacks just mimic
  446. // the behaviour of __sanitizer_cov_trace_cmp[1248] ones. This, however,
  447. // should be changed later to make full use of instrumentation.
  448. void __sanitizer_cov_trace_const_cmp8(uint64_t Arg1, uint64_t Arg2) {
  449. uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC());
  450. fuzzer::TPC.HandleCmp(PC, Arg1, Arg2);
  451. }
  452. ATTRIBUTE_INTERFACE
  453. ATTRIBUTE_NO_SANITIZE_ALL
  454. ATTRIBUTE_TARGET_POPCNT
  455. void __sanitizer_cov_trace_cmp4(uint32_t Arg1, uint32_t Arg2) {
  456. uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC());
  457. fuzzer::TPC.HandleCmp(PC, Arg1, Arg2);
  458. }
  459. ATTRIBUTE_INTERFACE
  460. ATTRIBUTE_NO_SANITIZE_ALL
  461. ATTRIBUTE_TARGET_POPCNT
  462. void __sanitizer_cov_trace_const_cmp4(uint32_t Arg1, uint32_t Arg2) {
  463. uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC());
  464. fuzzer::TPC.HandleCmp(PC, Arg1, Arg2);
  465. }
  466. ATTRIBUTE_INTERFACE
  467. ATTRIBUTE_NO_SANITIZE_ALL
  468. ATTRIBUTE_TARGET_POPCNT
  469. void __sanitizer_cov_trace_cmp2(uint16_t Arg1, uint16_t Arg2) {
  470. uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC());
  471. fuzzer::TPC.HandleCmp(PC, Arg1, Arg2);
  472. }
  473. ATTRIBUTE_INTERFACE
  474. ATTRIBUTE_NO_SANITIZE_ALL
  475. ATTRIBUTE_TARGET_POPCNT
  476. void __sanitizer_cov_trace_const_cmp2(uint16_t Arg1, uint16_t Arg2) {
  477. uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC());
  478. fuzzer::TPC.HandleCmp(PC, Arg1, Arg2);
  479. }
  480. ATTRIBUTE_INTERFACE
  481. ATTRIBUTE_NO_SANITIZE_ALL
  482. ATTRIBUTE_TARGET_POPCNT
  483. void __sanitizer_cov_trace_cmp1(uint8_t Arg1, uint8_t Arg2) {
  484. uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC());
  485. fuzzer::TPC.HandleCmp(PC, Arg1, Arg2);
  486. }
  487. ATTRIBUTE_INTERFACE
  488. ATTRIBUTE_NO_SANITIZE_ALL
  489. ATTRIBUTE_TARGET_POPCNT
  490. void __sanitizer_cov_trace_const_cmp1(uint8_t Arg1, uint8_t Arg2) {
  491. uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC());
  492. fuzzer::TPC.HandleCmp(PC, Arg1, Arg2);
  493. }
  494. ATTRIBUTE_INTERFACE
  495. ATTRIBUTE_NO_SANITIZE_ALL
  496. ATTRIBUTE_TARGET_POPCNT
  497. void __sanitizer_cov_trace_switch(uint64_t Val, uint64_t *Cases) {
  498. uint64_t N = Cases[0];
  499. uint64_t ValSizeInBits = Cases[1];
  500. uint64_t *Vals = Cases + 2;
  501. // Skip the most common and the most boring case: all switch values are small.
  502. // We may want to skip this at compile-time, but it will make the
  503. // instrumentation less general.
  504. if (Vals[N - 1] < 256)
  505. return;
  506. // Also skip small inputs values, they won't give good signal.
  507. if (Val < 256)
  508. return;
  509. uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC());
  510. size_t i;
  511. uint64_t Smaller = 0;
  512. uint64_t Larger = ~(uint64_t)0;
  513. // Find two switch values such that Smaller < Val < Larger.
  514. // Use 0 and 0xfff..f as the defaults.
  515. for (i = 0; i < N; i++) {
  516. if (Val < Vals[i]) {
  517. Larger = Vals[i];
  518. break;
  519. }
  520. if (Val > Vals[i]) Smaller = Vals[i];
  521. }
  522. // Apply HandleCmp to {Val,Smaller} and {Val, Larger},
  523. // use i as the PC modifier for HandleCmp.
  524. if (ValSizeInBits == 16) {
  525. fuzzer::TPC.HandleCmp(PC + 2 * i, static_cast<uint16_t>(Val),
  526. (uint16_t)(Smaller));
  527. fuzzer::TPC.HandleCmp(PC + 2 * i + 1, static_cast<uint16_t>(Val),
  528. (uint16_t)(Larger));
  529. } else if (ValSizeInBits == 32) {
  530. fuzzer::TPC.HandleCmp(PC + 2 * i, static_cast<uint32_t>(Val),
  531. (uint32_t)(Smaller));
  532. fuzzer::TPC.HandleCmp(PC + 2 * i + 1, static_cast<uint32_t>(Val),
  533. (uint32_t)(Larger));
  534. } else {
  535. fuzzer::TPC.HandleCmp(PC + 2*i, Val, Smaller);
  536. fuzzer::TPC.HandleCmp(PC + 2*i + 1, Val, Larger);
  537. }
  538. }
  539. ATTRIBUTE_INTERFACE
  540. ATTRIBUTE_NO_SANITIZE_ALL
  541. ATTRIBUTE_TARGET_POPCNT
  542. void __sanitizer_cov_trace_div4(uint32_t Val) {
  543. uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC());
  544. fuzzer::TPC.HandleCmp(PC, Val, (uint32_t)0);
  545. }
  546. ATTRIBUTE_INTERFACE
  547. ATTRIBUTE_NO_SANITIZE_ALL
  548. ATTRIBUTE_TARGET_POPCNT
  549. void __sanitizer_cov_trace_div8(uint64_t Val) {
  550. uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC());
  551. fuzzer::TPC.HandleCmp(PC, Val, (uint64_t)0);
  552. }
  553. ATTRIBUTE_INTERFACE
  554. ATTRIBUTE_NO_SANITIZE_ALL
  555. ATTRIBUTE_TARGET_POPCNT
  556. void __sanitizer_cov_trace_gep(uintptr_t Idx) {
  557. uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC());
  558. fuzzer::TPC.HandleCmp(PC, Idx, (uintptr_t)0);
  559. }
  560. ATTRIBUTE_INTERFACE ATTRIBUTE_NO_SANITIZE_MEMORY
  561. void __sanitizer_weak_hook_memcmp(void *caller_pc, const void *s1,
  562. const void *s2, size_t n, int result) {
  563. if (!fuzzer::RunningUserCallback) return;
  564. if (result == 0) return; // No reason to mutate.
  565. if (n <= 1) return; // Not interesting.
  566. fuzzer::TPC.AddValueForMemcmp(caller_pc, s1, s2, n, /*StopAtZero*/false);
  567. }
  568. ATTRIBUTE_INTERFACE ATTRIBUTE_NO_SANITIZE_MEMORY
  569. void __sanitizer_weak_hook_strncmp(void *caller_pc, const char *s1,
  570. const char *s2, size_t n, int result) {
  571. if (!fuzzer::RunningUserCallback) return;
  572. if (result == 0) return; // No reason to mutate.
  573. size_t Len1 = fuzzer::InternalStrnlen(s1, n);
  574. size_t Len2 = fuzzer::InternalStrnlen(s2, n);
  575. n = std::min(n, Len1);
  576. n = std::min(n, Len2);
  577. if (n <= 1) return; // Not interesting.
  578. fuzzer::TPC.AddValueForMemcmp(caller_pc, s1, s2, n, /*StopAtZero*/true);
  579. }
  580. ATTRIBUTE_INTERFACE ATTRIBUTE_NO_SANITIZE_MEMORY
  581. void __sanitizer_weak_hook_strcmp(void *caller_pc, const char *s1,
  582. const char *s2, int result) {
  583. if (!fuzzer::RunningUserCallback) return;
  584. if (result == 0) return; // No reason to mutate.
  585. size_t N = fuzzer::InternalStrnlen2(s1, s2);
  586. if (N <= 1) return; // Not interesting.
  587. fuzzer::TPC.AddValueForMemcmp(caller_pc, s1, s2, N, /*StopAtZero*/true);
  588. }
  589. ATTRIBUTE_INTERFACE ATTRIBUTE_NO_SANITIZE_MEMORY
  590. void __sanitizer_weak_hook_strncasecmp(void *called_pc, const char *s1,
  591. const char *s2, size_t n, int result) {
  592. if (!fuzzer::RunningUserCallback) return;
  593. return __sanitizer_weak_hook_strncmp(called_pc, s1, s2, n, result);
  594. }
  595. ATTRIBUTE_INTERFACE ATTRIBUTE_NO_SANITIZE_MEMORY
  596. void __sanitizer_weak_hook_strcasecmp(void *called_pc, const char *s1,
  597. const char *s2, int result) {
  598. if (!fuzzer::RunningUserCallback) return;
  599. return __sanitizer_weak_hook_strcmp(called_pc, s1, s2, result);
  600. }
  601. ATTRIBUTE_INTERFACE ATTRIBUTE_NO_SANITIZE_MEMORY
  602. void __sanitizer_weak_hook_strstr(void *called_pc, const char *s1,
  603. const char *s2, char *result) {
  604. if (!fuzzer::RunningUserCallback) return;
  605. fuzzer::TPC.MMT.Add(reinterpret_cast<const uint8_t *>(s2), strlen(s2));
  606. }
  607. ATTRIBUTE_INTERFACE ATTRIBUTE_NO_SANITIZE_MEMORY
  608. void __sanitizer_weak_hook_strcasestr(void *called_pc, const char *s1,
  609. const char *s2, char *result) {
  610. if (!fuzzer::RunningUserCallback) return;
  611. fuzzer::TPC.MMT.Add(reinterpret_cast<const uint8_t *>(s2), strlen(s2));
  612. }
  613. ATTRIBUTE_INTERFACE ATTRIBUTE_NO_SANITIZE_MEMORY
  614. void __sanitizer_weak_hook_memmem(void *called_pc, const void *s1, size_t len1,
  615. const void *s2, size_t len2, void *result) {
  616. if (!fuzzer::RunningUserCallback) return;
  617. fuzzer::TPC.MMT.Add(reinterpret_cast<const uint8_t *>(s2), len2);
  618. }
  619. } // extern "C"