xref: /freebsd/contrib/llvm-project/compiler-rt/lib/fuzzer/FuzzerUtilFuchsia.cpp (revision e8d8bef961a50d4dc22501cde4fb9fb0be1b2532)
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 
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 
71480093f4SDimitry Andric // CFAOffset is used to reference the stack pointer before entering the
72480093f4SDimitry Andric // trampoline (Stack Pointer + CFAOffset = prev Stack Pointer). Before jumping
73480093f4SDimitry Andric // to the trampoline we copy all the registers onto the stack. We need to make
74480093f4SDimitry Andric // sure that the new stack has enough space to store all the registers.
75480093f4SDimitry Andric //
76480093f4SDimitry Andric // The trampoline holds CFI information regarding the registers stored in the
77480093f4SDimitry Andric // stack, which is then used by the unwinder to restore them.
78480093f4SDimitry Andric #if defined(__x86_64__)
79480093f4SDimitry Andric // In x86_64 the crashing function might also be using the red zone (128 bytes
80480093f4SDimitry Andric // on top of their rsp).
81480093f4SDimitry Andric constexpr size_t CFAOffset = 128 + sizeof(zx_thread_state_general_regs_t);
82480093f4SDimitry Andric #elif defined(__aarch64__)
83480093f4SDimitry Andric // In aarch64 we need to always have the stack pointer aligned to 16 bytes, so we
84480093f4SDimitry Andric // make sure that we are keeping that same alignment.
85480093f4SDimitry Andric constexpr size_t CFAOffset = (sizeof(zx_thread_state_general_regs_t) + 15) & -(uintptr_t)16;
86480093f4SDimitry Andric #endif
87480093f4SDimitry Andric 
880b57cec5SDimitry Andric // For the crash handler, we need to call Fuzzer::StaticCrashSignalCallback
890b57cec5SDimitry Andric // without POSIX signal handlers.  To achieve this, we use an assembly function
900b57cec5SDimitry Andric // to add the necessary CFI unwinding information and a C function to bridge
910b57cec5SDimitry Andric // from that back into C++.
920b57cec5SDimitry Andric 
930b57cec5SDimitry Andric // FIXME: This works as a short-term solution, but this code really shouldn't be
940b57cec5SDimitry Andric // architecture dependent. A better long term solution is to implement remote
950b57cec5SDimitry Andric // unwinding and expose the necessary APIs through sanitizer_common and/or ASAN
960b57cec5SDimitry Andric // to allow the exception handling thread to gather the crash state directly.
970b57cec5SDimitry Andric //
980b57cec5SDimitry Andric // Alternatively, Fuchsia may in future actually implement basic signal
990b57cec5SDimitry Andric // handling for the machine trap signals.
1000b57cec5SDimitry Andric #if defined(__x86_64__)
1010b57cec5SDimitry Andric #define FOREACH_REGISTER(OP_REG, OP_NUM) \
1020b57cec5SDimitry Andric   OP_REG(rax)                            \
1030b57cec5SDimitry Andric   OP_REG(rbx)                            \
1040b57cec5SDimitry Andric   OP_REG(rcx)                            \
1050b57cec5SDimitry Andric   OP_REG(rdx)                            \
1060b57cec5SDimitry Andric   OP_REG(rsi)                            \
1070b57cec5SDimitry Andric   OP_REG(rdi)                            \
1080b57cec5SDimitry Andric   OP_REG(rbp)                            \
1090b57cec5SDimitry Andric   OP_REG(rsp)                            \
1100b57cec5SDimitry Andric   OP_REG(r8)                             \
1110b57cec5SDimitry Andric   OP_REG(r9)                             \
1120b57cec5SDimitry Andric   OP_REG(r10)                            \
1130b57cec5SDimitry Andric   OP_REG(r11)                            \
1140b57cec5SDimitry Andric   OP_REG(r12)                            \
1150b57cec5SDimitry Andric   OP_REG(r13)                            \
1160b57cec5SDimitry Andric   OP_REG(r14)                            \
1170b57cec5SDimitry Andric   OP_REG(r15)                            \
1180b57cec5SDimitry Andric   OP_REG(rip)
1190b57cec5SDimitry Andric 
1200b57cec5SDimitry Andric #elif defined(__aarch64__)
1210b57cec5SDimitry Andric #define FOREACH_REGISTER(OP_REG, OP_NUM) \
1220b57cec5SDimitry Andric   OP_NUM(0)                              \
1230b57cec5SDimitry Andric   OP_NUM(1)                              \
1240b57cec5SDimitry Andric   OP_NUM(2)                              \
1250b57cec5SDimitry Andric   OP_NUM(3)                              \
1260b57cec5SDimitry Andric   OP_NUM(4)                              \
1270b57cec5SDimitry Andric   OP_NUM(5)                              \
1280b57cec5SDimitry Andric   OP_NUM(6)                              \
1290b57cec5SDimitry Andric   OP_NUM(7)                              \
1300b57cec5SDimitry Andric   OP_NUM(8)                              \
1310b57cec5SDimitry Andric   OP_NUM(9)                              \
1320b57cec5SDimitry Andric   OP_NUM(10)                             \
1330b57cec5SDimitry Andric   OP_NUM(11)                             \
1340b57cec5SDimitry Andric   OP_NUM(12)                             \
1350b57cec5SDimitry Andric   OP_NUM(13)                             \
1360b57cec5SDimitry Andric   OP_NUM(14)                             \
1370b57cec5SDimitry Andric   OP_NUM(15)                             \
1380b57cec5SDimitry Andric   OP_NUM(16)                             \
1390b57cec5SDimitry Andric   OP_NUM(17)                             \
1400b57cec5SDimitry Andric   OP_NUM(18)                             \
1410b57cec5SDimitry Andric   OP_NUM(19)                             \
1420b57cec5SDimitry Andric   OP_NUM(20)                             \
1430b57cec5SDimitry Andric   OP_NUM(21)                             \
1440b57cec5SDimitry Andric   OP_NUM(22)                             \
1450b57cec5SDimitry Andric   OP_NUM(23)                             \
1460b57cec5SDimitry Andric   OP_NUM(24)                             \
1470b57cec5SDimitry Andric   OP_NUM(25)                             \
1480b57cec5SDimitry Andric   OP_NUM(26)                             \
1490b57cec5SDimitry Andric   OP_NUM(27)                             \
1500b57cec5SDimitry Andric   OP_NUM(28)                             \
1510b57cec5SDimitry Andric   OP_NUM(29)                             \
1520b57cec5SDimitry Andric   OP_REG(sp)
1530b57cec5SDimitry Andric 
1540b57cec5SDimitry Andric #else
1550b57cec5SDimitry Andric #error "Unsupported architecture for fuzzing on Fuchsia"
1560b57cec5SDimitry Andric #endif
1570b57cec5SDimitry Andric 
1580b57cec5SDimitry Andric // Produces a CFI directive for the named or numbered register.
159480093f4SDimitry Andric // The value used refers to an assembler immediate operand with the same name
160480093f4SDimitry Andric // as the register (see ASM_OPERAND_REG).
1610b57cec5SDimitry Andric #define CFI_OFFSET_REG(reg) ".cfi_offset " #reg ", %c[" #reg "]\n"
162480093f4SDimitry Andric #define CFI_OFFSET_NUM(num) CFI_OFFSET_REG(x##num)
1630b57cec5SDimitry Andric 
164480093f4SDimitry Andric // Produces an assembler immediate operand for the named or numbered register.
165480093f4SDimitry Andric // This operand contains the offset of the register relative to the CFA.
1660b57cec5SDimitry Andric #define ASM_OPERAND_REG(reg) \
167480093f4SDimitry Andric   [reg] "i"(offsetof(zx_thread_state_general_regs_t, reg) - CFAOffset),
1680b57cec5SDimitry Andric #define ASM_OPERAND_NUM(num)                                 \
169480093f4SDimitry Andric   [x##num] "i"(offsetof(zx_thread_state_general_regs_t, r[num]) - CFAOffset),
1700b57cec5SDimitry Andric 
1710b57cec5SDimitry Andric // Trampoline to bridge from the assembly below to the static C++ crash
1720b57cec5SDimitry Andric // callback.
1730b57cec5SDimitry Andric __attribute__((noreturn))
1740b57cec5SDimitry Andric static void StaticCrashHandler() {
1750b57cec5SDimitry Andric   Fuzzer::StaticCrashSignalCallback();
1760b57cec5SDimitry Andric   for (;;) {
1770b57cec5SDimitry Andric     _Exit(1);
1780b57cec5SDimitry Andric   }
1790b57cec5SDimitry Andric }
1800b57cec5SDimitry Andric 
1810b57cec5SDimitry Andric // Creates the trampoline with the necessary CFI information to unwind through
182480093f4SDimitry Andric // to the crashing call stack:
183480093f4SDimitry Andric //  * Defining the CFA so that it points to the stack pointer at the point
184480093f4SDimitry Andric //    of crash.
185480093f4SDimitry Andric //  * Storing all registers at the point of crash in the stack and refer to them
186480093f4SDimitry Andric //    via CFI information (relative to the CFA).
187480093f4SDimitry Andric //  * Setting the return column so the unwinder knows how to continue unwinding.
188480093f4SDimitry Andric //  * (x86_64) making sure rsp is aligned before calling StaticCrashHandler.
189480093f4SDimitry Andric //  * Calling StaticCrashHandler that will trigger the unwinder.
190480093f4SDimitry Andric //
191480093f4SDimitry Andric // The __attribute__((used)) is necessary because the function
1920b57cec5SDimitry Andric // is never called; it's just a container around the assembly to allow it to
1930b57cec5SDimitry Andric // use operands for compile-time computed constants.
1940b57cec5SDimitry Andric __attribute__((used))
1950b57cec5SDimitry Andric void MakeTrampoline() {
1960b57cec5SDimitry Andric   __asm__(".cfi_endproc\n"
1970b57cec5SDimitry Andric     ".pushsection .text.CrashTrampolineAsm\n"
1980b57cec5SDimitry Andric     ".type CrashTrampolineAsm,STT_FUNC\n"
1990b57cec5SDimitry Andric "CrashTrampolineAsm:\n"
2000b57cec5SDimitry Andric     ".cfi_startproc simple\n"
2010b57cec5SDimitry Andric     ".cfi_signal_frame\n"
2020b57cec5SDimitry Andric #if defined(__x86_64__)
2030b57cec5SDimitry Andric     ".cfi_return_column rip\n"
204480093f4SDimitry Andric     ".cfi_def_cfa rsp, %c[CFAOffset]\n"
2050b57cec5SDimitry Andric     FOREACH_REGISTER(CFI_OFFSET_REG, CFI_OFFSET_NUM)
206480093f4SDimitry Andric     "mov %%rsp, %%rbp\n"
207480093f4SDimitry Andric     ".cfi_def_cfa_register rbp\n"
208480093f4SDimitry Andric     "andq $-16, %%rsp\n"
2090b57cec5SDimitry Andric     "call %c[StaticCrashHandler]\n"
2100b57cec5SDimitry Andric     "ud2\n"
2110b57cec5SDimitry Andric #elif defined(__aarch64__)
2120b57cec5SDimitry Andric     ".cfi_return_column 33\n"
213480093f4SDimitry Andric     ".cfi_def_cfa sp, %c[CFAOffset]\n"
2140b57cec5SDimitry Andric     FOREACH_REGISTER(CFI_OFFSET_REG, CFI_OFFSET_NUM)
215480093f4SDimitry Andric     ".cfi_offset 33, %c[pc]\n"
216480093f4SDimitry Andric     ".cfi_offset 30, %c[lr]\n"
217480093f4SDimitry Andric     "bl %c[StaticCrashHandler]\n"
218480093f4SDimitry Andric     "brk 1\n"
2190b57cec5SDimitry Andric #else
2200b57cec5SDimitry Andric #error "Unsupported architecture for fuzzing on Fuchsia"
2210b57cec5SDimitry Andric #endif
2220b57cec5SDimitry Andric     ".cfi_endproc\n"
2230b57cec5SDimitry Andric     ".size CrashTrampolineAsm, . - CrashTrampolineAsm\n"
2240b57cec5SDimitry Andric     ".popsection\n"
2250b57cec5SDimitry Andric     ".cfi_startproc\n"
2260b57cec5SDimitry Andric     : // No outputs
2270b57cec5SDimitry Andric     : FOREACH_REGISTER(ASM_OPERAND_REG, ASM_OPERAND_NUM)
2280b57cec5SDimitry Andric #if defined(__aarch64__)
2290b57cec5SDimitry Andric       ASM_OPERAND_REG(pc)
230480093f4SDimitry Andric       ASM_OPERAND_REG(lr)
2310b57cec5SDimitry Andric #endif
232480093f4SDimitry Andric       [StaticCrashHandler] "i" (StaticCrashHandler),
233480093f4SDimitry Andric       [CFAOffset] "i" (CFAOffset));
2340b57cec5SDimitry Andric }
2350b57cec5SDimitry Andric 
2360b57cec5SDimitry Andric void CrashHandler(zx_handle_t *Event) {
2370b57cec5SDimitry Andric   // This structure is used to ensure we close handles to objects we create in
2380b57cec5SDimitry Andric   // this handler.
2390b57cec5SDimitry Andric   struct ScopedHandle {
2400b57cec5SDimitry Andric     ~ScopedHandle() { _zx_handle_close(Handle); }
2410b57cec5SDimitry Andric     zx_handle_t Handle = ZX_HANDLE_INVALID;
2420b57cec5SDimitry Andric   };
2430b57cec5SDimitry Andric 
2440b57cec5SDimitry Andric   // Create the exception channel.  We need to claim to be a "debugger" so the
2450b57cec5SDimitry Andric   // kernel will allow us to modify and resume dying threads (see below). Once
2460b57cec5SDimitry Andric   // the channel is set, we can signal the main thread to continue and wait
2470b57cec5SDimitry Andric   // for the exception to arrive.
2480b57cec5SDimitry Andric   ScopedHandle Channel;
2490b57cec5SDimitry Andric   zx_handle_t Self = _zx_process_self();
2500b57cec5SDimitry Andric   ExitOnErr(_zx_task_create_exception_channel(
2510b57cec5SDimitry Andric                 Self, ZX_EXCEPTION_CHANNEL_DEBUGGER, &Channel.Handle),
2520b57cec5SDimitry Andric             "_zx_task_create_exception_channel");
2530b57cec5SDimitry Andric 
2540b57cec5SDimitry Andric   ExitOnErr(_zx_object_signal(*Event, 0, ZX_USER_SIGNAL_0),
2550b57cec5SDimitry Andric             "_zx_object_signal");
2560b57cec5SDimitry Andric 
2570b57cec5SDimitry Andric   // This thread lives as long as the process in order to keep handling
2580b57cec5SDimitry Andric   // crashes.  In practice, the first crashed thread to reach the end of the
2590b57cec5SDimitry Andric   // StaticCrashHandler will end the process.
2600b57cec5SDimitry Andric   while (true) {
2610b57cec5SDimitry Andric     ExitOnErr(_zx_object_wait_one(Channel.Handle, ZX_CHANNEL_READABLE,
2620b57cec5SDimitry Andric                                   ZX_TIME_INFINITE, nullptr),
2630b57cec5SDimitry Andric               "_zx_object_wait_one");
2640b57cec5SDimitry Andric 
2650b57cec5SDimitry Andric     zx_exception_info_t ExceptionInfo;
2660b57cec5SDimitry Andric     ScopedHandle Exception;
2670b57cec5SDimitry Andric     ExitOnErr(_zx_channel_read(Channel.Handle, 0, &ExceptionInfo,
2680b57cec5SDimitry Andric                                &Exception.Handle, sizeof(ExceptionInfo), 1,
2690b57cec5SDimitry Andric                                nullptr, nullptr),
2700b57cec5SDimitry Andric               "_zx_channel_read");
2710b57cec5SDimitry Andric 
2720b57cec5SDimitry Andric     // Ignore informational synthetic exceptions.
2730b57cec5SDimitry Andric     if (ZX_EXCP_THREAD_STARTING == ExceptionInfo.type ||
2740b57cec5SDimitry Andric         ZX_EXCP_THREAD_EXITING == ExceptionInfo.type ||
2750b57cec5SDimitry Andric         ZX_EXCP_PROCESS_STARTING == ExceptionInfo.type) {
2760b57cec5SDimitry Andric       continue;
2770b57cec5SDimitry Andric     }
2780b57cec5SDimitry Andric 
2790b57cec5SDimitry Andric     // At this point, we want to get the state of the crashing thread, but
2800b57cec5SDimitry Andric     // libFuzzer and the sanitizers assume this will happen from that same
2810b57cec5SDimitry Andric     // thread via a POSIX signal handler. "Resurrecting" the thread in the
2820b57cec5SDimitry Andric     // middle of the appropriate callback is as simple as forcibly setting the
2830b57cec5SDimitry Andric     // instruction pointer/program counter, provided we NEVER EVER return from
2840b57cec5SDimitry Andric     // that function (since otherwise our stack will not be valid).
2850b57cec5SDimitry Andric     ScopedHandle Thread;
2860b57cec5SDimitry Andric     ExitOnErr(_zx_exception_get_thread(Exception.Handle, &Thread.Handle),
2870b57cec5SDimitry Andric               "_zx_exception_get_thread");
2880b57cec5SDimitry Andric 
2890b57cec5SDimitry Andric     zx_thread_state_general_regs_t GeneralRegisters;
2900b57cec5SDimitry Andric     ExitOnErr(_zx_thread_read_state(Thread.Handle, ZX_THREAD_STATE_GENERAL_REGS,
2910b57cec5SDimitry Andric                                     &GeneralRegisters,
2920b57cec5SDimitry Andric                                     sizeof(GeneralRegisters)),
2930b57cec5SDimitry Andric               "_zx_thread_read_state");
2940b57cec5SDimitry Andric 
2950b57cec5SDimitry Andric     // To unwind properly, we need to push the crashing thread's register state
2960b57cec5SDimitry Andric     // onto the stack and jump into a trampoline with CFI instructions on how
2970b57cec5SDimitry Andric     // to restore it.
2980b57cec5SDimitry Andric #if defined(__x86_64__)
299480093f4SDimitry Andric     uintptr_t StackPtr = GeneralRegisters.rsp - CFAOffset;
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__)
306480093f4SDimitry Andric     uintptr_t StackPtr = GeneralRegisters.sp - CFAOffset;
3070b57cec5SDimitry Andric     __unsanitized_memcpy(reinterpret_cast<void *>(StackPtr), &GeneralRegisters,
3080b57cec5SDimitry Andric                          sizeof(GeneralRegisters));
3090b57cec5SDimitry Andric     GeneralRegisters.sp = StackPtr;
3100b57cec5SDimitry Andric     GeneralRegisters.pc = reinterpret_cast<zx_vaddr_t>(CrashTrampolineAsm);
3110b57cec5SDimitry Andric 
3120b57cec5SDimitry Andric #else
3130b57cec5SDimitry Andric #error "Unsupported architecture for fuzzing on Fuchsia"
3140b57cec5SDimitry Andric #endif
3150b57cec5SDimitry Andric 
3160b57cec5SDimitry Andric     // Now force the crashing thread's state.
3170b57cec5SDimitry Andric     ExitOnErr(
3180b57cec5SDimitry Andric         _zx_thread_write_state(Thread.Handle, ZX_THREAD_STATE_GENERAL_REGS,
3190b57cec5SDimitry Andric                                &GeneralRegisters, sizeof(GeneralRegisters)),
3200b57cec5SDimitry Andric         "_zx_thread_write_state");
3210b57cec5SDimitry Andric 
3220b57cec5SDimitry Andric     // Set the exception to HANDLED so it resumes the thread on close.
3230b57cec5SDimitry Andric     uint32_t ExceptionState = ZX_EXCEPTION_STATE_HANDLED;
3240b57cec5SDimitry Andric     ExitOnErr(_zx_object_set_property(Exception.Handle, ZX_PROP_EXCEPTION_STATE,
3250b57cec5SDimitry Andric                                       &ExceptionState, sizeof(ExceptionState)),
3260b57cec5SDimitry Andric               "zx_object_set_property");
3270b57cec5SDimitry Andric   }
3280b57cec5SDimitry Andric }
3290b57cec5SDimitry Andric 
3300b57cec5SDimitry Andric } // namespace
3310b57cec5SDimitry Andric 
3320b57cec5SDimitry Andric // Platform specific functions.
3330b57cec5SDimitry Andric void SetSignalHandler(const FuzzingOptions &Options) {
33468d75effSDimitry Andric   // Make sure information from libFuzzer and the sanitizers are easy to
33568d75effSDimitry Andric   // reassemble. `__sanitizer_log_write` has the added benefit of ensuring the
33668d75effSDimitry Andric   // DSO map is always available for the symbolizer.
33768d75effSDimitry Andric   // A uint64_t fits in 20 chars, so 64 is plenty.
33868d75effSDimitry Andric   char Buf[64];
33968d75effSDimitry Andric   memset(Buf, 0, sizeof(Buf));
34068d75effSDimitry Andric   snprintf(Buf, sizeof(Buf), "==%lu== INFO: libFuzzer starting.\n", GetPid());
34168d75effSDimitry Andric   if (EF->__sanitizer_log_write)
34268d75effSDimitry Andric     __sanitizer_log_write(Buf, sizeof(Buf));
34368d75effSDimitry Andric   Printf("%s", Buf);
34468d75effSDimitry Andric 
3450b57cec5SDimitry Andric   // Set up alarm handler if needed.
346*e8d8bef9SDimitry Andric   if (Options.HandleAlrm && Options.UnitTimeoutSec > 0) {
3470b57cec5SDimitry Andric     std::thread T(AlarmHandler, Options.UnitTimeoutSec / 2 + 1);
3480b57cec5SDimitry Andric     T.detach();
3490b57cec5SDimitry Andric   }
3500b57cec5SDimitry Andric 
351*e8d8bef9SDimitry Andric   // Options.HandleInt and Options.HandleTerm are not supported on Fuchsia
3520b57cec5SDimitry Andric 
3530b57cec5SDimitry Andric   // Early exit if no crash handler needed.
3540b57cec5SDimitry Andric   if (!Options.HandleSegv && !Options.HandleBus && !Options.HandleIll &&
3550b57cec5SDimitry Andric       !Options.HandleFpe && !Options.HandleAbrt)
3560b57cec5SDimitry Andric     return;
3570b57cec5SDimitry Andric 
3580b57cec5SDimitry Andric   // Set up the crash handler and wait until it is ready before proceeding.
3590b57cec5SDimitry Andric   zx_handle_t Event;
3600b57cec5SDimitry Andric   ExitOnErr(_zx_event_create(0, &Event), "_zx_event_create");
3610b57cec5SDimitry Andric 
3620b57cec5SDimitry Andric   std::thread T(CrashHandler, &Event);
3630b57cec5SDimitry Andric   zx_status_t Status =
3640b57cec5SDimitry Andric       _zx_object_wait_one(Event, ZX_USER_SIGNAL_0, ZX_TIME_INFINITE, nullptr);
3650b57cec5SDimitry Andric   _zx_handle_close(Event);
3660b57cec5SDimitry Andric   ExitOnErr(Status, "_zx_object_wait_one");
3670b57cec5SDimitry Andric 
3680b57cec5SDimitry Andric   T.detach();
3690b57cec5SDimitry Andric }
3700b57cec5SDimitry Andric 
3710b57cec5SDimitry Andric void SleepSeconds(int Seconds) {
3720b57cec5SDimitry Andric   _zx_nanosleep(_zx_deadline_after(ZX_SEC(Seconds)));
3730b57cec5SDimitry Andric }
3740b57cec5SDimitry Andric 
3750b57cec5SDimitry Andric unsigned long GetPid() {
3760b57cec5SDimitry Andric   zx_status_t rc;
3770b57cec5SDimitry Andric   zx_info_handle_basic_t Info;
3780b57cec5SDimitry Andric   if ((rc = _zx_object_get_info(_zx_process_self(), ZX_INFO_HANDLE_BASIC, &Info,
3790b57cec5SDimitry Andric                                 sizeof(Info), NULL, NULL)) != ZX_OK) {
3800b57cec5SDimitry Andric     Printf("libFuzzer: unable to get info about self: %s\n",
3810b57cec5SDimitry Andric            _zx_status_get_string(rc));
3820b57cec5SDimitry Andric     exit(1);
3830b57cec5SDimitry Andric   }
3840b57cec5SDimitry Andric   return Info.koid;
3850b57cec5SDimitry Andric }
3860b57cec5SDimitry Andric 
3870b57cec5SDimitry Andric size_t GetPeakRSSMb() {
3880b57cec5SDimitry Andric   zx_status_t rc;
3890b57cec5SDimitry Andric   zx_info_task_stats_t Info;
3900b57cec5SDimitry Andric   if ((rc = _zx_object_get_info(_zx_process_self(), ZX_INFO_TASK_STATS, &Info,
3910b57cec5SDimitry Andric                                 sizeof(Info), NULL, NULL)) != ZX_OK) {
3920b57cec5SDimitry Andric     Printf("libFuzzer: unable to get info about self: %s\n",
3930b57cec5SDimitry Andric            _zx_status_get_string(rc));
3940b57cec5SDimitry Andric     exit(1);
3950b57cec5SDimitry Andric   }
3960b57cec5SDimitry Andric   return (Info.mem_private_bytes + Info.mem_shared_bytes) >> 20;
3970b57cec5SDimitry Andric }
3980b57cec5SDimitry Andric 
3990b57cec5SDimitry Andric template <typename Fn>
4000b57cec5SDimitry Andric class RunOnDestruction {
4010b57cec5SDimitry Andric  public:
4020b57cec5SDimitry Andric   explicit RunOnDestruction(Fn fn) : fn_(fn) {}
4030b57cec5SDimitry Andric   ~RunOnDestruction() { fn_(); }
4040b57cec5SDimitry Andric 
4050b57cec5SDimitry Andric  private:
4060b57cec5SDimitry Andric   Fn fn_;
4070b57cec5SDimitry Andric };
4080b57cec5SDimitry Andric 
4090b57cec5SDimitry Andric template <typename Fn>
4100b57cec5SDimitry Andric RunOnDestruction<Fn> at_scope_exit(Fn fn) {
4110b57cec5SDimitry Andric   return RunOnDestruction<Fn>(fn);
4120b57cec5SDimitry Andric }
4130b57cec5SDimitry Andric 
4145ffd83dbSDimitry Andric static fdio_spawn_action_t clone_fd_action(int localFd, int targetFd) {
4155ffd83dbSDimitry Andric   return {
4165ffd83dbSDimitry Andric       .action = FDIO_SPAWN_ACTION_CLONE_FD,
4175ffd83dbSDimitry Andric       .fd =
4185ffd83dbSDimitry Andric           {
4195ffd83dbSDimitry Andric               .local_fd = localFd,
4205ffd83dbSDimitry Andric               .target_fd = targetFd,
4215ffd83dbSDimitry Andric           },
4225ffd83dbSDimitry Andric   };
4235ffd83dbSDimitry Andric }
4245ffd83dbSDimitry Andric 
4250b57cec5SDimitry Andric int ExecuteCommand(const Command &Cmd) {
4260b57cec5SDimitry Andric   zx_status_t rc;
4270b57cec5SDimitry Andric 
4280b57cec5SDimitry Andric   // Convert arguments to C array
4290b57cec5SDimitry Andric   auto Args = Cmd.getArguments();
4300b57cec5SDimitry Andric   size_t Argc = Args.size();
4310b57cec5SDimitry Andric   assert(Argc != 0);
4320b57cec5SDimitry Andric   std::unique_ptr<const char *[]> Argv(new const char *[Argc + 1]);
4330b57cec5SDimitry Andric   for (size_t i = 0; i < Argc; ++i)
4340b57cec5SDimitry Andric     Argv[i] = Args[i].c_str();
4350b57cec5SDimitry Andric   Argv[Argc] = nullptr;
4360b57cec5SDimitry Andric 
4370b57cec5SDimitry Andric   // Determine output.  On Fuchsia, the fuzzer is typically run as a component
4380b57cec5SDimitry Andric   // that lacks a mutable working directory. Fortunately, when this is the case
4390b57cec5SDimitry Andric   // a mutable output directory must be specified using "-artifact_prefix=...",
4400b57cec5SDimitry Andric   // so write the log file(s) there.
44168d75effSDimitry Andric   // However, we don't want to apply this logic for absolute paths.
4420b57cec5SDimitry Andric   int FdOut = STDOUT_FILENO;
4435ffd83dbSDimitry Andric   bool discardStdout = false;
4445ffd83dbSDimitry Andric   bool discardStderr = false;
4455ffd83dbSDimitry Andric 
4460b57cec5SDimitry Andric   if (Cmd.hasOutputFile()) {
44768d75effSDimitry Andric     std::string Path = Cmd.getOutputFile();
4485ffd83dbSDimitry Andric     if (Path == getDevNull()) {
4495ffd83dbSDimitry Andric       // On Fuchsia, there's no "/dev/null" like-file, so we
4505ffd83dbSDimitry Andric       // just don't copy the FDs into the spawned process.
4515ffd83dbSDimitry Andric       discardStdout = true;
4525ffd83dbSDimitry Andric     } else {
45368d75effSDimitry Andric       bool IsAbsolutePath = Path.length() > 1 && Path[0] == '/';
45468d75effSDimitry Andric       if (!IsAbsolutePath && Cmd.hasFlag("artifact_prefix"))
45568d75effSDimitry Andric         Path = Cmd.getFlagValue("artifact_prefix") + "/" + Path;
45668d75effSDimitry Andric 
4570b57cec5SDimitry Andric       FdOut = open(Path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0);
4580b57cec5SDimitry Andric       if (FdOut == -1) {
4590b57cec5SDimitry Andric         Printf("libFuzzer: failed to open %s: %s\n", Path.c_str(),
4600b57cec5SDimitry Andric                strerror(errno));
4610b57cec5SDimitry Andric         return ZX_ERR_IO;
4620b57cec5SDimitry Andric       }
4630b57cec5SDimitry Andric     }
4645ffd83dbSDimitry Andric   }
4650b57cec5SDimitry Andric   auto CloseFdOut = at_scope_exit([FdOut]() {
4660b57cec5SDimitry Andric     if (FdOut != STDOUT_FILENO)
4670b57cec5SDimitry Andric       close(FdOut);
4680b57cec5SDimitry Andric   });
4690b57cec5SDimitry Andric 
4700b57cec5SDimitry Andric   // Determine stderr
4710b57cec5SDimitry Andric   int FdErr = STDERR_FILENO;
4725ffd83dbSDimitry Andric   if (Cmd.isOutAndErrCombined()) {
4730b57cec5SDimitry Andric     FdErr = FdOut;
4745ffd83dbSDimitry Andric     if (discardStdout)
4755ffd83dbSDimitry Andric       discardStderr = true;
4765ffd83dbSDimitry Andric   }
4770b57cec5SDimitry Andric 
4780b57cec5SDimitry Andric   // Clone the file descriptors into the new process
4795ffd83dbSDimitry Andric   std::vector<fdio_spawn_action_t> SpawnActions;
4805ffd83dbSDimitry Andric   SpawnActions.push_back(clone_fd_action(STDIN_FILENO, STDIN_FILENO));
4815ffd83dbSDimitry Andric 
4825ffd83dbSDimitry Andric   if (!discardStdout)
4835ffd83dbSDimitry Andric     SpawnActions.push_back(clone_fd_action(FdOut, STDOUT_FILENO));
4845ffd83dbSDimitry Andric   if (!discardStderr)
4855ffd83dbSDimitry Andric     SpawnActions.push_back(clone_fd_action(FdErr, STDERR_FILENO));
4860b57cec5SDimitry Andric 
4870b57cec5SDimitry Andric   // Start the process.
4880b57cec5SDimitry Andric   char ErrorMsg[FDIO_SPAWN_ERR_MSG_MAX_LENGTH];
4890b57cec5SDimitry Andric   zx_handle_t ProcessHandle = ZX_HANDLE_INVALID;
4905ffd83dbSDimitry Andric   rc = fdio_spawn_etc(ZX_HANDLE_INVALID,
4915ffd83dbSDimitry Andric                       FDIO_SPAWN_CLONE_ALL & (~FDIO_SPAWN_CLONE_STDIO), Argv[0],
4925ffd83dbSDimitry Andric                       Argv.get(), nullptr, SpawnActions.size(),
4935ffd83dbSDimitry Andric                       SpawnActions.data(), &ProcessHandle, ErrorMsg);
4945ffd83dbSDimitry Andric 
4950b57cec5SDimitry Andric   if (rc != ZX_OK) {
4960b57cec5SDimitry Andric     Printf("libFuzzer: failed to launch '%s': %s, %s\n", Argv[0], ErrorMsg,
4970b57cec5SDimitry Andric            _zx_status_get_string(rc));
4980b57cec5SDimitry Andric     return rc;
4990b57cec5SDimitry Andric   }
5000b57cec5SDimitry Andric   auto CloseHandle = at_scope_exit([&]() { _zx_handle_close(ProcessHandle); });
5010b57cec5SDimitry Andric 
5020b57cec5SDimitry Andric   // Now join the process and return the exit status.
5030b57cec5SDimitry Andric   if ((rc = _zx_object_wait_one(ProcessHandle, ZX_PROCESS_TERMINATED,
5040b57cec5SDimitry Andric                                 ZX_TIME_INFINITE, nullptr)) != ZX_OK) {
5050b57cec5SDimitry Andric     Printf("libFuzzer: failed to join '%s': %s\n", Argv[0],
5060b57cec5SDimitry Andric            _zx_status_get_string(rc));
5070b57cec5SDimitry Andric     return rc;
5080b57cec5SDimitry Andric   }
5090b57cec5SDimitry Andric 
5100b57cec5SDimitry Andric   zx_info_process_t Info;
5110b57cec5SDimitry Andric   if ((rc = _zx_object_get_info(ProcessHandle, ZX_INFO_PROCESS, &Info,
5120b57cec5SDimitry Andric                                 sizeof(Info), nullptr, nullptr)) != ZX_OK) {
5130b57cec5SDimitry Andric     Printf("libFuzzer: unable to get return code from '%s': %s\n", Argv[0],
5140b57cec5SDimitry Andric            _zx_status_get_string(rc));
5150b57cec5SDimitry Andric     return rc;
5160b57cec5SDimitry Andric   }
5170b57cec5SDimitry Andric 
5180b57cec5SDimitry Andric   return Info.return_code;
5190b57cec5SDimitry Andric }
5200b57cec5SDimitry Andric 
5215ffd83dbSDimitry Andric bool ExecuteCommand(const Command &BaseCmd, std::string *CmdOutput) {
5225ffd83dbSDimitry Andric   auto LogFilePath = TempPath("SimPopenOut", ".txt");
5235ffd83dbSDimitry Andric   Command Cmd(BaseCmd);
5245ffd83dbSDimitry Andric   Cmd.setOutputFile(LogFilePath);
5255ffd83dbSDimitry Andric   int Ret = ExecuteCommand(Cmd);
5265ffd83dbSDimitry Andric   *CmdOutput = FileToString(LogFilePath);
5275ffd83dbSDimitry Andric   RemoveFile(LogFilePath);
5285ffd83dbSDimitry Andric   return Ret == 0;
5295ffd83dbSDimitry Andric }
5305ffd83dbSDimitry Andric 
5310b57cec5SDimitry Andric const void *SearchMemory(const void *Data, size_t DataLen, const void *Patt,
5320b57cec5SDimitry Andric                          size_t PattLen) {
5330b57cec5SDimitry Andric   return memmem(Data, DataLen, Patt, PattLen);
5340b57cec5SDimitry Andric }
5350b57cec5SDimitry Andric 
536480093f4SDimitry Andric // In fuchsia, accessing /dev/null is not supported. There's nothing
537480093f4SDimitry Andric // similar to a file that discards everything that is written to it.
538480093f4SDimitry Andric // The way of doing something similar in fuchsia is by using
539480093f4SDimitry Andric // fdio_null_create and binding that to a file descriptor.
540480093f4SDimitry Andric void DiscardOutput(int Fd) {
541480093f4SDimitry Andric   fdio_t *fdio_null = fdio_null_create();
542480093f4SDimitry Andric   if (fdio_null == nullptr) return;
543480093f4SDimitry Andric   int nullfd = fdio_bind_to_fd(fdio_null, -1, 0);
544480093f4SDimitry Andric   if (nullfd < 0) return;
545480093f4SDimitry Andric   dup2(nullfd, Fd);
546480093f4SDimitry Andric }
547480093f4SDimitry Andric 
5480b57cec5SDimitry Andric } // namespace fuzzer
5490b57cec5SDimitry Andric 
5500b57cec5SDimitry Andric #endif // LIBFUZZER_FUCHSIA
551