1 //===- FuzzerUtilWindows.cpp - Misc utils for Windows. --------------------===//
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 implementation for Windows.
10 //===----------------------------------------------------------------------===//
11 #include "FuzzerDefs.h"
12 #if LIBFUZZER_WINDOWS
13 #include "FuzzerIO.h"
14 #include "FuzzerInternal.h"
15 #include <cassert>
16 #include <chrono>
17 #include <cstring>
18 #include <errno.h>
19 #include <iomanip>
20 #include <signal.h>
21 #include <stdio.h>
22 #include <sys/types.h>
23 #include <windows.h>
24 
25 // This must be included after windows.h.
26 #include <Psapi.h>
27 
28 namespace fuzzer {
29 
30 static const FuzzingOptions* HandlerOpt = nullptr;
31 
32 static LONG CALLBACK ExceptionHandler(PEXCEPTION_POINTERS ExceptionInfo) {
33   switch (ExceptionInfo->ExceptionRecord->ExceptionCode) {
34     case EXCEPTION_ACCESS_VIOLATION:
35     case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
36     case EXCEPTION_STACK_OVERFLOW:
37       if (HandlerOpt->HandleSegv)
38         Fuzzer::StaticCrashSignalCallback();
39       break;
40     case EXCEPTION_DATATYPE_MISALIGNMENT:
41     case EXCEPTION_IN_PAGE_ERROR:
42       if (HandlerOpt->HandleBus)
43         Fuzzer::StaticCrashSignalCallback();
44       break;
45     case EXCEPTION_ILLEGAL_INSTRUCTION:
46     case EXCEPTION_PRIV_INSTRUCTION:
47       if (HandlerOpt->HandleIll)
48         Fuzzer::StaticCrashSignalCallback();
49       break;
50     case EXCEPTION_FLT_DENORMAL_OPERAND:
51     case EXCEPTION_FLT_DIVIDE_BY_ZERO:
52     case EXCEPTION_FLT_INEXACT_RESULT:
53     case EXCEPTION_FLT_INVALID_OPERATION:
54     case EXCEPTION_FLT_OVERFLOW:
55     case EXCEPTION_FLT_STACK_CHECK:
56     case EXCEPTION_FLT_UNDERFLOW:
57     case EXCEPTION_INT_DIVIDE_BY_ZERO:
58     case EXCEPTION_INT_OVERFLOW:
59       if (HandlerOpt->HandleFpe)
60         Fuzzer::StaticCrashSignalCallback();
61       break;
62     // TODO: handle (Options.HandleXfsz)
63   }
64   return EXCEPTION_CONTINUE_SEARCH;
65 }
66 
67 BOOL WINAPI CtrlHandler(DWORD dwCtrlType) {
68   switch (dwCtrlType) {
69     case CTRL_C_EVENT:
70       if (HandlerOpt->HandleInt)
71         Fuzzer::StaticInterruptCallback();
72       return TRUE;
73     case CTRL_BREAK_EVENT:
74       if (HandlerOpt->HandleTerm)
75         Fuzzer::StaticInterruptCallback();
76       return TRUE;
77   }
78   return FALSE;
79 }
80 
81 void CALLBACK AlarmHandler(PVOID, BOOLEAN) {
82   Fuzzer::StaticAlarmCallback();
83 }
84 
85 class TimerQ {
86   HANDLE TimerQueue;
87  public:
88   TimerQ() : TimerQueue(NULL) {};
89   ~TimerQ() {
90     if (TimerQueue)
91       DeleteTimerQueueEx(TimerQueue, NULL);
92   };
93   void SetTimer(int Seconds) {
94     if (!TimerQueue) {
95       TimerQueue = CreateTimerQueue();
96       if (!TimerQueue) {
97         Printf("libFuzzer: CreateTimerQueue failed.\n");
98         exit(1);
99       }
100     }
101     HANDLE Timer;
102     if (!CreateTimerQueueTimer(&Timer, TimerQueue, AlarmHandler, NULL,
103         Seconds*1000, Seconds*1000, 0)) {
104       Printf("libFuzzer: CreateTimerQueueTimer failed.\n");
105       exit(1);
106     }
107   };
108 };
109 
110 static TimerQ Timer;
111 
112 static void CrashHandler(int) { Fuzzer::StaticCrashSignalCallback(); }
113 
114 void SetSignalHandler(const FuzzingOptions& Options) {
115   HandlerOpt = &Options;
116 
117   if (Options.UnitTimeoutSec > 0)
118     Timer.SetTimer(Options.UnitTimeoutSec / 2 + 1);
119 
120   if (Options.HandleInt || Options.HandleTerm)
121     if (!SetConsoleCtrlHandler(CtrlHandler, TRUE)) {
122       DWORD LastError = GetLastError();
123       Printf("libFuzzer: SetConsoleCtrlHandler failed (Error code: %lu).\n",
124         LastError);
125       exit(1);
126     }
127 
128   if (Options.HandleSegv || Options.HandleBus || Options.HandleIll ||
129       Options.HandleFpe)
130     SetUnhandledExceptionFilter(ExceptionHandler);
131 
132   if (Options.HandleAbrt)
133     if (SIG_ERR == signal(SIGABRT, CrashHandler)) {
134       Printf("libFuzzer: signal failed with %d\n", errno);
135       exit(1);
136     }
137 }
138 
139 void SleepSeconds(int Seconds) { Sleep(Seconds * 1000); }
140 
141 unsigned long GetPid() { return GetCurrentProcessId(); }
142 
143 size_t GetPeakRSSMb() {
144   PROCESS_MEMORY_COUNTERS info;
145   if (!GetProcessMemoryInfo(GetCurrentProcess(), &info, sizeof(info)))
146     return 0;
147   return info.PeakWorkingSetSize >> 20;
148 }
149 
150 FILE *OpenProcessPipe(const char *Command, const char *Mode) {
151   return _popen(Command, Mode);
152 }
153 
154 int ExecuteCommand(const std::string &Command) {
155   return system(Command.c_str());
156 }
157 
158 const void *SearchMemory(const void *Data, size_t DataLen, const void *Patt,
159                          size_t PattLen) {
160   // TODO: make this implementation more efficient.
161   const char *Cdata = (const char *)Data;
162   const char *Cpatt = (const char *)Patt;
163 
164   if (!Data || !Patt || DataLen == 0 || PattLen == 0 || DataLen < PattLen)
165     return NULL;
166 
167   if (PattLen == 1)
168     return memchr(Data, *Cpatt, DataLen);
169 
170   const char *End = Cdata + DataLen - PattLen + 1;
171 
172   for (const char *It = Cdata; It < End; ++It)
173     if (It[0] == Cpatt[0] && memcmp(It, Cpatt, PattLen) == 0)
174       return It;
175 
176   return NULL;
177 }
178 
179 std::string DisassembleCmd(const std::string &FileName) {
180   if (ExecuteCommand("dumpbin /summary > nul") == 0)
181     return "dumpbin /disasm " + FileName;
182   Printf("libFuzzer: couldn't find tool to disassemble (dumpbin)\n");
183   exit(1);
184 }
185 
186 std::string SearchRegexCmd(const std::string &Regex) {
187   return "findstr /r \"" + Regex + "\"";
188 }
189 
190 } // namespace fuzzer
191 
192 #endif // LIBFUZZER_WINDOWS
193