1ffb1132eSMatt Morehouse //===- FuzzerUtilFuchsia.cpp - Misc utils for Fuchsia. --------------------===//
2ffb1132eSMatt Morehouse //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6ffb1132eSMatt Morehouse //
7ffb1132eSMatt Morehouse //===----------------------------------------------------------------------===//
8ffb1132eSMatt Morehouse // Misc utils implementation using Fuchsia/Zircon APIs.
9ffb1132eSMatt Morehouse //===----------------------------------------------------------------------===//
10226866e1SDokyung Song #include "FuzzerPlatform.h"
11ffb1132eSMatt Morehouse 
12ffb1132eSMatt Morehouse #if LIBFUZZER_FUCHSIA
13ffb1132eSMatt Morehouse 
14ffb1132eSMatt Morehouse #include "FuzzerInternal.h"
15ffb1132eSMatt Morehouse #include "FuzzerUtil.h"
169bd4dc92SPetr Hosek #include <cassert>
17ffb1132eSMatt Morehouse #include <cerrno>
18ffb1132eSMatt Morehouse #include <cinttypes>
19ffb1132eSMatt Morehouse #include <cstdint>
20ffb1132eSMatt Morehouse #include <fcntl.h>
21e5b603a4SMarco Vanotti #include <lib/fdio/fdio.h>
22157a5c2fSPetr Hosek #include <lib/fdio/spawn.h>
23ffb1132eSMatt Morehouse #include <string>
24dd097445SPetr Hosek #include <sys/select.h>
25ffb1132eSMatt Morehouse #include <thread>
262f70693eSPetr Hosek #include <unistd.h>
27ffb1132eSMatt Morehouse #include <zircon/errors.h>
282f70693eSPetr Hosek #include <zircon/process.h>
294915d3a1SPetr Hosek #include <zircon/sanitizer.h>
30ffb1132eSMatt Morehouse #include <zircon/status.h>
31ffb1132eSMatt Morehouse #include <zircon/syscalls.h>
324915d3a1SPetr Hosek #include <zircon/syscalls/debug.h>
334915d3a1SPetr Hosek #include <zircon/syscalls/exception.h>
34d9a59aebSPetr Hosek #include <zircon/syscalls/object.h>
35ffb1132eSMatt Morehouse #include <zircon/types.h>
36ffb1132eSMatt Morehouse 
3744aaca3dSMarco Vanotti #include <vector>
3844aaca3dSMarco Vanotti 
39ffb1132eSMatt Morehouse namespace fuzzer {
40ffb1132eSMatt Morehouse 
414915d3a1SPetr Hosek // Given that Fuchsia doesn't have the POSIX signals that libFuzzer was written
424915d3a1SPetr Hosek // around, the general approach is to spin up dedicated threads to watch for
434915d3a1SPetr Hosek // each requested condition (alarm, interrupt, crash).  Of these, the crash
444915d3a1SPetr Hosek // handler is the most involved, as it requires resuming the crashed thread in
454915d3a1SPetr Hosek // order to invoke the sanitizers to get the needed state.
464915d3a1SPetr Hosek 
474915d3a1SPetr Hosek // Forward declaration of assembly trampoline needed to resume crashed threads.
484915d3a1SPetr Hosek // This appears to have external linkage to  C++, which is why it's not in the
494915d3a1SPetr Hosek // anonymous namespace.  The assembly definition inside MakeTrampoline()
504915d3a1SPetr Hosek // actually defines the symbol with internal linkage only.
514915d3a1SPetr Hosek void CrashTrampolineAsm() __asm__("CrashTrampolineAsm");
524915d3a1SPetr Hosek 
53ffb1132eSMatt Morehouse namespace {
54ffb1132eSMatt Morehouse 
55*5de8c7f1SAaron Green // The signal handler thread uses Zircon exceptions to resume crashed threads
56*5de8c7f1SAaron Green // into libFuzzer's POSIX signal handlers. The associated event is used to
57*5de8c7f1SAaron Green // signal when the thread is running, and when it should stop.
58*5de8c7f1SAaron Green std::thread SignalHandler;
59*5de8c7f1SAaron Green zx_handle_t SignalHandlerEvent = ZX_HANDLE_INVALID;
60*5de8c7f1SAaron Green 
614915d3a1SPetr Hosek // Helper function to handle Zircon syscall failures.
ExitOnErr(zx_status_t Status,const char * Syscall)624915d3a1SPetr Hosek void ExitOnErr(zx_status_t Status, const char *Syscall) {
634915d3a1SPetr Hosek   if (Status != ZX_OK) {
644915d3a1SPetr Hosek     Printf("libFuzzer: %s failed: %s\n", Syscall,
654915d3a1SPetr Hosek            _zx_status_get_string(Status));
664915d3a1SPetr Hosek     exit(1);
674915d3a1SPetr Hosek   }
684915d3a1SPetr Hosek }
694915d3a1SPetr Hosek 
AlarmHandler(int Seconds)70ffb1132eSMatt Morehouse void AlarmHandler(int Seconds) {
71ffb1132eSMatt Morehouse   while (true) {
72ffb1132eSMatt Morehouse     SleepSeconds(Seconds);
73ffb1132eSMatt Morehouse     Fuzzer::StaticAlarmCallback();
74ffb1132eSMatt Morehouse   }
75ffb1132eSMatt Morehouse }
76ffb1132eSMatt Morehouse 
774915d3a1SPetr Hosek // For the crash handler, we need to call Fuzzer::StaticCrashSignalCallback
784915d3a1SPetr Hosek // without POSIX signal handlers.  To achieve this, we use an assembly function
794915d3a1SPetr Hosek // to add the necessary CFI unwinding information and a C function to bridge
804915d3a1SPetr Hosek // from that back into C++.
814915d3a1SPetr Hosek 
824915d3a1SPetr Hosek // FIXME: This works as a short-term solution, but this code really shouldn't be
834915d3a1SPetr Hosek // architecture dependent. A better long term solution is to implement remote
844915d3a1SPetr Hosek // unwinding and expose the necessary APIs through sanitizer_common and/or ASAN
854915d3a1SPetr Hosek // to allow the exception handling thread to gather the crash state directly.
864915d3a1SPetr Hosek //
874915d3a1SPetr Hosek // Alternatively, Fuchsia may in future actually implement basic signal
884915d3a1SPetr Hosek // handling for the machine trap signals.
894915d3a1SPetr Hosek #if defined(__x86_64__)
904915d3a1SPetr Hosek #define FOREACH_REGISTER(OP_REG, OP_NUM) \
914915d3a1SPetr Hosek   OP_REG(rax)                            \
924915d3a1SPetr Hosek   OP_REG(rbx)                            \
934915d3a1SPetr Hosek   OP_REG(rcx)                            \
944915d3a1SPetr Hosek   OP_REG(rdx)                            \
954915d3a1SPetr Hosek   OP_REG(rsi)                            \
964915d3a1SPetr Hosek   OP_REG(rdi)                            \
974915d3a1SPetr Hosek   OP_REG(rbp)                            \
984915d3a1SPetr Hosek   OP_REG(rsp)                            \
994915d3a1SPetr Hosek   OP_REG(r8)                             \
1004915d3a1SPetr Hosek   OP_REG(r9)                             \
1014915d3a1SPetr Hosek   OP_REG(r10)                            \
1024915d3a1SPetr Hosek   OP_REG(r11)                            \
1034915d3a1SPetr Hosek   OP_REG(r12)                            \
1044915d3a1SPetr Hosek   OP_REG(r13)                            \
1054915d3a1SPetr Hosek   OP_REG(r14)                            \
1064915d3a1SPetr Hosek   OP_REG(r15)                            \
1074915d3a1SPetr Hosek   OP_REG(rip)
1084915d3a1SPetr Hosek 
1094915d3a1SPetr Hosek #elif defined(__aarch64__)
1104915d3a1SPetr Hosek #define FOREACH_REGISTER(OP_REG, OP_NUM) \
1114915d3a1SPetr Hosek   OP_NUM(0)                              \
1124915d3a1SPetr Hosek   OP_NUM(1)                              \
1134915d3a1SPetr Hosek   OP_NUM(2)                              \
1144915d3a1SPetr Hosek   OP_NUM(3)                              \
1154915d3a1SPetr Hosek   OP_NUM(4)                              \
1164915d3a1SPetr Hosek   OP_NUM(5)                              \
1174915d3a1SPetr Hosek   OP_NUM(6)                              \
1184915d3a1SPetr Hosek   OP_NUM(7)                              \
1194915d3a1SPetr Hosek   OP_NUM(8)                              \
1204915d3a1SPetr Hosek   OP_NUM(9)                              \
1214915d3a1SPetr Hosek   OP_NUM(10)                             \
1224915d3a1SPetr Hosek   OP_NUM(11)                             \
1234915d3a1SPetr Hosek   OP_NUM(12)                             \
1244915d3a1SPetr Hosek   OP_NUM(13)                             \
1254915d3a1SPetr Hosek   OP_NUM(14)                             \
1264915d3a1SPetr Hosek   OP_NUM(15)                             \
1274915d3a1SPetr Hosek   OP_NUM(16)                             \
1284915d3a1SPetr Hosek   OP_NUM(17)                             \
1294915d3a1SPetr Hosek   OP_NUM(18)                             \
1304915d3a1SPetr Hosek   OP_NUM(19)                             \
1314915d3a1SPetr Hosek   OP_NUM(20)                             \
1324915d3a1SPetr Hosek   OP_NUM(21)                             \
1334915d3a1SPetr Hosek   OP_NUM(22)                             \
1344915d3a1SPetr Hosek   OP_NUM(23)                             \
1354915d3a1SPetr Hosek   OP_NUM(24)                             \
1364915d3a1SPetr Hosek   OP_NUM(25)                             \
1374915d3a1SPetr Hosek   OP_NUM(26)                             \
1384915d3a1SPetr Hosek   OP_NUM(27)                             \
1394915d3a1SPetr Hosek   OP_NUM(28)                             \
1404915d3a1SPetr Hosek   OP_NUM(29)                             \
1414915d3a1SPetr Hosek   OP_REG(sp)
1424915d3a1SPetr Hosek 
1434915d3a1SPetr Hosek #else
1444915d3a1SPetr Hosek #error "Unsupported architecture for fuzzing on Fuchsia"
1454915d3a1SPetr Hosek #endif
1464915d3a1SPetr Hosek 
1474915d3a1SPetr Hosek // Produces a CFI directive for the named or numbered register.
14846c7fc22SMarco Vanotti // The value used refers to an assembler immediate operand with the same name
14946c7fc22SMarco Vanotti // as the register (see ASM_OPERAND_REG).
1504915d3a1SPetr Hosek #define CFI_OFFSET_REG(reg) ".cfi_offset " #reg ", %c[" #reg "]\n"
15146c7fc22SMarco Vanotti #define CFI_OFFSET_NUM(num) CFI_OFFSET_REG(x##num)
1524915d3a1SPetr Hosek 
15346c7fc22SMarco Vanotti // Produces an assembler immediate operand for the named or numbered register.
15446c7fc22SMarco Vanotti // This operand contains the offset of the register relative to the CFA.
1554915d3a1SPetr Hosek #define ASM_OPERAND_REG(reg)                                                   \
156a9c51598SMarco Vanotti   [reg] "i"(offsetof(zx_thread_state_general_regs_t, reg)),
1574915d3a1SPetr Hosek #define ASM_OPERAND_NUM(num)                                                   \
158a9c51598SMarco Vanotti   [x##num] "i"(offsetof(zx_thread_state_general_regs_t, r[num])),
1594915d3a1SPetr Hosek 
1604915d3a1SPetr Hosek // Trampoline to bridge from the assembly below to the static C++ crash
1614915d3a1SPetr Hosek // callback.
1624915d3a1SPetr Hosek __attribute__((noreturn))
StaticCrashHandler()1634915d3a1SPetr Hosek static void StaticCrashHandler() {
164ffb1132eSMatt Morehouse   Fuzzer::StaticCrashSignalCallback();
1654915d3a1SPetr Hosek   for (;;) {
1664915d3a1SPetr Hosek     _Exit(1);
1674915d3a1SPetr Hosek   }
1684915d3a1SPetr Hosek }
1694915d3a1SPetr Hosek 
170a9c51598SMarco Vanotti // This trampoline function has the necessary CFI information to unwind
171a9c51598SMarco Vanotti // and get a backtrace:
172a9c51598SMarco Vanotti //  * The stack contains a copy of all the registers at the point of crash,
173a9c51598SMarco Vanotti //    the code has CFI directives specifying how to restore them.
174a9c51598SMarco Vanotti //  * A call to StaticCrashHandler, which will print the stacktrace and exit
175a9c51598SMarco Vanotti //    the fuzzer, generating a crash artifact.
17646c7fc22SMarco Vanotti //
17746c7fc22SMarco Vanotti // The __attribute__((used)) is necessary because the function
1784915d3a1SPetr Hosek // is never called; it's just a container around the assembly to allow it to
1794915d3a1SPetr Hosek // use operands for compile-time computed constants.
1804915d3a1SPetr Hosek __attribute__((used))
MakeTrampoline()1814915d3a1SPetr Hosek void MakeTrampoline() {
182a9c51598SMarco Vanotti   __asm__(
183a9c51598SMarco Vanotti       ".cfi_endproc\n"
1844915d3a1SPetr Hosek       ".pushsection .text.CrashTrampolineAsm\n"
1854915d3a1SPetr Hosek       ".type CrashTrampolineAsm,STT_FUNC\n"
1864915d3a1SPetr Hosek       "CrashTrampolineAsm:\n"
1874915d3a1SPetr Hosek       ".cfi_startproc simple\n"
1884915d3a1SPetr Hosek       ".cfi_signal_frame\n"
1894915d3a1SPetr Hosek #if defined(__x86_64__)
1904915d3a1SPetr Hosek       ".cfi_return_column rip\n"
191a9c51598SMarco Vanotti       ".cfi_def_cfa rsp, 0\n"
1924915d3a1SPetr Hosek       FOREACH_REGISTER(CFI_OFFSET_REG, CFI_OFFSET_NUM)
1934915d3a1SPetr Hosek       "call %c[StaticCrashHandler]\n"
1944915d3a1SPetr Hosek       "ud2\n"
1954915d3a1SPetr Hosek #elif defined(__aarch64__)
1964915d3a1SPetr Hosek       ".cfi_return_column 33\n"
197a9c51598SMarco Vanotti       ".cfi_def_cfa sp, 0\n"
1984915d3a1SPetr Hosek       FOREACH_REGISTER(CFI_OFFSET_REG, CFI_OFFSET_NUM)
19946c7fc22SMarco Vanotti       ".cfi_offset 33, %c[pc]\n"
20046c7fc22SMarco Vanotti       ".cfi_offset 30, %c[lr]\n"
20146c7fc22SMarco Vanotti       "bl %c[StaticCrashHandler]\n"
20246c7fc22SMarco Vanotti       "brk 1\n"
2034915d3a1SPetr Hosek #else
2044915d3a1SPetr Hosek #error "Unsupported architecture for fuzzing on Fuchsia"
2054915d3a1SPetr Hosek #endif
2064915d3a1SPetr Hosek      ".cfi_endproc\n"
2074915d3a1SPetr Hosek      ".size CrashTrampolineAsm, . - CrashTrampolineAsm\n"
2084915d3a1SPetr Hosek      ".popsection\n"
2094915d3a1SPetr Hosek      ".cfi_startproc\n"
2104915d3a1SPetr Hosek       : // No outputs
2114915d3a1SPetr Hosek       : FOREACH_REGISTER(ASM_OPERAND_REG, ASM_OPERAND_NUM)
2124915d3a1SPetr Hosek #if defined(__aarch64__)
213a9c51598SMarco Vanotti         ASM_OPERAND_REG(pc) ASM_OPERAND_REG(lr)
2144915d3a1SPetr Hosek #endif
215a9c51598SMarco Vanotti         [StaticCrashHandler] "i"(StaticCrashHandler));
2164915d3a1SPetr Hosek }
2174915d3a1SPetr Hosek 
CrashHandler()218*5de8c7f1SAaron Green void CrashHandler() {
219*5de8c7f1SAaron Green   assert(SignalHandlerEvent != ZX_HANDLE_INVALID);
220*5de8c7f1SAaron Green 
2214915d3a1SPetr Hosek   // This structure is used to ensure we close handles to objects we create in
2224915d3a1SPetr Hosek   // this handler.
2234915d3a1SPetr Hosek   struct ScopedHandle {
2244915d3a1SPetr Hosek     ~ScopedHandle() { _zx_handle_close(Handle); }
2254915d3a1SPetr Hosek     zx_handle_t Handle = ZX_HANDLE_INVALID;
2264915d3a1SPetr Hosek   };
2274915d3a1SPetr Hosek 
228d9a59aebSPetr Hosek   // Create the exception channel.  We need to claim to be a "debugger" so the
229d9a59aebSPetr Hosek   // kernel will allow us to modify and resume dying threads (see below). Once
230d9a59aebSPetr Hosek   // the channel is set, we can signal the main thread to continue and wait
2314915d3a1SPetr Hosek   // for the exception to arrive.
232d9a59aebSPetr Hosek   ScopedHandle Channel;
2334915d3a1SPetr Hosek   zx_handle_t Self = _zx_process_self();
234d9a59aebSPetr Hosek   ExitOnErr(_zx_task_create_exception_channel(
235d9a59aebSPetr Hosek                 Self, ZX_EXCEPTION_CHANNEL_DEBUGGER, &Channel.Handle),
236d9a59aebSPetr Hosek             "_zx_task_create_exception_channel");
2374915d3a1SPetr Hosek 
238*5de8c7f1SAaron Green   ExitOnErr(_zx_object_signal(SignalHandlerEvent, 0, ZX_USER_SIGNAL_0),
2394915d3a1SPetr Hosek             "_zx_object_signal");
2404915d3a1SPetr Hosek 
2419bd4dc92SPetr Hosek   // This thread lives as long as the process in order to keep handling
2429bd4dc92SPetr Hosek   // crashes.  In practice, the first crashed thread to reach the end of the
2439bd4dc92SPetr Hosek   // StaticCrashHandler will end the process.
2449bd4dc92SPetr Hosek   while (true) {
245*5de8c7f1SAaron Green     zx_wait_item_t WaitItems[] = {
246*5de8c7f1SAaron Green         {
247*5de8c7f1SAaron Green             .handle = SignalHandlerEvent,
248*5de8c7f1SAaron Green             .waitfor = ZX_SIGNAL_HANDLE_CLOSED,
249*5de8c7f1SAaron Green             .pending = 0,
250*5de8c7f1SAaron Green         },
251*5de8c7f1SAaron Green         {
252*5de8c7f1SAaron Green             .handle = Channel.Handle,
253*5de8c7f1SAaron Green             .waitfor = ZX_CHANNEL_READABLE | ZX_CHANNEL_PEER_CLOSED,
254*5de8c7f1SAaron Green             .pending = 0,
255*5de8c7f1SAaron Green         },
256*5de8c7f1SAaron Green     };
257*5de8c7f1SAaron Green     auto Status = _zx_object_wait_many(
258*5de8c7f1SAaron Green         WaitItems, sizeof(WaitItems) / sizeof(WaitItems[0]), ZX_TIME_INFINITE);
259*5de8c7f1SAaron Green     if (Status != ZX_OK || (WaitItems[1].pending & ZX_CHANNEL_READABLE) == 0) {
260*5de8c7f1SAaron Green       break;
261*5de8c7f1SAaron Green     }
262d9a59aebSPetr Hosek 
263d9a59aebSPetr Hosek     zx_exception_info_t ExceptionInfo;
264d9a59aebSPetr Hosek     ScopedHandle Exception;
265d9a59aebSPetr Hosek     ExitOnErr(_zx_channel_read(Channel.Handle, 0, &ExceptionInfo,
266d9a59aebSPetr Hosek                                &Exception.Handle, sizeof(ExceptionInfo), 1,
267d9a59aebSPetr Hosek                                nullptr, nullptr),
268d9a59aebSPetr Hosek               "_zx_channel_read");
2694915d3a1SPetr Hosek 
2709bd4dc92SPetr Hosek     // Ignore informational synthetic exceptions.
271d9a59aebSPetr Hosek     if (ZX_EXCP_THREAD_STARTING == ExceptionInfo.type ||
272d9a59aebSPetr Hosek         ZX_EXCP_THREAD_EXITING == ExceptionInfo.type ||
273d9a59aebSPetr Hosek         ZX_EXCP_PROCESS_STARTING == ExceptionInfo.type) {
2749bd4dc92SPetr Hosek       continue;
2759bd4dc92SPetr Hosek     }
2769bd4dc92SPetr Hosek 
2774915d3a1SPetr Hosek     // At this point, we want to get the state of the crashing thread, but
2789bd4dc92SPetr Hosek     // libFuzzer and the sanitizers assume this will happen from that same
2799bd4dc92SPetr Hosek     // thread via a POSIX signal handler. "Resurrecting" the thread in the
2809bd4dc92SPetr Hosek     // middle of the appropriate callback is as simple as forcibly setting the
2819bd4dc92SPetr Hosek     // instruction pointer/program counter, provided we NEVER EVER return from
2829bd4dc92SPetr Hosek     // that function (since otherwise our stack will not be valid).
2834915d3a1SPetr Hosek     ScopedHandle Thread;
284d9a59aebSPetr Hosek     ExitOnErr(_zx_exception_get_thread(Exception.Handle, &Thread.Handle),
285d9a59aebSPetr Hosek               "_zx_exception_get_thread");
2864915d3a1SPetr Hosek 
2874915d3a1SPetr Hosek     zx_thread_state_general_regs_t GeneralRegisters;
2884915d3a1SPetr Hosek     ExitOnErr(_zx_thread_read_state(Thread.Handle, ZX_THREAD_STATE_GENERAL_REGS,
2899bd4dc92SPetr Hosek                                     &GeneralRegisters,
2909bd4dc92SPetr Hosek                                     sizeof(GeneralRegisters)),
2914915d3a1SPetr Hosek               "_zx_thread_read_state");
2924915d3a1SPetr Hosek 
2934915d3a1SPetr Hosek     // To unwind properly, we need to push the crashing thread's register state
2944915d3a1SPetr Hosek     // onto the stack and jump into a trampoline with CFI instructions on how
2954915d3a1SPetr Hosek     // to restore it.
2964915d3a1SPetr Hosek #if defined(__x86_64__)
297a9c51598SMarco Vanotti     uintptr_t StackPtr =
298a9c51598SMarco Vanotti         (GeneralRegisters.rsp - (128 + sizeof(GeneralRegisters))) &
299a9c51598SMarco Vanotti         -(uintptr_t)16;
3004915d3a1SPetr Hosek     __unsanitized_memcpy(reinterpret_cast<void *>(StackPtr), &GeneralRegisters,
3014915d3a1SPetr Hosek                          sizeof(GeneralRegisters));
3024915d3a1SPetr Hosek     GeneralRegisters.rsp = StackPtr;
3034915d3a1SPetr Hosek     GeneralRegisters.rip = reinterpret_cast<zx_vaddr_t>(CrashTrampolineAsm);
3044915d3a1SPetr Hosek 
3054915d3a1SPetr Hosek #elif defined(__aarch64__)
306a9c51598SMarco Vanotti     uintptr_t StackPtr =
307a9c51598SMarco Vanotti         (GeneralRegisters.sp - sizeof(GeneralRegisters)) & -(uintptr_t)16;
3084915d3a1SPetr Hosek     __unsanitized_memcpy(reinterpret_cast<void *>(StackPtr), &GeneralRegisters,
3094915d3a1SPetr Hosek                          sizeof(GeneralRegisters));
3104915d3a1SPetr Hosek     GeneralRegisters.sp = StackPtr;
3114915d3a1SPetr Hosek     GeneralRegisters.pc = reinterpret_cast<zx_vaddr_t>(CrashTrampolineAsm);
3124915d3a1SPetr Hosek 
3134915d3a1SPetr Hosek #else
3144915d3a1SPetr Hosek #error "Unsupported architecture for fuzzing on Fuchsia"
3154915d3a1SPetr Hosek #endif
3164915d3a1SPetr Hosek 
3174915d3a1SPetr Hosek     // Now force the crashing thread's state.
3189bd4dc92SPetr Hosek     ExitOnErr(
3199bd4dc92SPetr Hosek         _zx_thread_write_state(Thread.Handle, ZX_THREAD_STATE_GENERAL_REGS,
3204915d3a1SPetr Hosek                                &GeneralRegisters, sizeof(GeneralRegisters)),
3214915d3a1SPetr Hosek         "_zx_thread_write_state");
3224915d3a1SPetr Hosek 
323d9a59aebSPetr Hosek     // Set the exception to HANDLED so it resumes the thread on close.
324d9a59aebSPetr Hosek     uint32_t ExceptionState = ZX_EXCEPTION_STATE_HANDLED;
325d9a59aebSPetr Hosek     ExitOnErr(_zx_object_set_property(Exception.Handle, ZX_PROP_EXCEPTION_STATE,
326d9a59aebSPetr Hosek                                       &ExceptionState, sizeof(ExceptionState)),
327d9a59aebSPetr Hosek               "zx_object_set_property");
328ffb1132eSMatt Morehouse   }
3299bd4dc92SPetr Hosek }
330ffb1132eSMatt Morehouse 
StopSignalHandler()331*5de8c7f1SAaron Green void StopSignalHandler() {
332*5de8c7f1SAaron Green   _zx_handle_close(SignalHandlerEvent);
333*5de8c7f1SAaron Green   if (SignalHandler.joinable()) {
334*5de8c7f1SAaron Green     SignalHandler.join();
335*5de8c7f1SAaron Green   }
336*5de8c7f1SAaron Green }
337*5de8c7f1SAaron Green 
338ffb1132eSMatt Morehouse } // namespace
339ffb1132eSMatt Morehouse 
340ffb1132eSMatt Morehouse // Platform specific functions.
SetSignalHandler(const FuzzingOptions & Options)341ffb1132eSMatt Morehouse void SetSignalHandler(const FuzzingOptions &Options) {
3424b23c24bSJake Ehrlich   // Make sure information from libFuzzer and the sanitizers are easy to
3434b23c24bSJake Ehrlich   // reassemble. `__sanitizer_log_write` has the added benefit of ensuring the
3444b23c24bSJake Ehrlich   // DSO map is always available for the symbolizer.
3454b23c24bSJake Ehrlich   // A uint64_t fits in 20 chars, so 64 is plenty.
3464b23c24bSJake Ehrlich   char Buf[64];
3474b23c24bSJake Ehrlich   memset(Buf, 0, sizeof(Buf));
3484b23c24bSJake Ehrlich   snprintf(Buf, sizeof(Buf), "==%lu== INFO: libFuzzer starting.\n", GetPid());
3494b23c24bSJake Ehrlich   if (EF->__sanitizer_log_write)
3504b23c24bSJake Ehrlich     __sanitizer_log_write(Buf, sizeof(Buf));
3514b23c24bSJake Ehrlich   Printf("%s", Buf);
3524b23c24bSJake Ehrlich 
353ffb1132eSMatt Morehouse   // Set up alarm handler if needed.
3549df7ee34SIlya Leoshkevich   if (Options.HandleAlrm && Options.UnitTimeoutSec > 0) {
355ffb1132eSMatt Morehouse     std::thread T(AlarmHandler, Options.UnitTimeoutSec / 2 + 1);
356ffb1132eSMatt Morehouse     T.detach();
357ffb1132eSMatt Morehouse   }
358ffb1132eSMatt Morehouse 
3596777919dSCameron Finucane   // Options.HandleInt and Options.HandleTerm are not supported on Fuchsia
360ffb1132eSMatt Morehouse 
361ffb1132eSMatt Morehouse   // Early exit if no crash handler needed.
362ffb1132eSMatt Morehouse   if (!Options.HandleSegv && !Options.HandleBus && !Options.HandleIll &&
363ffb1132eSMatt Morehouse       !Options.HandleFpe && !Options.HandleAbrt)
364ffb1132eSMatt Morehouse     return;
365ffb1132eSMatt Morehouse 
3664915d3a1SPetr Hosek   // Set up the crash handler and wait until it is ready before proceeding.
367*5de8c7f1SAaron Green   ExitOnErr(_zx_event_create(0, &SignalHandlerEvent), "_zx_event_create");
368ffb1132eSMatt Morehouse 
369*5de8c7f1SAaron Green   SignalHandler = std::thread(CrashHandler);
370*5de8c7f1SAaron Green   zx_status_t Status = _zx_object_wait_one(SignalHandlerEvent, ZX_USER_SIGNAL_0,
371*5de8c7f1SAaron Green                                            ZX_TIME_INFINITE, nullptr);
3724915d3a1SPetr Hosek   ExitOnErr(Status, "_zx_object_wait_one");
373ffb1132eSMatt Morehouse 
374*5de8c7f1SAaron Green   std::atexit(StopSignalHandler);
375ffb1132eSMatt Morehouse }
376ffb1132eSMatt Morehouse 
SleepSeconds(int Seconds)377ffb1132eSMatt Morehouse void SleepSeconds(int Seconds) {
3782f70693eSPetr Hosek   _zx_nanosleep(_zx_deadline_after(ZX_SEC(Seconds)));
379ffb1132eSMatt Morehouse }
380ffb1132eSMatt Morehouse 
GetPid()381ffb1132eSMatt Morehouse unsigned long GetPid() {
382ffb1132eSMatt Morehouse   zx_status_t rc;
383ffb1132eSMatt Morehouse   zx_info_handle_basic_t Info;
384796bb7d4SPetr Hosek   if ((rc = _zx_object_get_info(_zx_process_self(), ZX_INFO_HANDLE_BASIC, &Info,
385ffb1132eSMatt Morehouse                                 sizeof(Info), NULL, NULL)) != ZX_OK) {
386ffb1132eSMatt Morehouse     Printf("libFuzzer: unable to get info about self: %s\n",
387796bb7d4SPetr Hosek            _zx_status_get_string(rc));
388ffb1132eSMatt Morehouse     exit(1);
389ffb1132eSMatt Morehouse   }
390ffb1132eSMatt Morehouse   return Info.koid;
391ffb1132eSMatt Morehouse }
392ffb1132eSMatt Morehouse 
GetPeakRSSMb()393ffb1132eSMatt Morehouse size_t GetPeakRSSMb() {
394ffb1132eSMatt Morehouse   zx_status_t rc;
395ffb1132eSMatt Morehouse   zx_info_task_stats_t Info;
3962f70693eSPetr Hosek   if ((rc = _zx_object_get_info(_zx_process_self(), ZX_INFO_TASK_STATS, &Info,
397ffb1132eSMatt Morehouse                                 sizeof(Info), NULL, NULL)) != ZX_OK) {
398ffb1132eSMatt Morehouse     Printf("libFuzzer: unable to get info about self: %s\n",
3992f70693eSPetr Hosek            _zx_status_get_string(rc));
400ffb1132eSMatt Morehouse     exit(1);
401ffb1132eSMatt Morehouse   }
402ffb1132eSMatt Morehouse   return (Info.mem_private_bytes + Info.mem_shared_bytes) >> 20;
403ffb1132eSMatt Morehouse }
404ffb1132eSMatt Morehouse 
4052f70693eSPetr Hosek template <typename Fn>
4062f70693eSPetr Hosek class RunOnDestruction {
4072f70693eSPetr Hosek  public:
RunOnDestruction(Fn fn)4082f70693eSPetr Hosek   explicit RunOnDestruction(Fn fn) : fn_(fn) {}
~RunOnDestruction()4092f70693eSPetr Hosek   ~RunOnDestruction() { fn_(); }
4102f70693eSPetr Hosek 
4112f70693eSPetr Hosek  private:
4122f70693eSPetr Hosek   Fn fn_;
4132f70693eSPetr Hosek };
4142f70693eSPetr Hosek 
4152f70693eSPetr Hosek template <typename Fn>
at_scope_exit(Fn fn)4162f70693eSPetr Hosek RunOnDestruction<Fn> at_scope_exit(Fn fn) {
4172f70693eSPetr Hosek   return RunOnDestruction<Fn>(fn);
4182f70693eSPetr Hosek }
4192f70693eSPetr Hosek 
clone_fd_action(int localFd,int targetFd)42044aaca3dSMarco Vanotti static fdio_spawn_action_t clone_fd_action(int localFd, int targetFd) {
42144aaca3dSMarco Vanotti   return {
42244aaca3dSMarco Vanotti       .action = FDIO_SPAWN_ACTION_CLONE_FD,
42344aaca3dSMarco Vanotti       .fd =
42444aaca3dSMarco Vanotti           {
42544aaca3dSMarco Vanotti               .local_fd = localFd,
42644aaca3dSMarco Vanotti               .target_fd = targetFd,
42744aaca3dSMarco Vanotti           },
42844aaca3dSMarco Vanotti   };
42944aaca3dSMarco Vanotti }
43044aaca3dSMarco Vanotti 
ExecuteCommand(const Command & Cmd)431ffb1132eSMatt Morehouse int ExecuteCommand(const Command &Cmd) {
432ffb1132eSMatt Morehouse   zx_status_t rc;
433ffb1132eSMatt Morehouse 
434ffb1132eSMatt Morehouse   // Convert arguments to C array
435ffb1132eSMatt Morehouse   auto Args = Cmd.getArguments();
436ffb1132eSMatt Morehouse   size_t Argc = Args.size();
437ffb1132eSMatt Morehouse   assert(Argc != 0);
4388908aa4eSPetr Hosek   std::unique_ptr<const char *[]> Argv(new const char *[Argc + 1]);
439ffb1132eSMatt Morehouse   for (size_t i = 0; i < Argc; ++i)
440ffb1132eSMatt Morehouse     Argv[i] = Args[i].c_str();
4418908aa4eSPetr Hosek   Argv[Argc] = nullptr;
442ffb1132eSMatt Morehouse 
443a70ece45SPetr Hosek   // Determine output.  On Fuchsia, the fuzzer is typically run as a component
444a70ece45SPetr Hosek   // that lacks a mutable working directory. Fortunately, when this is the case
445a70ece45SPetr Hosek   // a mutable output directory must be specified using "-artifact_prefix=...",
446a70ece45SPetr Hosek   // so write the log file(s) there.
447cde860a1SJake Ehrlich   // However, we don't want to apply this logic for absolute paths.
448ffb1132eSMatt Morehouse   int FdOut = STDOUT_FILENO;
44944aaca3dSMarco Vanotti   bool discardStdout = false;
45044aaca3dSMarco Vanotti   bool discardStderr = false;
45144aaca3dSMarco Vanotti 
452ffb1132eSMatt Morehouse   if (Cmd.hasOutputFile()) {
453cde860a1SJake Ehrlich     std::string Path = Cmd.getOutputFile();
45444aaca3dSMarco Vanotti     if (Path == getDevNull()) {
45544aaca3dSMarco Vanotti       // On Fuchsia, there's no "/dev/null" like-file, so we
45644aaca3dSMarco Vanotti       // just don't copy the FDs into the spawned process.
45744aaca3dSMarco Vanotti       discardStdout = true;
45844aaca3dSMarco Vanotti     } else {
459cde860a1SJake Ehrlich       bool IsAbsolutePath = Path.length() > 1 && Path[0] == '/';
460cde860a1SJake Ehrlich       if (!IsAbsolutePath && Cmd.hasFlag("artifact_prefix"))
461cde860a1SJake Ehrlich         Path = Cmd.getFlagValue("artifact_prefix") + "/" + Path;
462cde860a1SJake Ehrlich 
463a70ece45SPetr Hosek       FdOut = open(Path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0);
4642f70693eSPetr Hosek       if (FdOut == -1) {
465a70ece45SPetr Hosek         Printf("libFuzzer: failed to open %s: %s\n", Path.c_str(),
466ffb1132eSMatt Morehouse                strerror(errno));
467ffb1132eSMatt Morehouse         return ZX_ERR_IO;
468ffb1132eSMatt Morehouse       }
469ffb1132eSMatt Morehouse     }
47044aaca3dSMarco Vanotti   }
471a70ece45SPetr Hosek   auto CloseFdOut = at_scope_exit([FdOut]() {
472a70ece45SPetr Hosek     if (FdOut != STDOUT_FILENO)
473a70ece45SPetr Hosek       close(FdOut);
474a70ece45SPetr Hosek   });
475ffb1132eSMatt Morehouse 
476ffb1132eSMatt Morehouse   // Determine stderr
477ffb1132eSMatt Morehouse   int FdErr = STDERR_FILENO;
47844aaca3dSMarco Vanotti   if (Cmd.isOutAndErrCombined()) {
479ffb1132eSMatt Morehouse     FdErr = FdOut;
48044aaca3dSMarco Vanotti     if (discardStdout)
48144aaca3dSMarco Vanotti       discardStderr = true;
48244aaca3dSMarco Vanotti   }
483ffb1132eSMatt Morehouse 
484ffb1132eSMatt Morehouse   // Clone the file descriptors into the new process
48544aaca3dSMarco Vanotti   std::vector<fdio_spawn_action_t> SpawnActions;
48644aaca3dSMarco Vanotti   SpawnActions.push_back(clone_fd_action(STDIN_FILENO, STDIN_FILENO));
48744aaca3dSMarco Vanotti 
48844aaca3dSMarco Vanotti   if (!discardStdout)
48944aaca3dSMarco Vanotti     SpawnActions.push_back(clone_fd_action(FdOut, STDOUT_FILENO));
49044aaca3dSMarco Vanotti   if (!discardStderr)
49144aaca3dSMarco Vanotti     SpawnActions.push_back(clone_fd_action(FdErr, STDERR_FILENO));
492ffb1132eSMatt Morehouse 
4938908aa4eSPetr Hosek   // Start the process.
4948908aa4eSPetr Hosek   char ErrorMsg[FDIO_SPAWN_ERR_MSG_MAX_LENGTH];
495ffb1132eSMatt Morehouse   zx_handle_t ProcessHandle = ZX_HANDLE_INVALID;
49644aaca3dSMarco Vanotti   rc = fdio_spawn_etc(ZX_HANDLE_INVALID,
49744aaca3dSMarco Vanotti                       FDIO_SPAWN_CLONE_ALL & (~FDIO_SPAWN_CLONE_STDIO), Argv[0],
49844aaca3dSMarco Vanotti                       Argv.get(), nullptr, SpawnActions.size(),
49944aaca3dSMarco Vanotti                       SpawnActions.data(), &ProcessHandle, ErrorMsg);
50044aaca3dSMarco Vanotti 
5018908aa4eSPetr Hosek   if (rc != ZX_OK) {
502ffb1132eSMatt Morehouse     Printf("libFuzzer: failed to launch '%s': %s, %s\n", Argv[0], ErrorMsg,
5032f70693eSPetr Hosek            _zx_status_get_string(rc));
504ffb1132eSMatt Morehouse     return rc;
505ffb1132eSMatt Morehouse   }
5062f70693eSPetr Hosek   auto CloseHandle = at_scope_exit([&]() { _zx_handle_close(ProcessHandle); });
507ffb1132eSMatt Morehouse 
508ffb1132eSMatt Morehouse   // Now join the process and return the exit status.
5092f70693eSPetr Hosek   if ((rc = _zx_object_wait_one(ProcessHandle, ZX_PROCESS_TERMINATED,
510118dc299SPetr Hosek                                 ZX_TIME_INFINITE, nullptr)) != ZX_OK) {
511ffb1132eSMatt Morehouse     Printf("libFuzzer: failed to join '%s': %s\n", Argv[0],
5122f70693eSPetr Hosek            _zx_status_get_string(rc));
513ffb1132eSMatt Morehouse     return rc;
514ffb1132eSMatt Morehouse   }
515ffb1132eSMatt Morehouse 
516ffb1132eSMatt Morehouse   zx_info_process_t Info;
5172f70693eSPetr Hosek   if ((rc = _zx_object_get_info(ProcessHandle, ZX_INFO_PROCESS, &Info,
5182f70693eSPetr Hosek                                 sizeof(Info), nullptr, nullptr)) != ZX_OK) {
519ffb1132eSMatt Morehouse     Printf("libFuzzer: unable to get return code from '%s': %s\n", Argv[0],
520796bb7d4SPetr Hosek            _zx_status_get_string(rc));
521ffb1132eSMatt Morehouse     return rc;
522ffb1132eSMatt Morehouse   }
523ffb1132eSMatt Morehouse 
5246708186cSAaron Green   return static_cast<int>(Info.return_code);
525ffb1132eSMatt Morehouse }
526ffb1132eSMatt Morehouse 
ExecuteCommand(const Command & BaseCmd,std::string * CmdOutput)5274caeb62eSYuanfang Chen bool ExecuteCommand(const Command &BaseCmd, std::string *CmdOutput) {
5284caeb62eSYuanfang Chen   auto LogFilePath = TempPath("SimPopenOut", ".txt");
5294caeb62eSYuanfang Chen   Command Cmd(BaseCmd);
5304caeb62eSYuanfang Chen   Cmd.setOutputFile(LogFilePath);
5314caeb62eSYuanfang Chen   int Ret = ExecuteCommand(Cmd);
5324caeb62eSYuanfang Chen   *CmdOutput = FileToString(LogFilePath);
5334caeb62eSYuanfang Chen   RemoveFile(LogFilePath);
5344caeb62eSYuanfang Chen   return Ret == 0;
5354caeb62eSYuanfang Chen }
5364caeb62eSYuanfang Chen 
SearchMemory(const void * Data,size_t DataLen,const void * Patt,size_t PattLen)537c5d72517SMarco Vanotti const void *SearchMemory(const void *Data, size_t DataLen, const void *Patt,
538c5d72517SMarco Vanotti                          size_t PattLen) {
539c5d72517SMarco Vanotti   return memmem(Data, DataLen, Patt, PattLen);
540c5d72517SMarco Vanotti }
541c5d72517SMarco Vanotti 
542e5b603a4SMarco Vanotti // In fuchsia, accessing /dev/null is not supported. There's nothing
543e5b603a4SMarco Vanotti // similar to a file that discards everything that is written to it.
544e5b603a4SMarco Vanotti // The way of doing something similar in fuchsia is by using
545e5b603a4SMarco Vanotti // fdio_null_create and binding that to a file descriptor.
DiscardOutput(int Fd)546e5b603a4SMarco Vanotti void DiscardOutput(int Fd) {
547e5b603a4SMarco Vanotti   fdio_t *fdio_null = fdio_null_create();
548e5b603a4SMarco Vanotti   if (fdio_null == nullptr) return;
549e5b603a4SMarco Vanotti   int nullfd = fdio_bind_to_fd(fdio_null, -1, 0);
550e5b603a4SMarco Vanotti   if (nullfd < 0) return;
551e5b603a4SMarco Vanotti   dup2(nullfd, Fd);
552e5b603a4SMarco Vanotti }
553e5b603a4SMarco Vanotti 
554ffb1132eSMatt Morehouse } // namespace fuzzer
555ffb1132eSMatt Morehouse 
556ffb1132eSMatt Morehouse #endif // LIBFUZZER_FUCHSIA
557