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 {
33public:
34
35  Fuzzer(UserCallback CB, InputCorpus &Corpus, MutationDispatcher &MD,
36         FuzzingOptions Options);
37  ~Fuzzer();
38  void Loop(Vector<SizedFile> &CorporaFiles);
39  void ReadAndExecuteSeedCorpora(Vector<SizedFile> &CorporaFiles);
40  void MinimizeCrashLoop(const Unit &U);
41  void RereadOutputCorpus(size_t MaxSize);
42
43  size_t secondsSinceProcessStartUp() {
44    return duration_cast<seconds>(system_clock::now() - ProcessStartTime)
45        .count();
46  }
47
48  bool TimedOut() {
49    return Options.MaxTotalTimeSec > 0 &&
50           secondsSinceProcessStartUp() >
51               static_cast<size_t>(Options.MaxTotalTimeSec);
52  }
53
54  size_t execPerSec() {
55    size_t Seconds = secondsSinceProcessStartUp();
56    return Seconds ? TotalNumberOfRuns / Seconds : 0;
57  }
58
59  size_t getTotalNumberOfRuns() { return TotalNumberOfRuns; }
60
61  static void StaticAlarmCallback();
62  static void StaticCrashSignalCallback();
63  static void StaticExitCallback();
64  static void StaticInterruptCallback();
65  static void StaticFileSizeExceedCallback();
66  static void StaticGracefulExitCallback();
67
68  void ExecuteCallback(const uint8_t *Data, size_t Size);
69  bool RunOne(const uint8_t *Data, size_t Size, bool MayDeleteFile = false,
70              InputInfo *II = nullptr, bool *FoundUniqFeatures = nullptr);
71
72  // Merge Corpora[1:] into Corpora[0].
73  void Merge(const Vector<std::string> &Corpora);
74  void CrashResistantMergeInternalStep(const std::string &ControlFilePath);
75  MutationDispatcher &GetMD() { return MD; }
76  void PrintFinalStats();
77  void SetMaxInputLen(size_t MaxInputLen);
78  void SetMaxMutationLen(size_t MaxMutationLen);
79  void RssLimitCallback();
80
81  bool InFuzzingThread() const { return IsMyThread; }
82  size_t GetCurrentUnitInFuzzingThead(const uint8_t **Data) const;
83  void TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
84                               bool DuringInitialCorpusExecution);
85
86  void HandleMalloc(size_t Size);
87  static void MaybeExitGracefully();
88  std::string WriteToOutputCorpus(const Unit &U);
89
90private:
91  void AlarmCallback();
92  void CrashCallback();
93  void ExitCallback();
94  void CrashOnOverwrittenData();
95  void InterruptCallback();
96  void MutateAndTestOne();
97  void PurgeAllocator();
98  void ReportNewCoverage(InputInfo *II, const Unit &U);
99  void PrintPulseAndReportSlowInput(const uint8_t *Data, size_t Size);
100  void WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix);
101  void PrintStats(const char *Where, const char *End = "\n", size_t Units = 0,
102                  size_t Features = 0);
103  void PrintStatusForNewUnit(const Unit &U, const char *Text);
104  void CheckExitOnSrcPosOrItem();
105
106  static void StaticDeathCallback();
107  void DumpCurrentUnit(const char *Prefix);
108  void DeathCallback();
109
110  void AllocateCurrentUnitData();
111  uint8_t *CurrentUnitData = nullptr;
112  std::atomic<size_t> CurrentUnitSize;
113  uint8_t BaseSha1[kSHA1NumBytes];  // Checksum of the base unit.
114
115  bool GracefulExitRequested = false;
116
117  size_t TotalNumberOfRuns = 0;
118  size_t NumberOfNewUnitsAdded = 0;
119
120  size_t LastCorpusUpdateRun = 0;
121
122  bool HasMoreMallocsThanFrees = false;
123  size_t NumberOfLeakDetectionAttempts = 0;
124
125  system_clock::time_point LastAllocatorPurgeAttemptTime = system_clock::now();
126
127  UserCallback CB;
128  InputCorpus &Corpus;
129  MutationDispatcher &MD;
130  FuzzingOptions Options;
131  DataFlowTrace DFT;
132
133  system_clock::time_point ProcessStartTime = system_clock::now();
134  system_clock::time_point UnitStartTime, UnitStopTime;
135  long TimeOfLongestUnitInSeconds = 0;
136  long EpochOfLastReadOfOutputCorpus = 0;
137
138  size_t MaxInputLen = 0;
139  size_t MaxMutationLen = 0;
140  size_t TmpMaxMutationLen = 0;
141
142  Vector<uint32_t> UniqFeatureSetTmp;
143
144  // Need to know our own thread.
145  static thread_local bool IsMyThread;
146};
147
148struct ScopedEnableMsanInterceptorChecks {
149  ScopedEnableMsanInterceptorChecks() {
150    if (EF->__msan_scoped_enable_interceptor_checks)
151      EF->__msan_scoped_enable_interceptor_checks();
152  }
153  ~ScopedEnableMsanInterceptorChecks() {
154    if (EF->__msan_scoped_disable_interceptor_checks)
155      EF->__msan_scoped_disable_interceptor_checks();
156  }
157};
158
159struct ScopedDisableMsanInterceptorChecks {
160  ScopedDisableMsanInterceptorChecks() {
161    if (EF->__msan_scoped_disable_interceptor_checks)
162      EF->__msan_scoped_disable_interceptor_checks();
163  }
164  ~ScopedDisableMsanInterceptorChecks() {
165    if (EF->__msan_scoped_enable_interceptor_checks)
166      EF->__msan_scoped_enable_interceptor_checks();
167  }
168};
169
170} // namespace fuzzer
171
172#endif // LLVM_FUZZER_INTERNAL_H
173