1 //===- FuzzerUtil.cpp - Misc utils ----------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 //===----------------------------------------------------------------------===//
12 #include "FuzzerInternal.h"
22 void Print(const Unit &v, const char *PrintAfter) {
24 std::cerr << "0x" << std::hex << (unsigned) x << std::dec << ",";
25 std::cerr << PrintAfter;
28 void PrintASCII(const Unit &U, const char *PrintAfter) {
33 std::cerr << "\\x" << std::hex << (int)(unsigned)X << std::dec;
35 std::cerr << PrintAfter;
38 // Try to compute a SHA1 sum of this Unit using an external 'sha1sum' command.
39 // We can not use the SHA1 function from openssl directly because
40 // a) openssl may not be available,
41 // b) we may be fuzzing openssl itself.
42 // This is all very sad, suggestions are welcome.
43 static std::string TrySha1(const Unit &in) {
44 char TempPath[] = "/tmp/fuzzer-tmp-XXXXXX";
45 int FD = mkstemp(TempPath);
46 if (FD < 0) return "";
47 ssize_t Written = write(FD, in.data(), in.size());
49 if (static_cast<size_t>(Written) != in.size()) return "";
51 std::string Cmd = "sha1sum < ";
53 FILE *F = popen(Cmd.c_str(), "r");
56 fgets(Sha1, sizeof(Sha1), F);
63 std::string Hash(const Unit &in) {
64 std::string Sha1 = TrySha1(in);
68 size_t h1 = 0, h2 = 0;
75 return std::to_string(h1) + std::to_string(h2);
78 static void AlarmHandler(int, siginfo_t *, void *) {
79 Fuzzer::StaticAlarmCallback();
82 void SetTimer(int Seconds) {
83 struct itimerval T {{Seconds, 0}, {Seconds, 0}};
84 std::cerr << "SetTimer " << Seconds << "\n";
85 int Res = setitimer(ITIMER_REAL, &T, nullptr);
87 struct sigaction sigact;
88 memset(&sigact, 0, sizeof(sigact));
89 sigact.sa_sigaction = AlarmHandler;
90 Res = sigaction(SIGALRM, &sigact, 0);
94 int NumberOfCpuCores() {
95 FILE *F = popen("nproc", "r");
102 } // namespace fuzzer