blob: 36010f7f1d7f5b73e235ed39cbe8b9d6c0ddb940 [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"
phoseked73fdf2019-05-22 16:36:35 +000016#include <cassert>
morehouse400262a2017-12-08 22:54:44 +000017#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>
phosek154d0692019-06-27 21:13:06 +000033#include <zircon/syscalls/object.h>
morehouse400262a2017-12-08 22:54:44 +000034#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
phoseke59ddd22018-07-18 19:20:47 +000052// Helper function to handle Zircon syscall failures.
53void ExitOnErr(zx_status_t Status, const char *Syscall) {
54 if (Status != ZX_OK) {
55 Printf("libFuzzer: %s failed: %s\n", Syscall,
56 _zx_status_get_string(Status));
57 exit(1);
58 }
59}
60
morehouse400262a2017-12-08 22:54:44 +000061void AlarmHandler(int Seconds) {
62 while (true) {
63 SleepSeconds(Seconds);
64 Fuzzer::StaticAlarmCallback();
65 }
66}
67
68void InterruptHandler() {
phosek1631e452018-04-19 14:01:46 +000069 fd_set readfds;
morehouse400262a2017-12-08 22:54:44 +000070 // Ctrl-C sends ETX in Zircon.
phosek1631e452018-04-19 14:01:46 +000071 do {
72 FD_ZERO(&readfds);
73 FD_SET(STDIN_FILENO, &readfds);
74 select(STDIN_FILENO + 1, &readfds, nullptr, nullptr, nullptr);
75 } while(!FD_ISSET(STDIN_FILENO, &readfds) || getchar() != 0x03);
morehouse400262a2017-12-08 22:54:44 +000076 Fuzzer::StaticInterruptCallback();
77}
78
phoseke59ddd22018-07-18 19:20:47 +000079// For the crash handler, we need to call Fuzzer::StaticCrashSignalCallback
80// without POSIX signal handlers. To achieve this, we use an assembly function
81// to add the necessary CFI unwinding information and a C function to bridge
82// from that back into C++.
83
84// FIXME: This works as a short-term solution, but this code really shouldn't be
85// architecture dependent. A better long term solution is to implement remote
86// unwinding and expose the necessary APIs through sanitizer_common and/or ASAN
87// to allow the exception handling thread to gather the crash state directly.
88//
89// Alternatively, Fuchsia may in future actually implement basic signal
90// handling for the machine trap signals.
91#if defined(__x86_64__)
92#define FOREACH_REGISTER(OP_REG, OP_NUM) \
93 OP_REG(rax) \
94 OP_REG(rbx) \
95 OP_REG(rcx) \
96 OP_REG(rdx) \
97 OP_REG(rsi) \
98 OP_REG(rdi) \
99 OP_REG(rbp) \
100 OP_REG(rsp) \
101 OP_REG(r8) \
102 OP_REG(r9) \
103 OP_REG(r10) \
104 OP_REG(r11) \
105 OP_REG(r12) \
106 OP_REG(r13) \
107 OP_REG(r14) \
108 OP_REG(r15) \
109 OP_REG(rip)
110
111#elif defined(__aarch64__)
112#define FOREACH_REGISTER(OP_REG, OP_NUM) \
113 OP_NUM(0) \
114 OP_NUM(1) \
115 OP_NUM(2) \
116 OP_NUM(3) \
117 OP_NUM(4) \
118 OP_NUM(5) \
119 OP_NUM(6) \
120 OP_NUM(7) \
121 OP_NUM(8) \
122 OP_NUM(9) \
123 OP_NUM(10) \
124 OP_NUM(11) \
125 OP_NUM(12) \
126 OP_NUM(13) \
127 OP_NUM(14) \
128 OP_NUM(15) \
129 OP_NUM(16) \
130 OP_NUM(17) \
131 OP_NUM(18) \
132 OP_NUM(19) \
133 OP_NUM(20) \
134 OP_NUM(21) \
135 OP_NUM(22) \
136 OP_NUM(23) \
137 OP_NUM(24) \
138 OP_NUM(25) \
139 OP_NUM(26) \
140 OP_NUM(27) \
141 OP_NUM(28) \
142 OP_NUM(29) \
143 OP_NUM(30) \
144 OP_REG(sp)
145
146#else
147#error "Unsupported architecture for fuzzing on Fuchsia"
148#endif
149
150// Produces a CFI directive for the named or numbered register.
151#define CFI_OFFSET_REG(reg) ".cfi_offset " #reg ", %c[" #reg "]\n"
152#define CFI_OFFSET_NUM(num) CFI_OFFSET_REG(r##num)
153
154// Produces an assembler input operand for the named or numbered register.
155#define ASM_OPERAND_REG(reg) \
156 [reg] "i"(offsetof(zx_thread_state_general_regs_t, reg)),
157#define ASM_OPERAND_NUM(num) \
158 [r##num] "i"(offsetof(zx_thread_state_general_regs_t, r[num])),
159
160// Trampoline to bridge from the assembly below to the static C++ crash
161// callback.
162__attribute__((noreturn))
163static void StaticCrashHandler() {
morehouse400262a2017-12-08 22:54:44 +0000164 Fuzzer::StaticCrashSignalCallback();
phoseke59ddd22018-07-18 19:20:47 +0000165 for (;;) {
166 _Exit(1);
167 }
168}
169
170// Creates the trampoline with the necessary CFI information to unwind through
171// to the crashing call stack. The attribute is necessary because the function
172// is never called; it's just a container around the assembly to allow it to
173// use operands for compile-time computed constants.
174__attribute__((used))
175void MakeTrampoline() {
176 __asm__(".cfi_endproc\n"
177 ".pushsection .text.CrashTrampolineAsm\n"
178 ".type CrashTrampolineAsm,STT_FUNC\n"
179"CrashTrampolineAsm:\n"
180 ".cfi_startproc simple\n"
181 ".cfi_signal_frame\n"
182#if defined(__x86_64__)
183 ".cfi_return_column rip\n"
184 ".cfi_def_cfa rsp, 0\n"
185 FOREACH_REGISTER(CFI_OFFSET_REG, CFI_OFFSET_NUM)
186 "call %c[StaticCrashHandler]\n"
187 "ud2\n"
188#elif defined(__aarch64__)
189 ".cfi_return_column 33\n"
190 ".cfi_def_cfa sp, 0\n"
191 ".cfi_offset 33, %c[pc]\n"
192 FOREACH_REGISTER(CFI_OFFSET_REG, CFI_OFFSET_NUM)
193 "bl %[StaticCrashHandler]\n"
194#else
195#error "Unsupported architecture for fuzzing on Fuchsia"
196#endif
197 ".cfi_endproc\n"
198 ".size CrashTrampolineAsm, . - CrashTrampolineAsm\n"
199 ".popsection\n"
200 ".cfi_startproc\n"
201 : // No outputs
202 : FOREACH_REGISTER(ASM_OPERAND_REG, ASM_OPERAND_NUM)
203#if defined(__aarch64__)
204 ASM_OPERAND_REG(pc)
205#endif
206 [StaticCrashHandler] "i" (StaticCrashHandler));
207}
208
209void CrashHandler(zx_handle_t *Event) {
210 // This structure is used to ensure we close handles to objects we create in
211 // this handler.
212 struct ScopedHandle {
213 ~ScopedHandle() { _zx_handle_close(Handle); }
214 zx_handle_t Handle = ZX_HANDLE_INVALID;
215 };
216
phosek154d0692019-06-27 21:13:06 +0000217 // Create the exception channel. We need to claim to be a "debugger" so the
218 // kernel will allow us to modify and resume dying threads (see below). Once
219 // the channel is set, we can signal the main thread to continue and wait
phoseke59ddd22018-07-18 19:20:47 +0000220 // for the exception to arrive.
phosek154d0692019-06-27 21:13:06 +0000221 ScopedHandle Channel;
phoseke59ddd22018-07-18 19:20:47 +0000222 zx_handle_t Self = _zx_process_self();
phosek154d0692019-06-27 21:13:06 +0000223 ExitOnErr(_zx_task_create_exception_channel(
224 Self, ZX_EXCEPTION_CHANNEL_DEBUGGER, &Channel.Handle),
225 "_zx_task_create_exception_channel");
phoseke59ddd22018-07-18 19:20:47 +0000226
227 ExitOnErr(_zx_object_signal(*Event, 0, ZX_USER_SIGNAL_0),
228 "_zx_object_signal");
229
phoseked73fdf2019-05-22 16:36:35 +0000230 // This thread lives as long as the process in order to keep handling
231 // crashes. In practice, the first crashed thread to reach the end of the
232 // StaticCrashHandler will end the process.
233 while (true) {
phosek154d0692019-06-27 21:13:06 +0000234 ExitOnErr(_zx_object_wait_one(Channel.Handle, ZX_CHANNEL_READABLE,
235 ZX_TIME_INFINITE, nullptr),
236 "_zx_object_wait_one");
237
238 zx_exception_info_t ExceptionInfo;
239 ScopedHandle Exception;
240 ExitOnErr(_zx_channel_read(Channel.Handle, 0, &ExceptionInfo,
241 &Exception.Handle, sizeof(ExceptionInfo), 1,
242 nullptr, nullptr),
243 "_zx_channel_read");
phoseke59ddd22018-07-18 19:20:47 +0000244
phoseked73fdf2019-05-22 16:36:35 +0000245 // Ignore informational synthetic exceptions.
phosek154d0692019-06-27 21:13:06 +0000246 if (ZX_EXCP_THREAD_STARTING == ExceptionInfo.type ||
247 ZX_EXCP_THREAD_EXITING == ExceptionInfo.type ||
248 ZX_EXCP_PROCESS_STARTING == ExceptionInfo.type) {
phoseked73fdf2019-05-22 16:36:35 +0000249 continue;
250 }
phoseke59ddd22018-07-18 19:20:47 +0000251
phoseked73fdf2019-05-22 16:36:35 +0000252 // At this point, we want to get the state of the crashing thread, but
253 // libFuzzer and the sanitizers assume this will happen from that same
254 // thread via a POSIX signal handler. "Resurrecting" the thread in the
255 // middle of the appropriate callback is as simple as forcibly setting the
256 // instruction pointer/program counter, provided we NEVER EVER return from
257 // that function (since otherwise our stack will not be valid).
258 ScopedHandle Thread;
phosek154d0692019-06-27 21:13:06 +0000259 ExitOnErr(_zx_exception_get_thread(Exception.Handle, &Thread.Handle),
260 "_zx_exception_get_thread");
phoseke59ddd22018-07-18 19:20:47 +0000261
phoseked73fdf2019-05-22 16:36:35 +0000262 zx_thread_state_general_regs_t GeneralRegisters;
263 ExitOnErr(_zx_thread_read_state(Thread.Handle, ZX_THREAD_STATE_GENERAL_REGS,
264 &GeneralRegisters,
265 sizeof(GeneralRegisters)),
266 "_zx_thread_read_state");
267
268 // To unwind properly, we need to push the crashing thread's register state
269 // onto the stack and jump into a trampoline with CFI instructions on how
270 // to restore it.
phoseke59ddd22018-07-18 19:20:47 +0000271#if defined(__x86_64__)
phoseked73fdf2019-05-22 16:36:35 +0000272 uintptr_t StackPtr =
273 (GeneralRegisters.rsp - (128 + sizeof(GeneralRegisters))) &
274 -(uintptr_t)16;
275 __unsanitized_memcpy(reinterpret_cast<void *>(StackPtr), &GeneralRegisters,
276 sizeof(GeneralRegisters));
277 GeneralRegisters.rsp = StackPtr;
278 GeneralRegisters.rip = reinterpret_cast<zx_vaddr_t>(CrashTrampolineAsm);
phoseke59ddd22018-07-18 19:20:47 +0000279
280#elif defined(__aarch64__)
phoseked73fdf2019-05-22 16:36:35 +0000281 uintptr_t StackPtr =
282 (GeneralRegisters.sp - sizeof(GeneralRegisters)) & -(uintptr_t)16;
283 __unsanitized_memcpy(reinterpret_cast<void *>(StackPtr), &GeneralRegisters,
284 sizeof(GeneralRegisters));
285 GeneralRegisters.sp = StackPtr;
286 GeneralRegisters.pc = reinterpret_cast<zx_vaddr_t>(CrashTrampolineAsm);
phoseke59ddd22018-07-18 19:20:47 +0000287
288#else
289#error "Unsupported architecture for fuzzing on Fuchsia"
290#endif
291
phoseked73fdf2019-05-22 16:36:35 +0000292 // Now force the crashing thread's state.
293 ExitOnErr(
294 _zx_thread_write_state(Thread.Handle, ZX_THREAD_STATE_GENERAL_REGS,
295 &GeneralRegisters, sizeof(GeneralRegisters)),
296 "_zx_thread_write_state");
phoseke59ddd22018-07-18 19:20:47 +0000297
phosek154d0692019-06-27 21:13:06 +0000298 // Set the exception to HANDLED so it resumes the thread on close.
299 uint32_t ExceptionState = ZX_EXCEPTION_STATE_HANDLED;
300 ExitOnErr(_zx_object_set_property(Exception.Handle, ZX_PROP_EXCEPTION_STATE,
301 &ExceptionState, sizeof(ExceptionState)),
302 "zx_object_set_property");
phoseked73fdf2019-05-22 16:36:35 +0000303 }
morehouse400262a2017-12-08 22:54:44 +0000304}
305
306} // namespace
307
kccda168932019-01-31 00:09:43 +0000308bool Mprotect(void *Ptr, size_t Size, bool AllowReadWrite) {
309 return false; // UNIMPLEMENTED
310}
311
morehouse400262a2017-12-08 22:54:44 +0000312// Platform specific functions.
313void SetSignalHandler(const FuzzingOptions &Options) {
jakehehrlich1c533892019-09-17 00:34:41 +0000314 // Make sure information from libFuzzer and the sanitizers are easy to
315 // reassemble. `__sanitizer_log_write` has the added benefit of ensuring the
316 // DSO map is always available for the symbolizer.
317 // A uint64_t fits in 20 chars, so 64 is plenty.
318 char Buf[64];
319 memset(Buf, 0, sizeof(Buf));
320 snprintf(Buf, sizeof(Buf), "==%lu== INFO: libFuzzer starting.\n", GetPid());
321 if (EF->__sanitizer_log_write)
322 __sanitizer_log_write(Buf, sizeof(Buf));
323 Printf("%s", Buf);
324
morehouse400262a2017-12-08 22:54:44 +0000325 // Set up alarm handler if needed.
326 if (Options.UnitTimeoutSec > 0) {
327 std::thread T(AlarmHandler, Options.UnitTimeoutSec / 2 + 1);
328 T.detach();
329 }
330
331 // Set up interrupt handler if needed.
332 if (Options.HandleInt || Options.HandleTerm) {
333 std::thread T(InterruptHandler);
334 T.detach();
335 }
336
337 // Early exit if no crash handler needed.
338 if (!Options.HandleSegv && !Options.HandleBus && !Options.HandleIll &&
339 !Options.HandleFpe && !Options.HandleAbrt)
340 return;
341
phoseke59ddd22018-07-18 19:20:47 +0000342 // Set up the crash handler and wait until it is ready before proceeding.
343 zx_handle_t Event;
344 ExitOnErr(_zx_event_create(0, &Event), "_zx_event_create");
morehouse400262a2017-12-08 22:54:44 +0000345
phoseke59ddd22018-07-18 19:20:47 +0000346 std::thread T(CrashHandler, &Event);
phosekd2551d62018-08-27 17:51:52 +0000347 zx_status_t Status =
348 _zx_object_wait_one(Event, ZX_USER_SIGNAL_0, ZX_TIME_INFINITE, nullptr);
phoseke59ddd22018-07-18 19:20:47 +0000349 _zx_handle_close(Event);
350 ExitOnErr(Status, "_zx_object_wait_one");
morehouse400262a2017-12-08 22:54:44 +0000351
morehouse400262a2017-12-08 22:54:44 +0000352 T.detach();
353}
354
355void SleepSeconds(int Seconds) {
phosekf9123762018-02-07 08:22:58 +0000356 _zx_nanosleep(_zx_deadline_after(ZX_SEC(Seconds)));
morehouse400262a2017-12-08 22:54:44 +0000357}
358
359unsigned long GetPid() {
360 zx_status_t rc;
361 zx_info_handle_basic_t Info;
phoseke81389f2018-05-26 01:02:34 +0000362 if ((rc = _zx_object_get_info(_zx_process_self(), ZX_INFO_HANDLE_BASIC, &Info,
phoseke59ddd22018-07-18 19:20:47 +0000363 sizeof(Info), NULL, NULL)) != ZX_OK) {
morehouse400262a2017-12-08 22:54:44 +0000364 Printf("libFuzzer: unable to get info about self: %s\n",
phoseke81389f2018-05-26 01:02:34 +0000365 _zx_status_get_string(rc));
morehouse400262a2017-12-08 22:54:44 +0000366 exit(1);
367 }
368 return Info.koid;
369}
370
371size_t GetPeakRSSMb() {
372 zx_status_t rc;
373 zx_info_task_stats_t Info;
phosekf9123762018-02-07 08:22:58 +0000374 if ((rc = _zx_object_get_info(_zx_process_self(), ZX_INFO_TASK_STATS, &Info,
phoseke59ddd22018-07-18 19:20:47 +0000375 sizeof(Info), NULL, NULL)) != ZX_OK) {
morehouse400262a2017-12-08 22:54:44 +0000376 Printf("libFuzzer: unable to get info about self: %s\n",
phosekf9123762018-02-07 08:22:58 +0000377 _zx_status_get_string(rc));
morehouse400262a2017-12-08 22:54:44 +0000378 exit(1);
379 }
380 return (Info.mem_private_bytes + Info.mem_shared_bytes) >> 20;
381}
382
phosekf9123762018-02-07 08:22:58 +0000383template <typename Fn>
384class RunOnDestruction {
385 public:
386 explicit RunOnDestruction(Fn fn) : fn_(fn) {}
387 ~RunOnDestruction() { fn_(); }
388
389 private:
390 Fn fn_;
391};
392
393template <typename Fn>
394RunOnDestruction<Fn> at_scope_exit(Fn fn) {
395 return RunOnDestruction<Fn>(fn);
396}
397
morehouse400262a2017-12-08 22:54:44 +0000398int ExecuteCommand(const Command &Cmd) {
399 zx_status_t rc;
400
401 // Convert arguments to C array
402 auto Args = Cmd.getArguments();
403 size_t Argc = Args.size();
404 assert(Argc != 0);
phosek4b9efd12018-06-02 01:17:10 +0000405 std::unique_ptr<const char *[]> Argv(new const char *[Argc + 1]);
morehouse400262a2017-12-08 22:54:44 +0000406 for (size_t i = 0; i < Argc; ++i)
407 Argv[i] = Args[i].c_str();
phosek4b9efd12018-06-02 01:17:10 +0000408 Argv[Argc] = nullptr;
morehouse400262a2017-12-08 22:54:44 +0000409
phosekca62a262018-10-02 17:21:04 +0000410 // Determine output. On Fuchsia, the fuzzer is typically run as a component
411 // that lacks a mutable working directory. Fortunately, when this is the case
412 // a mutable output directory must be specified using "-artifact_prefix=...",
413 // so write the log file(s) there.
morehouse400262a2017-12-08 22:54:44 +0000414 int FdOut = STDOUT_FILENO;
morehouse400262a2017-12-08 22:54:44 +0000415 if (Cmd.hasOutputFile()) {
phosekca62a262018-10-02 17:21:04 +0000416 std::string Path;
417 if (Cmd.hasFlag("artifact_prefix"))
418 Path = Cmd.getFlagValue("artifact_prefix") + "/" + Cmd.getOutputFile();
419 else
420 Path = Cmd.getOutputFile();
421 FdOut = open(Path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0);
phosekf9123762018-02-07 08:22:58 +0000422 if (FdOut == -1) {
phosekca62a262018-10-02 17:21:04 +0000423 Printf("libFuzzer: failed to open %s: %s\n", Path.c_str(),
morehouse400262a2017-12-08 22:54:44 +0000424 strerror(errno));
425 return ZX_ERR_IO;
426 }
morehouse400262a2017-12-08 22:54:44 +0000427 }
phosekca62a262018-10-02 17:21:04 +0000428 auto CloseFdOut = at_scope_exit([FdOut]() {
429 if (FdOut != STDOUT_FILENO)
430 close(FdOut);
431 });
morehouse400262a2017-12-08 22:54:44 +0000432
433 // Determine stderr
434 int FdErr = STDERR_FILENO;
435 if (Cmd.isOutAndErrCombined())
436 FdErr = FdOut;
437
438 // Clone the file descriptors into the new process
phosek4b9efd12018-06-02 01:17:10 +0000439 fdio_spawn_action_t SpawnAction[] = {
440 {
441 .action = FDIO_SPAWN_ACTION_CLONE_FD,
442 .fd =
443 {
444 .local_fd = STDIN_FILENO,
445 .target_fd = STDIN_FILENO,
446 },
447 },
448 {
449 .action = FDIO_SPAWN_ACTION_CLONE_FD,
450 .fd =
451 {
452 .local_fd = FdOut,
453 .target_fd = STDOUT_FILENO,
454 },
455 },
456 {
457 .action = FDIO_SPAWN_ACTION_CLONE_FD,
458 .fd =
459 {
460 .local_fd = FdErr,
461 .target_fd = STDERR_FILENO,
462 },
463 },
464 };
morehouse400262a2017-12-08 22:54:44 +0000465
phosek4b9efd12018-06-02 01:17:10 +0000466 // Start the process.
467 char ErrorMsg[FDIO_SPAWN_ERR_MSG_MAX_LENGTH];
morehouse400262a2017-12-08 22:54:44 +0000468 zx_handle_t ProcessHandle = ZX_HANDLE_INVALID;
phosek4b9efd12018-06-02 01:17:10 +0000469 rc = fdio_spawn_etc(
470 ZX_HANDLE_INVALID, FDIO_SPAWN_CLONE_ALL & (~FDIO_SPAWN_CLONE_STDIO),
471 Argv[0], Argv.get(), nullptr, 3, SpawnAction, &ProcessHandle, ErrorMsg);
472 if (rc != ZX_OK) {
morehouse400262a2017-12-08 22:54:44 +0000473 Printf("libFuzzer: failed to launch '%s': %s, %s\n", Argv[0], ErrorMsg,
phosekf9123762018-02-07 08:22:58 +0000474 _zx_status_get_string(rc));
morehouse400262a2017-12-08 22:54:44 +0000475 return rc;
476 }
phosekf9123762018-02-07 08:22:58 +0000477 auto CloseHandle = at_scope_exit([&]() { _zx_handle_close(ProcessHandle); });
morehouse400262a2017-12-08 22:54:44 +0000478
479 // Now join the process and return the exit status.
phosekf9123762018-02-07 08:22:58 +0000480 if ((rc = _zx_object_wait_one(ProcessHandle, ZX_PROCESS_TERMINATED,
phosekd2551d62018-08-27 17:51:52 +0000481 ZX_TIME_INFINITE, nullptr)) != ZX_OK) {
morehouse400262a2017-12-08 22:54:44 +0000482 Printf("libFuzzer: failed to join '%s': %s\n", Argv[0],
phosekf9123762018-02-07 08:22:58 +0000483 _zx_status_get_string(rc));
morehouse400262a2017-12-08 22:54:44 +0000484 return rc;
485 }
486
487 zx_info_process_t Info;
phosekf9123762018-02-07 08:22:58 +0000488 if ((rc = _zx_object_get_info(ProcessHandle, ZX_INFO_PROCESS, &Info,
489 sizeof(Info), nullptr, nullptr)) != ZX_OK) {
morehouse400262a2017-12-08 22:54:44 +0000490 Printf("libFuzzer: unable to get return code from '%s': %s\n", Argv[0],
phoseke81389f2018-05-26 01:02:34 +0000491 _zx_status_get_string(rc));
morehouse400262a2017-12-08 22:54:44 +0000492 return rc;
493 }
494
495 return Info.return_code;
496}
497
498const void *SearchMemory(const void *Data, size_t DataLen, const void *Patt,
499 size_t PattLen) {
500 return memmem(Data, DataLen, Patt, PattLen);
501}
502
503} // namespace fuzzer
504
505#endif // LIBFUZZER_FUCHSIA