blob: 579c4f83a87dddf9d6df5670651eb6fb2e7aa70e [file] [log] [blame]
Aaron Ballmanef116982015-01-29 16:58:29 +00001//===- FuzzerUtil.cpp - Misc utils ----------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9// Misc utils.
10//===----------------------------------------------------------------------===//
11
Zachary Turner24a148b2016-11-30 19:06:14 +000012#include "FuzzerUtil.h"
Zachary Turner34dcfb92016-12-02 19:38:19 +000013#include "FuzzerInternal.h"
Zachary Turner3cfeab72016-12-02 20:54:56 +000014#include "FuzzerIO.h"
15#include <sstream>
16#include <iomanip>
17#include <sys/resource.h>
18#include <sys/time.h>
19#include <sys/types.h>
20#include <sys/syscall.h>
Aaron Ballmanef116982015-01-29 16:58:29 +000021#include <cassert>
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +000022#include <chrono>
Aaron Ballmanef116982015-01-29 16:58:29 +000023#include <cstring>
Zachary Turner3cfeab72016-12-02 20:54:56 +000024#include <stdio.h>
Aaron Ballmanef116982015-01-29 16:58:29 +000025#include <signal.h>
Kostya Serebryany9838b2b2015-09-03 20:23:46 +000026#include <sstream>
Zachary Turner3cfeab72016-12-02 20:54:56 +000027#include <unistd.h>
28#include <errno.h>
Kostya Serebryany8b8f7a32016-05-06 23:38:07 +000029#include <thread>
Aaron Ballmanef116982015-01-29 16:58:29 +000030
31namespace fuzzer {
32
Kostya Serebryany98abb2c2016-01-13 23:46:01 +000033void PrintHexArray(const uint8_t *Data, size_t Size,
34 const char *PrintAfter) {
35 for (size_t i = 0; i < Size; i++)
36 Printf("0x%x,", (unsigned)Data[i]);
Kostya Serebryany7c180ea2015-05-23 01:22:35 +000037 Printf("%s", PrintAfter);
Aaron Ballmanef116982015-01-29 16:58:29 +000038}
39
Kostya Serebryany98abb2c2016-01-13 23:46:01 +000040void Print(const Unit &v, const char *PrintAfter) {
41 PrintHexArray(v.data(), v.size(), PrintAfter);
42}
43
Kostya Serebryany41740052016-01-12 02:36:59 +000044void PrintASCIIByte(uint8_t Byte) {
45 if (Byte == '\\')
46 Printf("\\\\");
47 else if (Byte == '"')
48 Printf("\\\"");
49 else if (Byte >= 32 && Byte < 127)
50 Printf("%c", Byte);
51 else
52 Printf("\\x%02x", Byte);
53}
54
55void PrintASCII(const uint8_t *Data, size_t Size, const char *PrintAfter) {
56 for (size_t i = 0; i < Size; i++)
57 PrintASCIIByte(Data[i]);
58 Printf("%s", PrintAfter);
59}
60
Aaron Ballmanef116982015-01-29 16:58:29 +000061void PrintASCII(const Unit &U, const char *PrintAfter) {
Kostya Serebryany476f0ce2016-01-16 03:53:32 +000062 PrintASCII(U.data(), U.size(), PrintAfter);
Aaron Ballmanef116982015-01-29 16:58:29 +000063}
64
Zachary Turner3cfeab72016-12-02 20:54:56 +000065static void AlarmHandler(int, siginfo_t *, void *) {
66 Fuzzer::StaticAlarmCallback();
67}
68
69static void CrashHandler(int, siginfo_t *, void *) {
70 Fuzzer::StaticCrashSignalCallback();
71}
72
73static void InterruptHandler(int, siginfo_t *, void *) {
74 Fuzzer::StaticInterruptCallback();
75}
76
77static void SetSigaction(int signum,
78 void (*callback)(int, siginfo_t *, void *)) {
79 struct sigaction sigact;
80 memset(&sigact, 0, sizeof(sigact));
81 sigact.sa_sigaction = callback;
82 if (sigaction(signum, &sigact, 0)) {
83 Printf("libFuzzer: sigaction failed with %d\n", errno);
84 exit(1);
85 }
86}
87
88void SetTimer(int Seconds) {
89 struct itimerval T {{Seconds, 0}, {Seconds, 0}};
90 if (setitimer(ITIMER_REAL, &T, nullptr)) {
91 Printf("libFuzzer: setitimer failed with %d\n", errno);
92 exit(1);
93 }
94 SetSigaction(SIGALRM, AlarmHandler);
95}
96
97void SetSigSegvHandler() { SetSigaction(SIGSEGV, CrashHandler); }
98void SetSigBusHandler() { SetSigaction(SIGBUS, CrashHandler); }
99void SetSigAbrtHandler() { SetSigaction(SIGABRT, CrashHandler); }
100void SetSigIllHandler() { SetSigaction(SIGILL, CrashHandler); }
101void SetSigFpeHandler() { SetSigaction(SIGFPE, CrashHandler); }
102void SetSigIntHandler() { SetSigaction(SIGINT, InterruptHandler); }
103void SetSigTermHandler() { SetSigaction(SIGTERM, InterruptHandler); }
104
105int NumberOfCpuCores() {
106 const char *CmdLine = nullptr;
107 if (LIBFUZZER_LINUX) {
108 CmdLine = "nproc";
109 } else if (LIBFUZZER_APPLE) {
110 CmdLine = "sysctl -n hw.ncpu";
111 } else {
112 assert(0 && "NumberOfCpuCores() is not implemented for your platform");
113 }
114
115 FILE *F = popen(CmdLine, "r");
116 int N = 1;
117 if (!F || fscanf(F, "%d", &N) != 1) {
118 Printf("WARNING: Failed to parse output of command \"%s\" in %s(). "
119 "Assuming CPU count of 1.\n",
120 CmdLine, __func__);
121 N = 1;
122 }
123
124 if (pclose(F)) {
125 Printf("WARNING: Executing command \"%s\" failed in %s(). "
126 "Assuming CPU count of 1.\n",
127 CmdLine, __func__);
128 N = 1;
129 }
130 if (N < 1) {
131 Printf("WARNING: Reported CPU count (%d) from command \"%s\" was invalid "
132 "in %s(). Assuming CPU count of 1.\n",
133 N, CmdLine, __func__);
134 N = 1;
135 }
136 return N;
137}
138
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000139bool ToASCII(uint8_t *Data, size_t Size) {
Kostya Serebryanybc7c0ad2015-08-11 01:44:42 +0000140 bool Changed = false;
Kostya Serebryany8a5bef02016-02-13 17:56:51 +0000141 for (size_t i = 0; i < Size; i++) {
142 uint8_t &X = Data[i];
Kostya Serebryanybc7c0ad2015-08-11 01:44:42 +0000143 auto NewX = X;
144 NewX &= 127;
145 if (!isspace(NewX) && !isprint(NewX))
146 NewX = ' ';
147 Changed |= NewX != X;
148 X = NewX;
149 }
150 return Changed;
151}
152
Kostya Serebryanyf1f3f932016-05-26 20:03:02 +0000153bool IsASCII(const Unit &U) { return IsASCII(U.data(), U.size()); }
154
155bool IsASCII(const uint8_t *Data, size_t Size) {
156 for (size_t i = 0; i < Size; i++)
157 if (!(isprint(Data[i]) || isspace(Data[i]))) return false;
Kostya Serebryanya9346c22015-09-02 19:08:08 +0000158 return true;
159}
160
Kostya Serebryany9838b2b2015-09-03 20:23:46 +0000161bool ParseOneDictionaryEntry(const std::string &Str, Unit *U) {
162 U->clear();
163 if (Str.empty()) return false;
164 size_t L = 0, R = Str.size() - 1; // We are parsing the range [L,R].
165 // Skip spaces from both sides.
166 while (L < R && isspace(Str[L])) L++;
167 while (R > L && isspace(Str[R])) R--;
168 if (R - L < 2) return false;
169 // Check the closing "
170 if (Str[R] != '"') return false;
171 R--;
172 // Find the opening "
173 while (L < R && Str[L] != '"') L++;
174 if (L >= R) return false;
175 assert(Str[L] == '\"');
176 L++;
177 assert(L <= R);
178 for (size_t Pos = L; Pos <= R; Pos++) {
179 uint8_t V = (uint8_t)Str[Pos];
180 if (!isprint(V) && !isspace(V)) return false;
181 if (V =='\\') {
182 // Handle '\\'
183 if (Pos + 1 <= R && (Str[Pos + 1] == '\\' || Str[Pos + 1] == '"')) {
184 U->push_back(Str[Pos + 1]);
185 Pos++;
186 continue;
187 }
188 // Handle '\xAB'
189 if (Pos + 3 <= R && Str[Pos + 1] == 'x'
190 && isxdigit(Str[Pos + 2]) && isxdigit(Str[Pos + 3])) {
191 char Hex[] = "0xAA";
192 Hex[2] = Str[Pos + 2];
193 Hex[3] = Str[Pos + 3];
194 U->push_back(strtol(Hex, nullptr, 16));
195 Pos += 3;
196 continue;
197 }
198 return false; // Invalid escape.
199 } else {
200 // Any other character.
201 U->push_back(V);
202 }
203 }
204 return true;
205}
206
207bool ParseDictionaryFile(const std::string &Text, std::vector<Unit> *Units) {
208 if (Text.empty()) {
209 Printf("ParseDictionaryFile: file does not exist or is empty\n");
210 return false;
211 }
212 std::istringstream ISS(Text);
213 Units->clear();
214 Unit U;
215 int LineNo = 0;
216 std::string S;
217 while (std::getline(ISS, S, '\n')) {
218 LineNo++;
219 size_t Pos = 0;
220 while (Pos < S.size() && isspace(S[Pos])) Pos++; // Skip spaces.
221 if (Pos == S.size()) continue; // Empty line.
222 if (S[Pos] == '#') continue; // Comment line.
223 if (ParseOneDictionaryEntry(S, &U)) {
224 Units->push_back(U);
225 } else {
226 Printf("ParseDictionaryFile: error in line %d\n\t\t%s\n", LineNo,
227 S.c_str());
228 return false;
229 }
230 }
231 return true;
232}
233
Zachary Turner3cfeab72016-12-02 20:54:56 +0000234void SleepSeconds(int Seconds) {
235 sleep(Seconds); // Use C API to avoid coverage from instrumented libc++.
236}
237
238int GetPid() { return getpid(); }
239
Kostya Serebryany9e48cda2015-12-04 22:29:39 +0000240std::string Base64(const Unit &U) {
241 static const char Table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
242 "abcdefghijklmnopqrstuvwxyz"
243 "0123456789+/";
244 std::string Res;
245 size_t i;
246 for (i = 0; i + 2 < U.size(); i += 3) {
247 uint32_t x = (U[i] << 16) + (U[i + 1] << 8) + U[i + 2];
248 Res += Table[(x >> 18) & 63];
249 Res += Table[(x >> 12) & 63];
250 Res += Table[(x >> 6) & 63];
251 Res += Table[x & 63];
252 }
253 if (i + 1 == U.size()) {
254 uint32_t x = (U[i] << 16);
255 Res += Table[(x >> 18) & 63];
256 Res += Table[(x >> 12) & 63];
257 Res += "==";
258 } else if (i + 2 == U.size()) {
259 uint32_t x = (U[i] << 16) + (U[i + 1] << 8);
260 Res += Table[(x >> 18) & 63];
261 Res += Table[(x >> 12) & 63];
262 Res += Table[(x >> 6) & 63];
263 Res += "=";
264 }
265 return Res;
266}
267
Zachary Turner3cfeab72016-12-02 20:54:56 +0000268size_t GetPeakRSSMb() {
269 struct rusage usage;
270 if (getrusage(RUSAGE_SELF, &usage))
271 return 0;
272 if (LIBFUZZER_LINUX) {
273 // ru_maxrss is in KiB
274 return usage.ru_maxrss >> 10;
275 } else if (LIBFUZZER_APPLE) {
276 // ru_maxrss is in bytes
277 return usage.ru_maxrss >> 20;
278 }
279 assert(0 && "GetPeakRSSMb() is not implemented for your platform");
280 return 0;
281}
282
Kostya Serebryany5ff481f2016-09-27 00:10:20 +0000283std::string DescribePC(const char *SymbolizedFMT, uintptr_t PC) {
284 if (!EF->__sanitizer_symbolize_pc) return "<can not symbolize>";
285 char PcDescr[1024];
286 EF->__sanitizer_symbolize_pc(reinterpret_cast<void*>(PC),
287 SymbolizedFMT, PcDescr, sizeof(PcDescr));
288 PcDescr[sizeof(PcDescr) - 1] = 0; // Just in case.
289 return PcDescr;
290}
291
Kostya Serebryanyb706b482016-09-18 21:47:08 +0000292void PrintPC(const char *SymbolizedFMT, const char *FallbackFMT, uintptr_t PC) {
Kostya Serebryany5ff481f2016-09-27 00:10:20 +0000293 if (EF->__sanitizer_symbolize_pc)
294 Printf("%s", DescribePC(SymbolizedFMT, PC).c_str());
295 else
Kostya Serebryanyb706b482016-09-18 21:47:08 +0000296 Printf(FallbackFMT, PC);
Kostya Serebryanyb706b482016-09-18 21:47:08 +0000297}
298
Kostya Serebryany95b1a432016-10-19 00:12:03 +0000299bool ExecuteCommandAndReadOutput(const std::string &Command, std::string *Out) {
Zachary Turner3cfeab72016-12-02 20:54:56 +0000300 FILE *Pipe = popen(Command.c_str(), "r");
Kostya Serebryany95b1a432016-10-19 00:12:03 +0000301 if (!Pipe) return false;
302 char Buff[1024];
303 size_t N;
304 while ((N = fread(Buff, 1, sizeof(Buff), Pipe)) > 0)
305 Out->append(Buff, N);
306 return true;
307}
308
Aaron Ballmanef116982015-01-29 16:58:29 +0000309} // namespace fuzzer