blob: c4b0afa55d597a8e0d7f9ce0d6789ac1fef89b6e [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
12#include "FuzzerInternal.h"
Kostya Serebryany96eab652015-05-14 22:41:49 +000013#include <sstream>
14#include <iomanip>
Aaron Ballmanef116982015-01-29 16:58:29 +000015#include <iostream>
16#include <sys/time.h>
17#include <cassert>
18#include <cstring>
19#include <signal.h>
Kostya Serebryanyf47198a2015-05-12 22:03:34 +000020#include <unistd.h>
Aaron Ballmanef116982015-01-29 16:58:29 +000021
22namespace fuzzer {
23
24void Print(const Unit &v, const char *PrintAfter) {
Aaron Ballmanef116982015-01-29 16:58:29 +000025 for (auto x : v)
Kostya Serebryany043ab1c2015-04-01 21:33:20 +000026 std::cerr << "0x" << std::hex << (unsigned) x << std::dec << ",";
Aaron Ballmanef116982015-01-29 16:58:29 +000027 std::cerr << PrintAfter;
28}
29
30void PrintASCII(const Unit &U, const char *PrintAfter) {
Kostya Serebryany043ab1c2015-04-01 21:33:20 +000031 for (auto X : U) {
32 if (isprint(X))
33 std::cerr << X;
34 else
35 std::cerr << "\\x" << std::hex << (int)(unsigned)X << std::dec;
36 }
Aaron Ballmanef116982015-01-29 16:58:29 +000037 std::cerr << PrintAfter;
38}
39
Kostya Serebryany96eab652015-05-14 22:41:49 +000040std::string Hash(const Unit &U) {
41 uint8_t Hash[kSHA1NumBytes];
42 ComputeSHA1(U.data(), U.size(), Hash);
43 std::stringstream SS;
44 for (int i = 0; i < kSHA1NumBytes; i++)
45 SS << std::hex << std::setfill('0') << std::setw(2) << (unsigned)Hash[i];
46 return SS.str();
Aaron Ballmanef116982015-01-29 16:58:29 +000047}
48
49static void AlarmHandler(int, siginfo_t *, void *) {
Kostya Serebryany52a788e2015-03-31 20:13:20 +000050 Fuzzer::StaticAlarmCallback();
Aaron Ballmanef116982015-01-29 16:58:29 +000051}
52
53void SetTimer(int Seconds) {
54 struct itimerval T {{Seconds, 0}, {Seconds, 0}};
55 std::cerr << "SetTimer " << Seconds << "\n";
56 int Res = setitimer(ITIMER_REAL, &T, nullptr);
57 assert(Res == 0);
58 struct sigaction sigact;
59 memset(&sigact, 0, sizeof(sigact));
60 sigact.sa_sigaction = AlarmHandler;
61 Res = sigaction(SIGALRM, &sigact, 0);
62 assert(Res == 0);
63}
64
Kostya Serebryany9690fcf2015-05-12 18:51:57 +000065int NumberOfCpuCores() {
66 FILE *F = popen("nproc", "r");
67 int N = 0;
68 fscanf(F, "%d", &N);
69 fclose(F);
70 return N;
71}
72
Aaron Ballmanef116982015-01-29 16:58:29 +000073} // namespace fuzzer