blob: cd2bb7438e9d0508615073a4a390f985d6fb17e0 [file] [log] [blame]
morehouse400262a2017-12-08 22:54:44 +00001//===- FuzzerUtilFuchsia.cpp - Misc utils for Fuchsia. --------------------===//
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 using Fuchsia/Zircon APIs.
10//===----------------------------------------------------------------------===//
11#include "FuzzerDefs.h"
12
13#if LIBFUZZER_FUCHSIA
14
15#include "FuzzerInternal.h"
16#include "FuzzerUtil.h"
17#include <cerrno>
18#include <cinttypes>
19#include <cstdint>
morehouse400262a2017-12-08 22:54:44 +000020#include <fcntl.h>
phoseke7c6a592018-06-07 18:41:35 +000021#include <lib/fdio/spawn.h>
morehouse400262a2017-12-08 22:54:44 +000022#include <string>
phosek00c73322018-04-20 00:41:06 +000023#include <sys/select.h>
morehouse400262a2017-12-08 22:54:44 +000024#include <thread>
phosekf9123762018-02-07 08:22:58 +000025#include <unistd.h>
morehouse400262a2017-12-08 22:54:44 +000026#include <zircon/errors.h>
phosekf9123762018-02-07 08:22:58 +000027#include <zircon/process.h>
phoseke59ddd22018-07-18 19:20:47 +000028#include <zircon/sanitizer.h>
morehouse400262a2017-12-08 22:54:44 +000029#include <zircon/status.h>
30#include <zircon/syscalls.h>
phoseke59ddd22018-07-18 19:20:47 +000031#include <zircon/syscalls/debug.h>
32#include <zircon/syscalls/exception.h>
morehouse400262a2017-12-08 22:54:44 +000033#include <zircon/syscalls/port.h>
34#include <zircon/types.h>
morehouse400262a2017-12-08 22:54:44 +000035
36namespace fuzzer {
37
phoseke59ddd22018-07-18 19:20:47 +000038// Given that Fuchsia doesn't have the POSIX signals that libFuzzer was written
39// around, the general approach is to spin up dedicated threads to watch for
40// each requested condition (alarm, interrupt, crash). Of these, the crash
41// handler is the most involved, as it requires resuming the crashed thread in
42// order to invoke the sanitizers to get the needed state.
43
44// Forward declaration of assembly trampoline needed to resume crashed threads.
45// This appears to have external linkage to C++, which is why it's not in the
46// anonymous namespace. The assembly definition inside MakeTrampoline()
47// actually defines the symbol with internal linkage only.
48void CrashTrampolineAsm() __asm__("CrashTrampolineAsm");
49
morehouse400262a2017-12-08 22:54:44 +000050namespace {
51
phosekc8b3fb82018-07-24 02:34:24 +000052// TODO(phosek): remove this and replace it with ZX_TIME_INFINITE
53#define ZX_TIME_INFINITE_OLD INT64_MAX
54
morehouse400262a2017-12-08 22:54:44 +000055// A magic value for the Zircon exception port, chosen to spell 'FUZZING'
56// when interpreted as a byte sequence on little-endian platforms.
57const uint64_t kFuzzingCrash = 0x474e495a5a5546;
58
phoseke59ddd22018-07-18 19:20:47 +000059// Helper function to handle Zircon syscall failures.
60void ExitOnErr(zx_status_t Status, const char *Syscall) {
61 if (Status != ZX_OK) {
62 Printf("libFuzzer: %s failed: %s\n", Syscall,
63 _zx_status_get_string(Status));
64 exit(1);
65 }
66}
67
morehouse400262a2017-12-08 22:54:44 +000068void AlarmHandler(int Seconds) {
69 while (true) {
70 SleepSeconds(Seconds);
71 Fuzzer::StaticAlarmCallback();
72 }
73}
74
75void InterruptHandler() {
phosek1631e452018-04-19 14:01:46 +000076 fd_set readfds;
morehouse400262a2017-12-08 22:54:44 +000077 // Ctrl-C sends ETX in Zircon.
phosek1631e452018-04-19 14:01:46 +000078 do {
79 FD_ZERO(&readfds);
80 FD_SET(STDIN_FILENO, &readfds);
81 select(STDIN_FILENO + 1, &readfds, nullptr, nullptr, nullptr);
82 } while(!FD_ISSET(STDIN_FILENO, &readfds) || getchar() != 0x03);
morehouse400262a2017-12-08 22:54:44 +000083 Fuzzer::StaticInterruptCallback();
84}
85
phoseke59ddd22018-07-18 19:20:47 +000086// For the crash handler, we need to call Fuzzer::StaticCrashSignalCallback
87// without POSIX signal handlers. To achieve this, we use an assembly function
88// to add the necessary CFI unwinding information and a C function to bridge
89// from that back into C++.
90
91// FIXME: This works as a short-term solution, but this code really shouldn't be
92// architecture dependent. A better long term solution is to implement remote
93// unwinding and expose the necessary APIs through sanitizer_common and/or ASAN
94// to allow the exception handling thread to gather the crash state directly.
95//
96// Alternatively, Fuchsia may in future actually implement basic signal
97// handling for the machine trap signals.
98#if defined(__x86_64__)
99#define FOREACH_REGISTER(OP_REG, OP_NUM) \
100 OP_REG(rax) \
101 OP_REG(rbx) \
102 OP_REG(rcx) \
103 OP_REG(rdx) \
104 OP_REG(rsi) \
105 OP_REG(rdi) \
106 OP_REG(rbp) \
107 OP_REG(rsp) \
108 OP_REG(r8) \
109 OP_REG(r9) \
110 OP_REG(r10) \
111 OP_REG(r11) \
112 OP_REG(r12) \
113 OP_REG(r13) \
114 OP_REG(r14) \
115 OP_REG(r15) \
116 OP_REG(rip)
117
118#elif defined(__aarch64__)
119#define FOREACH_REGISTER(OP_REG, OP_NUM) \
120 OP_NUM(0) \
121 OP_NUM(1) \
122 OP_NUM(2) \
123 OP_NUM(3) \
124 OP_NUM(4) \
125 OP_NUM(5) \
126 OP_NUM(6) \
127 OP_NUM(7) \
128 OP_NUM(8) \
129 OP_NUM(9) \
130 OP_NUM(10) \
131 OP_NUM(11) \
132 OP_NUM(12) \
133 OP_NUM(13) \
134 OP_NUM(14) \
135 OP_NUM(15) \
136 OP_NUM(16) \
137 OP_NUM(17) \
138 OP_NUM(18) \
139 OP_NUM(19) \
140 OP_NUM(20) \
141 OP_NUM(21) \
142 OP_NUM(22) \
143 OP_NUM(23) \
144 OP_NUM(24) \
145 OP_NUM(25) \
146 OP_NUM(26) \
147 OP_NUM(27) \
148 OP_NUM(28) \
149 OP_NUM(29) \
150 OP_NUM(30) \
151 OP_REG(sp)
152
153#else
154#error "Unsupported architecture for fuzzing on Fuchsia"
155#endif
156
157// Produces a CFI directive for the named or numbered register.
158#define CFI_OFFSET_REG(reg) ".cfi_offset " #reg ", %c[" #reg "]\n"
159#define CFI_OFFSET_NUM(num) CFI_OFFSET_REG(r##num)
160
161// Produces an assembler input operand for the named or numbered register.
162#define ASM_OPERAND_REG(reg) \
163 [reg] "i"(offsetof(zx_thread_state_general_regs_t, reg)),
164#define ASM_OPERAND_NUM(num) \
165 [r##num] "i"(offsetof(zx_thread_state_general_regs_t, r[num])),
166
167// Trampoline to bridge from the assembly below to the static C++ crash
168// callback.
169__attribute__((noreturn))
170static void StaticCrashHandler() {
morehouse400262a2017-12-08 22:54:44 +0000171 Fuzzer::StaticCrashSignalCallback();
phoseke59ddd22018-07-18 19:20:47 +0000172 for (;;) {
173 _Exit(1);
174 }
175}
176
177// Creates the trampoline with the necessary CFI information to unwind through
178// to the crashing call stack. The attribute is necessary because the function
179// is never called; it's just a container around the assembly to allow it to
180// use operands for compile-time computed constants.
181__attribute__((used))
182void MakeTrampoline() {
183 __asm__(".cfi_endproc\n"
184 ".pushsection .text.CrashTrampolineAsm\n"
185 ".type CrashTrampolineAsm,STT_FUNC\n"
186"CrashTrampolineAsm:\n"
187 ".cfi_startproc simple\n"
188 ".cfi_signal_frame\n"
189#if defined(__x86_64__)
190 ".cfi_return_column rip\n"
191 ".cfi_def_cfa rsp, 0\n"
192 FOREACH_REGISTER(CFI_OFFSET_REG, CFI_OFFSET_NUM)
193 "call %c[StaticCrashHandler]\n"
194 "ud2\n"
195#elif defined(__aarch64__)
196 ".cfi_return_column 33\n"
197 ".cfi_def_cfa sp, 0\n"
198 ".cfi_offset 33, %c[pc]\n"
199 FOREACH_REGISTER(CFI_OFFSET_REG, CFI_OFFSET_NUM)
200 "bl %[StaticCrashHandler]\n"
201#else
202#error "Unsupported architecture for fuzzing on Fuchsia"
203#endif
204 ".cfi_endproc\n"
205 ".size CrashTrampolineAsm, . - CrashTrampolineAsm\n"
206 ".popsection\n"
207 ".cfi_startproc\n"
208 : // No outputs
209 : FOREACH_REGISTER(ASM_OPERAND_REG, ASM_OPERAND_NUM)
210#if defined(__aarch64__)
211 ASM_OPERAND_REG(pc)
212#endif
213 [StaticCrashHandler] "i" (StaticCrashHandler));
214}
215
216void CrashHandler(zx_handle_t *Event) {
217 // This structure is used to ensure we close handles to objects we create in
218 // this handler.
219 struct ScopedHandle {
220 ~ScopedHandle() { _zx_handle_close(Handle); }
221 zx_handle_t Handle = ZX_HANDLE_INVALID;
222 };
223
224 // Create and bind the exception port. We need to claim to be a "debugger" so
225 // the kernel will allow us to modify and resume dying threads (see below).
226 // Once the port is set, we can signal the main thread to continue and wait
227 // for the exception to arrive.
228 ScopedHandle Port;
229 ExitOnErr(_zx_port_create(0, &Port.Handle), "_zx_port_create");
230 zx_handle_t Self = _zx_process_self();
231
232 ExitOnErr(_zx_task_bind_exception_port(Self, Port.Handle, kFuzzingCrash,
233 ZX_EXCEPTION_PORT_DEBUGGER),
234 "_zx_task_bind_exception_port");
235
236 ExitOnErr(_zx_object_signal(*Event, 0, ZX_USER_SIGNAL_0),
237 "_zx_object_signal");
238
239 zx_port_packet_t Packet;
phosekc8b3fb82018-07-24 02:34:24 +0000240 ExitOnErr(_zx_port_wait(Port.Handle, ZX_TIME_INFINITE_OLD, &Packet),
phoseke59ddd22018-07-18 19:20:47 +0000241 "_zx_port_wait");
242
243 // At this point, we want to get the state of the crashing thread, but
244 // libFuzzer and the sanitizers assume this will happen from that same thread
245 // via a POSIX signal handler. "Resurrecting" the thread in the middle of the
246 // appropriate callback is as simple as forcibly setting the instruction
247 // pointer/program counter, provided we NEVER EVER return from that function
248 // (since otherwise our stack will not be valid).
249 ScopedHandle Thread;
250 ExitOnErr(_zx_object_get_child(Self, Packet.exception.tid,
251 ZX_RIGHT_SAME_RIGHTS, &Thread.Handle),
252 "_zx_object_get_child");
253
254 zx_thread_state_general_regs_t GeneralRegisters;
255 ExitOnErr(_zx_thread_read_state(Thread.Handle, ZX_THREAD_STATE_GENERAL_REGS,
256 &GeneralRegisters, sizeof(GeneralRegisters)),
257 "_zx_thread_read_state");
258
259 // To unwind properly, we need to push the crashing thread's register state
260 // onto the stack and jump into a trampoline with CFI instructions on how
261 // to restore it.
262#if defined(__x86_64__)
263 uintptr_t StackPtr =
264 (GeneralRegisters.rsp - (128 + sizeof(GeneralRegisters))) &
265 -(uintptr_t)16;
266 __unsanitized_memcpy(reinterpret_cast<void *>(StackPtr), &GeneralRegisters,
267 sizeof(GeneralRegisters));
268 GeneralRegisters.rsp = StackPtr;
269 GeneralRegisters.rip = reinterpret_cast<zx_vaddr_t>(CrashTrampolineAsm);
270
271#elif defined(__aarch64__)
272 uintptr_t StackPtr =
273 (GeneralRegisters.sp - sizeof(GeneralRegisters)) & -(uintptr_t)16;
274 __unsanitized_memcpy(reinterpret_cast<void *>(StackPtr), &GeneralRegisters,
275 sizeof(GeneralRegisters));
276 GeneralRegisters.sp = StackPtr;
277 GeneralRegisters.pc = reinterpret_cast<zx_vaddr_t>(CrashTrampolineAsm);
278
279#else
280#error "Unsupported architecture for fuzzing on Fuchsia"
281#endif
282
283 // Now force the crashing thread's state.
284 ExitOnErr(_zx_thread_write_state(Thread.Handle, ZX_THREAD_STATE_GENERAL_REGS,
285 &GeneralRegisters, sizeof(GeneralRegisters)),
286 "_zx_thread_write_state");
287
288 ExitOnErr(_zx_task_resume_from_exception(Thread.Handle, Port.Handle, 0),
289 "_zx_task_resume_from_exception");
morehouse400262a2017-12-08 22:54:44 +0000290}
291
292} // namespace
293
294// Platform specific functions.
295void SetSignalHandler(const FuzzingOptions &Options) {
morehouse400262a2017-12-08 22:54:44 +0000296 // Set up alarm handler if needed.
297 if (Options.UnitTimeoutSec > 0) {
298 std::thread T(AlarmHandler, Options.UnitTimeoutSec / 2 + 1);
299 T.detach();
300 }
301
302 // Set up interrupt handler if needed.
303 if (Options.HandleInt || Options.HandleTerm) {
304 std::thread T(InterruptHandler);
305 T.detach();
306 }
307
308 // Early exit if no crash handler needed.
309 if (!Options.HandleSegv && !Options.HandleBus && !Options.HandleIll &&
310 !Options.HandleFpe && !Options.HandleAbrt)
311 return;
312
phoseke59ddd22018-07-18 19:20:47 +0000313 // Set up the crash handler and wait until it is ready before proceeding.
314 zx_handle_t Event;
315 ExitOnErr(_zx_event_create(0, &Event), "_zx_event_create");
morehouse400262a2017-12-08 22:54:44 +0000316
phoseke59ddd22018-07-18 19:20:47 +0000317 std::thread T(CrashHandler, &Event);
phosekc8b3fb82018-07-24 02:34:24 +0000318 zx_status_t Status = _zx_object_wait_one(Event, ZX_USER_SIGNAL_0,
319 ZX_TIME_INFINITE_OLD, nullptr);
phoseke59ddd22018-07-18 19:20:47 +0000320 _zx_handle_close(Event);
321 ExitOnErr(Status, "_zx_object_wait_one");
morehouse400262a2017-12-08 22:54:44 +0000322
morehouse400262a2017-12-08 22:54:44 +0000323 T.detach();
324}
325
326void SleepSeconds(int Seconds) {
phosekf9123762018-02-07 08:22:58 +0000327 _zx_nanosleep(_zx_deadline_after(ZX_SEC(Seconds)));
morehouse400262a2017-12-08 22:54:44 +0000328}
329
330unsigned long GetPid() {
331 zx_status_t rc;
332 zx_info_handle_basic_t Info;
phoseke81389f2018-05-26 01:02:34 +0000333 if ((rc = _zx_object_get_info(_zx_process_self(), ZX_INFO_HANDLE_BASIC, &Info,
phoseke59ddd22018-07-18 19:20:47 +0000334 sizeof(Info), NULL, NULL)) != ZX_OK) {
morehouse400262a2017-12-08 22:54:44 +0000335 Printf("libFuzzer: unable to get info about self: %s\n",
phoseke81389f2018-05-26 01:02:34 +0000336 _zx_status_get_string(rc));
morehouse400262a2017-12-08 22:54:44 +0000337 exit(1);
338 }
339 return Info.koid;
340}
341
342size_t GetPeakRSSMb() {
343 zx_status_t rc;
344 zx_info_task_stats_t Info;
phosekf9123762018-02-07 08:22:58 +0000345 if ((rc = _zx_object_get_info(_zx_process_self(), ZX_INFO_TASK_STATS, &Info,
phoseke59ddd22018-07-18 19:20:47 +0000346 sizeof(Info), NULL, NULL)) != ZX_OK) {
morehouse400262a2017-12-08 22:54:44 +0000347 Printf("libFuzzer: unable to get info about self: %s\n",
phosekf9123762018-02-07 08:22:58 +0000348 _zx_status_get_string(rc));
morehouse400262a2017-12-08 22:54:44 +0000349 exit(1);
350 }
351 return (Info.mem_private_bytes + Info.mem_shared_bytes) >> 20;
352}
353
phosekf9123762018-02-07 08:22:58 +0000354template <typename Fn>
355class RunOnDestruction {
356 public:
357 explicit RunOnDestruction(Fn fn) : fn_(fn) {}
358 ~RunOnDestruction() { fn_(); }
359
360 private:
361 Fn fn_;
362};
363
364template <typename Fn>
365RunOnDestruction<Fn> at_scope_exit(Fn fn) {
366 return RunOnDestruction<Fn>(fn);
367}
368
morehouse400262a2017-12-08 22:54:44 +0000369int ExecuteCommand(const Command &Cmd) {
370 zx_status_t rc;
371
372 // Convert arguments to C array
373 auto Args = Cmd.getArguments();
374 size_t Argc = Args.size();
375 assert(Argc != 0);
phosek4b9efd12018-06-02 01:17:10 +0000376 std::unique_ptr<const char *[]> Argv(new const char *[Argc + 1]);
morehouse400262a2017-12-08 22:54:44 +0000377 for (size_t i = 0; i < Argc; ++i)
378 Argv[i] = Args[i].c_str();
phosek4b9efd12018-06-02 01:17:10 +0000379 Argv[Argc] = nullptr;
morehouse400262a2017-12-08 22:54:44 +0000380
381 // Determine stdout
382 int FdOut = STDOUT_FILENO;
phosekf9123762018-02-07 08:22:58 +0000383
morehouse400262a2017-12-08 22:54:44 +0000384 if (Cmd.hasOutputFile()) {
385 auto Filename = Cmd.getOutputFile();
phosekf9123762018-02-07 08:22:58 +0000386 FdOut = open(Filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0);
387 if (FdOut == -1) {
morehouse400262a2017-12-08 22:54:44 +0000388 Printf("libFuzzer: failed to open %s: %s\n", Filename.c_str(),
389 strerror(errno));
390 return ZX_ERR_IO;
391 }
morehouse400262a2017-12-08 22:54:44 +0000392 }
phosekf9123762018-02-07 08:22:58 +0000393 auto CloseFdOut = at_scope_exit([&]() { close(FdOut); } );
morehouse400262a2017-12-08 22:54:44 +0000394
395 // Determine stderr
396 int FdErr = STDERR_FILENO;
397 if (Cmd.isOutAndErrCombined())
398 FdErr = FdOut;
399
400 // Clone the file descriptors into the new process
phosek4b9efd12018-06-02 01:17:10 +0000401 fdio_spawn_action_t SpawnAction[] = {
402 {
403 .action = FDIO_SPAWN_ACTION_CLONE_FD,
404 .fd =
405 {
406 .local_fd = STDIN_FILENO,
407 .target_fd = STDIN_FILENO,
408 },
409 },
410 {
411 .action = FDIO_SPAWN_ACTION_CLONE_FD,
412 .fd =
413 {
414 .local_fd = FdOut,
415 .target_fd = STDOUT_FILENO,
416 },
417 },
418 {
419 .action = FDIO_SPAWN_ACTION_CLONE_FD,
420 .fd =
421 {
422 .local_fd = FdErr,
423 .target_fd = STDERR_FILENO,
424 },
425 },
426 };
morehouse400262a2017-12-08 22:54:44 +0000427
phosek4b9efd12018-06-02 01:17:10 +0000428 // Start the process.
429 char ErrorMsg[FDIO_SPAWN_ERR_MSG_MAX_LENGTH];
morehouse400262a2017-12-08 22:54:44 +0000430 zx_handle_t ProcessHandle = ZX_HANDLE_INVALID;
phosek4b9efd12018-06-02 01:17:10 +0000431 rc = fdio_spawn_etc(
432 ZX_HANDLE_INVALID, FDIO_SPAWN_CLONE_ALL & (~FDIO_SPAWN_CLONE_STDIO),
433 Argv[0], Argv.get(), nullptr, 3, SpawnAction, &ProcessHandle, ErrorMsg);
434 if (rc != ZX_OK) {
morehouse400262a2017-12-08 22:54:44 +0000435 Printf("libFuzzer: failed to launch '%s': %s, %s\n", Argv[0], ErrorMsg,
phosekf9123762018-02-07 08:22:58 +0000436 _zx_status_get_string(rc));
morehouse400262a2017-12-08 22:54:44 +0000437 return rc;
438 }
phosekf9123762018-02-07 08:22:58 +0000439 auto CloseHandle = at_scope_exit([&]() { _zx_handle_close(ProcessHandle); });
morehouse400262a2017-12-08 22:54:44 +0000440
441 // Now join the process and return the exit status.
phosekf9123762018-02-07 08:22:58 +0000442 if ((rc = _zx_object_wait_one(ProcessHandle, ZX_PROCESS_TERMINATED,
phosekc8b3fb82018-07-24 02:34:24 +0000443 ZX_TIME_INFINITE_OLD, nullptr)) != ZX_OK) {
morehouse400262a2017-12-08 22:54:44 +0000444 Printf("libFuzzer: failed to join '%s': %s\n", Argv[0],
phosekf9123762018-02-07 08:22:58 +0000445 _zx_status_get_string(rc));
morehouse400262a2017-12-08 22:54:44 +0000446 return rc;
447 }
448
449 zx_info_process_t Info;
phosekf9123762018-02-07 08:22:58 +0000450 if ((rc = _zx_object_get_info(ProcessHandle, ZX_INFO_PROCESS, &Info,
451 sizeof(Info), nullptr, nullptr)) != ZX_OK) {
morehouse400262a2017-12-08 22:54:44 +0000452 Printf("libFuzzer: unable to get return code from '%s': %s\n", Argv[0],
phoseke81389f2018-05-26 01:02:34 +0000453 _zx_status_get_string(rc));
morehouse400262a2017-12-08 22:54:44 +0000454 return rc;
455 }
456
457 return Info.return_code;
458}
459
460const void *SearchMemory(const void *Data, size_t DataLen, const void *Patt,
461 size_t PattLen) {
462 return memmem(Data, DataLen, Patt, PattLen);
463}
464
465} // namespace fuzzer
466
467#endif // LIBFUZZER_FUCHSIA