xref: /openbsd-src/gnu/llvm/compiler-rt/lib/fuzzer/FuzzerUtilFuchsia.cpp (revision 810390e339a5425391477d5d41c78d7cab2424ac)
13cab2bb3Spatrick //===- FuzzerUtilFuchsia.cpp - Misc utils for Fuchsia. --------------------===//
23cab2bb3Spatrick //
33cab2bb3Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
43cab2bb3Spatrick // See https://llvm.org/LICENSE.txt for license information.
53cab2bb3Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
63cab2bb3Spatrick //
73cab2bb3Spatrick //===----------------------------------------------------------------------===//
83cab2bb3Spatrick // Misc utils implementation using Fuchsia/Zircon APIs.
93cab2bb3Spatrick //===----------------------------------------------------------------------===//
101f9cb04fSpatrick #include "FuzzerPlatform.h"
113cab2bb3Spatrick 
123cab2bb3Spatrick #if LIBFUZZER_FUCHSIA
133cab2bb3Spatrick 
143cab2bb3Spatrick #include "FuzzerInternal.h"
153cab2bb3Spatrick #include "FuzzerUtil.h"
163cab2bb3Spatrick #include <cassert>
173cab2bb3Spatrick #include <cerrno>
183cab2bb3Spatrick #include <cinttypes>
193cab2bb3Spatrick #include <cstdint>
203cab2bb3Spatrick #include <fcntl.h>
213cab2bb3Spatrick #include <lib/fdio/fdio.h>
223cab2bb3Spatrick #include <lib/fdio/spawn.h>
233cab2bb3Spatrick #include <string>
243cab2bb3Spatrick #include <sys/select.h>
253cab2bb3Spatrick #include <thread>
263cab2bb3Spatrick #include <unistd.h>
273cab2bb3Spatrick #include <zircon/errors.h>
283cab2bb3Spatrick #include <zircon/process.h>
293cab2bb3Spatrick #include <zircon/sanitizer.h>
303cab2bb3Spatrick #include <zircon/status.h>
313cab2bb3Spatrick #include <zircon/syscalls.h>
323cab2bb3Spatrick #include <zircon/syscalls/debug.h>
333cab2bb3Spatrick #include <zircon/syscalls/exception.h>
343cab2bb3Spatrick #include <zircon/syscalls/object.h>
353cab2bb3Spatrick #include <zircon/types.h>
363cab2bb3Spatrick 
371f9cb04fSpatrick #include <vector>
381f9cb04fSpatrick 
393cab2bb3Spatrick namespace fuzzer {
403cab2bb3Spatrick 
413cab2bb3Spatrick // Given that Fuchsia doesn't have the POSIX signals that libFuzzer was written
423cab2bb3Spatrick // around, the general approach is to spin up dedicated threads to watch for
433cab2bb3Spatrick // each requested condition (alarm, interrupt, crash).  Of these, the crash
443cab2bb3Spatrick // handler is the most involved, as it requires resuming the crashed thread in
453cab2bb3Spatrick // order to invoke the sanitizers to get the needed state.
463cab2bb3Spatrick 
473cab2bb3Spatrick // Forward declaration of assembly trampoline needed to resume crashed threads.
483cab2bb3Spatrick // This appears to have external linkage to  C++, which is why it's not in the
493cab2bb3Spatrick // anonymous namespace.  The assembly definition inside MakeTrampoline()
503cab2bb3Spatrick // actually defines the symbol with internal linkage only.
513cab2bb3Spatrick void CrashTrampolineAsm() __asm__("CrashTrampolineAsm");
523cab2bb3Spatrick 
533cab2bb3Spatrick namespace {
543cab2bb3Spatrick 
55*810390e3Srobert // The signal handler thread uses Zircon exceptions to resume crashed threads
56*810390e3Srobert // into libFuzzer's POSIX signal handlers. The associated event is used to
57*810390e3Srobert // signal when the thread is running, and when it should stop.
58*810390e3Srobert std::thread SignalHandler;
59*810390e3Srobert zx_handle_t SignalHandlerEvent = ZX_HANDLE_INVALID;
60*810390e3Srobert 
613cab2bb3Spatrick // Helper function to handle Zircon syscall failures.
ExitOnErr(zx_status_t Status,const char * Syscall)623cab2bb3Spatrick void ExitOnErr(zx_status_t Status, const char *Syscall) {
633cab2bb3Spatrick   if (Status != ZX_OK) {
643cab2bb3Spatrick     Printf("libFuzzer: %s failed: %s\n", Syscall,
653cab2bb3Spatrick            _zx_status_get_string(Status));
663cab2bb3Spatrick     exit(1);
673cab2bb3Spatrick   }
683cab2bb3Spatrick }
693cab2bb3Spatrick 
AlarmHandler(int Seconds)703cab2bb3Spatrick void AlarmHandler(int Seconds) {
713cab2bb3Spatrick   while (true) {
723cab2bb3Spatrick     SleepSeconds(Seconds);
733cab2bb3Spatrick     Fuzzer::StaticAlarmCallback();
743cab2bb3Spatrick   }
753cab2bb3Spatrick }
763cab2bb3Spatrick 
773cab2bb3Spatrick // For the crash handler, we need to call Fuzzer::StaticCrashSignalCallback
783cab2bb3Spatrick // without POSIX signal handlers.  To achieve this, we use an assembly function
793cab2bb3Spatrick // to add the necessary CFI unwinding information and a C function to bridge
803cab2bb3Spatrick // from that back into C++.
813cab2bb3Spatrick 
823cab2bb3Spatrick // FIXME: This works as a short-term solution, but this code really shouldn't be
833cab2bb3Spatrick // architecture dependent. A better long term solution is to implement remote
843cab2bb3Spatrick // unwinding and expose the necessary APIs through sanitizer_common and/or ASAN
853cab2bb3Spatrick // to allow the exception handling thread to gather the crash state directly.
863cab2bb3Spatrick //
873cab2bb3Spatrick // Alternatively, Fuchsia may in future actually implement basic signal
883cab2bb3Spatrick // handling for the machine trap signals.
893cab2bb3Spatrick #if defined(__x86_64__)
903cab2bb3Spatrick #define FOREACH_REGISTER(OP_REG, OP_NUM) \
913cab2bb3Spatrick   OP_REG(rax)                            \
923cab2bb3Spatrick   OP_REG(rbx)                            \
933cab2bb3Spatrick   OP_REG(rcx)                            \
943cab2bb3Spatrick   OP_REG(rdx)                            \
953cab2bb3Spatrick   OP_REG(rsi)                            \
963cab2bb3Spatrick   OP_REG(rdi)                            \
973cab2bb3Spatrick   OP_REG(rbp)                            \
983cab2bb3Spatrick   OP_REG(rsp)                            \
993cab2bb3Spatrick   OP_REG(r8)                             \
1003cab2bb3Spatrick   OP_REG(r9)                             \
1013cab2bb3Spatrick   OP_REG(r10)                            \
1023cab2bb3Spatrick   OP_REG(r11)                            \
1033cab2bb3Spatrick   OP_REG(r12)                            \
1043cab2bb3Spatrick   OP_REG(r13)                            \
1053cab2bb3Spatrick   OP_REG(r14)                            \
1063cab2bb3Spatrick   OP_REG(r15)                            \
1073cab2bb3Spatrick   OP_REG(rip)
1083cab2bb3Spatrick 
1093cab2bb3Spatrick #elif defined(__aarch64__)
1103cab2bb3Spatrick #define FOREACH_REGISTER(OP_REG, OP_NUM) \
1113cab2bb3Spatrick   OP_NUM(0)                              \
1123cab2bb3Spatrick   OP_NUM(1)                              \
1133cab2bb3Spatrick   OP_NUM(2)                              \
1143cab2bb3Spatrick   OP_NUM(3)                              \
1153cab2bb3Spatrick   OP_NUM(4)                              \
1163cab2bb3Spatrick   OP_NUM(5)                              \
1173cab2bb3Spatrick   OP_NUM(6)                              \
1183cab2bb3Spatrick   OP_NUM(7)                              \
1193cab2bb3Spatrick   OP_NUM(8)                              \
1203cab2bb3Spatrick   OP_NUM(9)                              \
1213cab2bb3Spatrick   OP_NUM(10)                             \
1223cab2bb3Spatrick   OP_NUM(11)                             \
1233cab2bb3Spatrick   OP_NUM(12)                             \
1243cab2bb3Spatrick   OP_NUM(13)                             \
1253cab2bb3Spatrick   OP_NUM(14)                             \
1263cab2bb3Spatrick   OP_NUM(15)                             \
1273cab2bb3Spatrick   OP_NUM(16)                             \
1283cab2bb3Spatrick   OP_NUM(17)                             \
1293cab2bb3Spatrick   OP_NUM(18)                             \
1303cab2bb3Spatrick   OP_NUM(19)                             \
1313cab2bb3Spatrick   OP_NUM(20)                             \
1323cab2bb3Spatrick   OP_NUM(21)                             \
1333cab2bb3Spatrick   OP_NUM(22)                             \
1343cab2bb3Spatrick   OP_NUM(23)                             \
1353cab2bb3Spatrick   OP_NUM(24)                             \
1363cab2bb3Spatrick   OP_NUM(25)                             \
1373cab2bb3Spatrick   OP_NUM(26)                             \
1383cab2bb3Spatrick   OP_NUM(27)                             \
1393cab2bb3Spatrick   OP_NUM(28)                             \
1403cab2bb3Spatrick   OP_NUM(29)                             \
1413cab2bb3Spatrick   OP_REG(sp)
1423cab2bb3Spatrick 
1433cab2bb3Spatrick #else
1443cab2bb3Spatrick #error "Unsupported architecture for fuzzing on Fuchsia"
1453cab2bb3Spatrick #endif
1463cab2bb3Spatrick 
1473cab2bb3Spatrick // Produces a CFI directive for the named or numbered register.
1483cab2bb3Spatrick // The value used refers to an assembler immediate operand with the same name
1493cab2bb3Spatrick // as the register (see ASM_OPERAND_REG).
1503cab2bb3Spatrick #define CFI_OFFSET_REG(reg) ".cfi_offset " #reg ", %c[" #reg "]\n"
1513cab2bb3Spatrick #define CFI_OFFSET_NUM(num) CFI_OFFSET_REG(x##num)
1523cab2bb3Spatrick 
1533cab2bb3Spatrick // Produces an assembler immediate operand for the named or numbered register.
1543cab2bb3Spatrick // This operand contains the offset of the register relative to the CFA.
1553cab2bb3Spatrick #define ASM_OPERAND_REG(reg)                                                   \
156*810390e3Srobert   [reg] "i"(offsetof(zx_thread_state_general_regs_t, reg)),
1573cab2bb3Spatrick #define ASM_OPERAND_NUM(num)                                                   \
158*810390e3Srobert   [x##num] "i"(offsetof(zx_thread_state_general_regs_t, r[num])),
1593cab2bb3Spatrick 
1603cab2bb3Spatrick // Trampoline to bridge from the assembly below to the static C++ crash
1613cab2bb3Spatrick // callback.
1623cab2bb3Spatrick __attribute__((noreturn))
StaticCrashHandler()1633cab2bb3Spatrick static void StaticCrashHandler() {
1643cab2bb3Spatrick   Fuzzer::StaticCrashSignalCallback();
1653cab2bb3Spatrick   for (;;) {
1663cab2bb3Spatrick     _Exit(1);
1673cab2bb3Spatrick   }
1683cab2bb3Spatrick }
1693cab2bb3Spatrick 
170*810390e3Srobert // This trampoline function has the necessary CFI information to unwind
171*810390e3Srobert // and get a backtrace:
172*810390e3Srobert //  * The stack contains a copy of all the registers at the point of crash,
173*810390e3Srobert //    the code has CFI directives specifying how to restore them.
174*810390e3Srobert //  * A call to StaticCrashHandler, which will print the stacktrace and exit
175*810390e3Srobert //    the fuzzer, generating a crash artifact.
1763cab2bb3Spatrick //
1773cab2bb3Spatrick // The __attribute__((used)) is necessary because the function
1783cab2bb3Spatrick // is never called; it's just a container around the assembly to allow it to
1793cab2bb3Spatrick // use operands for compile-time computed constants.
1803cab2bb3Spatrick __attribute__((used))
MakeTrampoline()1813cab2bb3Spatrick void MakeTrampoline() {
182*810390e3Srobert   __asm__(
183*810390e3Srobert       ".cfi_endproc\n"
1843cab2bb3Spatrick       ".pushsection .text.CrashTrampolineAsm\n"
1853cab2bb3Spatrick       ".type CrashTrampolineAsm,STT_FUNC\n"
1863cab2bb3Spatrick       "CrashTrampolineAsm:\n"
1873cab2bb3Spatrick       ".cfi_startproc simple\n"
1883cab2bb3Spatrick       ".cfi_signal_frame\n"
1893cab2bb3Spatrick #if defined(__x86_64__)
1903cab2bb3Spatrick       ".cfi_return_column rip\n"
191*810390e3Srobert       ".cfi_def_cfa rsp, 0\n"
1923cab2bb3Spatrick       FOREACH_REGISTER(CFI_OFFSET_REG, CFI_OFFSET_NUM)
1933cab2bb3Spatrick       "call %c[StaticCrashHandler]\n"
1943cab2bb3Spatrick       "ud2\n"
1953cab2bb3Spatrick #elif defined(__aarch64__)
1963cab2bb3Spatrick       ".cfi_return_column 33\n"
197*810390e3Srobert       ".cfi_def_cfa sp, 0\n"
1983cab2bb3Spatrick       FOREACH_REGISTER(CFI_OFFSET_REG, CFI_OFFSET_NUM)
1993cab2bb3Spatrick       ".cfi_offset 33, %c[pc]\n"
2003cab2bb3Spatrick       ".cfi_offset 30, %c[lr]\n"
2013cab2bb3Spatrick       "bl %c[StaticCrashHandler]\n"
2023cab2bb3Spatrick       "brk 1\n"
2033cab2bb3Spatrick #else
2043cab2bb3Spatrick #error "Unsupported architecture for fuzzing on Fuchsia"
2053cab2bb3Spatrick #endif
2063cab2bb3Spatrick      ".cfi_endproc\n"
2073cab2bb3Spatrick      ".size CrashTrampolineAsm, . - CrashTrampolineAsm\n"
2083cab2bb3Spatrick      ".popsection\n"
2093cab2bb3Spatrick      ".cfi_startproc\n"
2103cab2bb3Spatrick       : // No outputs
2113cab2bb3Spatrick       : FOREACH_REGISTER(ASM_OPERAND_REG, ASM_OPERAND_NUM)
2123cab2bb3Spatrick #if defined(__aarch64__)
213*810390e3Srobert         ASM_OPERAND_REG(pc) ASM_OPERAND_REG(lr)
2143cab2bb3Spatrick #endif
215*810390e3Srobert         [StaticCrashHandler] "i"(StaticCrashHandler));
2163cab2bb3Spatrick }
2173cab2bb3Spatrick 
CrashHandler()218*810390e3Srobert void CrashHandler() {
219*810390e3Srobert   assert(SignalHandlerEvent != ZX_HANDLE_INVALID);
220*810390e3Srobert 
2213cab2bb3Spatrick   // This structure is used to ensure we close handles to objects we create in
2223cab2bb3Spatrick   // this handler.
2233cab2bb3Spatrick   struct ScopedHandle {
2243cab2bb3Spatrick     ~ScopedHandle() { _zx_handle_close(Handle); }
2253cab2bb3Spatrick     zx_handle_t Handle = ZX_HANDLE_INVALID;
2263cab2bb3Spatrick   };
2273cab2bb3Spatrick 
2283cab2bb3Spatrick   // Create the exception channel.  We need to claim to be a "debugger" so the
2293cab2bb3Spatrick   // kernel will allow us to modify and resume dying threads (see below). Once
2303cab2bb3Spatrick   // the channel is set, we can signal the main thread to continue and wait
2313cab2bb3Spatrick   // for the exception to arrive.
2323cab2bb3Spatrick   ScopedHandle Channel;
2333cab2bb3Spatrick   zx_handle_t Self = _zx_process_self();
2343cab2bb3Spatrick   ExitOnErr(_zx_task_create_exception_channel(
2353cab2bb3Spatrick                 Self, ZX_EXCEPTION_CHANNEL_DEBUGGER, &Channel.Handle),
2363cab2bb3Spatrick             "_zx_task_create_exception_channel");
2373cab2bb3Spatrick 
238*810390e3Srobert   ExitOnErr(_zx_object_signal(SignalHandlerEvent, 0, ZX_USER_SIGNAL_0),
2393cab2bb3Spatrick             "_zx_object_signal");
2403cab2bb3Spatrick 
2413cab2bb3Spatrick   // This thread lives as long as the process in order to keep handling
2423cab2bb3Spatrick   // crashes.  In practice, the first crashed thread to reach the end of the
2433cab2bb3Spatrick   // StaticCrashHandler will end the process.
2443cab2bb3Spatrick   while (true) {
245*810390e3Srobert     zx_wait_item_t WaitItems[] = {
246*810390e3Srobert         {
247*810390e3Srobert             .handle = SignalHandlerEvent,
248*810390e3Srobert             .waitfor = ZX_SIGNAL_HANDLE_CLOSED,
249*810390e3Srobert             .pending = 0,
250*810390e3Srobert         },
251*810390e3Srobert         {
252*810390e3Srobert             .handle = Channel.Handle,
253*810390e3Srobert             .waitfor = ZX_CHANNEL_READABLE | ZX_CHANNEL_PEER_CLOSED,
254*810390e3Srobert             .pending = 0,
255*810390e3Srobert         },
256*810390e3Srobert     };
257*810390e3Srobert     auto Status = _zx_object_wait_many(
258*810390e3Srobert         WaitItems, sizeof(WaitItems) / sizeof(WaitItems[0]), ZX_TIME_INFINITE);
259*810390e3Srobert     if (Status != ZX_OK || (WaitItems[1].pending & ZX_CHANNEL_READABLE) == 0) {
260*810390e3Srobert       break;
261*810390e3Srobert     }
2623cab2bb3Spatrick 
2633cab2bb3Spatrick     zx_exception_info_t ExceptionInfo;
2643cab2bb3Spatrick     ScopedHandle Exception;
2653cab2bb3Spatrick     ExitOnErr(_zx_channel_read(Channel.Handle, 0, &ExceptionInfo,
2663cab2bb3Spatrick                                &Exception.Handle, sizeof(ExceptionInfo), 1,
2673cab2bb3Spatrick                                nullptr, nullptr),
2683cab2bb3Spatrick               "_zx_channel_read");
2693cab2bb3Spatrick 
2703cab2bb3Spatrick     // Ignore informational synthetic exceptions.
2713cab2bb3Spatrick     if (ZX_EXCP_THREAD_STARTING == ExceptionInfo.type ||
2723cab2bb3Spatrick         ZX_EXCP_THREAD_EXITING == ExceptionInfo.type ||
2733cab2bb3Spatrick         ZX_EXCP_PROCESS_STARTING == ExceptionInfo.type) {
2743cab2bb3Spatrick       continue;
2753cab2bb3Spatrick     }
2763cab2bb3Spatrick 
2773cab2bb3Spatrick     // At this point, we want to get the state of the crashing thread, but
2783cab2bb3Spatrick     // libFuzzer and the sanitizers assume this will happen from that same
2793cab2bb3Spatrick     // thread via a POSIX signal handler. "Resurrecting" the thread in the
2803cab2bb3Spatrick     // middle of the appropriate callback is as simple as forcibly setting the
2813cab2bb3Spatrick     // instruction pointer/program counter, provided we NEVER EVER return from
2823cab2bb3Spatrick     // that function (since otherwise our stack will not be valid).
2833cab2bb3Spatrick     ScopedHandle Thread;
2843cab2bb3Spatrick     ExitOnErr(_zx_exception_get_thread(Exception.Handle, &Thread.Handle),
2853cab2bb3Spatrick               "_zx_exception_get_thread");
2863cab2bb3Spatrick 
2873cab2bb3Spatrick     zx_thread_state_general_regs_t GeneralRegisters;
2883cab2bb3Spatrick     ExitOnErr(_zx_thread_read_state(Thread.Handle, ZX_THREAD_STATE_GENERAL_REGS,
2893cab2bb3Spatrick                                     &GeneralRegisters,
2903cab2bb3Spatrick                                     sizeof(GeneralRegisters)),
2913cab2bb3Spatrick               "_zx_thread_read_state");
2923cab2bb3Spatrick 
2933cab2bb3Spatrick     // To unwind properly, we need to push the crashing thread's register state
2943cab2bb3Spatrick     // onto the stack and jump into a trampoline with CFI instructions on how
2953cab2bb3Spatrick     // to restore it.
2963cab2bb3Spatrick #if defined(__x86_64__)
297*810390e3Srobert     uintptr_t StackPtr =
298*810390e3Srobert         (GeneralRegisters.rsp - (128 + sizeof(GeneralRegisters))) &
299*810390e3Srobert         -(uintptr_t)16;
3003cab2bb3Spatrick     __unsanitized_memcpy(reinterpret_cast<void *>(StackPtr), &GeneralRegisters,
3013cab2bb3Spatrick                          sizeof(GeneralRegisters));
3023cab2bb3Spatrick     GeneralRegisters.rsp = StackPtr;
3033cab2bb3Spatrick     GeneralRegisters.rip = reinterpret_cast<zx_vaddr_t>(CrashTrampolineAsm);
3043cab2bb3Spatrick 
3053cab2bb3Spatrick #elif defined(__aarch64__)
306*810390e3Srobert     uintptr_t StackPtr =
307*810390e3Srobert         (GeneralRegisters.sp - sizeof(GeneralRegisters)) & -(uintptr_t)16;
3083cab2bb3Spatrick     __unsanitized_memcpy(reinterpret_cast<void *>(StackPtr), &GeneralRegisters,
3093cab2bb3Spatrick                          sizeof(GeneralRegisters));
3103cab2bb3Spatrick     GeneralRegisters.sp = StackPtr;
3113cab2bb3Spatrick     GeneralRegisters.pc = reinterpret_cast<zx_vaddr_t>(CrashTrampolineAsm);
3123cab2bb3Spatrick 
3133cab2bb3Spatrick #else
3143cab2bb3Spatrick #error "Unsupported architecture for fuzzing on Fuchsia"
3153cab2bb3Spatrick #endif
3163cab2bb3Spatrick 
3173cab2bb3Spatrick     // Now force the crashing thread's state.
3183cab2bb3Spatrick     ExitOnErr(
3193cab2bb3Spatrick         _zx_thread_write_state(Thread.Handle, ZX_THREAD_STATE_GENERAL_REGS,
3203cab2bb3Spatrick                                &GeneralRegisters, sizeof(GeneralRegisters)),
3213cab2bb3Spatrick         "_zx_thread_write_state");
3223cab2bb3Spatrick 
3233cab2bb3Spatrick     // Set the exception to HANDLED so it resumes the thread on close.
3243cab2bb3Spatrick     uint32_t ExceptionState = ZX_EXCEPTION_STATE_HANDLED;
3253cab2bb3Spatrick     ExitOnErr(_zx_object_set_property(Exception.Handle, ZX_PROP_EXCEPTION_STATE,
3263cab2bb3Spatrick                                       &ExceptionState, sizeof(ExceptionState)),
3273cab2bb3Spatrick               "zx_object_set_property");
3283cab2bb3Spatrick   }
3293cab2bb3Spatrick }
3303cab2bb3Spatrick 
StopSignalHandler()331*810390e3Srobert void StopSignalHandler() {
332*810390e3Srobert   _zx_handle_close(SignalHandlerEvent);
333*810390e3Srobert   if (SignalHandler.joinable()) {
334*810390e3Srobert     SignalHandler.join();
335*810390e3Srobert   }
336*810390e3Srobert }
337*810390e3Srobert 
3383cab2bb3Spatrick } // namespace
3393cab2bb3Spatrick 
3403cab2bb3Spatrick // Platform specific functions.
SetSignalHandler(const FuzzingOptions & Options)3413cab2bb3Spatrick void SetSignalHandler(const FuzzingOptions &Options) {
3423cab2bb3Spatrick   // Make sure information from libFuzzer and the sanitizers are easy to
3433cab2bb3Spatrick   // reassemble. `__sanitizer_log_write` has the added benefit of ensuring the
3443cab2bb3Spatrick   // DSO map is always available for the symbolizer.
3453cab2bb3Spatrick   // A uint64_t fits in 20 chars, so 64 is plenty.
3463cab2bb3Spatrick   char Buf[64];
3473cab2bb3Spatrick   memset(Buf, 0, sizeof(Buf));
3483cab2bb3Spatrick   snprintf(Buf, sizeof(Buf), "==%lu== INFO: libFuzzer starting.\n", GetPid());
3493cab2bb3Spatrick   if (EF->__sanitizer_log_write)
3503cab2bb3Spatrick     __sanitizer_log_write(Buf, sizeof(Buf));
3513cab2bb3Spatrick   Printf("%s", Buf);
3523cab2bb3Spatrick 
3533cab2bb3Spatrick   // Set up alarm handler if needed.
354d89ec533Spatrick   if (Options.HandleAlrm && Options.UnitTimeoutSec > 0) {
3553cab2bb3Spatrick     std::thread T(AlarmHandler, Options.UnitTimeoutSec / 2 + 1);
3563cab2bb3Spatrick     T.detach();
3573cab2bb3Spatrick   }
3583cab2bb3Spatrick 
359d89ec533Spatrick   // Options.HandleInt and Options.HandleTerm are not supported on Fuchsia
3603cab2bb3Spatrick 
3613cab2bb3Spatrick   // Early exit if no crash handler needed.
3623cab2bb3Spatrick   if (!Options.HandleSegv && !Options.HandleBus && !Options.HandleIll &&
3633cab2bb3Spatrick       !Options.HandleFpe && !Options.HandleAbrt)
3643cab2bb3Spatrick     return;
3653cab2bb3Spatrick 
3663cab2bb3Spatrick   // Set up the crash handler and wait until it is ready before proceeding.
367*810390e3Srobert   ExitOnErr(_zx_event_create(0, &SignalHandlerEvent), "_zx_event_create");
3683cab2bb3Spatrick 
369*810390e3Srobert   SignalHandler = std::thread(CrashHandler);
370*810390e3Srobert   zx_status_t Status = _zx_object_wait_one(SignalHandlerEvent, ZX_USER_SIGNAL_0,
371*810390e3Srobert                                            ZX_TIME_INFINITE, nullptr);
3723cab2bb3Spatrick   ExitOnErr(Status, "_zx_object_wait_one");
3733cab2bb3Spatrick 
374*810390e3Srobert   std::atexit(StopSignalHandler);
3753cab2bb3Spatrick }
3763cab2bb3Spatrick 
SleepSeconds(int Seconds)3773cab2bb3Spatrick void SleepSeconds(int Seconds) {
3783cab2bb3Spatrick   _zx_nanosleep(_zx_deadline_after(ZX_SEC(Seconds)));
3793cab2bb3Spatrick }
3803cab2bb3Spatrick 
GetPid()3813cab2bb3Spatrick unsigned long GetPid() {
3823cab2bb3Spatrick   zx_status_t rc;
3833cab2bb3Spatrick   zx_info_handle_basic_t Info;
3843cab2bb3Spatrick   if ((rc = _zx_object_get_info(_zx_process_self(), ZX_INFO_HANDLE_BASIC, &Info,
3853cab2bb3Spatrick                                 sizeof(Info), NULL, NULL)) != ZX_OK) {
3863cab2bb3Spatrick     Printf("libFuzzer: unable to get info about self: %s\n",
3873cab2bb3Spatrick            _zx_status_get_string(rc));
3883cab2bb3Spatrick     exit(1);
3893cab2bb3Spatrick   }
3903cab2bb3Spatrick   return Info.koid;
3913cab2bb3Spatrick }
3923cab2bb3Spatrick 
GetPeakRSSMb()3933cab2bb3Spatrick size_t GetPeakRSSMb() {
3943cab2bb3Spatrick   zx_status_t rc;
3953cab2bb3Spatrick   zx_info_task_stats_t Info;
3963cab2bb3Spatrick   if ((rc = _zx_object_get_info(_zx_process_self(), ZX_INFO_TASK_STATS, &Info,
3973cab2bb3Spatrick                                 sizeof(Info), NULL, NULL)) != ZX_OK) {
3983cab2bb3Spatrick     Printf("libFuzzer: unable to get info about self: %s\n",
3993cab2bb3Spatrick            _zx_status_get_string(rc));
4003cab2bb3Spatrick     exit(1);
4013cab2bb3Spatrick   }
4023cab2bb3Spatrick   return (Info.mem_private_bytes + Info.mem_shared_bytes) >> 20;
4033cab2bb3Spatrick }
4043cab2bb3Spatrick 
4053cab2bb3Spatrick template <typename Fn>
4063cab2bb3Spatrick class RunOnDestruction {
4073cab2bb3Spatrick  public:
RunOnDestruction(Fn fn)4083cab2bb3Spatrick   explicit RunOnDestruction(Fn fn) : fn_(fn) {}
~RunOnDestruction()4093cab2bb3Spatrick   ~RunOnDestruction() { fn_(); }
4103cab2bb3Spatrick 
4113cab2bb3Spatrick  private:
4123cab2bb3Spatrick   Fn fn_;
4133cab2bb3Spatrick };
4143cab2bb3Spatrick 
4153cab2bb3Spatrick template <typename Fn>
at_scope_exit(Fn fn)4163cab2bb3Spatrick RunOnDestruction<Fn> at_scope_exit(Fn fn) {
4173cab2bb3Spatrick   return RunOnDestruction<Fn>(fn);
4183cab2bb3Spatrick }
4193cab2bb3Spatrick 
clone_fd_action(int localFd,int targetFd)4201f9cb04fSpatrick static fdio_spawn_action_t clone_fd_action(int localFd, int targetFd) {
4211f9cb04fSpatrick   return {
4221f9cb04fSpatrick       .action = FDIO_SPAWN_ACTION_CLONE_FD,
4231f9cb04fSpatrick       .fd =
4241f9cb04fSpatrick           {
4251f9cb04fSpatrick               .local_fd = localFd,
4261f9cb04fSpatrick               .target_fd = targetFd,
4271f9cb04fSpatrick           },
4281f9cb04fSpatrick   };
4291f9cb04fSpatrick }
4301f9cb04fSpatrick 
ExecuteCommand(const Command & Cmd)4313cab2bb3Spatrick int ExecuteCommand(const Command &Cmd) {
4323cab2bb3Spatrick   zx_status_t rc;
4333cab2bb3Spatrick 
4343cab2bb3Spatrick   // Convert arguments to C array
4353cab2bb3Spatrick   auto Args = Cmd.getArguments();
4363cab2bb3Spatrick   size_t Argc = Args.size();
4373cab2bb3Spatrick   assert(Argc != 0);
4383cab2bb3Spatrick   std::unique_ptr<const char *[]> Argv(new const char *[Argc + 1]);
4393cab2bb3Spatrick   for (size_t i = 0; i < Argc; ++i)
4403cab2bb3Spatrick     Argv[i] = Args[i].c_str();
4413cab2bb3Spatrick   Argv[Argc] = nullptr;
4423cab2bb3Spatrick 
4433cab2bb3Spatrick   // Determine output.  On Fuchsia, the fuzzer is typically run as a component
4443cab2bb3Spatrick   // that lacks a mutable working directory. Fortunately, when this is the case
4453cab2bb3Spatrick   // a mutable output directory must be specified using "-artifact_prefix=...",
4463cab2bb3Spatrick   // so write the log file(s) there.
4473cab2bb3Spatrick   // However, we don't want to apply this logic for absolute paths.
4483cab2bb3Spatrick   int FdOut = STDOUT_FILENO;
4491f9cb04fSpatrick   bool discardStdout = false;
4501f9cb04fSpatrick   bool discardStderr = false;
4511f9cb04fSpatrick 
4523cab2bb3Spatrick   if (Cmd.hasOutputFile()) {
4533cab2bb3Spatrick     std::string Path = Cmd.getOutputFile();
4541f9cb04fSpatrick     if (Path == getDevNull()) {
4551f9cb04fSpatrick       // On Fuchsia, there's no "/dev/null" like-file, so we
4561f9cb04fSpatrick       // just don't copy the FDs into the spawned process.
4571f9cb04fSpatrick       discardStdout = true;
4581f9cb04fSpatrick     } else {
4593cab2bb3Spatrick       bool IsAbsolutePath = Path.length() > 1 && Path[0] == '/';
4603cab2bb3Spatrick       if (!IsAbsolutePath && Cmd.hasFlag("artifact_prefix"))
4613cab2bb3Spatrick         Path = Cmd.getFlagValue("artifact_prefix") + "/" + Path;
4623cab2bb3Spatrick 
4633cab2bb3Spatrick       FdOut = open(Path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0);
4643cab2bb3Spatrick       if (FdOut == -1) {
4653cab2bb3Spatrick         Printf("libFuzzer: failed to open %s: %s\n", Path.c_str(),
4663cab2bb3Spatrick                strerror(errno));
4673cab2bb3Spatrick         return ZX_ERR_IO;
4683cab2bb3Spatrick       }
4693cab2bb3Spatrick     }
4701f9cb04fSpatrick   }
4713cab2bb3Spatrick   auto CloseFdOut = at_scope_exit([FdOut]() {
4723cab2bb3Spatrick     if (FdOut != STDOUT_FILENO)
4733cab2bb3Spatrick       close(FdOut);
4743cab2bb3Spatrick   });
4753cab2bb3Spatrick 
4763cab2bb3Spatrick   // Determine stderr
4773cab2bb3Spatrick   int FdErr = STDERR_FILENO;
4781f9cb04fSpatrick   if (Cmd.isOutAndErrCombined()) {
4793cab2bb3Spatrick     FdErr = FdOut;
4801f9cb04fSpatrick     if (discardStdout)
4811f9cb04fSpatrick       discardStderr = true;
4821f9cb04fSpatrick   }
4833cab2bb3Spatrick 
4843cab2bb3Spatrick   // Clone the file descriptors into the new process
4851f9cb04fSpatrick   std::vector<fdio_spawn_action_t> SpawnActions;
4861f9cb04fSpatrick   SpawnActions.push_back(clone_fd_action(STDIN_FILENO, STDIN_FILENO));
4871f9cb04fSpatrick 
4881f9cb04fSpatrick   if (!discardStdout)
4891f9cb04fSpatrick     SpawnActions.push_back(clone_fd_action(FdOut, STDOUT_FILENO));
4901f9cb04fSpatrick   if (!discardStderr)
4911f9cb04fSpatrick     SpawnActions.push_back(clone_fd_action(FdErr, STDERR_FILENO));
4923cab2bb3Spatrick 
4933cab2bb3Spatrick   // Start the process.
4943cab2bb3Spatrick   char ErrorMsg[FDIO_SPAWN_ERR_MSG_MAX_LENGTH];
4953cab2bb3Spatrick   zx_handle_t ProcessHandle = ZX_HANDLE_INVALID;
4961f9cb04fSpatrick   rc = fdio_spawn_etc(ZX_HANDLE_INVALID,
4971f9cb04fSpatrick                       FDIO_SPAWN_CLONE_ALL & (~FDIO_SPAWN_CLONE_STDIO), Argv[0],
4981f9cb04fSpatrick                       Argv.get(), nullptr, SpawnActions.size(),
4991f9cb04fSpatrick                       SpawnActions.data(), &ProcessHandle, ErrorMsg);
5001f9cb04fSpatrick 
5013cab2bb3Spatrick   if (rc != ZX_OK) {
5023cab2bb3Spatrick     Printf("libFuzzer: failed to launch '%s': %s, %s\n", Argv[0], ErrorMsg,
5033cab2bb3Spatrick            _zx_status_get_string(rc));
5043cab2bb3Spatrick     return rc;
5053cab2bb3Spatrick   }
5063cab2bb3Spatrick   auto CloseHandle = at_scope_exit([&]() { _zx_handle_close(ProcessHandle); });
5073cab2bb3Spatrick 
5083cab2bb3Spatrick   // Now join the process and return the exit status.
5093cab2bb3Spatrick   if ((rc = _zx_object_wait_one(ProcessHandle, ZX_PROCESS_TERMINATED,
5103cab2bb3Spatrick                                 ZX_TIME_INFINITE, nullptr)) != ZX_OK) {
5113cab2bb3Spatrick     Printf("libFuzzer: failed to join '%s': %s\n", Argv[0],
5123cab2bb3Spatrick            _zx_status_get_string(rc));
5133cab2bb3Spatrick     return rc;
5143cab2bb3Spatrick   }
5153cab2bb3Spatrick 
5163cab2bb3Spatrick   zx_info_process_t Info;
5173cab2bb3Spatrick   if ((rc = _zx_object_get_info(ProcessHandle, ZX_INFO_PROCESS, &Info,
5183cab2bb3Spatrick                                 sizeof(Info), nullptr, nullptr)) != ZX_OK) {
5193cab2bb3Spatrick     Printf("libFuzzer: unable to get return code from '%s': %s\n", Argv[0],
5203cab2bb3Spatrick            _zx_status_get_string(rc));
5213cab2bb3Spatrick     return rc;
5223cab2bb3Spatrick   }
5233cab2bb3Spatrick 
524d89ec533Spatrick   return static_cast<int>(Info.return_code);
5253cab2bb3Spatrick }
5263cab2bb3Spatrick 
ExecuteCommand(const Command & BaseCmd,std::string * CmdOutput)5271f9cb04fSpatrick bool ExecuteCommand(const Command &BaseCmd, std::string *CmdOutput) {
5281f9cb04fSpatrick   auto LogFilePath = TempPath("SimPopenOut", ".txt");
5291f9cb04fSpatrick   Command Cmd(BaseCmd);
5301f9cb04fSpatrick   Cmd.setOutputFile(LogFilePath);
5311f9cb04fSpatrick   int Ret = ExecuteCommand(Cmd);
5321f9cb04fSpatrick   *CmdOutput = FileToString(LogFilePath);
5331f9cb04fSpatrick   RemoveFile(LogFilePath);
5341f9cb04fSpatrick   return Ret == 0;
5351f9cb04fSpatrick }
5361f9cb04fSpatrick 
SearchMemory(const void * Data,size_t DataLen,const void * Patt,size_t PattLen)5373cab2bb3Spatrick const void *SearchMemory(const void *Data, size_t DataLen, const void *Patt,
5383cab2bb3Spatrick                          size_t PattLen) {
5393cab2bb3Spatrick   return memmem(Data, DataLen, Patt, PattLen);
5403cab2bb3Spatrick }
5413cab2bb3Spatrick 
5423cab2bb3Spatrick // In fuchsia, accessing /dev/null is not supported. There's nothing
5433cab2bb3Spatrick // similar to a file that discards everything that is written to it.
5443cab2bb3Spatrick // The way of doing something similar in fuchsia is by using
5453cab2bb3Spatrick // fdio_null_create and binding that to a file descriptor.
DiscardOutput(int Fd)5463cab2bb3Spatrick void DiscardOutput(int Fd) {
5473cab2bb3Spatrick   fdio_t *fdio_null = fdio_null_create();
5483cab2bb3Spatrick   if (fdio_null == nullptr) return;
5493cab2bb3Spatrick   int nullfd = fdio_bind_to_fd(fdio_null, -1, 0);
5503cab2bb3Spatrick   if (nullfd < 0) return;
5513cab2bb3Spatrick   dup2(nullfd, Fd);
5523cab2bb3Spatrick }
5533cab2bb3Spatrick 
5543cab2bb3Spatrick } // namespace fuzzer
5553cab2bb3Spatrick 
5563cab2bb3Spatrick #endif // LIBFUZZER_FUCHSIA
557