xref: /freebsd/contrib/llvm-project/compiler-rt/lib/fuzzer/FuzzerUtilFuchsia.cpp (revision 480093f4440d54b30b3025afeac24b48f2ba7a2e)
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 //===----------------------------------------------------------------------===//
100b57cec5SDimitry Andric #include "FuzzerDefs.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>
21*480093f4SDimitry 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 
370b57cec5SDimitry Andric namespace fuzzer {
380b57cec5SDimitry Andric 
390b57cec5SDimitry Andric // Given that Fuchsia doesn't have the POSIX signals that libFuzzer was written
400b57cec5SDimitry Andric // around, the general approach is to spin up dedicated threads to watch for
410b57cec5SDimitry Andric // each requested condition (alarm, interrupt, crash).  Of these, the crash
420b57cec5SDimitry Andric // handler is the most involved, as it requires resuming the crashed thread in
430b57cec5SDimitry Andric // order to invoke the sanitizers to get the needed state.
440b57cec5SDimitry Andric 
450b57cec5SDimitry Andric // Forward declaration of assembly trampoline needed to resume crashed threads.
460b57cec5SDimitry Andric // This appears to have external linkage to  C++, which is why it's not in the
470b57cec5SDimitry Andric // anonymous namespace.  The assembly definition inside MakeTrampoline()
480b57cec5SDimitry Andric // actually defines the symbol with internal linkage only.
490b57cec5SDimitry Andric void CrashTrampolineAsm() __asm__("CrashTrampolineAsm");
500b57cec5SDimitry Andric 
510b57cec5SDimitry Andric namespace {
520b57cec5SDimitry Andric 
530b57cec5SDimitry Andric // Helper function to handle Zircon syscall failures.
540b57cec5SDimitry Andric void ExitOnErr(zx_status_t Status, const char *Syscall) {
550b57cec5SDimitry Andric   if (Status != ZX_OK) {
560b57cec5SDimitry Andric     Printf("libFuzzer: %s failed: %s\n", Syscall,
570b57cec5SDimitry Andric            _zx_status_get_string(Status));
580b57cec5SDimitry Andric     exit(1);
590b57cec5SDimitry Andric   }
600b57cec5SDimitry Andric }
610b57cec5SDimitry Andric 
620b57cec5SDimitry Andric void AlarmHandler(int Seconds) {
630b57cec5SDimitry Andric   while (true) {
640b57cec5SDimitry Andric     SleepSeconds(Seconds);
650b57cec5SDimitry Andric     Fuzzer::StaticAlarmCallback();
660b57cec5SDimitry Andric   }
670b57cec5SDimitry Andric }
680b57cec5SDimitry Andric 
690b57cec5SDimitry Andric void InterruptHandler() {
700b57cec5SDimitry Andric   fd_set readfds;
710b57cec5SDimitry Andric   // Ctrl-C sends ETX in Zircon.
720b57cec5SDimitry Andric   do {
730b57cec5SDimitry Andric     FD_ZERO(&readfds);
740b57cec5SDimitry Andric     FD_SET(STDIN_FILENO, &readfds);
750b57cec5SDimitry Andric     select(STDIN_FILENO + 1, &readfds, nullptr, nullptr, nullptr);
760b57cec5SDimitry Andric   } while(!FD_ISSET(STDIN_FILENO, &readfds) || getchar() != 0x03);
770b57cec5SDimitry Andric   Fuzzer::StaticInterruptCallback();
780b57cec5SDimitry Andric }
790b57cec5SDimitry Andric 
80*480093f4SDimitry Andric // CFAOffset is used to reference the stack pointer before entering the
81*480093f4SDimitry Andric // trampoline (Stack Pointer + CFAOffset = prev Stack Pointer). Before jumping
82*480093f4SDimitry Andric // to the trampoline we copy all the registers onto the stack. We need to make
83*480093f4SDimitry Andric // sure that the new stack has enough space to store all the registers.
84*480093f4SDimitry Andric //
85*480093f4SDimitry Andric // The trampoline holds CFI information regarding the registers stored in the
86*480093f4SDimitry Andric // stack, which is then used by the unwinder to restore them.
87*480093f4SDimitry Andric #if defined(__x86_64__)
88*480093f4SDimitry Andric // In x86_64 the crashing function might also be using the red zone (128 bytes
89*480093f4SDimitry Andric // on top of their rsp).
90*480093f4SDimitry Andric constexpr size_t CFAOffset = 128 + sizeof(zx_thread_state_general_regs_t);
91*480093f4SDimitry Andric #elif defined(__aarch64__)
92*480093f4SDimitry Andric // In aarch64 we need to always have the stack pointer aligned to 16 bytes, so we
93*480093f4SDimitry Andric // make sure that we are keeping that same alignment.
94*480093f4SDimitry Andric constexpr size_t CFAOffset = (sizeof(zx_thread_state_general_regs_t) + 15) & -(uintptr_t)16;
95*480093f4SDimitry Andric #endif
96*480093f4SDimitry Andric 
970b57cec5SDimitry Andric // For the crash handler, we need to call Fuzzer::StaticCrashSignalCallback
980b57cec5SDimitry Andric // without POSIX signal handlers.  To achieve this, we use an assembly function
990b57cec5SDimitry Andric // to add the necessary CFI unwinding information and a C function to bridge
1000b57cec5SDimitry Andric // from that back into C++.
1010b57cec5SDimitry Andric 
1020b57cec5SDimitry Andric // FIXME: This works as a short-term solution, but this code really shouldn't be
1030b57cec5SDimitry Andric // architecture dependent. A better long term solution is to implement remote
1040b57cec5SDimitry Andric // unwinding and expose the necessary APIs through sanitizer_common and/or ASAN
1050b57cec5SDimitry Andric // to allow the exception handling thread to gather the crash state directly.
1060b57cec5SDimitry Andric //
1070b57cec5SDimitry Andric // Alternatively, Fuchsia may in future actually implement basic signal
1080b57cec5SDimitry Andric // handling for the machine trap signals.
1090b57cec5SDimitry Andric #if defined(__x86_64__)
1100b57cec5SDimitry Andric #define FOREACH_REGISTER(OP_REG, OP_NUM) \
1110b57cec5SDimitry Andric   OP_REG(rax)                            \
1120b57cec5SDimitry Andric   OP_REG(rbx)                            \
1130b57cec5SDimitry Andric   OP_REG(rcx)                            \
1140b57cec5SDimitry Andric   OP_REG(rdx)                            \
1150b57cec5SDimitry Andric   OP_REG(rsi)                            \
1160b57cec5SDimitry Andric   OP_REG(rdi)                            \
1170b57cec5SDimitry Andric   OP_REG(rbp)                            \
1180b57cec5SDimitry Andric   OP_REG(rsp)                            \
1190b57cec5SDimitry Andric   OP_REG(r8)                             \
1200b57cec5SDimitry Andric   OP_REG(r9)                             \
1210b57cec5SDimitry Andric   OP_REG(r10)                            \
1220b57cec5SDimitry Andric   OP_REG(r11)                            \
1230b57cec5SDimitry Andric   OP_REG(r12)                            \
1240b57cec5SDimitry Andric   OP_REG(r13)                            \
1250b57cec5SDimitry Andric   OP_REG(r14)                            \
1260b57cec5SDimitry Andric   OP_REG(r15)                            \
1270b57cec5SDimitry Andric   OP_REG(rip)
1280b57cec5SDimitry Andric 
1290b57cec5SDimitry Andric #elif defined(__aarch64__)
1300b57cec5SDimitry Andric #define FOREACH_REGISTER(OP_REG, OP_NUM) \
1310b57cec5SDimitry Andric   OP_NUM(0)                              \
1320b57cec5SDimitry Andric   OP_NUM(1)                              \
1330b57cec5SDimitry Andric   OP_NUM(2)                              \
1340b57cec5SDimitry Andric   OP_NUM(3)                              \
1350b57cec5SDimitry Andric   OP_NUM(4)                              \
1360b57cec5SDimitry Andric   OP_NUM(5)                              \
1370b57cec5SDimitry Andric   OP_NUM(6)                              \
1380b57cec5SDimitry Andric   OP_NUM(7)                              \
1390b57cec5SDimitry Andric   OP_NUM(8)                              \
1400b57cec5SDimitry Andric   OP_NUM(9)                              \
1410b57cec5SDimitry Andric   OP_NUM(10)                             \
1420b57cec5SDimitry Andric   OP_NUM(11)                             \
1430b57cec5SDimitry Andric   OP_NUM(12)                             \
1440b57cec5SDimitry Andric   OP_NUM(13)                             \
1450b57cec5SDimitry Andric   OP_NUM(14)                             \
1460b57cec5SDimitry Andric   OP_NUM(15)                             \
1470b57cec5SDimitry Andric   OP_NUM(16)                             \
1480b57cec5SDimitry Andric   OP_NUM(17)                             \
1490b57cec5SDimitry Andric   OP_NUM(18)                             \
1500b57cec5SDimitry Andric   OP_NUM(19)                             \
1510b57cec5SDimitry Andric   OP_NUM(20)                             \
1520b57cec5SDimitry Andric   OP_NUM(21)                             \
1530b57cec5SDimitry Andric   OP_NUM(22)                             \
1540b57cec5SDimitry Andric   OP_NUM(23)                             \
1550b57cec5SDimitry Andric   OP_NUM(24)                             \
1560b57cec5SDimitry Andric   OP_NUM(25)                             \
1570b57cec5SDimitry Andric   OP_NUM(26)                             \
1580b57cec5SDimitry Andric   OP_NUM(27)                             \
1590b57cec5SDimitry Andric   OP_NUM(28)                             \
1600b57cec5SDimitry Andric   OP_NUM(29)                             \
1610b57cec5SDimitry Andric   OP_REG(sp)
1620b57cec5SDimitry Andric 
1630b57cec5SDimitry Andric #else
1640b57cec5SDimitry Andric #error "Unsupported architecture for fuzzing on Fuchsia"
1650b57cec5SDimitry Andric #endif
1660b57cec5SDimitry Andric 
1670b57cec5SDimitry Andric // Produces a CFI directive for the named or numbered register.
168*480093f4SDimitry Andric // The value used refers to an assembler immediate operand with the same name
169*480093f4SDimitry Andric // as the register (see ASM_OPERAND_REG).
1700b57cec5SDimitry Andric #define CFI_OFFSET_REG(reg) ".cfi_offset " #reg ", %c[" #reg "]\n"
171*480093f4SDimitry Andric #define CFI_OFFSET_NUM(num) CFI_OFFSET_REG(x##num)
1720b57cec5SDimitry Andric 
173*480093f4SDimitry Andric // Produces an assembler immediate operand for the named or numbered register.
174*480093f4SDimitry Andric // This operand contains the offset of the register relative to the CFA.
1750b57cec5SDimitry Andric #define ASM_OPERAND_REG(reg) \
176*480093f4SDimitry Andric   [reg] "i"(offsetof(zx_thread_state_general_regs_t, reg) - CFAOffset),
1770b57cec5SDimitry Andric #define ASM_OPERAND_NUM(num)                                 \
178*480093f4SDimitry Andric   [x##num] "i"(offsetof(zx_thread_state_general_regs_t, r[num]) - CFAOffset),
1790b57cec5SDimitry Andric 
1800b57cec5SDimitry Andric // Trampoline to bridge from the assembly below to the static C++ crash
1810b57cec5SDimitry Andric // callback.
1820b57cec5SDimitry Andric __attribute__((noreturn))
1830b57cec5SDimitry Andric static void StaticCrashHandler() {
1840b57cec5SDimitry Andric   Fuzzer::StaticCrashSignalCallback();
1850b57cec5SDimitry Andric   for (;;) {
1860b57cec5SDimitry Andric     _Exit(1);
1870b57cec5SDimitry Andric   }
1880b57cec5SDimitry Andric }
1890b57cec5SDimitry Andric 
1900b57cec5SDimitry Andric // Creates the trampoline with the necessary CFI information to unwind through
191*480093f4SDimitry Andric // to the crashing call stack:
192*480093f4SDimitry Andric //  * Defining the CFA so that it points to the stack pointer at the point
193*480093f4SDimitry Andric //    of crash.
194*480093f4SDimitry Andric //  * Storing all registers at the point of crash in the stack and refer to them
195*480093f4SDimitry Andric //    via CFI information (relative to the CFA).
196*480093f4SDimitry Andric //  * Setting the return column so the unwinder knows how to continue unwinding.
197*480093f4SDimitry Andric //  * (x86_64) making sure rsp is aligned before calling StaticCrashHandler.
198*480093f4SDimitry Andric //  * Calling StaticCrashHandler that will trigger the unwinder.
199*480093f4SDimitry Andric //
200*480093f4SDimitry Andric // The __attribute__((used)) is necessary because the function
2010b57cec5SDimitry Andric // is never called; it's just a container around the assembly to allow it to
2020b57cec5SDimitry Andric // use operands for compile-time computed constants.
2030b57cec5SDimitry Andric __attribute__((used))
2040b57cec5SDimitry Andric void MakeTrampoline() {
2050b57cec5SDimitry Andric   __asm__(".cfi_endproc\n"
2060b57cec5SDimitry Andric     ".pushsection .text.CrashTrampolineAsm\n"
2070b57cec5SDimitry Andric     ".type CrashTrampolineAsm,STT_FUNC\n"
2080b57cec5SDimitry Andric "CrashTrampolineAsm:\n"
2090b57cec5SDimitry Andric     ".cfi_startproc simple\n"
2100b57cec5SDimitry Andric     ".cfi_signal_frame\n"
2110b57cec5SDimitry Andric #if defined(__x86_64__)
2120b57cec5SDimitry Andric     ".cfi_return_column rip\n"
213*480093f4SDimitry Andric     ".cfi_def_cfa rsp, %c[CFAOffset]\n"
2140b57cec5SDimitry Andric     FOREACH_REGISTER(CFI_OFFSET_REG, CFI_OFFSET_NUM)
215*480093f4SDimitry Andric     "mov %%rsp, %%rbp\n"
216*480093f4SDimitry Andric     ".cfi_def_cfa_register rbp\n"
217*480093f4SDimitry Andric     "andq $-16, %%rsp\n"
2180b57cec5SDimitry Andric     "call %c[StaticCrashHandler]\n"
2190b57cec5SDimitry Andric     "ud2\n"
2200b57cec5SDimitry Andric #elif defined(__aarch64__)
2210b57cec5SDimitry Andric     ".cfi_return_column 33\n"
222*480093f4SDimitry Andric     ".cfi_def_cfa sp, %c[CFAOffset]\n"
2230b57cec5SDimitry Andric     FOREACH_REGISTER(CFI_OFFSET_REG, CFI_OFFSET_NUM)
224*480093f4SDimitry Andric     ".cfi_offset 33, %c[pc]\n"
225*480093f4SDimitry Andric     ".cfi_offset 30, %c[lr]\n"
226*480093f4SDimitry Andric     "bl %c[StaticCrashHandler]\n"
227*480093f4SDimitry Andric     "brk 1\n"
2280b57cec5SDimitry Andric #else
2290b57cec5SDimitry Andric #error "Unsupported architecture for fuzzing on Fuchsia"
2300b57cec5SDimitry Andric #endif
2310b57cec5SDimitry Andric     ".cfi_endproc\n"
2320b57cec5SDimitry Andric     ".size CrashTrampolineAsm, . - CrashTrampolineAsm\n"
2330b57cec5SDimitry Andric     ".popsection\n"
2340b57cec5SDimitry Andric     ".cfi_startproc\n"
2350b57cec5SDimitry Andric     : // No outputs
2360b57cec5SDimitry Andric     : FOREACH_REGISTER(ASM_OPERAND_REG, ASM_OPERAND_NUM)
2370b57cec5SDimitry Andric #if defined(__aarch64__)
2380b57cec5SDimitry Andric       ASM_OPERAND_REG(pc)
239*480093f4SDimitry Andric       ASM_OPERAND_REG(lr)
2400b57cec5SDimitry Andric #endif
241*480093f4SDimitry Andric       [StaticCrashHandler] "i" (StaticCrashHandler),
242*480093f4SDimitry Andric       [CFAOffset] "i" (CFAOffset));
2430b57cec5SDimitry Andric }
2440b57cec5SDimitry Andric 
2450b57cec5SDimitry Andric void CrashHandler(zx_handle_t *Event) {
2460b57cec5SDimitry Andric   // This structure is used to ensure we close handles to objects we create in
2470b57cec5SDimitry Andric   // this handler.
2480b57cec5SDimitry Andric   struct ScopedHandle {
2490b57cec5SDimitry Andric     ~ScopedHandle() { _zx_handle_close(Handle); }
2500b57cec5SDimitry Andric     zx_handle_t Handle = ZX_HANDLE_INVALID;
2510b57cec5SDimitry Andric   };
2520b57cec5SDimitry Andric 
2530b57cec5SDimitry Andric   // Create the exception channel.  We need to claim to be a "debugger" so the
2540b57cec5SDimitry Andric   // kernel will allow us to modify and resume dying threads (see below). Once
2550b57cec5SDimitry Andric   // the channel is set, we can signal the main thread to continue and wait
2560b57cec5SDimitry Andric   // for the exception to arrive.
2570b57cec5SDimitry Andric   ScopedHandle Channel;
2580b57cec5SDimitry Andric   zx_handle_t Self = _zx_process_self();
2590b57cec5SDimitry Andric   ExitOnErr(_zx_task_create_exception_channel(
2600b57cec5SDimitry Andric                 Self, ZX_EXCEPTION_CHANNEL_DEBUGGER, &Channel.Handle),
2610b57cec5SDimitry Andric             "_zx_task_create_exception_channel");
2620b57cec5SDimitry Andric 
2630b57cec5SDimitry Andric   ExitOnErr(_zx_object_signal(*Event, 0, ZX_USER_SIGNAL_0),
2640b57cec5SDimitry Andric             "_zx_object_signal");
2650b57cec5SDimitry Andric 
2660b57cec5SDimitry Andric   // This thread lives as long as the process in order to keep handling
2670b57cec5SDimitry Andric   // crashes.  In practice, the first crashed thread to reach the end of the
2680b57cec5SDimitry Andric   // StaticCrashHandler will end the process.
2690b57cec5SDimitry Andric   while (true) {
2700b57cec5SDimitry Andric     ExitOnErr(_zx_object_wait_one(Channel.Handle, ZX_CHANNEL_READABLE,
2710b57cec5SDimitry Andric                                   ZX_TIME_INFINITE, nullptr),
2720b57cec5SDimitry Andric               "_zx_object_wait_one");
2730b57cec5SDimitry Andric 
2740b57cec5SDimitry Andric     zx_exception_info_t ExceptionInfo;
2750b57cec5SDimitry Andric     ScopedHandle Exception;
2760b57cec5SDimitry Andric     ExitOnErr(_zx_channel_read(Channel.Handle, 0, &ExceptionInfo,
2770b57cec5SDimitry Andric                                &Exception.Handle, sizeof(ExceptionInfo), 1,
2780b57cec5SDimitry Andric                                nullptr, nullptr),
2790b57cec5SDimitry Andric               "_zx_channel_read");
2800b57cec5SDimitry Andric 
2810b57cec5SDimitry Andric     // Ignore informational synthetic exceptions.
2820b57cec5SDimitry Andric     if (ZX_EXCP_THREAD_STARTING == ExceptionInfo.type ||
2830b57cec5SDimitry Andric         ZX_EXCP_THREAD_EXITING == ExceptionInfo.type ||
2840b57cec5SDimitry Andric         ZX_EXCP_PROCESS_STARTING == ExceptionInfo.type) {
2850b57cec5SDimitry Andric       continue;
2860b57cec5SDimitry Andric     }
2870b57cec5SDimitry Andric 
2880b57cec5SDimitry Andric     // At this point, we want to get the state of the crashing thread, but
2890b57cec5SDimitry Andric     // libFuzzer and the sanitizers assume this will happen from that same
2900b57cec5SDimitry Andric     // thread via a POSIX signal handler. "Resurrecting" the thread in the
2910b57cec5SDimitry Andric     // middle of the appropriate callback is as simple as forcibly setting the
2920b57cec5SDimitry Andric     // instruction pointer/program counter, provided we NEVER EVER return from
2930b57cec5SDimitry Andric     // that function (since otherwise our stack will not be valid).
2940b57cec5SDimitry Andric     ScopedHandle Thread;
2950b57cec5SDimitry Andric     ExitOnErr(_zx_exception_get_thread(Exception.Handle, &Thread.Handle),
2960b57cec5SDimitry Andric               "_zx_exception_get_thread");
2970b57cec5SDimitry Andric 
2980b57cec5SDimitry Andric     zx_thread_state_general_regs_t GeneralRegisters;
2990b57cec5SDimitry Andric     ExitOnErr(_zx_thread_read_state(Thread.Handle, ZX_THREAD_STATE_GENERAL_REGS,
3000b57cec5SDimitry Andric                                     &GeneralRegisters,
3010b57cec5SDimitry Andric                                     sizeof(GeneralRegisters)),
3020b57cec5SDimitry Andric               "_zx_thread_read_state");
3030b57cec5SDimitry Andric 
3040b57cec5SDimitry Andric     // To unwind properly, we need to push the crashing thread's register state
3050b57cec5SDimitry Andric     // onto the stack and jump into a trampoline with CFI instructions on how
3060b57cec5SDimitry Andric     // to restore it.
3070b57cec5SDimitry Andric #if defined(__x86_64__)
308*480093f4SDimitry Andric     uintptr_t StackPtr = GeneralRegisters.rsp - CFAOffset;
3090b57cec5SDimitry Andric     __unsanitized_memcpy(reinterpret_cast<void *>(StackPtr), &GeneralRegisters,
3100b57cec5SDimitry Andric                          sizeof(GeneralRegisters));
3110b57cec5SDimitry Andric     GeneralRegisters.rsp = StackPtr;
3120b57cec5SDimitry Andric     GeneralRegisters.rip = reinterpret_cast<zx_vaddr_t>(CrashTrampolineAsm);
3130b57cec5SDimitry Andric 
3140b57cec5SDimitry Andric #elif defined(__aarch64__)
315*480093f4SDimitry Andric     uintptr_t StackPtr = GeneralRegisters.sp - CFAOffset;
3160b57cec5SDimitry Andric     __unsanitized_memcpy(reinterpret_cast<void *>(StackPtr), &GeneralRegisters,
3170b57cec5SDimitry Andric                          sizeof(GeneralRegisters));
3180b57cec5SDimitry Andric     GeneralRegisters.sp = StackPtr;
3190b57cec5SDimitry Andric     GeneralRegisters.pc = reinterpret_cast<zx_vaddr_t>(CrashTrampolineAsm);
3200b57cec5SDimitry Andric 
3210b57cec5SDimitry Andric #else
3220b57cec5SDimitry Andric #error "Unsupported architecture for fuzzing on Fuchsia"
3230b57cec5SDimitry Andric #endif
3240b57cec5SDimitry Andric 
3250b57cec5SDimitry Andric     // Now force the crashing thread's state.
3260b57cec5SDimitry Andric     ExitOnErr(
3270b57cec5SDimitry Andric         _zx_thread_write_state(Thread.Handle, ZX_THREAD_STATE_GENERAL_REGS,
3280b57cec5SDimitry Andric                                &GeneralRegisters, sizeof(GeneralRegisters)),
3290b57cec5SDimitry Andric         "_zx_thread_write_state");
3300b57cec5SDimitry Andric 
3310b57cec5SDimitry Andric     // Set the exception to HANDLED so it resumes the thread on close.
3320b57cec5SDimitry Andric     uint32_t ExceptionState = ZX_EXCEPTION_STATE_HANDLED;
3330b57cec5SDimitry Andric     ExitOnErr(_zx_object_set_property(Exception.Handle, ZX_PROP_EXCEPTION_STATE,
3340b57cec5SDimitry Andric                                       &ExceptionState, sizeof(ExceptionState)),
3350b57cec5SDimitry Andric               "zx_object_set_property");
3360b57cec5SDimitry Andric   }
3370b57cec5SDimitry Andric }
3380b57cec5SDimitry Andric 
3390b57cec5SDimitry Andric } // namespace
3400b57cec5SDimitry Andric 
3410b57cec5SDimitry Andric // Platform specific functions.
3420b57cec5SDimitry Andric void SetSignalHandler(const FuzzingOptions &Options) {
34368d75effSDimitry Andric   // Make sure information from libFuzzer and the sanitizers are easy to
34468d75effSDimitry Andric   // reassemble. `__sanitizer_log_write` has the added benefit of ensuring the
34568d75effSDimitry Andric   // DSO map is always available for the symbolizer.
34668d75effSDimitry Andric   // A uint64_t fits in 20 chars, so 64 is plenty.
34768d75effSDimitry Andric   char Buf[64];
34868d75effSDimitry Andric   memset(Buf, 0, sizeof(Buf));
34968d75effSDimitry Andric   snprintf(Buf, sizeof(Buf), "==%lu== INFO: libFuzzer starting.\n", GetPid());
35068d75effSDimitry Andric   if (EF->__sanitizer_log_write)
35168d75effSDimitry Andric     __sanitizer_log_write(Buf, sizeof(Buf));
35268d75effSDimitry Andric   Printf("%s", Buf);
35368d75effSDimitry Andric 
3540b57cec5SDimitry Andric   // Set up alarm handler if needed.
3550b57cec5SDimitry Andric   if (Options.UnitTimeoutSec > 0) {
3560b57cec5SDimitry Andric     std::thread T(AlarmHandler, Options.UnitTimeoutSec / 2 + 1);
3570b57cec5SDimitry Andric     T.detach();
3580b57cec5SDimitry Andric   }
3590b57cec5SDimitry Andric 
3600b57cec5SDimitry Andric   // Set up interrupt handler if needed.
3610b57cec5SDimitry Andric   if (Options.HandleInt || Options.HandleTerm) {
3620b57cec5SDimitry Andric     std::thread T(InterruptHandler);
3630b57cec5SDimitry Andric     T.detach();
3640b57cec5SDimitry Andric   }
3650b57cec5SDimitry Andric 
3660b57cec5SDimitry Andric   // Early exit if no crash handler needed.
3670b57cec5SDimitry Andric   if (!Options.HandleSegv && !Options.HandleBus && !Options.HandleIll &&
3680b57cec5SDimitry Andric       !Options.HandleFpe && !Options.HandleAbrt)
3690b57cec5SDimitry Andric     return;
3700b57cec5SDimitry Andric 
3710b57cec5SDimitry Andric   // Set up the crash handler and wait until it is ready before proceeding.
3720b57cec5SDimitry Andric   zx_handle_t Event;
3730b57cec5SDimitry Andric   ExitOnErr(_zx_event_create(0, &Event), "_zx_event_create");
3740b57cec5SDimitry Andric 
3750b57cec5SDimitry Andric   std::thread T(CrashHandler, &Event);
3760b57cec5SDimitry Andric   zx_status_t Status =
3770b57cec5SDimitry Andric       _zx_object_wait_one(Event, ZX_USER_SIGNAL_0, ZX_TIME_INFINITE, nullptr);
3780b57cec5SDimitry Andric   _zx_handle_close(Event);
3790b57cec5SDimitry Andric   ExitOnErr(Status, "_zx_object_wait_one");
3800b57cec5SDimitry Andric 
3810b57cec5SDimitry Andric   T.detach();
3820b57cec5SDimitry Andric }
3830b57cec5SDimitry Andric 
3840b57cec5SDimitry Andric void SleepSeconds(int Seconds) {
3850b57cec5SDimitry Andric   _zx_nanosleep(_zx_deadline_after(ZX_SEC(Seconds)));
3860b57cec5SDimitry Andric }
3870b57cec5SDimitry Andric 
3880b57cec5SDimitry Andric unsigned long GetPid() {
3890b57cec5SDimitry Andric   zx_status_t rc;
3900b57cec5SDimitry Andric   zx_info_handle_basic_t Info;
3910b57cec5SDimitry Andric   if ((rc = _zx_object_get_info(_zx_process_self(), ZX_INFO_HANDLE_BASIC, &Info,
3920b57cec5SDimitry Andric                                 sizeof(Info), NULL, NULL)) != ZX_OK) {
3930b57cec5SDimitry Andric     Printf("libFuzzer: unable to get info about self: %s\n",
3940b57cec5SDimitry Andric            _zx_status_get_string(rc));
3950b57cec5SDimitry Andric     exit(1);
3960b57cec5SDimitry Andric   }
3970b57cec5SDimitry Andric   return Info.koid;
3980b57cec5SDimitry Andric }
3990b57cec5SDimitry Andric 
4000b57cec5SDimitry Andric size_t GetPeakRSSMb() {
4010b57cec5SDimitry Andric   zx_status_t rc;
4020b57cec5SDimitry Andric   zx_info_task_stats_t Info;
4030b57cec5SDimitry Andric   if ((rc = _zx_object_get_info(_zx_process_self(), ZX_INFO_TASK_STATS, &Info,
4040b57cec5SDimitry Andric                                 sizeof(Info), NULL, NULL)) != ZX_OK) {
4050b57cec5SDimitry Andric     Printf("libFuzzer: unable to get info about self: %s\n",
4060b57cec5SDimitry Andric            _zx_status_get_string(rc));
4070b57cec5SDimitry Andric     exit(1);
4080b57cec5SDimitry Andric   }
4090b57cec5SDimitry Andric   return (Info.mem_private_bytes + Info.mem_shared_bytes) >> 20;
4100b57cec5SDimitry Andric }
4110b57cec5SDimitry Andric 
4120b57cec5SDimitry Andric template <typename Fn>
4130b57cec5SDimitry Andric class RunOnDestruction {
4140b57cec5SDimitry Andric  public:
4150b57cec5SDimitry Andric   explicit RunOnDestruction(Fn fn) : fn_(fn) {}
4160b57cec5SDimitry Andric   ~RunOnDestruction() { fn_(); }
4170b57cec5SDimitry Andric 
4180b57cec5SDimitry Andric  private:
4190b57cec5SDimitry Andric   Fn fn_;
4200b57cec5SDimitry Andric };
4210b57cec5SDimitry Andric 
4220b57cec5SDimitry Andric template <typename Fn>
4230b57cec5SDimitry Andric RunOnDestruction<Fn> at_scope_exit(Fn fn) {
4240b57cec5SDimitry Andric   return RunOnDestruction<Fn>(fn);
4250b57cec5SDimitry Andric }
4260b57cec5SDimitry Andric 
4270b57cec5SDimitry Andric int ExecuteCommand(const Command &Cmd) {
4280b57cec5SDimitry Andric   zx_status_t rc;
4290b57cec5SDimitry Andric 
4300b57cec5SDimitry Andric   // Convert arguments to C array
4310b57cec5SDimitry Andric   auto Args = Cmd.getArguments();
4320b57cec5SDimitry Andric   size_t Argc = Args.size();
4330b57cec5SDimitry Andric   assert(Argc != 0);
4340b57cec5SDimitry Andric   std::unique_ptr<const char *[]> Argv(new const char *[Argc + 1]);
4350b57cec5SDimitry Andric   for (size_t i = 0; i < Argc; ++i)
4360b57cec5SDimitry Andric     Argv[i] = Args[i].c_str();
4370b57cec5SDimitry Andric   Argv[Argc] = nullptr;
4380b57cec5SDimitry Andric 
4390b57cec5SDimitry Andric   // Determine output.  On Fuchsia, the fuzzer is typically run as a component
4400b57cec5SDimitry Andric   // that lacks a mutable working directory. Fortunately, when this is the case
4410b57cec5SDimitry Andric   // a mutable output directory must be specified using "-artifact_prefix=...",
4420b57cec5SDimitry Andric   // so write the log file(s) there.
44368d75effSDimitry Andric   // However, we don't want to apply this logic for absolute paths.
4440b57cec5SDimitry Andric   int FdOut = STDOUT_FILENO;
4450b57cec5SDimitry Andric   if (Cmd.hasOutputFile()) {
44668d75effSDimitry Andric     std::string Path = Cmd.getOutputFile();
44768d75effSDimitry Andric     bool IsAbsolutePath = Path.length() > 1 && Path[0] == '/';
44868d75effSDimitry Andric     if (!IsAbsolutePath && Cmd.hasFlag("artifact_prefix"))
44968d75effSDimitry Andric       Path = Cmd.getFlagValue("artifact_prefix") + "/" + Path;
45068d75effSDimitry Andric 
4510b57cec5SDimitry Andric     FdOut = open(Path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0);
4520b57cec5SDimitry Andric     if (FdOut == -1) {
4530b57cec5SDimitry Andric       Printf("libFuzzer: failed to open %s: %s\n", Path.c_str(),
4540b57cec5SDimitry Andric              strerror(errno));
4550b57cec5SDimitry Andric       return ZX_ERR_IO;
4560b57cec5SDimitry Andric     }
4570b57cec5SDimitry Andric   }
4580b57cec5SDimitry Andric   auto CloseFdOut = at_scope_exit([FdOut]() {
4590b57cec5SDimitry Andric     if (FdOut != STDOUT_FILENO)
4600b57cec5SDimitry Andric       close(FdOut);
4610b57cec5SDimitry Andric   });
4620b57cec5SDimitry Andric 
4630b57cec5SDimitry Andric   // Determine stderr
4640b57cec5SDimitry Andric   int FdErr = STDERR_FILENO;
4650b57cec5SDimitry Andric   if (Cmd.isOutAndErrCombined())
4660b57cec5SDimitry Andric     FdErr = FdOut;
4670b57cec5SDimitry Andric 
4680b57cec5SDimitry Andric   // Clone the file descriptors into the new process
4690b57cec5SDimitry Andric   fdio_spawn_action_t SpawnAction[] = {
4700b57cec5SDimitry Andric       {
4710b57cec5SDimitry Andric           .action = FDIO_SPAWN_ACTION_CLONE_FD,
4720b57cec5SDimitry Andric           .fd =
4730b57cec5SDimitry Andric               {
4740b57cec5SDimitry Andric                   .local_fd = STDIN_FILENO,
4750b57cec5SDimitry Andric                   .target_fd = STDIN_FILENO,
4760b57cec5SDimitry Andric               },
4770b57cec5SDimitry Andric       },
4780b57cec5SDimitry Andric       {
4790b57cec5SDimitry Andric           .action = FDIO_SPAWN_ACTION_CLONE_FD,
4800b57cec5SDimitry Andric           .fd =
4810b57cec5SDimitry Andric               {
4820b57cec5SDimitry Andric                   .local_fd = FdOut,
4830b57cec5SDimitry Andric                   .target_fd = STDOUT_FILENO,
4840b57cec5SDimitry Andric               },
4850b57cec5SDimitry Andric       },
4860b57cec5SDimitry Andric       {
4870b57cec5SDimitry Andric           .action = FDIO_SPAWN_ACTION_CLONE_FD,
4880b57cec5SDimitry Andric           .fd =
4890b57cec5SDimitry Andric               {
4900b57cec5SDimitry Andric                   .local_fd = FdErr,
4910b57cec5SDimitry Andric                   .target_fd = STDERR_FILENO,
4920b57cec5SDimitry Andric               },
4930b57cec5SDimitry Andric       },
4940b57cec5SDimitry Andric   };
4950b57cec5SDimitry Andric 
4960b57cec5SDimitry Andric   // Start the process.
4970b57cec5SDimitry Andric   char ErrorMsg[FDIO_SPAWN_ERR_MSG_MAX_LENGTH];
4980b57cec5SDimitry Andric   zx_handle_t ProcessHandle = ZX_HANDLE_INVALID;
4990b57cec5SDimitry Andric   rc = fdio_spawn_etc(
5000b57cec5SDimitry Andric       ZX_HANDLE_INVALID, FDIO_SPAWN_CLONE_ALL & (~FDIO_SPAWN_CLONE_STDIO),
5010b57cec5SDimitry Andric       Argv[0], Argv.get(), nullptr, 3, SpawnAction, &ProcessHandle, ErrorMsg);
5020b57cec5SDimitry Andric   if (rc != ZX_OK) {
5030b57cec5SDimitry Andric     Printf("libFuzzer: failed to launch '%s': %s, %s\n", Argv[0], ErrorMsg,
5040b57cec5SDimitry Andric            _zx_status_get_string(rc));
5050b57cec5SDimitry Andric     return rc;
5060b57cec5SDimitry Andric   }
5070b57cec5SDimitry Andric   auto CloseHandle = at_scope_exit([&]() { _zx_handle_close(ProcessHandle); });
5080b57cec5SDimitry Andric 
5090b57cec5SDimitry Andric   // Now join the process and return the exit status.
5100b57cec5SDimitry Andric   if ((rc = _zx_object_wait_one(ProcessHandle, ZX_PROCESS_TERMINATED,
5110b57cec5SDimitry Andric                                 ZX_TIME_INFINITE, nullptr)) != ZX_OK) {
5120b57cec5SDimitry Andric     Printf("libFuzzer: failed to join '%s': %s\n", Argv[0],
5130b57cec5SDimitry Andric            _zx_status_get_string(rc));
5140b57cec5SDimitry Andric     return rc;
5150b57cec5SDimitry Andric   }
5160b57cec5SDimitry Andric 
5170b57cec5SDimitry Andric   zx_info_process_t Info;
5180b57cec5SDimitry Andric   if ((rc = _zx_object_get_info(ProcessHandle, ZX_INFO_PROCESS, &Info,
5190b57cec5SDimitry Andric                                 sizeof(Info), nullptr, nullptr)) != ZX_OK) {
5200b57cec5SDimitry Andric     Printf("libFuzzer: unable to get return code from '%s': %s\n", Argv[0],
5210b57cec5SDimitry Andric            _zx_status_get_string(rc));
5220b57cec5SDimitry Andric     return rc;
5230b57cec5SDimitry Andric   }
5240b57cec5SDimitry Andric 
5250b57cec5SDimitry Andric   return Info.return_code;
5260b57cec5SDimitry Andric }
5270b57cec5SDimitry Andric 
5280b57cec5SDimitry Andric const void *SearchMemory(const void *Data, size_t DataLen, const void *Patt,
5290b57cec5SDimitry Andric                          size_t PattLen) {
5300b57cec5SDimitry Andric   return memmem(Data, DataLen, Patt, PattLen);
5310b57cec5SDimitry Andric }
5320b57cec5SDimitry Andric 
533*480093f4SDimitry Andric // In fuchsia, accessing /dev/null is not supported. There's nothing
534*480093f4SDimitry Andric // similar to a file that discards everything that is written to it.
535*480093f4SDimitry Andric // The way of doing something similar in fuchsia is by using
536*480093f4SDimitry Andric // fdio_null_create and binding that to a file descriptor.
537*480093f4SDimitry Andric void DiscardOutput(int Fd) {
538*480093f4SDimitry Andric   fdio_t *fdio_null = fdio_null_create();
539*480093f4SDimitry Andric   if (fdio_null == nullptr) return;
540*480093f4SDimitry Andric   int nullfd = fdio_bind_to_fd(fdio_null, -1, 0);
541*480093f4SDimitry Andric   if (nullfd < 0) return;
542*480093f4SDimitry Andric   dup2(nullfd, Fd);
543*480093f4SDimitry Andric }
544*480093f4SDimitry Andric 
5450b57cec5SDimitry Andric } // namespace fuzzer
5460b57cec5SDimitry Andric 
5470b57cec5SDimitry Andric #endif // LIBFUZZER_FUCHSIA
548