e76adb37481ce400e64a6b3db06e6956fc79ae4a
[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 <unistd.h>
20
21 namespace fuzzer {
22
23 void Print(const Unit &v, const char *PrintAfter) {
24   for (auto x : v)
25     Printf("0x%x,", (unsigned) x);
26   Printf("%s", PrintAfter);
27 }
28
29 void PrintASCII(const Unit &U, const char *PrintAfter) {
30   for (auto X : U) {
31     if (isprint(X))
32       Printf("%c", X);
33     else
34       Printf("\\x%x", (unsigned)X);
35   }
36   Printf("%s", PrintAfter);
37 }
38
39 std::string Hash(const Unit &U) {
40   uint8_t Hash[kSHA1NumBytes];
41   ComputeSHA1(U.data(), U.size(), Hash);
42   std::stringstream SS;
43   for (int i = 0; i < kSHA1NumBytes; i++)
44     SS << std::hex << std::setfill('0') << std::setw(2) << (unsigned)Hash[i];
45   return SS.str();
46 }
47
48 static void AlarmHandler(int, siginfo_t *, void *) {
49   Fuzzer::StaticAlarmCallback();
50 }
51
52 void SetTimer(int Seconds) {
53   struct itimerval T {{Seconds, 0}, {Seconds, 0}};
54   Printf("SetTimer %d\n", Seconds);
55   int Res = setitimer(ITIMER_REAL, &T, nullptr);
56   assert(Res == 0);
57   struct sigaction sigact;
58   memset(&sigact, 0, sizeof(sigact));
59   sigact.sa_sigaction = AlarmHandler;
60   Res = sigaction(SIGALRM, &sigact, 0);
61   assert(Res == 0);
62 }
63
64 int NumberOfCpuCores() {
65   FILE *F = popen("nproc", "r");
66   int N = 0;
67   fscanf(F, "%d", &N);
68   fclose(F);
69   return N;
70 }
71
72 void ExecuteCommand(const std::string &Command) {
73   system(Command.c_str());
74 }
75
76 bool ToASCII(Unit &U) {
77   bool Changed = false;
78   for (auto &X : U) {
79     auto NewX = X;
80     NewX &= 127;
81     if (!isspace(NewX) && !isprint(NewX))
82       NewX = ' ';
83     Changed |= NewX != X;
84     X = NewX;
85   }
86   return Changed;
87 }
88
89 }  // namespace fuzzer