1 //===- FuzzerUtilPosix.cpp - Misc utils for Posix. ------------------------===//
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 //===----------------------------------------------------------------------===//
9 // Misc utils implementation using Posix API.
10 //===----------------------------------------------------------------------===//
11 #include "FuzzerDefs.h"
14 #include "FuzzerInternal.h"
23 #include <sys/resource.h>
24 #include <sys/syscall.h>
26 #include <sys/types.h>
32 static void AlarmHandler(int, siginfo_t *, void *) {
33 Fuzzer::StaticAlarmCallback();
36 static void CrashHandler(int, siginfo_t *, void *) {
37 Fuzzer::StaticCrashSignalCallback();
40 static void InterruptHandler(int, siginfo_t *, void *) {
41 Fuzzer::StaticInterruptCallback();
44 static void SetSigaction(int signum,
45 void (*callback)(int, siginfo_t *, void *)) {
46 struct sigaction sigact;
47 memset(&sigact, 0, sizeof(sigact));
48 sigact.sa_sigaction = callback;
49 if (sigaction(signum, &sigact, 0)) {
50 Printf("libFuzzer: sigaction failed with %d\n", errno);
55 void SetTimer(int Seconds) {
57 {Seconds, 0}, { Seconds, 0 }
59 if (setitimer(ITIMER_REAL, &T, nullptr)) {
60 Printf("libFuzzer: setitimer failed with %d\n", errno);
63 SetSigaction(SIGALRM, AlarmHandler);
66 void SetSignalHandler(const FuzzingOptions& Options) {
67 if (Options.UnitTimeoutSec > 0)
68 SetTimer(Options.UnitTimeoutSec / 2 + 1);
69 if (Options.HandleInt)
70 SetSigaction(SIGINT, InterruptHandler);
71 if (Options.HandleTerm)
72 SetSigaction(SIGTERM, InterruptHandler);
73 if (Options.HandleSegv)
74 SetSigaction(SIGSEGV, CrashHandler);
75 if (Options.HandleBus)
76 SetSigaction(SIGBUS, CrashHandler);
77 if (Options.HandleAbrt)
78 SetSigaction(SIGABRT, CrashHandler);
79 if (Options.HandleIll)
80 SetSigaction(SIGILL, CrashHandler);
81 if (Options.HandleFpe)
82 SetSigaction(SIGFPE, CrashHandler);
85 void SleepSeconds(int Seconds) {
86 sleep(Seconds); // Use C API to avoid coverage from instrumented libc++.
89 unsigned long GetPid() { return (unsigned long)getpid(); }
91 size_t GetPeakRSSMb() {
93 if (getrusage(RUSAGE_SELF, &usage))
95 if (LIBFUZZER_LINUX) {
96 // ru_maxrss is in KiB
97 return usage.ru_maxrss >> 10;
98 } else if (LIBFUZZER_APPLE) {
99 // ru_maxrss is in bytes
100 return usage.ru_maxrss >> 20;
102 assert(0 && "GetPeakRSSMb() is not implemented for your platform");
106 FILE *OpenProcessPipe(const char *Command, const char *Mode) {
107 return popen(Command, Mode);
110 const void *SearchMemory(const void *Data, size_t DataLen, const void *Patt,
112 return memmem(Data, DataLen, Patt, PattLen);
115 } // namespace fuzzer
117 #endif // LIBFUZZER_POSIX