Merging r259342 (with s/p2align 4/align 16) because r258750 is not in 3.8.
[oota-llvm.git] / lib / Fuzzer / FuzzerUtil.cpp
1 //===- 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
12 #include "FuzzerInternal.h"
13 #include <sstream>
14 #include <iomanip>
15 #include <sys/time.h>
16 #include <cassert>
17 #include <cstring>
18 #include <signal.h>
19 #include <sstream>
20 #include <unistd.h>
21
22 namespace fuzzer {
23
24 void Print(const Unit &v, const char *PrintAfter) {
25   for (auto x : v)
26     Printf("0x%x,", (unsigned) x);
27   Printf("%s", PrintAfter);
28 }
29
30 void PrintASCIIByte(uint8_t Byte) {
31   if (Byte == '\\')
32     Printf("\\\\");
33   else if (Byte == '"')
34     Printf("\\\"");
35   else if (Byte >= 32 && Byte < 127)
36     Printf("%c", Byte);
37   else
38     Printf("\\x%02x", Byte);
39 }
40
41 void PrintASCII(const uint8_t *Data, size_t Size, const char *PrintAfter) {
42   for (size_t i = 0; i < Size; i++)
43     PrintASCIIByte(Data[i]);
44   Printf("%s", PrintAfter);
45 }
46
47 void PrintASCII(const Unit &U, const char *PrintAfter) {
48   for (auto X : U)
49     PrintASCIIByte(X);
50   Printf("%s", PrintAfter);
51 }
52
53 std::string Hash(const Unit &U) {
54   uint8_t Hash[kSHA1NumBytes];
55   ComputeSHA1(U.data(), U.size(), Hash);
56   std::stringstream SS;
57   for (int i = 0; i < kSHA1NumBytes; i++)
58     SS << std::hex << std::setfill('0') << std::setw(2) << (unsigned)Hash[i];
59   return SS.str();
60 }
61
62 static void AlarmHandler(int, siginfo_t *, void *) {
63   Fuzzer::StaticAlarmCallback();
64 }
65
66 void SetTimer(int Seconds) {
67   struct itimerval T {{Seconds, 0}, {Seconds, 0}};
68   int Res = setitimer(ITIMER_REAL, &T, nullptr);
69   assert(Res == 0);
70   struct sigaction sigact;
71   memset(&sigact, 0, sizeof(sigact));
72   sigact.sa_sigaction = AlarmHandler;
73   Res = sigaction(SIGALRM, &sigact, 0);
74   assert(Res == 0);
75 }
76
77 int NumberOfCpuCores() {
78   FILE *F = popen("nproc", "r");
79   int N = 0;
80   fscanf(F, "%d", &N);
81   fclose(F);
82   return N;
83 }
84
85 int ExecuteCommand(const std::string &Command) {
86   return system(Command.c_str());
87 }
88
89 bool ToASCII(Unit &U) {
90   bool Changed = false;
91   for (auto &X : U) {
92     auto NewX = X;
93     NewX &= 127;
94     if (!isspace(NewX) && !isprint(NewX))
95       NewX = ' ';
96     Changed |= NewX != X;
97     X = NewX;
98   }
99   return Changed;
100 }
101
102 bool IsASCII(const Unit &U) {
103   for (auto X : U)
104     if (!(isprint(X) || isspace(X))) return false;
105   return true;
106 }
107
108 bool ParseOneDictionaryEntry(const std::string &Str, Unit *U) {
109   U->clear();
110   if (Str.empty()) return false;
111   size_t L = 0, R = Str.size() - 1;  // We are parsing the range [L,R].
112   // Skip spaces from both sides.
113   while (L < R && isspace(Str[L])) L++;
114   while (R > L && isspace(Str[R])) R--;
115   if (R - L < 2) return false;
116   // Check the closing "
117   if (Str[R] != '"') return false;
118   R--;
119   // Find the opening "
120   while (L < R && Str[L] != '"') L++;
121   if (L >= R) return false;
122   assert(Str[L] == '\"');
123   L++;
124   assert(L <= R);
125   for (size_t Pos = L; Pos <= R; Pos++) {
126     uint8_t V = (uint8_t)Str[Pos];
127     if (!isprint(V) && !isspace(V)) return false;
128     if (V =='\\') {
129       // Handle '\\'
130       if (Pos + 1 <= R && (Str[Pos + 1] == '\\' || Str[Pos + 1] == '"')) {
131         U->push_back(Str[Pos + 1]);
132         Pos++;
133         continue;
134       }
135       // Handle '\xAB'
136       if (Pos + 3 <= R && Str[Pos + 1] == 'x'
137            && isxdigit(Str[Pos + 2]) && isxdigit(Str[Pos + 3])) {
138         char Hex[] = "0xAA";
139         Hex[2] = Str[Pos + 2];
140         Hex[3] = Str[Pos + 3];
141         U->push_back(strtol(Hex, nullptr, 16));
142         Pos += 3;
143         continue;
144       }
145       return false;  // Invalid escape.
146     } else {
147       // Any other character.
148       U->push_back(V);
149     }
150   }
151   return true;
152 }
153
154 bool ParseDictionaryFile(const std::string &Text, std::vector<Unit> *Units) {
155   if (Text.empty()) {
156     Printf("ParseDictionaryFile: file does not exist or is empty\n");
157     return false;
158   }
159   std::istringstream ISS(Text);
160   Units->clear();
161   Unit U;
162   int LineNo = 0;
163   std::string S;
164   while (std::getline(ISS, S, '\n')) {
165     LineNo++;
166     size_t Pos = 0;
167     while (Pos < S.size() && isspace(S[Pos])) Pos++;  // Skip spaces.
168     if (Pos == S.size()) continue;  // Empty line.
169     if (S[Pos] == '#') continue;  // Comment line.
170     if (ParseOneDictionaryEntry(S, &U)) {
171       Units->push_back(U);
172     } else {
173       Printf("ParseDictionaryFile: error in line %d\n\t\t%s\n", LineNo,
174              S.c_str());
175       return false;
176     }
177   }
178   return true;
179 }
180
181 int GetPid() { return getpid(); }
182
183
184 std::string Base64(const Unit &U) {
185   static const char Table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
186                               "abcdefghijklmnopqrstuvwxyz"
187                               "0123456789+/";
188   std::string Res;
189   size_t i;
190   for (i = 0; i + 2 < U.size(); i += 3) {
191     uint32_t x = (U[i] << 16) + (U[i + 1] << 8) + U[i + 2];
192     Res += Table[(x >> 18) & 63];
193     Res += Table[(x >> 12) & 63];
194     Res += Table[(x >> 6) & 63];
195     Res += Table[x & 63];
196   }
197   if (i + 1 == U.size()) {
198     uint32_t x = (U[i] << 16);
199     Res += Table[(x >> 18) & 63];
200     Res += Table[(x >> 12) & 63];
201     Res += "==";
202   } else if (i + 2 == U.size()) {
203     uint32_t x = (U[i] << 16) + (U[i + 1] << 8);
204     Res += Table[(x >> 18) & 63];
205     Res += Table[(x >> 12) & 63];
206     Res += Table[(x >> 6) & 63];
207     Res += "=";
208   }
209   return Res;
210 }
211
212 }  // namespace fuzzer