xref: /freebsd/contrib/llvm-project/compiler-rt/lib/fuzzer/FuzzerUtilFuchsia.cpp (revision 349cc55c9796c4596a5b9904cd3281af295f878f)
10b57cec5SDimitry Andric //===- FuzzerUtilFuchsia.cpp - Misc utils for Fuchsia. --------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric // Misc utils implementation using Fuchsia/Zircon APIs.
90b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
105ffd83dbSDimitry Andric #include "FuzzerPlatform.h"
110b57cec5SDimitry Andric 
120b57cec5SDimitry Andric #if LIBFUZZER_FUCHSIA
130b57cec5SDimitry Andric 
140b57cec5SDimitry Andric #include "FuzzerInternal.h"
150b57cec5SDimitry Andric #include "FuzzerUtil.h"
160b57cec5SDimitry Andric #include <cassert>
170b57cec5SDimitry Andric #include <cerrno>
180b57cec5SDimitry Andric #include <cinttypes>
190b57cec5SDimitry Andric #include <cstdint>
200b57cec5SDimitry Andric #include <fcntl.h>
21480093f4SDimitry Andric #include <lib/fdio/fdio.h>
220b57cec5SDimitry Andric #include <lib/fdio/spawn.h>
230b57cec5SDimitry Andric #include <string>
240b57cec5SDimitry Andric #include <sys/select.h>
250b57cec5SDimitry Andric #include <thread>
260b57cec5SDimitry Andric #include <unistd.h>
270b57cec5SDimitry Andric #include <zircon/errors.h>
280b57cec5SDimitry Andric #include <zircon/process.h>
290b57cec5SDimitry Andric #include <zircon/sanitizer.h>
300b57cec5SDimitry Andric #include <zircon/status.h>
310b57cec5SDimitry Andric #include <zircon/syscalls.h>
320b57cec5SDimitry Andric #include <zircon/syscalls/debug.h>
330b57cec5SDimitry Andric #include <zircon/syscalls/exception.h>
340b57cec5SDimitry Andric #include <zircon/syscalls/object.h>
350b57cec5SDimitry Andric #include <zircon/types.h>
360b57cec5SDimitry Andric 
375ffd83dbSDimitry Andric #include <vector>
385ffd83dbSDimitry Andric 
390b57cec5SDimitry Andric namespace fuzzer {
400b57cec5SDimitry Andric 
410b57cec5SDimitry Andric // Given that Fuchsia doesn't have the POSIX signals that libFuzzer was written
420b57cec5SDimitry Andric // around, the general approach is to spin up dedicated threads to watch for
430b57cec5SDimitry Andric // each requested condition (alarm, interrupt, crash).  Of these, the crash
440b57cec5SDimitry Andric // handler is the most involved, as it requires resuming the crashed thread in
450b57cec5SDimitry Andric // order to invoke the sanitizers to get the needed state.
460b57cec5SDimitry Andric 
470b57cec5SDimitry Andric // Forward declaration of assembly trampoline needed to resume crashed threads.
480b57cec5SDimitry Andric // This appears to have external linkage to  C++, which is why it's not in the
490b57cec5SDimitry Andric // anonymous namespace.  The assembly definition inside MakeTrampoline()
500b57cec5SDimitry Andric // actually defines the symbol with internal linkage only.
510b57cec5SDimitry Andric void CrashTrampolineAsm() __asm__("CrashTrampolineAsm");
520b57cec5SDimitry Andric 
530b57cec5SDimitry Andric namespace {
540b57cec5SDimitry Andric 
55*349cc55cSDimitry Andric // The signal handler thread uses Zircon exceptions to resume crashed threads
56*349cc55cSDimitry Andric // into libFuzzer's POSIX signal handlers. The associated event is used to
57*349cc55cSDimitry Andric // signal when the thread is running, and when it should stop.
58*349cc55cSDimitry Andric std::thread SignalHandler;
59*349cc55cSDimitry Andric zx_handle_t SignalHandlerEvent = ZX_HANDLE_INVALID;
60*349cc55cSDimitry Andric 
610b57cec5SDimitry Andric // Helper function to handle Zircon syscall failures.
620b57cec5SDimitry Andric void ExitOnErr(zx_status_t Status, const char *Syscall) {
630b57cec5SDimitry Andric   if (Status != ZX_OK) {
640b57cec5SDimitry Andric     Printf("libFuzzer: %s failed: %s\n", Syscall,
650b57cec5SDimitry Andric            _zx_status_get_string(Status));
660b57cec5SDimitry Andric     exit(1);
670b57cec5SDimitry Andric   }
680b57cec5SDimitry Andric }
690b57cec5SDimitry Andric 
700b57cec5SDimitry Andric void AlarmHandler(int Seconds) {
710b57cec5SDimitry Andric   while (true) {
720b57cec5SDimitry Andric     SleepSeconds(Seconds);
730b57cec5SDimitry Andric     Fuzzer::StaticAlarmCallback();
740b57cec5SDimitry Andric   }
750b57cec5SDimitry Andric }
760b57cec5SDimitry Andric 
770b57cec5SDimitry Andric // For the crash handler, we need to call Fuzzer::StaticCrashSignalCallback
780b57cec5SDimitry Andric // without POSIX signal handlers.  To achieve this, we use an assembly function
790b57cec5SDimitry Andric // to add the necessary CFI unwinding information and a C function to bridge
800b57cec5SDimitry Andric // from that back into C++.
810b57cec5SDimitry Andric 
820b57cec5SDimitry Andric // FIXME: This works as a short-term solution, but this code really shouldn't be
830b57cec5SDimitry Andric // architecture dependent. A better long term solution is to implement remote
840b57cec5SDimitry Andric // unwinding and expose the necessary APIs through sanitizer_common and/or ASAN
850b57cec5SDimitry Andric // to allow the exception handling thread to gather the crash state directly.
860b57cec5SDimitry Andric //
870b57cec5SDimitry Andric // Alternatively, Fuchsia may in future actually implement basic signal
880b57cec5SDimitry Andric // handling for the machine trap signals.
890b57cec5SDimitry Andric #if defined(__x86_64__)
900b57cec5SDimitry Andric #define FOREACH_REGISTER(OP_REG, OP_NUM) \
910b57cec5SDimitry Andric   OP_REG(rax)                            \
920b57cec5SDimitry Andric   OP_REG(rbx)                            \
930b57cec5SDimitry Andric   OP_REG(rcx)                            \
940b57cec5SDimitry Andric   OP_REG(rdx)                            \
950b57cec5SDimitry Andric   OP_REG(rsi)                            \
960b57cec5SDimitry Andric   OP_REG(rdi)                            \
970b57cec5SDimitry Andric   OP_REG(rbp)                            \
980b57cec5SDimitry Andric   OP_REG(rsp)                            \
990b57cec5SDimitry Andric   OP_REG(r8)                             \
1000b57cec5SDimitry Andric   OP_REG(r9)                             \
1010b57cec5SDimitry Andric   OP_REG(r10)                            \
1020b57cec5SDimitry Andric   OP_REG(r11)                            \
1030b57cec5SDimitry Andric   OP_REG(r12)                            \
1040b57cec5SDimitry Andric   OP_REG(r13)                            \
1050b57cec5SDimitry Andric   OP_REG(r14)                            \
1060b57cec5SDimitry Andric   OP_REG(r15)                            \
1070b57cec5SDimitry Andric   OP_REG(rip)
1080b57cec5SDimitry Andric 
1090b57cec5SDimitry Andric #elif defined(__aarch64__)
1100b57cec5SDimitry Andric #define FOREACH_REGISTER(OP_REG, OP_NUM) \
1110b57cec5SDimitry Andric   OP_NUM(0)                              \
1120b57cec5SDimitry Andric   OP_NUM(1)                              \
1130b57cec5SDimitry Andric   OP_NUM(2)                              \
1140b57cec5SDimitry Andric   OP_NUM(3)                              \
1150b57cec5SDimitry Andric   OP_NUM(4)                              \
1160b57cec5SDimitry Andric   OP_NUM(5)                              \
1170b57cec5SDimitry Andric   OP_NUM(6)                              \
1180b57cec5SDimitry Andric   OP_NUM(7)                              \
1190b57cec5SDimitry Andric   OP_NUM(8)                              \
1200b57cec5SDimitry Andric   OP_NUM(9)                              \
1210b57cec5SDimitry Andric   OP_NUM(10)                             \
1220b57cec5SDimitry Andric   OP_NUM(11)                             \
1230b57cec5SDimitry Andric   OP_NUM(12)                             \
1240b57cec5SDimitry Andric   OP_NUM(13)                             \
1250b57cec5SDimitry Andric   OP_NUM(14)                             \
1260b57cec5SDimitry Andric   OP_NUM(15)                             \
1270b57cec5SDimitry Andric   OP_NUM(16)                             \
1280b57cec5SDimitry Andric   OP_NUM(17)                             \
1290b57cec5SDimitry Andric   OP_NUM(18)                             \
1300b57cec5SDimitry Andric   OP_NUM(19)                             \
1310b57cec5SDimitry Andric   OP_NUM(20)                             \
1320b57cec5SDimitry Andric   OP_NUM(21)                             \
1330b57cec5SDimitry Andric   OP_NUM(22)                             \
1340b57cec5SDimitry Andric   OP_NUM(23)                             \
1350b57cec5SDimitry Andric   OP_NUM(24)                             \
1360b57cec5SDimitry Andric   OP_NUM(25)                             \
1370b57cec5SDimitry Andric   OP_NUM(26)                             \
1380b57cec5SDimitry Andric   OP_NUM(27)                             \
1390b57cec5SDimitry Andric   OP_NUM(28)                             \
1400b57cec5SDimitry Andric   OP_NUM(29)                             \
1410b57cec5SDimitry Andric   OP_REG(sp)
1420b57cec5SDimitry Andric 
1430b57cec5SDimitry Andric #else
1440b57cec5SDimitry Andric #error "Unsupported architecture for fuzzing on Fuchsia"
1450b57cec5SDimitry Andric #endif
1460b57cec5SDimitry Andric 
1470b57cec5SDimitry Andric // Produces a CFI directive for the named or numbered register.
148480093f4SDimitry Andric // The value used refers to an assembler immediate operand with the same name
149480093f4SDimitry Andric // as the register (see ASM_OPERAND_REG).
1500b57cec5SDimitry Andric #define CFI_OFFSET_REG(reg) ".cfi_offset " #reg ", %c[" #reg "]\n"
151480093f4SDimitry Andric #define CFI_OFFSET_NUM(num) CFI_OFFSET_REG(x##num)
1520b57cec5SDimitry Andric 
153480093f4SDimitry Andric // Produces an assembler immediate operand for the named or numbered register.
154480093f4SDimitry Andric // This operand contains the offset of the register relative to the CFA.
1550b57cec5SDimitry Andric #define ASM_OPERAND_REG(reg)                                                   \
156*349cc55cSDimitry Andric   [reg] "i"(offsetof(zx_thread_state_general_regs_t, reg)),
1570b57cec5SDimitry Andric #define ASM_OPERAND_NUM(num)                                                   \
158*349cc55cSDimitry Andric   [x##num] "i"(offsetof(zx_thread_state_general_regs_t, r[num])),
1590b57cec5SDimitry Andric 
1600b57cec5SDimitry Andric // Trampoline to bridge from the assembly below to the static C++ crash
1610b57cec5SDimitry Andric // callback.
1620b57cec5SDimitry Andric __attribute__((noreturn))
1630b57cec5SDimitry Andric static void StaticCrashHandler() {
1640b57cec5SDimitry Andric   Fuzzer::StaticCrashSignalCallback();
1650b57cec5SDimitry Andric   for (;;) {
1660b57cec5SDimitry Andric     _Exit(1);
1670b57cec5SDimitry Andric   }
1680b57cec5SDimitry Andric }
1690b57cec5SDimitry Andric 
170*349cc55cSDimitry Andric // This trampoline function has the necessary CFI information to unwind
171*349cc55cSDimitry Andric // and get a backtrace:
172*349cc55cSDimitry Andric //  * The stack contains a copy of all the registers at the point of crash,
173*349cc55cSDimitry Andric //    the code has CFI directives specifying how to restore them.
174*349cc55cSDimitry Andric //  * A call to StaticCrashHandler, which will print the stacktrace and exit
175*349cc55cSDimitry Andric //    the fuzzer, generating a crash artifact.
176480093f4SDimitry Andric //
177480093f4SDimitry Andric // The __attribute__((used)) is necessary because the function
1780b57cec5SDimitry Andric // is never called; it's just a container around the assembly to allow it to
1790b57cec5SDimitry Andric // use operands for compile-time computed constants.
1800b57cec5SDimitry Andric __attribute__((used))
1810b57cec5SDimitry Andric void MakeTrampoline() {
182*349cc55cSDimitry Andric   __asm__(
183*349cc55cSDimitry Andric       ".cfi_endproc\n"
1840b57cec5SDimitry Andric       ".pushsection .text.CrashTrampolineAsm\n"
1850b57cec5SDimitry Andric       ".type CrashTrampolineAsm,STT_FUNC\n"
1860b57cec5SDimitry Andric       "CrashTrampolineAsm:\n"
1870b57cec5SDimitry Andric       ".cfi_startproc simple\n"
1880b57cec5SDimitry Andric       ".cfi_signal_frame\n"
1890b57cec5SDimitry Andric #if defined(__x86_64__)
1900b57cec5SDimitry Andric       ".cfi_return_column rip\n"
191*349cc55cSDimitry Andric       ".cfi_def_cfa rsp, 0\n"
1920b57cec5SDimitry Andric       FOREACH_REGISTER(CFI_OFFSET_REG, CFI_OFFSET_NUM)
1930b57cec5SDimitry Andric       "call %c[StaticCrashHandler]\n"
1940b57cec5SDimitry Andric       "ud2\n"
1950b57cec5SDimitry Andric #elif defined(__aarch64__)
1960b57cec5SDimitry Andric       ".cfi_return_column 33\n"
197*349cc55cSDimitry Andric       ".cfi_def_cfa sp, 0\n"
1980b57cec5SDimitry Andric       FOREACH_REGISTER(CFI_OFFSET_REG, CFI_OFFSET_NUM)
199480093f4SDimitry Andric       ".cfi_offset 33, %c[pc]\n"
200480093f4SDimitry Andric       ".cfi_offset 30, %c[lr]\n"
201480093f4SDimitry Andric       "bl %c[StaticCrashHandler]\n"
202480093f4SDimitry Andric       "brk 1\n"
2030b57cec5SDimitry Andric #else
2040b57cec5SDimitry Andric #error "Unsupported architecture for fuzzing on Fuchsia"
2050b57cec5SDimitry Andric #endif
2060b57cec5SDimitry Andric      ".cfi_endproc\n"
2070b57cec5SDimitry Andric      ".size CrashTrampolineAsm, . - CrashTrampolineAsm\n"
2080b57cec5SDimitry Andric      ".popsection\n"
2090b57cec5SDimitry Andric      ".cfi_startproc\n"
2100b57cec5SDimitry Andric       : // No outputs
2110b57cec5SDimitry Andric       : FOREACH_REGISTER(ASM_OPERAND_REG, ASM_OPERAND_NUM)
2120b57cec5SDimitry Andric #if defined(__aarch64__)
213*349cc55cSDimitry Andric         ASM_OPERAND_REG(pc) ASM_OPERAND_REG(lr)
2140b57cec5SDimitry Andric #endif
215*349cc55cSDimitry Andric         [StaticCrashHandler] "i"(StaticCrashHandler));
2160b57cec5SDimitry Andric }
2170b57cec5SDimitry Andric 
218*349cc55cSDimitry Andric void CrashHandler() {
219*349cc55cSDimitry Andric   assert(SignalHandlerEvent != ZX_HANDLE_INVALID);
220*349cc55cSDimitry Andric 
2210b57cec5SDimitry Andric   // This structure is used to ensure we close handles to objects we create in
2220b57cec5SDimitry Andric   // this handler.
2230b57cec5SDimitry Andric   struct ScopedHandle {
2240b57cec5SDimitry Andric     ~ScopedHandle() { _zx_handle_close(Handle); }
2250b57cec5SDimitry Andric     zx_handle_t Handle = ZX_HANDLE_INVALID;
2260b57cec5SDimitry Andric   };
2270b57cec5SDimitry Andric 
2280b57cec5SDimitry Andric   // Create the exception channel.  We need to claim to be a "debugger" so the
2290b57cec5SDimitry Andric   // kernel will allow us to modify and resume dying threads (see below). Once
2300b57cec5SDimitry Andric   // the channel is set, we can signal the main thread to continue and wait
2310b57cec5SDimitry Andric   // for the exception to arrive.
2320b57cec5SDimitry Andric   ScopedHandle Channel;
2330b57cec5SDimitry Andric   zx_handle_t Self = _zx_process_self();
2340b57cec5SDimitry Andric   ExitOnErr(_zx_task_create_exception_channel(
2350b57cec5SDimitry Andric                 Self, ZX_EXCEPTION_CHANNEL_DEBUGGER, &Channel.Handle),
2360b57cec5SDimitry Andric             "_zx_task_create_exception_channel");
2370b57cec5SDimitry Andric 
238*349cc55cSDimitry Andric   ExitOnErr(_zx_object_signal(SignalHandlerEvent, 0, ZX_USER_SIGNAL_0),
2390b57cec5SDimitry Andric             "_zx_object_signal");
2400b57cec5SDimitry Andric 
2410b57cec5SDimitry Andric   // This thread lives as long as the process in order to keep handling
2420b57cec5SDimitry Andric   // crashes.  In practice, the first crashed thread to reach the end of the
2430b57cec5SDimitry Andric   // StaticCrashHandler will end the process.
2440b57cec5SDimitry Andric   while (true) {
245*349cc55cSDimitry Andric     zx_wait_item_t WaitItems[] = {
246*349cc55cSDimitry Andric         {
247*349cc55cSDimitry Andric             .handle = SignalHandlerEvent,
248*349cc55cSDimitry Andric             .waitfor = ZX_SIGNAL_HANDLE_CLOSED,
249*349cc55cSDimitry Andric             .pending = 0,
250*349cc55cSDimitry Andric         },
251*349cc55cSDimitry Andric         {
252*349cc55cSDimitry Andric             .handle = Channel.Handle,
253*349cc55cSDimitry Andric             .waitfor = ZX_CHANNEL_READABLE | ZX_CHANNEL_PEER_CLOSED,
254*349cc55cSDimitry Andric             .pending = 0,
255*349cc55cSDimitry Andric         },
256*349cc55cSDimitry Andric     };
257*349cc55cSDimitry Andric     auto Status = _zx_object_wait_many(
258*349cc55cSDimitry Andric         WaitItems, sizeof(WaitItems) / sizeof(WaitItems[0]), ZX_TIME_INFINITE);
259*349cc55cSDimitry Andric     if (Status != ZX_OK || (WaitItems[1].pending & ZX_CHANNEL_READABLE) == 0) {
260*349cc55cSDimitry Andric       break;
261*349cc55cSDimitry Andric     }
2620b57cec5SDimitry Andric 
2630b57cec5SDimitry Andric     zx_exception_info_t ExceptionInfo;
2640b57cec5SDimitry Andric     ScopedHandle Exception;
2650b57cec5SDimitry Andric     ExitOnErr(_zx_channel_read(Channel.Handle, 0, &ExceptionInfo,
2660b57cec5SDimitry Andric                                &Exception.Handle, sizeof(ExceptionInfo), 1,
2670b57cec5SDimitry Andric                                nullptr, nullptr),
2680b57cec5SDimitry Andric               "_zx_channel_read");
2690b57cec5SDimitry Andric 
2700b57cec5SDimitry Andric     // Ignore informational synthetic exceptions.
2710b57cec5SDimitry Andric     if (ZX_EXCP_THREAD_STARTING == ExceptionInfo.type ||
2720b57cec5SDimitry Andric         ZX_EXCP_THREAD_EXITING == ExceptionInfo.type ||
2730b57cec5SDimitry Andric         ZX_EXCP_PROCESS_STARTING == ExceptionInfo.type) {
2740b57cec5SDimitry Andric       continue;
2750b57cec5SDimitry Andric     }
2760b57cec5SDimitry Andric 
2770b57cec5SDimitry Andric     // At this point, we want to get the state of the crashing thread, but
2780b57cec5SDimitry Andric     // libFuzzer and the sanitizers assume this will happen from that same
2790b57cec5SDimitry Andric     // thread via a POSIX signal handler. "Resurrecting" the thread in the
2800b57cec5SDimitry Andric     // middle of the appropriate callback is as simple as forcibly setting the
2810b57cec5SDimitry Andric     // instruction pointer/program counter, provided we NEVER EVER return from
2820b57cec5SDimitry Andric     // that function (since otherwise our stack will not be valid).
2830b57cec5SDimitry Andric     ScopedHandle Thread;
2840b57cec5SDimitry Andric     ExitOnErr(_zx_exception_get_thread(Exception.Handle, &Thread.Handle),
2850b57cec5SDimitry Andric               "_zx_exception_get_thread");
2860b57cec5SDimitry Andric 
2870b57cec5SDimitry Andric     zx_thread_state_general_regs_t GeneralRegisters;
2880b57cec5SDimitry Andric     ExitOnErr(_zx_thread_read_state(Thread.Handle, ZX_THREAD_STATE_GENERAL_REGS,
2890b57cec5SDimitry Andric                                     &GeneralRegisters,
2900b57cec5SDimitry Andric                                     sizeof(GeneralRegisters)),
2910b57cec5SDimitry Andric               "_zx_thread_read_state");
2920b57cec5SDimitry Andric 
2930b57cec5SDimitry Andric     // To unwind properly, we need to push the crashing thread's register state
2940b57cec5SDimitry Andric     // onto the stack and jump into a trampoline with CFI instructions on how
2950b57cec5SDimitry Andric     // to restore it.
2960b57cec5SDimitry Andric #if defined(__x86_64__)
297*349cc55cSDimitry Andric     uintptr_t StackPtr =
298*349cc55cSDimitry Andric         (GeneralRegisters.rsp - (128 + sizeof(GeneralRegisters))) &
299*349cc55cSDimitry Andric         -(uintptr_t)16;
3000b57cec5SDimitry Andric     __unsanitized_memcpy(reinterpret_cast<void *>(StackPtr), &GeneralRegisters,
3010b57cec5SDimitry Andric                          sizeof(GeneralRegisters));
3020b57cec5SDimitry Andric     GeneralRegisters.rsp = StackPtr;
3030b57cec5SDimitry Andric     GeneralRegisters.rip = reinterpret_cast<zx_vaddr_t>(CrashTrampolineAsm);
3040b57cec5SDimitry Andric 
3050b57cec5SDimitry Andric #elif defined(__aarch64__)
306*349cc55cSDimitry Andric     uintptr_t StackPtr =
307*349cc55cSDimitry Andric         (GeneralRegisters.sp - sizeof(GeneralRegisters)) & -(uintptr_t)16;
3080b57cec5SDimitry Andric     __unsanitized_memcpy(reinterpret_cast<void *>(StackPtr), &GeneralRegisters,
3090b57cec5SDimitry Andric                          sizeof(GeneralRegisters));
3100b57cec5SDimitry Andric     GeneralRegisters.sp = StackPtr;
3110b57cec5SDimitry Andric     GeneralRegisters.pc = reinterpret_cast<zx_vaddr_t>(CrashTrampolineAsm);
3120b57cec5SDimitry Andric 
3130b57cec5SDimitry Andric #else
3140b57cec5SDimitry Andric #error "Unsupported architecture for fuzzing on Fuchsia"
3150b57cec5SDimitry Andric #endif
3160b57cec5SDimitry Andric 
3170b57cec5SDimitry Andric     // Now force the crashing thread's state.
3180b57cec5SDimitry Andric     ExitOnErr(
3190b57cec5SDimitry Andric         _zx_thread_write_state(Thread.Handle, ZX_THREAD_STATE_GENERAL_REGS,
3200b57cec5SDimitry Andric                                &GeneralRegisters, sizeof(GeneralRegisters)),
3210b57cec5SDimitry Andric         "_zx_thread_write_state");
3220b57cec5SDimitry Andric 
3230b57cec5SDimitry Andric     // Set the exception to HANDLED so it resumes the thread on close.
3240b57cec5SDimitry Andric     uint32_t ExceptionState = ZX_EXCEPTION_STATE_HANDLED;
3250b57cec5SDimitry Andric     ExitOnErr(_zx_object_set_property(Exception.Handle, ZX_PROP_EXCEPTION_STATE,
3260b57cec5SDimitry Andric                                       &ExceptionState, sizeof(ExceptionState)),
3270b57cec5SDimitry Andric               "zx_object_set_property");
3280b57cec5SDimitry Andric   }
3290b57cec5SDimitry Andric }
3300b57cec5SDimitry Andric 
331*349cc55cSDimitry Andric void StopSignalHandler() {
332*349cc55cSDimitry Andric   _zx_handle_close(SignalHandlerEvent);
333*349cc55cSDimitry Andric   if (SignalHandler.joinable()) {
334*349cc55cSDimitry Andric     SignalHandler.join();
335*349cc55cSDimitry Andric   }
336*349cc55cSDimitry Andric }
337*349cc55cSDimitry Andric 
3380b57cec5SDimitry Andric } // namespace
3390b57cec5SDimitry Andric 
3400b57cec5SDimitry Andric // Platform specific functions.
3410b57cec5SDimitry Andric void SetSignalHandler(const FuzzingOptions &Options) {
34268d75effSDimitry Andric   // Make sure information from libFuzzer and the sanitizers are easy to
34368d75effSDimitry Andric   // reassemble. `__sanitizer_log_write` has the added benefit of ensuring the
34468d75effSDimitry Andric   // DSO map is always available for the symbolizer.
34568d75effSDimitry Andric   // A uint64_t fits in 20 chars, so 64 is plenty.
34668d75effSDimitry Andric   char Buf[64];
34768d75effSDimitry Andric   memset(Buf, 0, sizeof(Buf));
34868d75effSDimitry Andric   snprintf(Buf, sizeof(Buf), "==%lu== INFO: libFuzzer starting.\n", GetPid());
34968d75effSDimitry Andric   if (EF->__sanitizer_log_write)
35068d75effSDimitry Andric     __sanitizer_log_write(Buf, sizeof(Buf));
35168d75effSDimitry Andric   Printf("%s", Buf);
35268d75effSDimitry Andric 
3530b57cec5SDimitry Andric   // Set up alarm handler if needed.
354e8d8bef9SDimitry Andric   if (Options.HandleAlrm && Options.UnitTimeoutSec > 0) {
3550b57cec5SDimitry Andric     std::thread T(AlarmHandler, Options.UnitTimeoutSec / 2 + 1);
3560b57cec5SDimitry Andric     T.detach();
3570b57cec5SDimitry Andric   }
3580b57cec5SDimitry Andric 
359e8d8bef9SDimitry Andric   // Options.HandleInt and Options.HandleTerm are not supported on Fuchsia
3600b57cec5SDimitry Andric 
3610b57cec5SDimitry Andric   // Early exit if no crash handler needed.
3620b57cec5SDimitry Andric   if (!Options.HandleSegv && !Options.HandleBus && !Options.HandleIll &&
3630b57cec5SDimitry Andric       !Options.HandleFpe && !Options.HandleAbrt)
3640b57cec5SDimitry Andric     return;
3650b57cec5SDimitry Andric 
3660b57cec5SDimitry Andric   // Set up the crash handler and wait until it is ready before proceeding.
367*349cc55cSDimitry Andric   ExitOnErr(_zx_event_create(0, &SignalHandlerEvent), "_zx_event_create");
3680b57cec5SDimitry Andric 
369*349cc55cSDimitry Andric   SignalHandler = std::thread(CrashHandler);
370*349cc55cSDimitry Andric   zx_status_t Status = _zx_object_wait_one(SignalHandlerEvent, ZX_USER_SIGNAL_0,
371*349cc55cSDimitry Andric                                            ZX_TIME_INFINITE, nullptr);
3720b57cec5SDimitry Andric   ExitOnErr(Status, "_zx_object_wait_one");
3730b57cec5SDimitry Andric 
374*349cc55cSDimitry Andric   std::atexit(StopSignalHandler);
3750b57cec5SDimitry Andric }
3760b57cec5SDimitry Andric 
3770b57cec5SDimitry Andric void SleepSeconds(int Seconds) {
3780b57cec5SDimitry Andric   _zx_nanosleep(_zx_deadline_after(ZX_SEC(Seconds)));
3790b57cec5SDimitry Andric }
3800b57cec5SDimitry Andric 
3810b57cec5SDimitry Andric unsigned long GetPid() {
3820b57cec5SDimitry Andric   zx_status_t rc;
3830b57cec5SDimitry Andric   zx_info_handle_basic_t Info;
3840b57cec5SDimitry Andric   if ((rc = _zx_object_get_info(_zx_process_self(), ZX_INFO_HANDLE_BASIC, &Info,
3850b57cec5SDimitry Andric                                 sizeof(Info), NULL, NULL)) != ZX_OK) {
3860b57cec5SDimitry Andric     Printf("libFuzzer: unable to get info about self: %s\n",
3870b57cec5SDimitry Andric            _zx_status_get_string(rc));
3880b57cec5SDimitry Andric     exit(1);
3890b57cec5SDimitry Andric   }
3900b57cec5SDimitry Andric   return Info.koid;
3910b57cec5SDimitry Andric }
3920b57cec5SDimitry Andric 
3930b57cec5SDimitry Andric size_t GetPeakRSSMb() {
3940b57cec5SDimitry Andric   zx_status_t rc;
3950b57cec5SDimitry Andric   zx_info_task_stats_t Info;
3960b57cec5SDimitry Andric   if ((rc = _zx_object_get_info(_zx_process_self(), ZX_INFO_TASK_STATS, &Info,
3970b57cec5SDimitry Andric                                 sizeof(Info), NULL, NULL)) != ZX_OK) {
3980b57cec5SDimitry Andric     Printf("libFuzzer: unable to get info about self: %s\n",
3990b57cec5SDimitry Andric            _zx_status_get_string(rc));
4000b57cec5SDimitry Andric     exit(1);
4010b57cec5SDimitry Andric   }
4020b57cec5SDimitry Andric   return (Info.mem_private_bytes + Info.mem_shared_bytes) >> 20;
4030b57cec5SDimitry Andric }
4040b57cec5SDimitry Andric 
4050b57cec5SDimitry Andric template <typename Fn>
4060b57cec5SDimitry Andric class RunOnDestruction {
4070b57cec5SDimitry Andric  public:
4080b57cec5SDimitry Andric   explicit RunOnDestruction(Fn fn) : fn_(fn) {}
4090b57cec5SDimitry Andric   ~RunOnDestruction() { fn_(); }
4100b57cec5SDimitry Andric 
4110b57cec5SDimitry Andric  private:
4120b57cec5SDimitry Andric   Fn fn_;
4130b57cec5SDimitry Andric };
4140b57cec5SDimitry Andric 
4150b57cec5SDimitry Andric template <typename Fn>
4160b57cec5SDimitry Andric RunOnDestruction<Fn> at_scope_exit(Fn fn) {
4170b57cec5SDimitry Andric   return RunOnDestruction<Fn>(fn);
4180b57cec5SDimitry Andric }
4190b57cec5SDimitry Andric 
4205ffd83dbSDimitry Andric static fdio_spawn_action_t clone_fd_action(int localFd, int targetFd) {
4215ffd83dbSDimitry Andric   return {
4225ffd83dbSDimitry Andric       .action = FDIO_SPAWN_ACTION_CLONE_FD,
4235ffd83dbSDimitry Andric       .fd =
4245ffd83dbSDimitry Andric           {
4255ffd83dbSDimitry Andric               .local_fd = localFd,
4265ffd83dbSDimitry Andric               .target_fd = targetFd,
4275ffd83dbSDimitry Andric           },
4285ffd83dbSDimitry Andric   };
4295ffd83dbSDimitry Andric }
4305ffd83dbSDimitry Andric 
4310b57cec5SDimitry Andric int ExecuteCommand(const Command &Cmd) {
4320b57cec5SDimitry Andric   zx_status_t rc;
4330b57cec5SDimitry Andric 
4340b57cec5SDimitry Andric   // Convert arguments to C array
4350b57cec5SDimitry Andric   auto Args = Cmd.getArguments();
4360b57cec5SDimitry Andric   size_t Argc = Args.size();
4370b57cec5SDimitry Andric   assert(Argc != 0);
4380b57cec5SDimitry Andric   std::unique_ptr<const char *[]> Argv(new const char *[Argc + 1]);
4390b57cec5SDimitry Andric   for (size_t i = 0; i < Argc; ++i)
4400b57cec5SDimitry Andric     Argv[i] = Args[i].c_str();
4410b57cec5SDimitry Andric   Argv[Argc] = nullptr;
4420b57cec5SDimitry Andric 
4430b57cec5SDimitry Andric   // Determine output.  On Fuchsia, the fuzzer is typically run as a component
4440b57cec5SDimitry Andric   // that lacks a mutable working directory. Fortunately, when this is the case
4450b57cec5SDimitry Andric   // a mutable output directory must be specified using "-artifact_prefix=...",
4460b57cec5SDimitry Andric   // so write the log file(s) there.
44768d75effSDimitry Andric   // However, we don't want to apply this logic for absolute paths.
4480b57cec5SDimitry Andric   int FdOut = STDOUT_FILENO;
4495ffd83dbSDimitry Andric   bool discardStdout = false;
4505ffd83dbSDimitry Andric   bool discardStderr = false;
4515ffd83dbSDimitry Andric 
4520b57cec5SDimitry Andric   if (Cmd.hasOutputFile()) {
45368d75effSDimitry Andric     std::string Path = Cmd.getOutputFile();
4545ffd83dbSDimitry Andric     if (Path == getDevNull()) {
4555ffd83dbSDimitry Andric       // On Fuchsia, there's no "/dev/null" like-file, so we
4565ffd83dbSDimitry Andric       // just don't copy the FDs into the spawned process.
4575ffd83dbSDimitry Andric       discardStdout = true;
4585ffd83dbSDimitry Andric     } else {
45968d75effSDimitry Andric       bool IsAbsolutePath = Path.length() > 1 && Path[0] == '/';
46068d75effSDimitry Andric       if (!IsAbsolutePath && Cmd.hasFlag("artifact_prefix"))
46168d75effSDimitry Andric         Path = Cmd.getFlagValue("artifact_prefix") + "/" + Path;
46268d75effSDimitry Andric 
4630b57cec5SDimitry Andric       FdOut = open(Path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0);
4640b57cec5SDimitry Andric       if (FdOut == -1) {
4650b57cec5SDimitry Andric         Printf("libFuzzer: failed to open %s: %s\n", Path.c_str(),
4660b57cec5SDimitry Andric                strerror(errno));
4670b57cec5SDimitry Andric         return ZX_ERR_IO;
4680b57cec5SDimitry Andric       }
4690b57cec5SDimitry Andric     }
4705ffd83dbSDimitry Andric   }
4710b57cec5SDimitry Andric   auto CloseFdOut = at_scope_exit([FdOut]() {
4720b57cec5SDimitry Andric     if (FdOut != STDOUT_FILENO)
4730b57cec5SDimitry Andric       close(FdOut);
4740b57cec5SDimitry Andric   });
4750b57cec5SDimitry Andric 
4760b57cec5SDimitry Andric   // Determine stderr
4770b57cec5SDimitry Andric   int FdErr = STDERR_FILENO;
4785ffd83dbSDimitry Andric   if (Cmd.isOutAndErrCombined()) {
4790b57cec5SDimitry Andric     FdErr = FdOut;
4805ffd83dbSDimitry Andric     if (discardStdout)
4815ffd83dbSDimitry Andric       discardStderr = true;
4825ffd83dbSDimitry Andric   }
4830b57cec5SDimitry Andric 
4840b57cec5SDimitry Andric   // Clone the file descriptors into the new process
4855ffd83dbSDimitry Andric   std::vector<fdio_spawn_action_t> SpawnActions;
4865ffd83dbSDimitry Andric   SpawnActions.push_back(clone_fd_action(STDIN_FILENO, STDIN_FILENO));
4875ffd83dbSDimitry Andric 
4885ffd83dbSDimitry Andric   if (!discardStdout)
4895ffd83dbSDimitry Andric     SpawnActions.push_back(clone_fd_action(FdOut, STDOUT_FILENO));
4905ffd83dbSDimitry Andric   if (!discardStderr)
4915ffd83dbSDimitry Andric     SpawnActions.push_back(clone_fd_action(FdErr, STDERR_FILENO));
4920b57cec5SDimitry Andric 
4930b57cec5SDimitry Andric   // Start the process.
4940b57cec5SDimitry Andric   char ErrorMsg[FDIO_SPAWN_ERR_MSG_MAX_LENGTH];
4950b57cec5SDimitry Andric   zx_handle_t ProcessHandle = ZX_HANDLE_INVALID;
4965ffd83dbSDimitry Andric   rc = fdio_spawn_etc(ZX_HANDLE_INVALID,
4975ffd83dbSDimitry Andric                       FDIO_SPAWN_CLONE_ALL & (~FDIO_SPAWN_CLONE_STDIO), Argv[0],
4985ffd83dbSDimitry Andric                       Argv.get(), nullptr, SpawnActions.size(),
4995ffd83dbSDimitry Andric                       SpawnActions.data(), &ProcessHandle, ErrorMsg);
5005ffd83dbSDimitry Andric 
5010b57cec5SDimitry Andric   if (rc != ZX_OK) {
5020b57cec5SDimitry Andric     Printf("libFuzzer: failed to launch '%s': %s, %s\n", Argv[0], ErrorMsg,
5030b57cec5SDimitry Andric            _zx_status_get_string(rc));
5040b57cec5SDimitry Andric     return rc;
5050b57cec5SDimitry Andric   }
5060b57cec5SDimitry Andric   auto CloseHandle = at_scope_exit([&]() { _zx_handle_close(ProcessHandle); });
5070b57cec5SDimitry Andric 
5080b57cec5SDimitry Andric   // Now join the process and return the exit status.
5090b57cec5SDimitry Andric   if ((rc = _zx_object_wait_one(ProcessHandle, ZX_PROCESS_TERMINATED,
5100b57cec5SDimitry Andric                                 ZX_TIME_INFINITE, nullptr)) != ZX_OK) {
5110b57cec5SDimitry Andric     Printf("libFuzzer: failed to join '%s': %s\n", Argv[0],
5120b57cec5SDimitry Andric            _zx_status_get_string(rc));
5130b57cec5SDimitry Andric     return rc;
5140b57cec5SDimitry Andric   }
5150b57cec5SDimitry Andric 
5160b57cec5SDimitry Andric   zx_info_process_t Info;
5170b57cec5SDimitry Andric   if ((rc = _zx_object_get_info(ProcessHandle, ZX_INFO_PROCESS, &Info,
5180b57cec5SDimitry Andric                                 sizeof(Info), nullptr, nullptr)) != ZX_OK) {
5190b57cec5SDimitry Andric     Printf("libFuzzer: unable to get return code from '%s': %s\n", Argv[0],
5200b57cec5SDimitry Andric            _zx_status_get_string(rc));
5210b57cec5SDimitry Andric     return rc;
5220b57cec5SDimitry Andric   }
5230b57cec5SDimitry Andric 
524fe6060f1SDimitry Andric   return static_cast<int>(Info.return_code);
5250b57cec5SDimitry Andric }
5260b57cec5SDimitry Andric 
5275ffd83dbSDimitry Andric bool ExecuteCommand(const Command &BaseCmd, std::string *CmdOutput) {
5285ffd83dbSDimitry Andric   auto LogFilePath = TempPath("SimPopenOut", ".txt");
5295ffd83dbSDimitry Andric   Command Cmd(BaseCmd);
5305ffd83dbSDimitry Andric   Cmd.setOutputFile(LogFilePath);
5315ffd83dbSDimitry Andric   int Ret = ExecuteCommand(Cmd);
5325ffd83dbSDimitry Andric   *CmdOutput = FileToString(LogFilePath);
5335ffd83dbSDimitry Andric   RemoveFile(LogFilePath);
5345ffd83dbSDimitry Andric   return Ret == 0;
5355ffd83dbSDimitry Andric }
5365ffd83dbSDimitry Andric 
5370b57cec5SDimitry Andric const void *SearchMemory(const void *Data, size_t DataLen, const void *Patt,
5380b57cec5SDimitry Andric                          size_t PattLen) {
5390b57cec5SDimitry Andric   return memmem(Data, DataLen, Patt, PattLen);
5400b57cec5SDimitry Andric }
5410b57cec5SDimitry Andric 
542480093f4SDimitry Andric // In fuchsia, accessing /dev/null is not supported. There's nothing
543480093f4SDimitry Andric // similar to a file that discards everything that is written to it.
544480093f4SDimitry Andric // The way of doing something similar in fuchsia is by using
545480093f4SDimitry Andric // fdio_null_create and binding that to a file descriptor.
546480093f4SDimitry Andric void DiscardOutput(int Fd) {
547480093f4SDimitry Andric   fdio_t *fdio_null = fdio_null_create();
548480093f4SDimitry Andric   if (fdio_null == nullptr) return;
549480093f4SDimitry Andric   int nullfd = fdio_bind_to_fd(fdio_null, -1, 0);
550480093f4SDimitry Andric   if (nullfd < 0) return;
551480093f4SDimitry Andric   dup2(nullfd, Fd);
552480093f4SDimitry Andric }
553480093f4SDimitry Andric 
5540b57cec5SDimitry Andric } // namespace fuzzer
5550b57cec5SDimitry Andric 
5560b57cec5SDimitry Andric #endif // LIBFUZZER_FUCHSIA
557