xref: /freebsd/contrib/llvm-project/compiler-rt/lib/fuzzer/FuzzerUtilFuchsia.cpp (revision 5ffd83dbcc34f10e07f6d3e968ae6365869615f4)
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 //===----------------------------------------------------------------------===//
10*5ffd83dbSDimitry 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 
37*5ffd83dbSDimitry Andric #include <vector>
38*5ffd83dbSDimitry 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 
550b57cec5SDimitry Andric // Helper function to handle Zircon syscall failures.
560b57cec5SDimitry Andric void ExitOnErr(zx_status_t Status, const char *Syscall) {
570b57cec5SDimitry Andric   if (Status != ZX_OK) {
580b57cec5SDimitry Andric     Printf("libFuzzer: %s failed: %s\n", Syscall,
590b57cec5SDimitry Andric            _zx_status_get_string(Status));
600b57cec5SDimitry Andric     exit(1);
610b57cec5SDimitry Andric   }
620b57cec5SDimitry Andric }
630b57cec5SDimitry Andric 
640b57cec5SDimitry Andric void AlarmHandler(int Seconds) {
650b57cec5SDimitry Andric   while (true) {
660b57cec5SDimitry Andric     SleepSeconds(Seconds);
670b57cec5SDimitry Andric     Fuzzer::StaticAlarmCallback();
680b57cec5SDimitry Andric   }
690b57cec5SDimitry Andric }
700b57cec5SDimitry Andric 
710b57cec5SDimitry Andric void InterruptHandler() {
720b57cec5SDimitry Andric   fd_set readfds;
730b57cec5SDimitry Andric   // Ctrl-C sends ETX in Zircon.
740b57cec5SDimitry Andric   do {
750b57cec5SDimitry Andric     FD_ZERO(&readfds);
760b57cec5SDimitry Andric     FD_SET(STDIN_FILENO, &readfds);
770b57cec5SDimitry Andric     select(STDIN_FILENO + 1, &readfds, nullptr, nullptr, nullptr);
780b57cec5SDimitry Andric   } while(!FD_ISSET(STDIN_FILENO, &readfds) || getchar() != 0x03);
790b57cec5SDimitry Andric   Fuzzer::StaticInterruptCallback();
800b57cec5SDimitry Andric }
810b57cec5SDimitry Andric 
82480093f4SDimitry Andric // CFAOffset is used to reference the stack pointer before entering the
83480093f4SDimitry Andric // trampoline (Stack Pointer + CFAOffset = prev Stack Pointer). Before jumping
84480093f4SDimitry Andric // to the trampoline we copy all the registers onto the stack. We need to make
85480093f4SDimitry Andric // sure that the new stack has enough space to store all the registers.
86480093f4SDimitry Andric //
87480093f4SDimitry Andric // The trampoline holds CFI information regarding the registers stored in the
88480093f4SDimitry Andric // stack, which is then used by the unwinder to restore them.
89480093f4SDimitry Andric #if defined(__x86_64__)
90480093f4SDimitry Andric // In x86_64 the crashing function might also be using the red zone (128 bytes
91480093f4SDimitry Andric // on top of their rsp).
92480093f4SDimitry Andric constexpr size_t CFAOffset = 128 + sizeof(zx_thread_state_general_regs_t);
93480093f4SDimitry Andric #elif defined(__aarch64__)
94480093f4SDimitry Andric // In aarch64 we need to always have the stack pointer aligned to 16 bytes, so we
95480093f4SDimitry Andric // make sure that we are keeping that same alignment.
96480093f4SDimitry Andric constexpr size_t CFAOffset = (sizeof(zx_thread_state_general_regs_t) + 15) & -(uintptr_t)16;
97480093f4SDimitry Andric #endif
98480093f4SDimitry Andric 
990b57cec5SDimitry Andric // For the crash handler, we need to call Fuzzer::StaticCrashSignalCallback
1000b57cec5SDimitry Andric // without POSIX signal handlers.  To achieve this, we use an assembly function
1010b57cec5SDimitry Andric // to add the necessary CFI unwinding information and a C function to bridge
1020b57cec5SDimitry Andric // from that back into C++.
1030b57cec5SDimitry Andric 
1040b57cec5SDimitry Andric // FIXME: This works as a short-term solution, but this code really shouldn't be
1050b57cec5SDimitry Andric // architecture dependent. A better long term solution is to implement remote
1060b57cec5SDimitry Andric // unwinding and expose the necessary APIs through sanitizer_common and/or ASAN
1070b57cec5SDimitry Andric // to allow the exception handling thread to gather the crash state directly.
1080b57cec5SDimitry Andric //
1090b57cec5SDimitry Andric // Alternatively, Fuchsia may in future actually implement basic signal
1100b57cec5SDimitry Andric // handling for the machine trap signals.
1110b57cec5SDimitry Andric #if defined(__x86_64__)
1120b57cec5SDimitry Andric #define FOREACH_REGISTER(OP_REG, OP_NUM) \
1130b57cec5SDimitry Andric   OP_REG(rax)                            \
1140b57cec5SDimitry Andric   OP_REG(rbx)                            \
1150b57cec5SDimitry Andric   OP_REG(rcx)                            \
1160b57cec5SDimitry Andric   OP_REG(rdx)                            \
1170b57cec5SDimitry Andric   OP_REG(rsi)                            \
1180b57cec5SDimitry Andric   OP_REG(rdi)                            \
1190b57cec5SDimitry Andric   OP_REG(rbp)                            \
1200b57cec5SDimitry Andric   OP_REG(rsp)                            \
1210b57cec5SDimitry Andric   OP_REG(r8)                             \
1220b57cec5SDimitry Andric   OP_REG(r9)                             \
1230b57cec5SDimitry Andric   OP_REG(r10)                            \
1240b57cec5SDimitry Andric   OP_REG(r11)                            \
1250b57cec5SDimitry Andric   OP_REG(r12)                            \
1260b57cec5SDimitry Andric   OP_REG(r13)                            \
1270b57cec5SDimitry Andric   OP_REG(r14)                            \
1280b57cec5SDimitry Andric   OP_REG(r15)                            \
1290b57cec5SDimitry Andric   OP_REG(rip)
1300b57cec5SDimitry Andric 
1310b57cec5SDimitry Andric #elif defined(__aarch64__)
1320b57cec5SDimitry Andric #define FOREACH_REGISTER(OP_REG, OP_NUM) \
1330b57cec5SDimitry Andric   OP_NUM(0)                              \
1340b57cec5SDimitry Andric   OP_NUM(1)                              \
1350b57cec5SDimitry Andric   OP_NUM(2)                              \
1360b57cec5SDimitry Andric   OP_NUM(3)                              \
1370b57cec5SDimitry Andric   OP_NUM(4)                              \
1380b57cec5SDimitry Andric   OP_NUM(5)                              \
1390b57cec5SDimitry Andric   OP_NUM(6)                              \
1400b57cec5SDimitry Andric   OP_NUM(7)                              \
1410b57cec5SDimitry Andric   OP_NUM(8)                              \
1420b57cec5SDimitry Andric   OP_NUM(9)                              \
1430b57cec5SDimitry Andric   OP_NUM(10)                             \
1440b57cec5SDimitry Andric   OP_NUM(11)                             \
1450b57cec5SDimitry Andric   OP_NUM(12)                             \
1460b57cec5SDimitry Andric   OP_NUM(13)                             \
1470b57cec5SDimitry Andric   OP_NUM(14)                             \
1480b57cec5SDimitry Andric   OP_NUM(15)                             \
1490b57cec5SDimitry Andric   OP_NUM(16)                             \
1500b57cec5SDimitry Andric   OP_NUM(17)                             \
1510b57cec5SDimitry Andric   OP_NUM(18)                             \
1520b57cec5SDimitry Andric   OP_NUM(19)                             \
1530b57cec5SDimitry Andric   OP_NUM(20)                             \
1540b57cec5SDimitry Andric   OP_NUM(21)                             \
1550b57cec5SDimitry Andric   OP_NUM(22)                             \
1560b57cec5SDimitry Andric   OP_NUM(23)                             \
1570b57cec5SDimitry Andric   OP_NUM(24)                             \
1580b57cec5SDimitry Andric   OP_NUM(25)                             \
1590b57cec5SDimitry Andric   OP_NUM(26)                             \
1600b57cec5SDimitry Andric   OP_NUM(27)                             \
1610b57cec5SDimitry Andric   OP_NUM(28)                             \
1620b57cec5SDimitry Andric   OP_NUM(29)                             \
1630b57cec5SDimitry Andric   OP_REG(sp)
1640b57cec5SDimitry Andric 
1650b57cec5SDimitry Andric #else
1660b57cec5SDimitry Andric #error "Unsupported architecture for fuzzing on Fuchsia"
1670b57cec5SDimitry Andric #endif
1680b57cec5SDimitry Andric 
1690b57cec5SDimitry Andric // Produces a CFI directive for the named or numbered register.
170480093f4SDimitry Andric // The value used refers to an assembler immediate operand with the same name
171480093f4SDimitry Andric // as the register (see ASM_OPERAND_REG).
1720b57cec5SDimitry Andric #define CFI_OFFSET_REG(reg) ".cfi_offset " #reg ", %c[" #reg "]\n"
173480093f4SDimitry Andric #define CFI_OFFSET_NUM(num) CFI_OFFSET_REG(x##num)
1740b57cec5SDimitry Andric 
175480093f4SDimitry Andric // Produces an assembler immediate operand for the named or numbered register.
176480093f4SDimitry Andric // This operand contains the offset of the register relative to the CFA.
1770b57cec5SDimitry Andric #define ASM_OPERAND_REG(reg) \
178480093f4SDimitry Andric   [reg] "i"(offsetof(zx_thread_state_general_regs_t, reg) - CFAOffset),
1790b57cec5SDimitry Andric #define ASM_OPERAND_NUM(num)                                 \
180480093f4SDimitry Andric   [x##num] "i"(offsetof(zx_thread_state_general_regs_t, r[num]) - CFAOffset),
1810b57cec5SDimitry Andric 
1820b57cec5SDimitry Andric // Trampoline to bridge from the assembly below to the static C++ crash
1830b57cec5SDimitry Andric // callback.
1840b57cec5SDimitry Andric __attribute__((noreturn))
1850b57cec5SDimitry Andric static void StaticCrashHandler() {
1860b57cec5SDimitry Andric   Fuzzer::StaticCrashSignalCallback();
1870b57cec5SDimitry Andric   for (;;) {
1880b57cec5SDimitry Andric     _Exit(1);
1890b57cec5SDimitry Andric   }
1900b57cec5SDimitry Andric }
1910b57cec5SDimitry Andric 
1920b57cec5SDimitry Andric // Creates the trampoline with the necessary CFI information to unwind through
193480093f4SDimitry Andric // to the crashing call stack:
194480093f4SDimitry Andric //  * Defining the CFA so that it points to the stack pointer at the point
195480093f4SDimitry Andric //    of crash.
196480093f4SDimitry Andric //  * Storing all registers at the point of crash in the stack and refer to them
197480093f4SDimitry Andric //    via CFI information (relative to the CFA).
198480093f4SDimitry Andric //  * Setting the return column so the unwinder knows how to continue unwinding.
199480093f4SDimitry Andric //  * (x86_64) making sure rsp is aligned before calling StaticCrashHandler.
200480093f4SDimitry Andric //  * Calling StaticCrashHandler that will trigger the unwinder.
201480093f4SDimitry Andric //
202480093f4SDimitry Andric // The __attribute__((used)) is necessary because the function
2030b57cec5SDimitry Andric // is never called; it's just a container around the assembly to allow it to
2040b57cec5SDimitry Andric // use operands for compile-time computed constants.
2050b57cec5SDimitry Andric __attribute__((used))
2060b57cec5SDimitry Andric void MakeTrampoline() {
2070b57cec5SDimitry Andric   __asm__(".cfi_endproc\n"
2080b57cec5SDimitry Andric     ".pushsection .text.CrashTrampolineAsm\n"
2090b57cec5SDimitry Andric     ".type CrashTrampolineAsm,STT_FUNC\n"
2100b57cec5SDimitry Andric "CrashTrampolineAsm:\n"
2110b57cec5SDimitry Andric     ".cfi_startproc simple\n"
2120b57cec5SDimitry Andric     ".cfi_signal_frame\n"
2130b57cec5SDimitry Andric #if defined(__x86_64__)
2140b57cec5SDimitry Andric     ".cfi_return_column rip\n"
215480093f4SDimitry Andric     ".cfi_def_cfa rsp, %c[CFAOffset]\n"
2160b57cec5SDimitry Andric     FOREACH_REGISTER(CFI_OFFSET_REG, CFI_OFFSET_NUM)
217480093f4SDimitry Andric     "mov %%rsp, %%rbp\n"
218480093f4SDimitry Andric     ".cfi_def_cfa_register rbp\n"
219480093f4SDimitry Andric     "andq $-16, %%rsp\n"
2200b57cec5SDimitry Andric     "call %c[StaticCrashHandler]\n"
2210b57cec5SDimitry Andric     "ud2\n"
2220b57cec5SDimitry Andric #elif defined(__aarch64__)
2230b57cec5SDimitry Andric     ".cfi_return_column 33\n"
224480093f4SDimitry Andric     ".cfi_def_cfa sp, %c[CFAOffset]\n"
2250b57cec5SDimitry Andric     FOREACH_REGISTER(CFI_OFFSET_REG, CFI_OFFSET_NUM)
226480093f4SDimitry Andric     ".cfi_offset 33, %c[pc]\n"
227480093f4SDimitry Andric     ".cfi_offset 30, %c[lr]\n"
228480093f4SDimitry Andric     "bl %c[StaticCrashHandler]\n"
229480093f4SDimitry Andric     "brk 1\n"
2300b57cec5SDimitry Andric #else
2310b57cec5SDimitry Andric #error "Unsupported architecture for fuzzing on Fuchsia"
2320b57cec5SDimitry Andric #endif
2330b57cec5SDimitry Andric     ".cfi_endproc\n"
2340b57cec5SDimitry Andric     ".size CrashTrampolineAsm, . - CrashTrampolineAsm\n"
2350b57cec5SDimitry Andric     ".popsection\n"
2360b57cec5SDimitry Andric     ".cfi_startproc\n"
2370b57cec5SDimitry Andric     : // No outputs
2380b57cec5SDimitry Andric     : FOREACH_REGISTER(ASM_OPERAND_REG, ASM_OPERAND_NUM)
2390b57cec5SDimitry Andric #if defined(__aarch64__)
2400b57cec5SDimitry Andric       ASM_OPERAND_REG(pc)
241480093f4SDimitry Andric       ASM_OPERAND_REG(lr)
2420b57cec5SDimitry Andric #endif
243480093f4SDimitry Andric       [StaticCrashHandler] "i" (StaticCrashHandler),
244480093f4SDimitry Andric       [CFAOffset] "i" (CFAOffset));
2450b57cec5SDimitry Andric }
2460b57cec5SDimitry Andric 
2470b57cec5SDimitry Andric void CrashHandler(zx_handle_t *Event) {
2480b57cec5SDimitry Andric   // This structure is used to ensure we close handles to objects we create in
2490b57cec5SDimitry Andric   // this handler.
2500b57cec5SDimitry Andric   struct ScopedHandle {
2510b57cec5SDimitry Andric     ~ScopedHandle() { _zx_handle_close(Handle); }
2520b57cec5SDimitry Andric     zx_handle_t Handle = ZX_HANDLE_INVALID;
2530b57cec5SDimitry Andric   };
2540b57cec5SDimitry Andric 
2550b57cec5SDimitry Andric   // Create the exception channel.  We need to claim to be a "debugger" so the
2560b57cec5SDimitry Andric   // kernel will allow us to modify and resume dying threads (see below). Once
2570b57cec5SDimitry Andric   // the channel is set, we can signal the main thread to continue and wait
2580b57cec5SDimitry Andric   // for the exception to arrive.
2590b57cec5SDimitry Andric   ScopedHandle Channel;
2600b57cec5SDimitry Andric   zx_handle_t Self = _zx_process_self();
2610b57cec5SDimitry Andric   ExitOnErr(_zx_task_create_exception_channel(
2620b57cec5SDimitry Andric                 Self, ZX_EXCEPTION_CHANNEL_DEBUGGER, &Channel.Handle),
2630b57cec5SDimitry Andric             "_zx_task_create_exception_channel");
2640b57cec5SDimitry Andric 
2650b57cec5SDimitry Andric   ExitOnErr(_zx_object_signal(*Event, 0, ZX_USER_SIGNAL_0),
2660b57cec5SDimitry Andric             "_zx_object_signal");
2670b57cec5SDimitry Andric 
2680b57cec5SDimitry Andric   // This thread lives as long as the process in order to keep handling
2690b57cec5SDimitry Andric   // crashes.  In practice, the first crashed thread to reach the end of the
2700b57cec5SDimitry Andric   // StaticCrashHandler will end the process.
2710b57cec5SDimitry Andric   while (true) {
2720b57cec5SDimitry Andric     ExitOnErr(_zx_object_wait_one(Channel.Handle, ZX_CHANNEL_READABLE,
2730b57cec5SDimitry Andric                                   ZX_TIME_INFINITE, nullptr),
2740b57cec5SDimitry Andric               "_zx_object_wait_one");
2750b57cec5SDimitry Andric 
2760b57cec5SDimitry Andric     zx_exception_info_t ExceptionInfo;
2770b57cec5SDimitry Andric     ScopedHandle Exception;
2780b57cec5SDimitry Andric     ExitOnErr(_zx_channel_read(Channel.Handle, 0, &ExceptionInfo,
2790b57cec5SDimitry Andric                                &Exception.Handle, sizeof(ExceptionInfo), 1,
2800b57cec5SDimitry Andric                                nullptr, nullptr),
2810b57cec5SDimitry Andric               "_zx_channel_read");
2820b57cec5SDimitry Andric 
2830b57cec5SDimitry Andric     // Ignore informational synthetic exceptions.
2840b57cec5SDimitry Andric     if (ZX_EXCP_THREAD_STARTING == ExceptionInfo.type ||
2850b57cec5SDimitry Andric         ZX_EXCP_THREAD_EXITING == ExceptionInfo.type ||
2860b57cec5SDimitry Andric         ZX_EXCP_PROCESS_STARTING == ExceptionInfo.type) {
2870b57cec5SDimitry Andric       continue;
2880b57cec5SDimitry Andric     }
2890b57cec5SDimitry Andric 
2900b57cec5SDimitry Andric     // At this point, we want to get the state of the crashing thread, but
2910b57cec5SDimitry Andric     // libFuzzer and the sanitizers assume this will happen from that same
2920b57cec5SDimitry Andric     // thread via a POSIX signal handler. "Resurrecting" the thread in the
2930b57cec5SDimitry Andric     // middle of the appropriate callback is as simple as forcibly setting the
2940b57cec5SDimitry Andric     // instruction pointer/program counter, provided we NEVER EVER return from
2950b57cec5SDimitry Andric     // that function (since otherwise our stack will not be valid).
2960b57cec5SDimitry Andric     ScopedHandle Thread;
2970b57cec5SDimitry Andric     ExitOnErr(_zx_exception_get_thread(Exception.Handle, &Thread.Handle),
2980b57cec5SDimitry Andric               "_zx_exception_get_thread");
2990b57cec5SDimitry Andric 
3000b57cec5SDimitry Andric     zx_thread_state_general_regs_t GeneralRegisters;
3010b57cec5SDimitry Andric     ExitOnErr(_zx_thread_read_state(Thread.Handle, ZX_THREAD_STATE_GENERAL_REGS,
3020b57cec5SDimitry Andric                                     &GeneralRegisters,
3030b57cec5SDimitry Andric                                     sizeof(GeneralRegisters)),
3040b57cec5SDimitry Andric               "_zx_thread_read_state");
3050b57cec5SDimitry Andric 
3060b57cec5SDimitry Andric     // To unwind properly, we need to push the crashing thread's register state
3070b57cec5SDimitry Andric     // onto the stack and jump into a trampoline with CFI instructions on how
3080b57cec5SDimitry Andric     // to restore it.
3090b57cec5SDimitry Andric #if defined(__x86_64__)
310480093f4SDimitry Andric     uintptr_t StackPtr = GeneralRegisters.rsp - CFAOffset;
3110b57cec5SDimitry Andric     __unsanitized_memcpy(reinterpret_cast<void *>(StackPtr), &GeneralRegisters,
3120b57cec5SDimitry Andric                          sizeof(GeneralRegisters));
3130b57cec5SDimitry Andric     GeneralRegisters.rsp = StackPtr;
3140b57cec5SDimitry Andric     GeneralRegisters.rip = reinterpret_cast<zx_vaddr_t>(CrashTrampolineAsm);
3150b57cec5SDimitry Andric 
3160b57cec5SDimitry Andric #elif defined(__aarch64__)
317480093f4SDimitry Andric     uintptr_t StackPtr = GeneralRegisters.sp - CFAOffset;
3180b57cec5SDimitry Andric     __unsanitized_memcpy(reinterpret_cast<void *>(StackPtr), &GeneralRegisters,
3190b57cec5SDimitry Andric                          sizeof(GeneralRegisters));
3200b57cec5SDimitry Andric     GeneralRegisters.sp = StackPtr;
3210b57cec5SDimitry Andric     GeneralRegisters.pc = reinterpret_cast<zx_vaddr_t>(CrashTrampolineAsm);
3220b57cec5SDimitry Andric 
3230b57cec5SDimitry Andric #else
3240b57cec5SDimitry Andric #error "Unsupported architecture for fuzzing on Fuchsia"
3250b57cec5SDimitry Andric #endif
3260b57cec5SDimitry Andric 
3270b57cec5SDimitry Andric     // Now force the crashing thread's state.
3280b57cec5SDimitry Andric     ExitOnErr(
3290b57cec5SDimitry Andric         _zx_thread_write_state(Thread.Handle, ZX_THREAD_STATE_GENERAL_REGS,
3300b57cec5SDimitry Andric                                &GeneralRegisters, sizeof(GeneralRegisters)),
3310b57cec5SDimitry Andric         "_zx_thread_write_state");
3320b57cec5SDimitry Andric 
3330b57cec5SDimitry Andric     // Set the exception to HANDLED so it resumes the thread on close.
3340b57cec5SDimitry Andric     uint32_t ExceptionState = ZX_EXCEPTION_STATE_HANDLED;
3350b57cec5SDimitry Andric     ExitOnErr(_zx_object_set_property(Exception.Handle, ZX_PROP_EXCEPTION_STATE,
3360b57cec5SDimitry Andric                                       &ExceptionState, sizeof(ExceptionState)),
3370b57cec5SDimitry Andric               "zx_object_set_property");
3380b57cec5SDimitry Andric   }
3390b57cec5SDimitry Andric }
3400b57cec5SDimitry Andric 
3410b57cec5SDimitry Andric } // namespace
3420b57cec5SDimitry Andric 
3430b57cec5SDimitry Andric // Platform specific functions.
3440b57cec5SDimitry Andric void SetSignalHandler(const FuzzingOptions &Options) {
34568d75effSDimitry Andric   // Make sure information from libFuzzer and the sanitizers are easy to
34668d75effSDimitry Andric   // reassemble. `__sanitizer_log_write` has the added benefit of ensuring the
34768d75effSDimitry Andric   // DSO map is always available for the symbolizer.
34868d75effSDimitry Andric   // A uint64_t fits in 20 chars, so 64 is plenty.
34968d75effSDimitry Andric   char Buf[64];
35068d75effSDimitry Andric   memset(Buf, 0, sizeof(Buf));
35168d75effSDimitry Andric   snprintf(Buf, sizeof(Buf), "==%lu== INFO: libFuzzer starting.\n", GetPid());
35268d75effSDimitry Andric   if (EF->__sanitizer_log_write)
35368d75effSDimitry Andric     __sanitizer_log_write(Buf, sizeof(Buf));
35468d75effSDimitry Andric   Printf("%s", Buf);
35568d75effSDimitry Andric 
3560b57cec5SDimitry Andric   // Set up alarm handler if needed.
3570b57cec5SDimitry Andric   if (Options.UnitTimeoutSec > 0) {
3580b57cec5SDimitry Andric     std::thread T(AlarmHandler, Options.UnitTimeoutSec / 2 + 1);
3590b57cec5SDimitry Andric     T.detach();
3600b57cec5SDimitry Andric   }
3610b57cec5SDimitry Andric 
3620b57cec5SDimitry Andric   // Set up interrupt handler if needed.
3630b57cec5SDimitry Andric   if (Options.HandleInt || Options.HandleTerm) {
3640b57cec5SDimitry Andric     std::thread T(InterruptHandler);
3650b57cec5SDimitry Andric     T.detach();
3660b57cec5SDimitry Andric   }
3670b57cec5SDimitry Andric 
3680b57cec5SDimitry Andric   // Early exit if no crash handler needed.
3690b57cec5SDimitry Andric   if (!Options.HandleSegv && !Options.HandleBus && !Options.HandleIll &&
3700b57cec5SDimitry Andric       !Options.HandleFpe && !Options.HandleAbrt)
3710b57cec5SDimitry Andric     return;
3720b57cec5SDimitry Andric 
3730b57cec5SDimitry Andric   // Set up the crash handler and wait until it is ready before proceeding.
3740b57cec5SDimitry Andric   zx_handle_t Event;
3750b57cec5SDimitry Andric   ExitOnErr(_zx_event_create(0, &Event), "_zx_event_create");
3760b57cec5SDimitry Andric 
3770b57cec5SDimitry Andric   std::thread T(CrashHandler, &Event);
3780b57cec5SDimitry Andric   zx_status_t Status =
3790b57cec5SDimitry Andric       _zx_object_wait_one(Event, ZX_USER_SIGNAL_0, ZX_TIME_INFINITE, nullptr);
3800b57cec5SDimitry Andric   _zx_handle_close(Event);
3810b57cec5SDimitry Andric   ExitOnErr(Status, "_zx_object_wait_one");
3820b57cec5SDimitry Andric 
3830b57cec5SDimitry Andric   T.detach();
3840b57cec5SDimitry Andric }
3850b57cec5SDimitry Andric 
3860b57cec5SDimitry Andric void SleepSeconds(int Seconds) {
3870b57cec5SDimitry Andric   _zx_nanosleep(_zx_deadline_after(ZX_SEC(Seconds)));
3880b57cec5SDimitry Andric }
3890b57cec5SDimitry Andric 
3900b57cec5SDimitry Andric unsigned long GetPid() {
3910b57cec5SDimitry Andric   zx_status_t rc;
3920b57cec5SDimitry Andric   zx_info_handle_basic_t Info;
3930b57cec5SDimitry Andric   if ((rc = _zx_object_get_info(_zx_process_self(), ZX_INFO_HANDLE_BASIC, &Info,
3940b57cec5SDimitry Andric                                 sizeof(Info), NULL, NULL)) != ZX_OK) {
3950b57cec5SDimitry Andric     Printf("libFuzzer: unable to get info about self: %s\n",
3960b57cec5SDimitry Andric            _zx_status_get_string(rc));
3970b57cec5SDimitry Andric     exit(1);
3980b57cec5SDimitry Andric   }
3990b57cec5SDimitry Andric   return Info.koid;
4000b57cec5SDimitry Andric }
4010b57cec5SDimitry Andric 
4020b57cec5SDimitry Andric size_t GetPeakRSSMb() {
4030b57cec5SDimitry Andric   zx_status_t rc;
4040b57cec5SDimitry Andric   zx_info_task_stats_t Info;
4050b57cec5SDimitry Andric   if ((rc = _zx_object_get_info(_zx_process_self(), ZX_INFO_TASK_STATS, &Info,
4060b57cec5SDimitry Andric                                 sizeof(Info), NULL, NULL)) != ZX_OK) {
4070b57cec5SDimitry Andric     Printf("libFuzzer: unable to get info about self: %s\n",
4080b57cec5SDimitry Andric            _zx_status_get_string(rc));
4090b57cec5SDimitry Andric     exit(1);
4100b57cec5SDimitry Andric   }
4110b57cec5SDimitry Andric   return (Info.mem_private_bytes + Info.mem_shared_bytes) >> 20;
4120b57cec5SDimitry Andric }
4130b57cec5SDimitry Andric 
4140b57cec5SDimitry Andric template <typename Fn>
4150b57cec5SDimitry Andric class RunOnDestruction {
4160b57cec5SDimitry Andric  public:
4170b57cec5SDimitry Andric   explicit RunOnDestruction(Fn fn) : fn_(fn) {}
4180b57cec5SDimitry Andric   ~RunOnDestruction() { fn_(); }
4190b57cec5SDimitry Andric 
4200b57cec5SDimitry Andric  private:
4210b57cec5SDimitry Andric   Fn fn_;
4220b57cec5SDimitry Andric };
4230b57cec5SDimitry Andric 
4240b57cec5SDimitry Andric template <typename Fn>
4250b57cec5SDimitry Andric RunOnDestruction<Fn> at_scope_exit(Fn fn) {
4260b57cec5SDimitry Andric   return RunOnDestruction<Fn>(fn);
4270b57cec5SDimitry Andric }
4280b57cec5SDimitry Andric 
429*5ffd83dbSDimitry Andric static fdio_spawn_action_t clone_fd_action(int localFd, int targetFd) {
430*5ffd83dbSDimitry Andric   return {
431*5ffd83dbSDimitry Andric       .action = FDIO_SPAWN_ACTION_CLONE_FD,
432*5ffd83dbSDimitry Andric       .fd =
433*5ffd83dbSDimitry Andric           {
434*5ffd83dbSDimitry Andric               .local_fd = localFd,
435*5ffd83dbSDimitry Andric               .target_fd = targetFd,
436*5ffd83dbSDimitry Andric           },
437*5ffd83dbSDimitry Andric   };
438*5ffd83dbSDimitry Andric }
439*5ffd83dbSDimitry Andric 
4400b57cec5SDimitry Andric int ExecuteCommand(const Command &Cmd) {
4410b57cec5SDimitry Andric   zx_status_t rc;
4420b57cec5SDimitry Andric 
4430b57cec5SDimitry Andric   // Convert arguments to C array
4440b57cec5SDimitry Andric   auto Args = Cmd.getArguments();
4450b57cec5SDimitry Andric   size_t Argc = Args.size();
4460b57cec5SDimitry Andric   assert(Argc != 0);
4470b57cec5SDimitry Andric   std::unique_ptr<const char *[]> Argv(new const char *[Argc + 1]);
4480b57cec5SDimitry Andric   for (size_t i = 0; i < Argc; ++i)
4490b57cec5SDimitry Andric     Argv[i] = Args[i].c_str();
4500b57cec5SDimitry Andric   Argv[Argc] = nullptr;
4510b57cec5SDimitry Andric 
4520b57cec5SDimitry Andric   // Determine output.  On Fuchsia, the fuzzer is typically run as a component
4530b57cec5SDimitry Andric   // that lacks a mutable working directory. Fortunately, when this is the case
4540b57cec5SDimitry Andric   // a mutable output directory must be specified using "-artifact_prefix=...",
4550b57cec5SDimitry Andric   // so write the log file(s) there.
45668d75effSDimitry Andric   // However, we don't want to apply this logic for absolute paths.
4570b57cec5SDimitry Andric   int FdOut = STDOUT_FILENO;
458*5ffd83dbSDimitry Andric   bool discardStdout = false;
459*5ffd83dbSDimitry Andric   bool discardStderr = false;
460*5ffd83dbSDimitry Andric 
4610b57cec5SDimitry Andric   if (Cmd.hasOutputFile()) {
46268d75effSDimitry Andric     std::string Path = Cmd.getOutputFile();
463*5ffd83dbSDimitry Andric     if (Path == getDevNull()) {
464*5ffd83dbSDimitry Andric       // On Fuchsia, there's no "/dev/null" like-file, so we
465*5ffd83dbSDimitry Andric       // just don't copy the FDs into the spawned process.
466*5ffd83dbSDimitry Andric       discardStdout = true;
467*5ffd83dbSDimitry Andric     } else {
46868d75effSDimitry Andric       bool IsAbsolutePath = Path.length() > 1 && Path[0] == '/';
46968d75effSDimitry Andric       if (!IsAbsolutePath && Cmd.hasFlag("artifact_prefix"))
47068d75effSDimitry Andric         Path = Cmd.getFlagValue("artifact_prefix") + "/" + Path;
47168d75effSDimitry Andric 
4720b57cec5SDimitry Andric       FdOut = open(Path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0);
4730b57cec5SDimitry Andric       if (FdOut == -1) {
4740b57cec5SDimitry Andric         Printf("libFuzzer: failed to open %s: %s\n", Path.c_str(),
4750b57cec5SDimitry Andric                strerror(errno));
4760b57cec5SDimitry Andric         return ZX_ERR_IO;
4770b57cec5SDimitry Andric       }
4780b57cec5SDimitry Andric     }
479*5ffd83dbSDimitry Andric   }
4800b57cec5SDimitry Andric   auto CloseFdOut = at_scope_exit([FdOut]() {
4810b57cec5SDimitry Andric     if (FdOut != STDOUT_FILENO)
4820b57cec5SDimitry Andric       close(FdOut);
4830b57cec5SDimitry Andric   });
4840b57cec5SDimitry Andric 
4850b57cec5SDimitry Andric   // Determine stderr
4860b57cec5SDimitry Andric   int FdErr = STDERR_FILENO;
487*5ffd83dbSDimitry Andric   if (Cmd.isOutAndErrCombined()) {
4880b57cec5SDimitry Andric     FdErr = FdOut;
489*5ffd83dbSDimitry Andric     if (discardStdout)
490*5ffd83dbSDimitry Andric       discardStderr = true;
491*5ffd83dbSDimitry Andric   }
4920b57cec5SDimitry Andric 
4930b57cec5SDimitry Andric   // Clone the file descriptors into the new process
494*5ffd83dbSDimitry Andric   std::vector<fdio_spawn_action_t> SpawnActions;
495*5ffd83dbSDimitry Andric   SpawnActions.push_back(clone_fd_action(STDIN_FILENO, STDIN_FILENO));
496*5ffd83dbSDimitry Andric 
497*5ffd83dbSDimitry Andric   if (!discardStdout)
498*5ffd83dbSDimitry Andric     SpawnActions.push_back(clone_fd_action(FdOut, STDOUT_FILENO));
499*5ffd83dbSDimitry Andric   if (!discardStderr)
500*5ffd83dbSDimitry Andric     SpawnActions.push_back(clone_fd_action(FdErr, STDERR_FILENO));
5010b57cec5SDimitry Andric 
5020b57cec5SDimitry Andric   // Start the process.
5030b57cec5SDimitry Andric   char ErrorMsg[FDIO_SPAWN_ERR_MSG_MAX_LENGTH];
5040b57cec5SDimitry Andric   zx_handle_t ProcessHandle = ZX_HANDLE_INVALID;
505*5ffd83dbSDimitry Andric   rc = fdio_spawn_etc(ZX_HANDLE_INVALID,
506*5ffd83dbSDimitry Andric                       FDIO_SPAWN_CLONE_ALL & (~FDIO_SPAWN_CLONE_STDIO), Argv[0],
507*5ffd83dbSDimitry Andric                       Argv.get(), nullptr, SpawnActions.size(),
508*5ffd83dbSDimitry Andric                       SpawnActions.data(), &ProcessHandle, ErrorMsg);
509*5ffd83dbSDimitry Andric 
5100b57cec5SDimitry Andric   if (rc != ZX_OK) {
5110b57cec5SDimitry Andric     Printf("libFuzzer: failed to launch '%s': %s, %s\n", Argv[0], ErrorMsg,
5120b57cec5SDimitry Andric            _zx_status_get_string(rc));
5130b57cec5SDimitry Andric     return rc;
5140b57cec5SDimitry Andric   }
5150b57cec5SDimitry Andric   auto CloseHandle = at_scope_exit([&]() { _zx_handle_close(ProcessHandle); });
5160b57cec5SDimitry Andric 
5170b57cec5SDimitry Andric   // Now join the process and return the exit status.
5180b57cec5SDimitry Andric   if ((rc = _zx_object_wait_one(ProcessHandle, ZX_PROCESS_TERMINATED,
5190b57cec5SDimitry Andric                                 ZX_TIME_INFINITE, nullptr)) != ZX_OK) {
5200b57cec5SDimitry Andric     Printf("libFuzzer: failed to join '%s': %s\n", Argv[0],
5210b57cec5SDimitry Andric            _zx_status_get_string(rc));
5220b57cec5SDimitry Andric     return rc;
5230b57cec5SDimitry Andric   }
5240b57cec5SDimitry Andric 
5250b57cec5SDimitry Andric   zx_info_process_t Info;
5260b57cec5SDimitry Andric   if ((rc = _zx_object_get_info(ProcessHandle, ZX_INFO_PROCESS, &Info,
5270b57cec5SDimitry Andric                                 sizeof(Info), nullptr, nullptr)) != ZX_OK) {
5280b57cec5SDimitry Andric     Printf("libFuzzer: unable to get return code from '%s': %s\n", Argv[0],
5290b57cec5SDimitry Andric            _zx_status_get_string(rc));
5300b57cec5SDimitry Andric     return rc;
5310b57cec5SDimitry Andric   }
5320b57cec5SDimitry Andric 
5330b57cec5SDimitry Andric   return Info.return_code;
5340b57cec5SDimitry Andric }
5350b57cec5SDimitry Andric 
536*5ffd83dbSDimitry Andric bool ExecuteCommand(const Command &BaseCmd, std::string *CmdOutput) {
537*5ffd83dbSDimitry Andric   auto LogFilePath = TempPath("SimPopenOut", ".txt");
538*5ffd83dbSDimitry Andric   Command Cmd(BaseCmd);
539*5ffd83dbSDimitry Andric   Cmd.setOutputFile(LogFilePath);
540*5ffd83dbSDimitry Andric   int Ret = ExecuteCommand(Cmd);
541*5ffd83dbSDimitry Andric   *CmdOutput = FileToString(LogFilePath);
542*5ffd83dbSDimitry Andric   RemoveFile(LogFilePath);
543*5ffd83dbSDimitry Andric   return Ret == 0;
544*5ffd83dbSDimitry Andric }
545*5ffd83dbSDimitry Andric 
5460b57cec5SDimitry Andric const void *SearchMemory(const void *Data, size_t DataLen, const void *Patt,
5470b57cec5SDimitry Andric                          size_t PattLen) {
5480b57cec5SDimitry Andric   return memmem(Data, DataLen, Patt, PattLen);
5490b57cec5SDimitry Andric }
5500b57cec5SDimitry Andric 
551480093f4SDimitry Andric // In fuchsia, accessing /dev/null is not supported. There's nothing
552480093f4SDimitry Andric // similar to a file that discards everything that is written to it.
553480093f4SDimitry Andric // The way of doing something similar in fuchsia is by using
554480093f4SDimitry Andric // fdio_null_create and binding that to a file descriptor.
555480093f4SDimitry Andric void DiscardOutput(int Fd) {
556480093f4SDimitry Andric   fdio_t *fdio_null = fdio_null_create();
557480093f4SDimitry Andric   if (fdio_null == nullptr) return;
558480093f4SDimitry Andric   int nullfd = fdio_bind_to_fd(fdio_null, -1, 0);
559480093f4SDimitry Andric   if (nullfd < 0) return;
560480093f4SDimitry Andric   dup2(nullfd, Fd);
561480093f4SDimitry Andric }
562480093f4SDimitry Andric 
5630b57cec5SDimitry Andric } // namespace fuzzer
5640b57cec5SDimitry Andric 
5650b57cec5SDimitry Andric #endif // LIBFUZZER_FUCHSIA
566