blob: 7b5c8f647ae942c67c8a76250c56069c0dd4adc2 [file] [log] [blame]
morehouse400262a2017-12-08 22:54:44 +00001//===- FuzzerUtilFuchsia.cpp - Misc utils for Fuchsia. --------------------===//
2//
chandlerc40284492019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
morehouse400262a2017-12-08 22:54:44 +00006//
7//===----------------------------------------------------------------------===//
8// Misc utils implementation using Fuchsia/Zircon APIs.
9//===----------------------------------------------------------------------===//
10#include "FuzzerDefs.h"
11
12#if LIBFUZZER_FUCHSIA
13
14#include "FuzzerInternal.h"
15#include "FuzzerUtil.h"
16#include <cerrno>
17#include <cinttypes>
18#include <cstdint>
morehouse400262a2017-12-08 22:54:44 +000019#include <fcntl.h>
phoseke7c6a592018-06-07 18:41:35 +000020#include <lib/fdio/spawn.h>
morehouse400262a2017-12-08 22:54:44 +000021#include <string>
phosek00c73322018-04-20 00:41:06 +000022#include <sys/select.h>
morehouse400262a2017-12-08 22:54:44 +000023#include <thread>
phosekf9123762018-02-07 08:22:58 +000024#include <unistd.h>
morehouse400262a2017-12-08 22:54:44 +000025#include <zircon/errors.h>
phosekf9123762018-02-07 08:22:58 +000026#include <zircon/process.h>
phoseke59ddd22018-07-18 19:20:47 +000027#include <zircon/sanitizer.h>
morehouse400262a2017-12-08 22:54:44 +000028#include <zircon/status.h>
29#include <zircon/syscalls.h>
phoseke59ddd22018-07-18 19:20:47 +000030#include <zircon/syscalls/debug.h>
31#include <zircon/syscalls/exception.h>
morehouse400262a2017-12-08 22:54:44 +000032#include <zircon/syscalls/port.h>
33#include <zircon/types.h>
morehouse400262a2017-12-08 22:54:44 +000034
35namespace fuzzer {
36
phoseke59ddd22018-07-18 19:20:47 +000037// Given that Fuchsia doesn't have the POSIX signals that libFuzzer was written
38// around, the general approach is to spin up dedicated threads to watch for
39// each requested condition (alarm, interrupt, crash). Of these, the crash
40// handler is the most involved, as it requires resuming the crashed thread in
41// order to invoke the sanitizers to get the needed state.
42
43// Forward declaration of assembly trampoline needed to resume crashed threads.
44// This appears to have external linkage to C++, which is why it's not in the
45// anonymous namespace. The assembly definition inside MakeTrampoline()
46// actually defines the symbol with internal linkage only.
47void CrashTrampolineAsm() __asm__("CrashTrampolineAsm");
48
morehouse400262a2017-12-08 22:54:44 +000049namespace {
50
51// A magic value for the Zircon exception port, chosen to spell 'FUZZING'
52// when interpreted as a byte sequence on little-endian platforms.
53const uint64_t kFuzzingCrash = 0x474e495a5a5546;
54
phoseke59ddd22018-07-18 19:20:47 +000055// Helper function to handle Zircon syscall failures.
56void ExitOnErr(zx_status_t Status, const char *Syscall) {
57 if (Status != ZX_OK) {
58 Printf("libFuzzer: %s failed: %s\n", Syscall,
59 _zx_status_get_string(Status));
60 exit(1);
61 }
62}
63
morehouse400262a2017-12-08 22:54:44 +000064void AlarmHandler(int Seconds) {
65 while (true) {
66 SleepSeconds(Seconds);
67 Fuzzer::StaticAlarmCallback();
68 }
69}
70
71void InterruptHandler() {
phosek1631e452018-04-19 14:01:46 +000072 fd_set readfds;
morehouse400262a2017-12-08 22:54:44 +000073 // Ctrl-C sends ETX in Zircon.
phosek1631e452018-04-19 14:01:46 +000074 do {
75 FD_ZERO(&readfds);
76 FD_SET(STDIN_FILENO, &readfds);
77 select(STDIN_FILENO + 1, &readfds, nullptr, nullptr, nullptr);
78 } while(!FD_ISSET(STDIN_FILENO, &readfds) || getchar() != 0x03);
morehouse400262a2017-12-08 22:54:44 +000079 Fuzzer::StaticInterruptCallback();
80}
81
phoseke59ddd22018-07-18 19:20:47 +000082// For the crash handler, we need to call Fuzzer::StaticCrashSignalCallback
83// without POSIX signal handlers. To achieve this, we use an assembly function
84// to add the necessary CFI unwinding information and a C function to bridge
85// from that back into C++.
86
87// FIXME: This works as a short-term solution, but this code really shouldn't be
88// architecture dependent. A better long term solution is to implement remote
89// unwinding and expose the necessary APIs through sanitizer_common and/or ASAN
90// to allow the exception handling thread to gather the crash state directly.
91//
92// Alternatively, Fuchsia may in future actually implement basic signal
93// handling for the machine trap signals.
94#if defined(__x86_64__)
95#define FOREACH_REGISTER(OP_REG, OP_NUM) \
96 OP_REG(rax) \
97 OP_REG(rbx) \
98 OP_REG(rcx) \
99 OP_REG(rdx) \
100 OP_REG(rsi) \
101 OP_REG(rdi) \
102 OP_REG(rbp) \
103 OP_REG(rsp) \
104 OP_REG(r8) \
105 OP_REG(r9) \
106 OP_REG(r10) \
107 OP_REG(r11) \
108 OP_REG(r12) \
109 OP_REG(r13) \
110 OP_REG(r14) \
111 OP_REG(r15) \
112 OP_REG(rip)
113
114#elif defined(__aarch64__)
115#define FOREACH_REGISTER(OP_REG, OP_NUM) \
116 OP_NUM(0) \
117 OP_NUM(1) \
118 OP_NUM(2) \
119 OP_NUM(3) \
120 OP_NUM(4) \
121 OP_NUM(5) \
122 OP_NUM(6) \
123 OP_NUM(7) \
124 OP_NUM(8) \
125 OP_NUM(9) \
126 OP_NUM(10) \
127 OP_NUM(11) \
128 OP_NUM(12) \
129 OP_NUM(13) \
130 OP_NUM(14) \
131 OP_NUM(15) \
132 OP_NUM(16) \
133 OP_NUM(17) \
134 OP_NUM(18) \
135 OP_NUM(19) \
136 OP_NUM(20) \
137 OP_NUM(21) \
138 OP_NUM(22) \
139 OP_NUM(23) \
140 OP_NUM(24) \
141 OP_NUM(25) \
142 OP_NUM(26) \
143 OP_NUM(27) \
144 OP_NUM(28) \
145 OP_NUM(29) \
146 OP_NUM(30) \
147 OP_REG(sp)
148
149#else
150#error "Unsupported architecture for fuzzing on Fuchsia"
151#endif
152
153// Produces a CFI directive for the named or numbered register.
154#define CFI_OFFSET_REG(reg) ".cfi_offset " #reg ", %c[" #reg "]\n"
155#define CFI_OFFSET_NUM(num) CFI_OFFSET_REG(r##num)
156
157// Produces an assembler input operand for the named or numbered register.
158#define ASM_OPERAND_REG(reg) \
159 [reg] "i"(offsetof(zx_thread_state_general_regs_t, reg)),
160#define ASM_OPERAND_NUM(num) \
161 [r##num] "i"(offsetof(zx_thread_state_general_regs_t, r[num])),
162
163// Trampoline to bridge from the assembly below to the static C++ crash
164// callback.
165__attribute__((noreturn))
166static void StaticCrashHandler() {
morehouse400262a2017-12-08 22:54:44 +0000167 Fuzzer::StaticCrashSignalCallback();
phoseke59ddd22018-07-18 19:20:47 +0000168 for (;;) {
169 _Exit(1);
170 }
171}
172
173// Creates the trampoline with the necessary CFI information to unwind through
174// to the crashing call stack. The attribute is necessary because the function
175// is never called; it's just a container around the assembly to allow it to
176// use operands for compile-time computed constants.
177__attribute__((used))
178void MakeTrampoline() {
179 __asm__(".cfi_endproc\n"
180 ".pushsection .text.CrashTrampolineAsm\n"
181 ".type CrashTrampolineAsm,STT_FUNC\n"
182"CrashTrampolineAsm:\n"
183 ".cfi_startproc simple\n"
184 ".cfi_signal_frame\n"
185#if defined(__x86_64__)
186 ".cfi_return_column rip\n"
187 ".cfi_def_cfa rsp, 0\n"
188 FOREACH_REGISTER(CFI_OFFSET_REG, CFI_OFFSET_NUM)
189 "call %c[StaticCrashHandler]\n"
190 "ud2\n"
191#elif defined(__aarch64__)
192 ".cfi_return_column 33\n"
193 ".cfi_def_cfa sp, 0\n"
194 ".cfi_offset 33, %c[pc]\n"
195 FOREACH_REGISTER(CFI_OFFSET_REG, CFI_OFFSET_NUM)
196 "bl %[StaticCrashHandler]\n"
197#else
198#error "Unsupported architecture for fuzzing on Fuchsia"
199#endif
200 ".cfi_endproc\n"
201 ".size CrashTrampolineAsm, . - CrashTrampolineAsm\n"
202 ".popsection\n"
203 ".cfi_startproc\n"
204 : // No outputs
205 : FOREACH_REGISTER(ASM_OPERAND_REG, ASM_OPERAND_NUM)
206#if defined(__aarch64__)
207 ASM_OPERAND_REG(pc)
208#endif
209 [StaticCrashHandler] "i" (StaticCrashHandler));
210}
211
212void CrashHandler(zx_handle_t *Event) {
213 // This structure is used to ensure we close handles to objects we create in
214 // this handler.
215 struct ScopedHandle {
216 ~ScopedHandle() { _zx_handle_close(Handle); }
217 zx_handle_t Handle = ZX_HANDLE_INVALID;
218 };
219
220 // Create and bind the exception port. We need to claim to be a "debugger" so
221 // the kernel will allow us to modify and resume dying threads (see below).
222 // Once the port is set, we can signal the main thread to continue and wait
223 // for the exception to arrive.
224 ScopedHandle Port;
225 ExitOnErr(_zx_port_create(0, &Port.Handle), "_zx_port_create");
226 zx_handle_t Self = _zx_process_self();
227
228 ExitOnErr(_zx_task_bind_exception_port(Self, Port.Handle, kFuzzingCrash,
229 ZX_EXCEPTION_PORT_DEBUGGER),
230 "_zx_task_bind_exception_port");
231
232 ExitOnErr(_zx_object_signal(*Event, 0, ZX_USER_SIGNAL_0),
233 "_zx_object_signal");
234
235 zx_port_packet_t Packet;
phosekd2551d62018-08-27 17:51:52 +0000236 ExitOnErr(_zx_port_wait(Port.Handle, ZX_TIME_INFINITE, &Packet),
phoseke59ddd22018-07-18 19:20:47 +0000237 "_zx_port_wait");
238
239 // At this point, we want to get the state of the crashing thread, but
240 // libFuzzer and the sanitizers assume this will happen from that same thread
241 // via a POSIX signal handler. "Resurrecting" the thread in the middle of the
242 // appropriate callback is as simple as forcibly setting the instruction
243 // pointer/program counter, provided we NEVER EVER return from that function
244 // (since otherwise our stack will not be valid).
245 ScopedHandle Thread;
246 ExitOnErr(_zx_object_get_child(Self, Packet.exception.tid,
247 ZX_RIGHT_SAME_RIGHTS, &Thread.Handle),
248 "_zx_object_get_child");
249
250 zx_thread_state_general_regs_t GeneralRegisters;
251 ExitOnErr(_zx_thread_read_state(Thread.Handle, ZX_THREAD_STATE_GENERAL_REGS,
252 &GeneralRegisters, sizeof(GeneralRegisters)),
253 "_zx_thread_read_state");
254
255 // To unwind properly, we need to push the crashing thread's register state
256 // onto the stack and jump into a trampoline with CFI instructions on how
257 // to restore it.
258#if defined(__x86_64__)
259 uintptr_t StackPtr =
260 (GeneralRegisters.rsp - (128 + sizeof(GeneralRegisters))) &
261 -(uintptr_t)16;
262 __unsanitized_memcpy(reinterpret_cast<void *>(StackPtr), &GeneralRegisters,
263 sizeof(GeneralRegisters));
264 GeneralRegisters.rsp = StackPtr;
265 GeneralRegisters.rip = reinterpret_cast<zx_vaddr_t>(CrashTrampolineAsm);
266
267#elif defined(__aarch64__)
268 uintptr_t StackPtr =
269 (GeneralRegisters.sp - sizeof(GeneralRegisters)) & -(uintptr_t)16;
270 __unsanitized_memcpy(reinterpret_cast<void *>(StackPtr), &GeneralRegisters,
271 sizeof(GeneralRegisters));
272 GeneralRegisters.sp = StackPtr;
273 GeneralRegisters.pc = reinterpret_cast<zx_vaddr_t>(CrashTrampolineAsm);
274
275#else
276#error "Unsupported architecture for fuzzing on Fuchsia"
277#endif
278
279 // Now force the crashing thread's state.
280 ExitOnErr(_zx_thread_write_state(Thread.Handle, ZX_THREAD_STATE_GENERAL_REGS,
281 &GeneralRegisters, sizeof(GeneralRegisters)),
282 "_zx_thread_write_state");
283
284 ExitOnErr(_zx_task_resume_from_exception(Thread.Handle, Port.Handle, 0),
285 "_zx_task_resume_from_exception");
morehouse400262a2017-12-08 22:54:44 +0000286}
287
288} // namespace
289
kccda168932019-01-31 00:09:43 +0000290bool Mprotect(void *Ptr, size_t Size, bool AllowReadWrite) {
291 return false; // UNIMPLEMENTED
292}
293
morehouse400262a2017-12-08 22:54:44 +0000294// 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);
phosekd2551d62018-08-27 17:51:52 +0000318 zx_status_t Status =
319 _zx_object_wait_one(Event, ZX_USER_SIGNAL_0, ZX_TIME_INFINITE, 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
phosekca62a262018-10-02 17:21:04 +0000381 // Determine output. On Fuchsia, the fuzzer is typically run as a component
382 // that lacks a mutable working directory. Fortunately, when this is the case
383 // a mutable output directory must be specified using "-artifact_prefix=...",
384 // so write the log file(s) there.
morehouse400262a2017-12-08 22:54:44 +0000385 int FdOut = STDOUT_FILENO;
morehouse400262a2017-12-08 22:54:44 +0000386 if (Cmd.hasOutputFile()) {
phosekca62a262018-10-02 17:21:04 +0000387 std::string Path;
388 if (Cmd.hasFlag("artifact_prefix"))
389 Path = Cmd.getFlagValue("artifact_prefix") + "/" + Cmd.getOutputFile();
390 else
391 Path = Cmd.getOutputFile();
392 FdOut = open(Path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0);
phosekf9123762018-02-07 08:22:58 +0000393 if (FdOut == -1) {
phosekca62a262018-10-02 17:21:04 +0000394 Printf("libFuzzer: failed to open %s: %s\n", Path.c_str(),
morehouse400262a2017-12-08 22:54:44 +0000395 strerror(errno));
396 return ZX_ERR_IO;
397 }
morehouse400262a2017-12-08 22:54:44 +0000398 }
phosekca62a262018-10-02 17:21:04 +0000399 auto CloseFdOut = at_scope_exit([FdOut]() {
400 if (FdOut != STDOUT_FILENO)
401 close(FdOut);
402 });
morehouse400262a2017-12-08 22:54:44 +0000403
404 // Determine stderr
405 int FdErr = STDERR_FILENO;
406 if (Cmd.isOutAndErrCombined())
407 FdErr = FdOut;
408
409 // Clone the file descriptors into the new process
phosek4b9efd12018-06-02 01:17:10 +0000410 fdio_spawn_action_t SpawnAction[] = {
411 {
412 .action = FDIO_SPAWN_ACTION_CLONE_FD,
413 .fd =
414 {
415 .local_fd = STDIN_FILENO,
416 .target_fd = STDIN_FILENO,
417 },
418 },
419 {
420 .action = FDIO_SPAWN_ACTION_CLONE_FD,
421 .fd =
422 {
423 .local_fd = FdOut,
424 .target_fd = STDOUT_FILENO,
425 },
426 },
427 {
428 .action = FDIO_SPAWN_ACTION_CLONE_FD,
429 .fd =
430 {
431 .local_fd = FdErr,
432 .target_fd = STDERR_FILENO,
433 },
434 },
435 };
morehouse400262a2017-12-08 22:54:44 +0000436
phosek4b9efd12018-06-02 01:17:10 +0000437 // Start the process.
438 char ErrorMsg[FDIO_SPAWN_ERR_MSG_MAX_LENGTH];
morehouse400262a2017-12-08 22:54:44 +0000439 zx_handle_t ProcessHandle = ZX_HANDLE_INVALID;
phosek4b9efd12018-06-02 01:17:10 +0000440 rc = fdio_spawn_etc(
441 ZX_HANDLE_INVALID, FDIO_SPAWN_CLONE_ALL & (~FDIO_SPAWN_CLONE_STDIO),
442 Argv[0], Argv.get(), nullptr, 3, SpawnAction, &ProcessHandle, ErrorMsg);
443 if (rc != ZX_OK) {
morehouse400262a2017-12-08 22:54:44 +0000444 Printf("libFuzzer: failed to launch '%s': %s, %s\n", Argv[0], ErrorMsg,
phosekf9123762018-02-07 08:22:58 +0000445 _zx_status_get_string(rc));
morehouse400262a2017-12-08 22:54:44 +0000446 return rc;
447 }
phosekf9123762018-02-07 08:22:58 +0000448 auto CloseHandle = at_scope_exit([&]() { _zx_handle_close(ProcessHandle); });
morehouse400262a2017-12-08 22:54:44 +0000449
450 // Now join the process and return the exit status.
phosekf9123762018-02-07 08:22:58 +0000451 if ((rc = _zx_object_wait_one(ProcessHandle, ZX_PROCESS_TERMINATED,
phosekd2551d62018-08-27 17:51:52 +0000452 ZX_TIME_INFINITE, nullptr)) != ZX_OK) {
morehouse400262a2017-12-08 22:54:44 +0000453 Printf("libFuzzer: failed to join '%s': %s\n", Argv[0],
phosekf9123762018-02-07 08:22:58 +0000454 _zx_status_get_string(rc));
morehouse400262a2017-12-08 22:54:44 +0000455 return rc;
456 }
457
458 zx_info_process_t Info;
phosekf9123762018-02-07 08:22:58 +0000459 if ((rc = _zx_object_get_info(ProcessHandle, ZX_INFO_PROCESS, &Info,
460 sizeof(Info), nullptr, nullptr)) != ZX_OK) {
morehouse400262a2017-12-08 22:54:44 +0000461 Printf("libFuzzer: unable to get return code from '%s': %s\n", Argv[0],
phoseke81389f2018-05-26 01:02:34 +0000462 _zx_status_get_string(rc));
morehouse400262a2017-12-08 22:54:44 +0000463 return rc;
464 }
465
466 return Info.return_code;
467}
468
469const void *SearchMemory(const void *Data, size_t DataLen, const void *Patt,
470 size_t PattLen) {
471 return memmem(Data, DataLen, Patt, PattLen);
472}
473
474} // namespace fuzzer
475
476#endif // LIBFUZZER_FUCHSIA