1//===- FuzzerInternal.h - Internal header for the Fuzzer --------*- C++ -* ===//
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// Define the main class fuzzer::Fuzzer and most functions.
9//===----------------------------------------------------------------------===//
10
11#ifndef LLVM_FUZZER_INTERNAL_H
12#define LLVM_FUZZER_INTERNAL_H
13
14#include "FuzzerDataFlowTrace.h"
15#include "FuzzerDefs.h"
16#include "FuzzerExtFunctions.h"
17#include "FuzzerInterface.h"
18#include "FuzzerOptions.h"
19#include "FuzzerSHA1.h"
20#include "FuzzerValueBitMap.h"
21#include <algorithm>
22#include <atomic>
23#include <chrono>
24#include <climits>
25#include <cstdlib>
26#include <string.h>
27
28namespace fuzzer {
29
30using namespace std::chrono;
31
32class Fuzzer final {
33public:
34 Fuzzer(UserCallback CB, InputCorpus &Corpus, MutationDispatcher &MD,
35 const FuzzingOptions &Options);
36 ~Fuzzer() = delete;
37 void Loop(std::vector<SizedFile> &CorporaFiles);
38 void ReadAndExecuteSeedCorpora(std::vector<SizedFile> &CorporaFiles);
39 void MinimizeCrashLoop(const Unit &U);
40 void RereadOutputCorpus(size_t MaxSize);
41
42 size_t secondsSinceProcessStartUp() {
43 return duration_cast<seconds>(fd: system_clock::now() - ProcessStartTime)
44 .count();
45 }
46
47 size_t secondsSinceLastNewCorpus() {
48 return duration_cast<seconds>(fd: system_clock::now() - LastNewCorpusTime)
49 .count();
50 }
51
52 bool TimedOut() {
53 return (Options.MaxTotalTimeSec > 0 &&
54 secondsSinceProcessStartUp() >
55 static_cast<size_t>(Options.MaxTotalTimeSec)) ||
56 (Options.StaleCorpusTimeoutSec > 0 &&
57 secondsSinceLastNewCorpus() >
58 static_cast<size_t>(Options.StaleCorpusTimeoutSec));
59 }
60
61 size_t execPerSec() {
62 size_t Seconds = secondsSinceProcessStartUp();
63 return Seconds ? TotalNumberOfRuns / Seconds : 0;
64 }
65
66 size_t getTotalNumberOfRuns() { return TotalNumberOfRuns; }
67
68 static void StaticAlarmCallback();
69 static void StaticCrashSignalCallback();
70 static void StaticExitCallback();
71 static void StaticInterruptCallback();
72 static void StaticFileSizeExceedCallback();
73 static void StaticGracefulExitCallback();
74
75 // Executes the target callback on {Data, Size} once.
76 // Returns false if the input was rejected by the target (target returned -1),
77 // and true otherwise.
78 bool ExecuteCallback(const uint8_t *Data, size_t Size);
79 bool RunOne(const uint8_t *Data, size_t Size, bool MayDeleteFile = false,
80 InputInfo *II = nullptr, bool ForceAddToCorpus = false,
81 bool *FoundUniqFeatures = nullptr);
82 void TPCUpdateObservedPCs();
83
84 // Merge Corpora[1:] into Corpora[0].
85 void Merge(const std::vector<std::string> &Corpora);
86 void CrashResistantMergeInternalStep(const std::string &ControlFilePath,
87 bool IsSetCoverMerge);
88 MutationDispatcher &GetMD() { return MD; }
89 void PrintFinalStats();
90 void SetMaxInputLen(size_t MaxInputLen);
91 void SetMaxMutationLen(size_t MaxMutationLen);
92 void RssLimitCallback();
93
94 bool InFuzzingThread() const { return IsMyThread; }
95 size_t GetCurrentUnitInFuzzingThead(const uint8_t **Data) const;
96 void TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
97 bool DuringInitialCorpusExecution);
98
99 void HandleMalloc(size_t Size);
100 static void MaybeExitGracefully();
101 static int InterruptExitCode();
102 std::string WriteToOutputCorpus(const Unit &U);
103
104private:
105 void AlarmCallback();
106 void CrashCallback();
107 void ExitCallback();
108 void CrashOnOverwrittenData();
109 void InterruptCallback();
110 void MutateAndTestOne();
111 void PurgeAllocator();
112 void ReportNewCoverage(InputInfo *II, const Unit &U);
113 void PrintPulseAndReportSlowInput(const uint8_t *Data, size_t Size);
114 void WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix);
115 void PrintStats(const char *Where, const char *End = "\n", size_t Units = 0,
116 size_t Features = 0);
117 void PrintStatusForNewUnit(const Unit &U, const char *Text);
118 void CheckExitOnSrcPosOrItem();
119
120 static void StaticDeathCallback();
121 void DumpCurrentUnit(const char *Prefix);
122 void DeathCallback();
123
124 void AllocateCurrentUnitData();
125 uint8_t *CurrentUnitData = nullptr;
126 std::atomic<size_t> CurrentUnitSize;
127 uint8_t BaseSha1[kSHA1NumBytes]; // Checksum of the base unit.
128
129 bool GracefulExitRequested = false;
130
131 size_t TotalNumberOfRuns = 0;
132 size_t NumberOfNewUnitsAdded = 0;
133
134 size_t LastCorpusUpdateRun = 0;
135
136 bool HasMoreMallocsThanFrees = false;
137 size_t NumberOfLeakDetectionAttempts = 0;
138
139 system_clock::time_point LastAllocatorPurgeAttemptTime = system_clock::now();
140
141 UserCallback CB;
142 InputCorpus &Corpus;
143 MutationDispatcher &MD;
144 FuzzingOptions Options;
145 DataFlowTrace DFT;
146
147 system_clock::time_point ProcessStartTime = system_clock::now();
148 system_clock::time_point LastNewCorpusTime = system_clock::now();
149 system_clock::time_point UnitStartTime, UnitStopTime;
150 long TimeOfLongestUnitInSeconds = 0;
151 long EpochOfLastReadOfOutputCorpus = 0;
152
153 size_t MaxInputLen = 0;
154 size_t MaxMutationLen = 0;
155 size_t TmpMaxMutationLen = 0;
156
157 std::vector<uint32_t> UniqFeatureSetTmp;
158
159 // Need to know our own thread.
160 static thread_local bool IsMyThread;
161};
162
163struct ScopedEnableMsanInterceptorChecks {
164 ScopedEnableMsanInterceptorChecks() {
165 if (EF->__msan_scoped_enable_interceptor_checks)
166 EF->__msan_scoped_enable_interceptor_checks();
167 }
168 ~ScopedEnableMsanInterceptorChecks() {
169 if (EF->__msan_scoped_disable_interceptor_checks)
170 EF->__msan_scoped_disable_interceptor_checks();
171 }
172};
173
174struct ScopedDisableMsanInterceptorChecks {
175 ScopedDisableMsanInterceptorChecks() {
176 if (EF->__msan_scoped_disable_interceptor_checks)
177 EF->__msan_scoped_disable_interceptor_checks();
178 }
179 ~ScopedDisableMsanInterceptorChecks() {
180 if (EF->__msan_scoped_enable_interceptor_checks)
181 EF->__msan_scoped_enable_interceptor_checks();
182 }
183};
184
185} // namespace fuzzer
186
187#endif // LLVM_FUZZER_INTERNAL_H
188