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
55349cc55cSDimitry Andric // The signal handler thread uses Zircon exceptions to resume crashed threads
56349cc55cSDimitry Andric // into libFuzzer's POSIX signal handlers. The associated event is used to
57349cc55cSDimitry Andric // signal when the thread is running, and when it should stop.
58349cc55cSDimitry Andric std::thread SignalHandler;
59349cc55cSDimitry Andric zx_handle_t SignalHandlerEvent = ZX_HANDLE_INVALID;
60349cc55cSDimitry Andric
610b57cec5SDimitry Andric // Helper function to handle Zircon syscall failures.
ExitOnErr(zx_status_t Status,const char * Syscall)620b57cec5SDimitry Andric void ExitOnErr(zx_status_t Status, const char *Syscall) {
630b57cec5SDimitry Andric if (Status != ZX_OK) {
640b57cec5SDimitry Andric Printf("libFuzzer: %s failed: %s\n", Syscall,
650b57cec5SDimitry Andric _zx_status_get_string(Status));
660b57cec5SDimitry Andric exit(1);
670b57cec5SDimitry Andric }
680b57cec5SDimitry Andric }
690b57cec5SDimitry Andric
AlarmHandler(int Seconds)700b57cec5SDimitry Andric void AlarmHandler(int Seconds) {
710b57cec5SDimitry Andric while (true) {
720b57cec5SDimitry Andric SleepSeconds(Seconds);
730b57cec5SDimitry Andric Fuzzer::StaticAlarmCallback();
740b57cec5SDimitry Andric }
750b57cec5SDimitry Andric }
760b57cec5SDimitry Andric
770b57cec5SDimitry Andric // For the crash handler, we need to call Fuzzer::StaticCrashSignalCallback
780b57cec5SDimitry Andric // without POSIX signal handlers. To achieve this, we use an assembly function
790b57cec5SDimitry Andric // to add the necessary CFI unwinding information and a C function to bridge
800b57cec5SDimitry Andric // from that back into C++.
810b57cec5SDimitry Andric
820b57cec5SDimitry Andric // FIXME: This works as a short-term solution, but this code really shouldn't be
830b57cec5SDimitry Andric // architecture dependent. A better long term solution is to implement remote
840b57cec5SDimitry Andric // unwinding and expose the necessary APIs through sanitizer_common and/or ASAN
850b57cec5SDimitry Andric // to allow the exception handling thread to gather the crash state directly.
860b57cec5SDimitry Andric //
870b57cec5SDimitry Andric // Alternatively, Fuchsia may in future actually implement basic signal
880b57cec5SDimitry Andric // handling for the machine trap signals.
890b57cec5SDimitry Andric #if defined(__x86_64__)
9006c3fb27SDimitry Andric
910b57cec5SDimitry Andric #define FOREACH_REGISTER(OP_REG, OP_NUM) \
920b57cec5SDimitry Andric OP_REG(rax) \
930b57cec5SDimitry Andric OP_REG(rbx) \
940b57cec5SDimitry Andric OP_REG(rcx) \
950b57cec5SDimitry Andric OP_REG(rdx) \
960b57cec5SDimitry Andric OP_REG(rsi) \
970b57cec5SDimitry Andric OP_REG(rdi) \
980b57cec5SDimitry Andric OP_REG(rbp) \
990b57cec5SDimitry Andric OP_REG(rsp) \
1000b57cec5SDimitry Andric OP_REG(r8) \
1010b57cec5SDimitry Andric OP_REG(r9) \
1020b57cec5SDimitry Andric OP_REG(r10) \
1030b57cec5SDimitry Andric OP_REG(r11) \
1040b57cec5SDimitry Andric OP_REG(r12) \
1050b57cec5SDimitry Andric OP_REG(r13) \
1060b57cec5SDimitry Andric OP_REG(r14) \
1070b57cec5SDimitry Andric OP_REG(r15) \
1080b57cec5SDimitry Andric OP_REG(rip)
1090b57cec5SDimitry Andric
1100b57cec5SDimitry Andric #elif defined(__aarch64__)
11106c3fb27SDimitry Andric
1120b57cec5SDimitry Andric #define FOREACH_REGISTER(OP_REG, OP_NUM) \
1130b57cec5SDimitry Andric OP_NUM(0) \
1140b57cec5SDimitry Andric OP_NUM(1) \
1150b57cec5SDimitry Andric OP_NUM(2) \
1160b57cec5SDimitry Andric OP_NUM(3) \
1170b57cec5SDimitry Andric OP_NUM(4) \
1180b57cec5SDimitry Andric OP_NUM(5) \
1190b57cec5SDimitry Andric OP_NUM(6) \
1200b57cec5SDimitry Andric OP_NUM(7) \
1210b57cec5SDimitry Andric OP_NUM(8) \
1220b57cec5SDimitry Andric OP_NUM(9) \
1230b57cec5SDimitry Andric OP_NUM(10) \
1240b57cec5SDimitry Andric OP_NUM(11) \
1250b57cec5SDimitry Andric OP_NUM(12) \
1260b57cec5SDimitry Andric OP_NUM(13) \
1270b57cec5SDimitry Andric OP_NUM(14) \
1280b57cec5SDimitry Andric OP_NUM(15) \
1290b57cec5SDimitry Andric OP_NUM(16) \
1300b57cec5SDimitry Andric OP_NUM(17) \
1310b57cec5SDimitry Andric OP_NUM(18) \
1320b57cec5SDimitry Andric OP_NUM(19) \
1330b57cec5SDimitry Andric OP_NUM(20) \
1340b57cec5SDimitry Andric OP_NUM(21) \
1350b57cec5SDimitry Andric OP_NUM(22) \
1360b57cec5SDimitry Andric OP_NUM(23) \
1370b57cec5SDimitry Andric OP_NUM(24) \
1380b57cec5SDimitry Andric OP_NUM(25) \
1390b57cec5SDimitry Andric OP_NUM(26) \
1400b57cec5SDimitry Andric OP_NUM(27) \
1410b57cec5SDimitry Andric OP_NUM(28) \
1420b57cec5SDimitry Andric OP_NUM(29) \
1430b57cec5SDimitry Andric OP_REG(sp)
1440b57cec5SDimitry Andric
14506c3fb27SDimitry Andric #elif defined(__riscv)
14606c3fb27SDimitry Andric
14706c3fb27SDimitry Andric #define FOREACH_REGISTER(OP_REG, OP_NUM) \
14806c3fb27SDimitry Andric OP_REG(ra) \
14906c3fb27SDimitry Andric OP_REG(sp) \
15006c3fb27SDimitry Andric OP_REG(gp) \
15106c3fb27SDimitry Andric OP_REG(tp) \
15206c3fb27SDimitry Andric OP_REG(t0) \
15306c3fb27SDimitry Andric OP_REG(t1) \
15406c3fb27SDimitry Andric OP_REG(t2) \
15506c3fb27SDimitry Andric OP_REG(s0) \
15606c3fb27SDimitry Andric OP_REG(s1) \
15706c3fb27SDimitry Andric OP_REG(a0) \
15806c3fb27SDimitry Andric OP_REG(a1) \
15906c3fb27SDimitry Andric OP_REG(a2) \
16006c3fb27SDimitry Andric OP_REG(a3) \
16106c3fb27SDimitry Andric OP_REG(a4) \
16206c3fb27SDimitry Andric OP_REG(a5) \
16306c3fb27SDimitry Andric OP_REG(a6) \
16406c3fb27SDimitry Andric OP_REG(a7) \
16506c3fb27SDimitry Andric OP_REG(s2) \
16606c3fb27SDimitry Andric OP_REG(s3) \
16706c3fb27SDimitry Andric OP_REG(s4) \
16806c3fb27SDimitry Andric OP_REG(s5) \
16906c3fb27SDimitry Andric OP_REG(s6) \
17006c3fb27SDimitry Andric OP_REG(s7) \
17106c3fb27SDimitry Andric OP_REG(s8) \
17206c3fb27SDimitry Andric OP_REG(s9) \
17306c3fb27SDimitry Andric OP_REG(s10) \
17406c3fb27SDimitry Andric OP_REG(s11) \
17506c3fb27SDimitry Andric OP_REG(t3) \
17606c3fb27SDimitry Andric OP_REG(t4) \
17706c3fb27SDimitry Andric OP_REG(t5) \
17806c3fb27SDimitry Andric OP_REG(t6) \
17906c3fb27SDimitry Andric
1800b57cec5SDimitry Andric #else
1810b57cec5SDimitry Andric #error "Unsupported architecture for fuzzing on Fuchsia"
1820b57cec5SDimitry Andric #endif
1830b57cec5SDimitry Andric
1840b57cec5SDimitry Andric // Produces a CFI directive for the named or numbered register.
185480093f4SDimitry Andric // The value used refers to an assembler immediate operand with the same name
186480093f4SDimitry Andric // as the register (see ASM_OPERAND_REG).
1870b57cec5SDimitry Andric #define CFI_OFFSET_REG(reg) ".cfi_offset " #reg ", %c[" #reg "]\n"
188480093f4SDimitry Andric #define CFI_OFFSET_NUM(num) CFI_OFFSET_REG(x##num)
1890b57cec5SDimitry Andric
190480093f4SDimitry Andric // Produces an assembler immediate operand for the named or numbered register.
191480093f4SDimitry Andric // This operand contains the offset of the register relative to the CFA.
1920b57cec5SDimitry Andric #define ASM_OPERAND_REG(reg) \
193349cc55cSDimitry Andric [reg] "i"(offsetof(zx_thread_state_general_regs_t, reg)),
1940b57cec5SDimitry Andric #define ASM_OPERAND_NUM(num) \
195349cc55cSDimitry Andric [x##num] "i"(offsetof(zx_thread_state_general_regs_t, r[num])),
1960b57cec5SDimitry Andric
1970b57cec5SDimitry Andric // Trampoline to bridge from the assembly below to the static C++ crash
1980b57cec5SDimitry Andric // callback.
1990b57cec5SDimitry Andric __attribute__((noreturn))
StaticCrashHandler()2000b57cec5SDimitry Andric static void StaticCrashHandler() {
2010b57cec5SDimitry Andric Fuzzer::StaticCrashSignalCallback();
2020b57cec5SDimitry Andric for (;;) {
2030b57cec5SDimitry Andric _Exit(1);
2040b57cec5SDimitry Andric }
2050b57cec5SDimitry Andric }
2060b57cec5SDimitry Andric
207349cc55cSDimitry Andric // This trampoline function has the necessary CFI information to unwind
208349cc55cSDimitry Andric // and get a backtrace:
209349cc55cSDimitry Andric // * The stack contains a copy of all the registers at the point of crash,
210349cc55cSDimitry Andric // the code has CFI directives specifying how to restore them.
211349cc55cSDimitry Andric // * A call to StaticCrashHandler, which will print the stacktrace and exit
212349cc55cSDimitry Andric // the fuzzer, generating a crash artifact.
213480093f4SDimitry Andric //
214480093f4SDimitry Andric // The __attribute__((used)) is necessary because the function
2150b57cec5SDimitry Andric // is never called; it's just a container around the assembly to allow it to
2160b57cec5SDimitry Andric // use operands for compile-time computed constants.
2170b57cec5SDimitry Andric __attribute__((used))
MakeTrampoline()2180b57cec5SDimitry Andric void MakeTrampoline() {
219349cc55cSDimitry Andric __asm__(
220349cc55cSDimitry Andric ".cfi_endproc\n"
2210b57cec5SDimitry Andric ".pushsection .text.CrashTrampolineAsm\n"
2220b57cec5SDimitry Andric ".type CrashTrampolineAsm,STT_FUNC\n"
2230b57cec5SDimitry Andric "CrashTrampolineAsm:\n"
2240b57cec5SDimitry Andric ".cfi_startproc simple\n"
2250b57cec5SDimitry Andric ".cfi_signal_frame\n"
2260b57cec5SDimitry Andric #if defined(__x86_64__)
2270b57cec5SDimitry Andric ".cfi_return_column rip\n"
228349cc55cSDimitry Andric ".cfi_def_cfa rsp, 0\n"
2290b57cec5SDimitry Andric FOREACH_REGISTER(CFI_OFFSET_REG, CFI_OFFSET_NUM)
2300b57cec5SDimitry Andric "call %c[StaticCrashHandler]\n"
2310b57cec5SDimitry Andric "ud2\n"
2320b57cec5SDimitry Andric #elif defined(__aarch64__)
2330b57cec5SDimitry Andric ".cfi_return_column 33\n"
234349cc55cSDimitry Andric ".cfi_def_cfa sp, 0\n"
2350b57cec5SDimitry Andric FOREACH_REGISTER(CFI_OFFSET_REG, CFI_OFFSET_NUM)
236480093f4SDimitry Andric ".cfi_offset 33, %c[pc]\n"
237480093f4SDimitry Andric ".cfi_offset 30, %c[lr]\n"
238480093f4SDimitry Andric "bl %c[StaticCrashHandler]\n"
239480093f4SDimitry Andric "brk 1\n"
24006c3fb27SDimitry Andric #elif defined(__riscv)
24106c3fb27SDimitry Andric ".cfi_return_column 64\n"
24206c3fb27SDimitry Andric ".cfi_def_cfa sp, 0\n"
24306c3fb27SDimitry Andric ".cfi_offset 64, %[pc]\n"
24406c3fb27SDimitry Andric FOREACH_REGISTER(CFI_OFFSET_REG, CFI_OFFSET_NUM)
24506c3fb27SDimitry Andric "call %c[StaticCrashHandler]\n"
24606c3fb27SDimitry Andric "unimp\n"
2470b57cec5SDimitry Andric #else
2480b57cec5SDimitry Andric #error "Unsupported architecture for fuzzing on Fuchsia"
2490b57cec5SDimitry Andric #endif
2500b57cec5SDimitry Andric ".cfi_endproc\n"
2510b57cec5SDimitry Andric ".size CrashTrampolineAsm, . - CrashTrampolineAsm\n"
2520b57cec5SDimitry Andric ".popsection\n"
2530b57cec5SDimitry Andric ".cfi_startproc\n"
2540b57cec5SDimitry Andric : // No outputs
2550b57cec5SDimitry Andric : FOREACH_REGISTER(ASM_OPERAND_REG, ASM_OPERAND_NUM)
25606c3fb27SDimitry Andric #if defined(__aarch64__) || defined(__riscv)
25706c3fb27SDimitry Andric ASM_OPERAND_REG(pc)
25806c3fb27SDimitry Andric #endif
2590b57cec5SDimitry Andric #if defined(__aarch64__)
26006c3fb27SDimitry Andric ASM_OPERAND_REG(lr)
2610b57cec5SDimitry Andric #endif
262349cc55cSDimitry Andric [StaticCrashHandler] "i"(StaticCrashHandler));
2630b57cec5SDimitry Andric }
2640b57cec5SDimitry Andric
CrashHandler()265349cc55cSDimitry Andric void CrashHandler() {
266349cc55cSDimitry Andric assert(SignalHandlerEvent != ZX_HANDLE_INVALID);
267349cc55cSDimitry Andric
2680b57cec5SDimitry Andric // This structure is used to ensure we close handles to objects we create in
2690b57cec5SDimitry Andric // this handler.
2700b57cec5SDimitry Andric struct ScopedHandle {
2710b57cec5SDimitry Andric ~ScopedHandle() { _zx_handle_close(Handle); }
2720b57cec5SDimitry Andric zx_handle_t Handle = ZX_HANDLE_INVALID;
2730b57cec5SDimitry Andric };
2740b57cec5SDimitry Andric
2750b57cec5SDimitry Andric // Create the exception channel. We need to claim to be a "debugger" so the
2760b57cec5SDimitry Andric // kernel will allow us to modify and resume dying threads (see below). Once
2770b57cec5SDimitry Andric // the channel is set, we can signal the main thread to continue and wait
2780b57cec5SDimitry Andric // for the exception to arrive.
2790b57cec5SDimitry Andric ScopedHandle Channel;
2800b57cec5SDimitry Andric zx_handle_t Self = _zx_process_self();
2810b57cec5SDimitry Andric ExitOnErr(_zx_task_create_exception_channel(
2820b57cec5SDimitry Andric Self, ZX_EXCEPTION_CHANNEL_DEBUGGER, &Channel.Handle),
2830b57cec5SDimitry Andric "_zx_task_create_exception_channel");
2840b57cec5SDimitry Andric
285349cc55cSDimitry Andric ExitOnErr(_zx_object_signal(SignalHandlerEvent, 0, ZX_USER_SIGNAL_0),
2860b57cec5SDimitry Andric "_zx_object_signal");
2870b57cec5SDimitry Andric
2880b57cec5SDimitry Andric // This thread lives as long as the process in order to keep handling
2890b57cec5SDimitry Andric // crashes. In practice, the first crashed thread to reach the end of the
2900b57cec5SDimitry Andric // StaticCrashHandler will end the process.
2910b57cec5SDimitry Andric while (true) {
292349cc55cSDimitry Andric zx_wait_item_t WaitItems[] = {
293349cc55cSDimitry Andric {
294349cc55cSDimitry Andric .handle = SignalHandlerEvent,
295*0fca6ea1SDimitry Andric .waitfor = ZX_USER_SIGNAL_1,
296349cc55cSDimitry Andric .pending = 0,
297349cc55cSDimitry Andric },
298349cc55cSDimitry Andric {
299349cc55cSDimitry Andric .handle = Channel.Handle,
300349cc55cSDimitry Andric .waitfor = ZX_CHANNEL_READABLE | ZX_CHANNEL_PEER_CLOSED,
301349cc55cSDimitry Andric .pending = 0,
302349cc55cSDimitry Andric },
303349cc55cSDimitry Andric };
304349cc55cSDimitry Andric auto Status = _zx_object_wait_many(
305349cc55cSDimitry Andric WaitItems, sizeof(WaitItems) / sizeof(WaitItems[0]), ZX_TIME_INFINITE);
306349cc55cSDimitry Andric if (Status != ZX_OK || (WaitItems[1].pending & ZX_CHANNEL_READABLE) == 0) {
307349cc55cSDimitry Andric break;
308349cc55cSDimitry Andric }
3090b57cec5SDimitry Andric
3100b57cec5SDimitry Andric zx_exception_info_t ExceptionInfo;
3110b57cec5SDimitry Andric ScopedHandle Exception;
3120b57cec5SDimitry Andric ExitOnErr(_zx_channel_read(Channel.Handle, 0, &ExceptionInfo,
3130b57cec5SDimitry Andric &Exception.Handle, sizeof(ExceptionInfo), 1,
3140b57cec5SDimitry Andric nullptr, nullptr),
3150b57cec5SDimitry Andric "_zx_channel_read");
3160b57cec5SDimitry Andric
3170b57cec5SDimitry Andric // Ignore informational synthetic exceptions.
3180b57cec5SDimitry Andric if (ZX_EXCP_THREAD_STARTING == ExceptionInfo.type ||
3190b57cec5SDimitry Andric ZX_EXCP_THREAD_EXITING == ExceptionInfo.type ||
3200b57cec5SDimitry Andric ZX_EXCP_PROCESS_STARTING == ExceptionInfo.type) {
3210b57cec5SDimitry Andric continue;
3220b57cec5SDimitry Andric }
3230b57cec5SDimitry Andric
3240b57cec5SDimitry Andric // At this point, we want to get the state of the crashing thread, but
3250b57cec5SDimitry Andric // libFuzzer and the sanitizers assume this will happen from that same
3260b57cec5SDimitry Andric // thread via a POSIX signal handler. "Resurrecting" the thread in the
3270b57cec5SDimitry Andric // middle of the appropriate callback is as simple as forcibly setting the
3280b57cec5SDimitry Andric // instruction pointer/program counter, provided we NEVER EVER return from
3290b57cec5SDimitry Andric // that function (since otherwise our stack will not be valid).
3300b57cec5SDimitry Andric ScopedHandle Thread;
3310b57cec5SDimitry Andric ExitOnErr(_zx_exception_get_thread(Exception.Handle, &Thread.Handle),
3320b57cec5SDimitry Andric "_zx_exception_get_thread");
3330b57cec5SDimitry Andric
3340b57cec5SDimitry Andric zx_thread_state_general_regs_t GeneralRegisters;
3350b57cec5SDimitry Andric ExitOnErr(_zx_thread_read_state(Thread.Handle, ZX_THREAD_STATE_GENERAL_REGS,
3360b57cec5SDimitry Andric &GeneralRegisters,
3370b57cec5SDimitry Andric sizeof(GeneralRegisters)),
3380b57cec5SDimitry Andric "_zx_thread_read_state");
3390b57cec5SDimitry Andric
3400b57cec5SDimitry Andric // To unwind properly, we need to push the crashing thread's register state
3410b57cec5SDimitry Andric // onto the stack and jump into a trampoline with CFI instructions on how
3420b57cec5SDimitry Andric // to restore it.
3430b57cec5SDimitry Andric #if defined(__x86_64__)
34406c3fb27SDimitry Andric
345349cc55cSDimitry Andric uintptr_t StackPtr =
346349cc55cSDimitry Andric (GeneralRegisters.rsp - (128 + sizeof(GeneralRegisters))) &
347349cc55cSDimitry Andric -(uintptr_t)16;
3480b57cec5SDimitry Andric __unsanitized_memcpy(reinterpret_cast<void *>(StackPtr), &GeneralRegisters,
3490b57cec5SDimitry Andric sizeof(GeneralRegisters));
3500b57cec5SDimitry Andric GeneralRegisters.rsp = StackPtr;
3510b57cec5SDimitry Andric GeneralRegisters.rip = reinterpret_cast<zx_vaddr_t>(CrashTrampolineAsm);
3520b57cec5SDimitry Andric
35306c3fb27SDimitry Andric #elif defined(__aarch64__) || defined(__riscv)
35406c3fb27SDimitry Andric
355349cc55cSDimitry Andric uintptr_t StackPtr =
356349cc55cSDimitry Andric (GeneralRegisters.sp - sizeof(GeneralRegisters)) & -(uintptr_t)16;
3570b57cec5SDimitry Andric __unsanitized_memcpy(reinterpret_cast<void *>(StackPtr), &GeneralRegisters,
3580b57cec5SDimitry Andric sizeof(GeneralRegisters));
3590b57cec5SDimitry Andric GeneralRegisters.sp = StackPtr;
3600b57cec5SDimitry Andric GeneralRegisters.pc = reinterpret_cast<zx_vaddr_t>(CrashTrampolineAsm);
3610b57cec5SDimitry Andric
3620b57cec5SDimitry Andric #else
3630b57cec5SDimitry Andric #error "Unsupported architecture for fuzzing on Fuchsia"
3640b57cec5SDimitry Andric #endif
3650b57cec5SDimitry Andric
3660b57cec5SDimitry Andric // Now force the crashing thread's state.
3670b57cec5SDimitry Andric ExitOnErr(
3680b57cec5SDimitry Andric _zx_thread_write_state(Thread.Handle, ZX_THREAD_STATE_GENERAL_REGS,
3690b57cec5SDimitry Andric &GeneralRegisters, sizeof(GeneralRegisters)),
3700b57cec5SDimitry Andric "_zx_thread_write_state");
3710b57cec5SDimitry Andric
3720b57cec5SDimitry Andric // Set the exception to HANDLED so it resumes the thread on close.
3730b57cec5SDimitry Andric uint32_t ExceptionState = ZX_EXCEPTION_STATE_HANDLED;
3740b57cec5SDimitry Andric ExitOnErr(_zx_object_set_property(Exception.Handle, ZX_PROP_EXCEPTION_STATE,
3750b57cec5SDimitry Andric &ExceptionState, sizeof(ExceptionState)),
3760b57cec5SDimitry Andric "zx_object_set_property");
3770b57cec5SDimitry Andric }
3780b57cec5SDimitry Andric }
3790b57cec5SDimitry Andric
StopSignalHandler()380349cc55cSDimitry Andric void StopSignalHandler() {
381*0fca6ea1SDimitry Andric _zx_object_signal(SignalHandlerEvent, 0, ZX_USER_SIGNAL_1);
382349cc55cSDimitry Andric if (SignalHandler.joinable()) {
383349cc55cSDimitry Andric SignalHandler.join();
384349cc55cSDimitry Andric }
385*0fca6ea1SDimitry Andric _zx_handle_close(SignalHandlerEvent);
386349cc55cSDimitry Andric }
387349cc55cSDimitry Andric
3880b57cec5SDimitry Andric } // namespace
3890b57cec5SDimitry Andric
3900b57cec5SDimitry Andric // Platform specific functions.
SetSignalHandler(const FuzzingOptions & Options)3910b57cec5SDimitry Andric void SetSignalHandler(const FuzzingOptions &Options) {
39268d75effSDimitry Andric // Make sure information from libFuzzer and the sanitizers are easy to
39368d75effSDimitry Andric // reassemble. `__sanitizer_log_write` has the added benefit of ensuring the
39468d75effSDimitry Andric // DSO map is always available for the symbolizer.
39568d75effSDimitry Andric // A uint64_t fits in 20 chars, so 64 is plenty.
39668d75effSDimitry Andric char Buf[64];
39768d75effSDimitry Andric memset(Buf, 0, sizeof(Buf));
39868d75effSDimitry Andric snprintf(Buf, sizeof(Buf), "==%lu== INFO: libFuzzer starting.\n", GetPid());
39968d75effSDimitry Andric if (EF->__sanitizer_log_write)
40068d75effSDimitry Andric __sanitizer_log_write(Buf, sizeof(Buf));
40168d75effSDimitry Andric Printf("%s", Buf);
40268d75effSDimitry Andric
4030b57cec5SDimitry Andric // Set up alarm handler if needed.
404e8d8bef9SDimitry Andric if (Options.HandleAlrm && Options.UnitTimeoutSec > 0) {
4050b57cec5SDimitry Andric std::thread T(AlarmHandler, Options.UnitTimeoutSec / 2 + 1);
4060b57cec5SDimitry Andric T.detach();
4070b57cec5SDimitry Andric }
4080b57cec5SDimitry Andric
409e8d8bef9SDimitry Andric // Options.HandleInt and Options.HandleTerm are not supported on Fuchsia
4100b57cec5SDimitry Andric
4110b57cec5SDimitry Andric // Early exit if no crash handler needed.
4120b57cec5SDimitry Andric if (!Options.HandleSegv && !Options.HandleBus && !Options.HandleIll &&
4130b57cec5SDimitry Andric !Options.HandleFpe && !Options.HandleAbrt)
4140b57cec5SDimitry Andric return;
4150b57cec5SDimitry Andric
4160b57cec5SDimitry Andric // Set up the crash handler and wait until it is ready before proceeding.
417349cc55cSDimitry Andric ExitOnErr(_zx_event_create(0, &SignalHandlerEvent), "_zx_event_create");
4180b57cec5SDimitry Andric
419349cc55cSDimitry Andric SignalHandler = std::thread(CrashHandler);
420349cc55cSDimitry Andric zx_status_t Status = _zx_object_wait_one(SignalHandlerEvent, ZX_USER_SIGNAL_0,
421349cc55cSDimitry Andric ZX_TIME_INFINITE, nullptr);
4220b57cec5SDimitry Andric ExitOnErr(Status, "_zx_object_wait_one");
4230b57cec5SDimitry Andric
424349cc55cSDimitry Andric std::atexit(StopSignalHandler);
4250b57cec5SDimitry Andric }
4260b57cec5SDimitry Andric
SleepSeconds(int Seconds)4270b57cec5SDimitry Andric void SleepSeconds(int Seconds) {
4280b57cec5SDimitry Andric _zx_nanosleep(_zx_deadline_after(ZX_SEC(Seconds)));
4290b57cec5SDimitry Andric }
4300b57cec5SDimitry Andric
GetPid()4310b57cec5SDimitry Andric unsigned long GetPid() {
4320b57cec5SDimitry Andric zx_status_t rc;
4330b57cec5SDimitry Andric zx_info_handle_basic_t Info;
4340b57cec5SDimitry Andric if ((rc = _zx_object_get_info(_zx_process_self(), ZX_INFO_HANDLE_BASIC, &Info,
4350b57cec5SDimitry Andric sizeof(Info), NULL, NULL)) != ZX_OK) {
4360b57cec5SDimitry Andric Printf("libFuzzer: unable to get info about self: %s\n",
4370b57cec5SDimitry Andric _zx_status_get_string(rc));
4380b57cec5SDimitry Andric exit(1);
4390b57cec5SDimitry Andric }
4400b57cec5SDimitry Andric return Info.koid;
4410b57cec5SDimitry Andric }
4420b57cec5SDimitry Andric
GetPeakRSSMb()4430b57cec5SDimitry Andric size_t GetPeakRSSMb() {
4440b57cec5SDimitry Andric zx_status_t rc;
4450b57cec5SDimitry Andric zx_info_task_stats_t Info;
4460b57cec5SDimitry Andric if ((rc = _zx_object_get_info(_zx_process_self(), ZX_INFO_TASK_STATS, &Info,
4470b57cec5SDimitry Andric sizeof(Info), NULL, NULL)) != ZX_OK) {
4480b57cec5SDimitry Andric Printf("libFuzzer: unable to get info about self: %s\n",
4490b57cec5SDimitry Andric _zx_status_get_string(rc));
4500b57cec5SDimitry Andric exit(1);
4510b57cec5SDimitry Andric }
4520b57cec5SDimitry Andric return (Info.mem_private_bytes + Info.mem_shared_bytes) >> 20;
4530b57cec5SDimitry Andric }
4540b57cec5SDimitry Andric
4550b57cec5SDimitry Andric template <typename Fn>
4560b57cec5SDimitry Andric class RunOnDestruction {
4570b57cec5SDimitry Andric public:
RunOnDestruction(Fn fn)4580b57cec5SDimitry Andric explicit RunOnDestruction(Fn fn) : fn_(fn) {}
~RunOnDestruction()4590b57cec5SDimitry Andric ~RunOnDestruction() { fn_(); }
4600b57cec5SDimitry Andric
4610b57cec5SDimitry Andric private:
4620b57cec5SDimitry Andric Fn fn_;
4630b57cec5SDimitry Andric };
4640b57cec5SDimitry Andric
4650b57cec5SDimitry Andric template <typename Fn>
at_scope_exit(Fn fn)4660b57cec5SDimitry Andric RunOnDestruction<Fn> at_scope_exit(Fn fn) {
4670b57cec5SDimitry Andric return RunOnDestruction<Fn>(fn);
4680b57cec5SDimitry Andric }
4690b57cec5SDimitry Andric
clone_fd_action(int localFd,int targetFd)4705ffd83dbSDimitry Andric static fdio_spawn_action_t clone_fd_action(int localFd, int targetFd) {
4715ffd83dbSDimitry Andric return {
4725ffd83dbSDimitry Andric .action = FDIO_SPAWN_ACTION_CLONE_FD,
4735ffd83dbSDimitry Andric .fd =
4745ffd83dbSDimitry Andric {
4755ffd83dbSDimitry Andric .local_fd = localFd,
4765ffd83dbSDimitry Andric .target_fd = targetFd,
4775ffd83dbSDimitry Andric },
4785ffd83dbSDimitry Andric };
4795ffd83dbSDimitry Andric }
4805ffd83dbSDimitry Andric
ExecuteCommand(const Command & Cmd)4810b57cec5SDimitry Andric int ExecuteCommand(const Command &Cmd) {
4820b57cec5SDimitry Andric zx_status_t rc;
4830b57cec5SDimitry Andric
4840b57cec5SDimitry Andric // Convert arguments to C array
4850b57cec5SDimitry Andric auto Args = Cmd.getArguments();
4860b57cec5SDimitry Andric size_t Argc = Args.size();
4870b57cec5SDimitry Andric assert(Argc != 0);
4880b57cec5SDimitry Andric std::unique_ptr<const char *[]> Argv(new const char *[Argc + 1]);
4890b57cec5SDimitry Andric for (size_t i = 0; i < Argc; ++i)
4900b57cec5SDimitry Andric Argv[i] = Args[i].c_str();
4910b57cec5SDimitry Andric Argv[Argc] = nullptr;
4920b57cec5SDimitry Andric
4930b57cec5SDimitry Andric // Determine output. On Fuchsia, the fuzzer is typically run as a component
4940b57cec5SDimitry Andric // that lacks a mutable working directory. Fortunately, when this is the case
4950b57cec5SDimitry Andric // a mutable output directory must be specified using "-artifact_prefix=...",
4960b57cec5SDimitry Andric // so write the log file(s) there.
49768d75effSDimitry Andric // However, we don't want to apply this logic for absolute paths.
4980b57cec5SDimitry Andric int FdOut = STDOUT_FILENO;
4995ffd83dbSDimitry Andric bool discardStdout = false;
5005ffd83dbSDimitry Andric bool discardStderr = false;
5015ffd83dbSDimitry Andric
5020b57cec5SDimitry Andric if (Cmd.hasOutputFile()) {
50368d75effSDimitry Andric std::string Path = Cmd.getOutputFile();
5045ffd83dbSDimitry Andric if (Path == getDevNull()) {
5055ffd83dbSDimitry Andric // On Fuchsia, there's no "/dev/null" like-file, so we
5065ffd83dbSDimitry Andric // just don't copy the FDs into the spawned process.
5075ffd83dbSDimitry Andric discardStdout = true;
5085ffd83dbSDimitry Andric } else {
50968d75effSDimitry Andric bool IsAbsolutePath = Path.length() > 1 && Path[0] == '/';
51068d75effSDimitry Andric if (!IsAbsolutePath && Cmd.hasFlag("artifact_prefix"))
51168d75effSDimitry Andric Path = Cmd.getFlagValue("artifact_prefix") + "/" + Path;
51268d75effSDimitry Andric
5130b57cec5SDimitry Andric FdOut = open(Path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0);
5140b57cec5SDimitry Andric if (FdOut == -1) {
5150b57cec5SDimitry Andric Printf("libFuzzer: failed to open %s: %s\n", Path.c_str(),
5160b57cec5SDimitry Andric strerror(errno));
5170b57cec5SDimitry Andric return ZX_ERR_IO;
5180b57cec5SDimitry Andric }
5190b57cec5SDimitry Andric }
5205ffd83dbSDimitry Andric }
5210b57cec5SDimitry Andric auto CloseFdOut = at_scope_exit([FdOut]() {
5220b57cec5SDimitry Andric if (FdOut != STDOUT_FILENO)
5230b57cec5SDimitry Andric close(FdOut);
5240b57cec5SDimitry Andric });
5250b57cec5SDimitry Andric
5260b57cec5SDimitry Andric // Determine stderr
5270b57cec5SDimitry Andric int FdErr = STDERR_FILENO;
5285ffd83dbSDimitry Andric if (Cmd.isOutAndErrCombined()) {
5290b57cec5SDimitry Andric FdErr = FdOut;
5305ffd83dbSDimitry Andric if (discardStdout)
5315ffd83dbSDimitry Andric discardStderr = true;
5325ffd83dbSDimitry Andric }
5330b57cec5SDimitry Andric
5340b57cec5SDimitry Andric // Clone the file descriptors into the new process
5355ffd83dbSDimitry Andric std::vector<fdio_spawn_action_t> SpawnActions;
5365ffd83dbSDimitry Andric SpawnActions.push_back(clone_fd_action(STDIN_FILENO, STDIN_FILENO));
5375ffd83dbSDimitry Andric
5385ffd83dbSDimitry Andric if (!discardStdout)
5395ffd83dbSDimitry Andric SpawnActions.push_back(clone_fd_action(FdOut, STDOUT_FILENO));
5405ffd83dbSDimitry Andric if (!discardStderr)
5415ffd83dbSDimitry Andric SpawnActions.push_back(clone_fd_action(FdErr, STDERR_FILENO));
5420b57cec5SDimitry Andric
5430b57cec5SDimitry Andric // Start the process.
5440b57cec5SDimitry Andric char ErrorMsg[FDIO_SPAWN_ERR_MSG_MAX_LENGTH];
5450b57cec5SDimitry Andric zx_handle_t ProcessHandle = ZX_HANDLE_INVALID;
5465ffd83dbSDimitry Andric rc = fdio_spawn_etc(ZX_HANDLE_INVALID,
5475ffd83dbSDimitry Andric FDIO_SPAWN_CLONE_ALL & (~FDIO_SPAWN_CLONE_STDIO), Argv[0],
5485ffd83dbSDimitry Andric Argv.get(), nullptr, SpawnActions.size(),
5495ffd83dbSDimitry Andric SpawnActions.data(), &ProcessHandle, ErrorMsg);
5505ffd83dbSDimitry Andric
5510b57cec5SDimitry Andric if (rc != ZX_OK) {
5520b57cec5SDimitry Andric Printf("libFuzzer: failed to launch '%s': %s, %s\n", Argv[0], ErrorMsg,
5530b57cec5SDimitry Andric _zx_status_get_string(rc));
5540b57cec5SDimitry Andric return rc;
5550b57cec5SDimitry Andric }
5560b57cec5SDimitry Andric auto CloseHandle = at_scope_exit([&]() { _zx_handle_close(ProcessHandle); });
5570b57cec5SDimitry Andric
5580b57cec5SDimitry Andric // Now join the process and return the exit status.
5590b57cec5SDimitry Andric if ((rc = _zx_object_wait_one(ProcessHandle, ZX_PROCESS_TERMINATED,
5600b57cec5SDimitry Andric ZX_TIME_INFINITE, nullptr)) != ZX_OK) {
5610b57cec5SDimitry Andric Printf("libFuzzer: failed to join '%s': %s\n", Argv[0],
5620b57cec5SDimitry Andric _zx_status_get_string(rc));
5630b57cec5SDimitry Andric return rc;
5640b57cec5SDimitry Andric }
5650b57cec5SDimitry Andric
5660b57cec5SDimitry Andric zx_info_process_t Info;
5670b57cec5SDimitry Andric if ((rc = _zx_object_get_info(ProcessHandle, ZX_INFO_PROCESS, &Info,
5680b57cec5SDimitry Andric sizeof(Info), nullptr, nullptr)) != ZX_OK) {
5690b57cec5SDimitry Andric Printf("libFuzzer: unable to get return code from '%s': %s\n", Argv[0],
5700b57cec5SDimitry Andric _zx_status_get_string(rc));
5710b57cec5SDimitry Andric return rc;
5720b57cec5SDimitry Andric }
5730b57cec5SDimitry Andric
574fe6060f1SDimitry Andric return static_cast<int>(Info.return_code);
5750b57cec5SDimitry Andric }
5760b57cec5SDimitry Andric
ExecuteCommand(const Command & BaseCmd,std::string * CmdOutput)5775ffd83dbSDimitry Andric bool ExecuteCommand(const Command &BaseCmd, std::string *CmdOutput) {
5785ffd83dbSDimitry Andric auto LogFilePath = TempPath("SimPopenOut", ".txt");
5795ffd83dbSDimitry Andric Command Cmd(BaseCmd);
5805ffd83dbSDimitry Andric Cmd.setOutputFile(LogFilePath);
5815ffd83dbSDimitry Andric int Ret = ExecuteCommand(Cmd);
5825ffd83dbSDimitry Andric *CmdOutput = FileToString(LogFilePath);
5835ffd83dbSDimitry Andric RemoveFile(LogFilePath);
5845ffd83dbSDimitry Andric return Ret == 0;
5855ffd83dbSDimitry Andric }
5865ffd83dbSDimitry Andric
SearchMemory(const void * Data,size_t DataLen,const void * Patt,size_t PattLen)5870b57cec5SDimitry Andric const void *SearchMemory(const void *Data, size_t DataLen, const void *Patt,
5880b57cec5SDimitry Andric size_t PattLen) {
5890b57cec5SDimitry Andric return memmem(Data, DataLen, Patt, PattLen);
5900b57cec5SDimitry Andric }
5910b57cec5SDimitry Andric
592480093f4SDimitry Andric // In fuchsia, accessing /dev/null is not supported. There's nothing
593480093f4SDimitry Andric // similar to a file that discards everything that is written to it.
594480093f4SDimitry Andric // The way of doing something similar in fuchsia is by using
595480093f4SDimitry Andric // fdio_null_create and binding that to a file descriptor.
DiscardOutput(int Fd)596480093f4SDimitry Andric void DiscardOutput(int Fd) {
597480093f4SDimitry Andric fdio_t *fdio_null = fdio_null_create();
598480093f4SDimitry Andric if (fdio_null == nullptr) return;
599480093f4SDimitry Andric int nullfd = fdio_bind_to_fd(fdio_null, -1, 0);
600480093f4SDimitry Andric if (nullfd < 0) return;
601480093f4SDimitry Andric dup2(nullfd, Fd);
602480093f4SDimitry Andric }
603480093f4SDimitry Andric
PageSize()60406c3fb27SDimitry Andric size_t PageSize() {
60506c3fb27SDimitry Andric static size_t PageSizeCached = _zx_system_get_page_size();
60606c3fb27SDimitry Andric return PageSizeCached;
60706c3fb27SDimitry Andric }
60806c3fb27SDimitry Andric
SetThreadName(std::thread & thread,const std::string & name)6095f757f3fSDimitry Andric void SetThreadName(std::thread &thread, const std::string &name) {
6105f757f3fSDimitry Andric // TODO ?
6115f757f3fSDimitry Andric }
6125f757f3fSDimitry Andric
6130b57cec5SDimitry Andric } // namespace fuzzer
6140b57cec5SDimitry Andric
6150b57cec5SDimitry Andric #endif // LIBFUZZER_FUCHSIA
616