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 FileSizeExceedHandler(int, siginfo_t *, void *) {
45 Fuzzer::StaticFileSizeExceedCallback();
48 static void SetSigaction(int signum,
49 void (*callback)(int, siginfo_t *, void *)) {
50 struct sigaction sigact;
51 memset(&sigact, 0, sizeof(sigact));
52 sigact.sa_sigaction = callback;
53 if (sigaction(signum, &sigact, 0)) {
54 Printf("libFuzzer: sigaction failed with %d\n", errno);
59 void SetTimer(int Seconds) {
61 {Seconds, 0}, { Seconds, 0 }
63 if (setitimer(ITIMER_REAL, &T, nullptr)) {
64 Printf("libFuzzer: setitimer failed with %d\n", errno);
67 SetSigaction(SIGALRM, AlarmHandler);
70 void SetSignalHandler(const FuzzingOptions& Options) {
71 if (Options.UnitTimeoutSec > 0)
72 SetTimer(Options.UnitTimeoutSec / 2 + 1);
73 if (Options.HandleInt)
74 SetSigaction(SIGINT, InterruptHandler);
75 if (Options.HandleTerm)
76 SetSigaction(SIGTERM, InterruptHandler);
77 if (Options.HandleSegv)
78 SetSigaction(SIGSEGV, CrashHandler);
79 if (Options.HandleBus)
80 SetSigaction(SIGBUS, CrashHandler);
81 if (Options.HandleAbrt)
82 SetSigaction(SIGABRT, CrashHandler);
83 if (Options.HandleIll)
84 SetSigaction(SIGILL, CrashHandler);
85 if (Options.HandleFpe)
86 SetSigaction(SIGFPE, CrashHandler);
87 if (Options.HandleXfsz)
88 SetSigaction(SIGXFSZ, FileSizeExceedHandler);
91 void SleepSeconds(int Seconds) {
92 sleep(Seconds); // Use C API to avoid coverage from instrumented libc++.
95 unsigned long GetPid() { return (unsigned long)getpid(); }
97 size_t GetPeakRSSMb() {
99 if (getrusage(RUSAGE_SELF, &usage))
101 if (LIBFUZZER_LINUX) {
102 // ru_maxrss is in KiB
103 return usage.ru_maxrss >> 10;
104 } else if (LIBFUZZER_APPLE) {
105 // ru_maxrss is in bytes
106 return usage.ru_maxrss >> 20;
108 assert(0 && "GetPeakRSSMb() is not implemented for your platform");
112 FILE *OpenProcessPipe(const char *Command, const char *Mode) {
113 return popen(Command, Mode);
116 const void *SearchMemory(const void *Data, size_t DataLen, const void *Patt,
118 return memmem(Data, DataLen, Patt, PattLen);
121 } // namespace fuzzer
123 #endif // LIBFUZZER_POSIX