1 //===- FuzzerUtilFuchsia.cpp - Misc utils for Fuchsia. --------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
8 // Misc utils implementation using Fuchsia/Zircon APIs.
9 //===----------------------------------------------------------------------===//
10 #include "FuzzerPlatform.h"
14 #include "FuzzerInternal.h"
15 #include "FuzzerUtil.h"
21 #include <lib/fdio/fdio.h>
22 #include <lib/fdio/spawn.h>
24 #include <sys/select.h>
27 #include <zircon/errors.h>
28 #include <zircon/process.h>
29 #include <zircon/sanitizer.h>
30 #include <zircon/status.h>
31 #include <zircon/syscalls.h>
32 #include <zircon/syscalls/debug.h>
33 #include <zircon/syscalls/exception.h>
34 #include <zircon/syscalls/object.h>
35 #include <zircon/types.h>
41 // Given that Fuchsia doesn't have the POSIX signals that libFuzzer was written
42 // around, the general approach is to spin up dedicated threads to watch for
43 // each requested condition (alarm, interrupt, crash). Of these, the crash
44 // handler is the most involved, as it requires resuming the crashed thread in
45 // order to invoke the sanitizers to get the needed state.
47 // Forward declaration of assembly trampoline needed to resume crashed threads.
48 // This appears to have external linkage to C++, which is why it's not in the
49 // anonymous namespace. The assembly definition inside MakeTrampoline()
50 // actually defines the symbol with internal linkage only.
51 void CrashTrampolineAsm() __asm__("CrashTrampolineAsm");
55 // Helper function to handle Zircon syscall failures.
56 void ExitOnErr(zx_status_t Status, const char *Syscall) {
57 if (Status != ZX_OK) {
58 Printf("libFuzzer: %s failed: %s\n", Syscall,
59 _zx_status_get_string(Status));
64 void AlarmHandler(int Seconds) {
66 SleepSeconds(Seconds);
67 Fuzzer::StaticAlarmCallback();
71 void InterruptHandler() {
73 // Ctrl-C sends ETX in Zircon.
76 FD_SET(STDIN_FILENO, &readfds);
77 select(STDIN_FILENO + 1, &readfds, nullptr, nullptr, nullptr);
78 } while(!FD_ISSET(STDIN_FILENO, &readfds) || getchar() != 0x03);
79 Fuzzer::StaticInterruptCallback();
82 // CFAOffset is used to reference the stack pointer before entering the
83 // trampoline (Stack Pointer + CFAOffset = prev Stack Pointer). Before jumping
84 // to the trampoline we copy all the registers onto the stack. We need to make
85 // sure that the new stack has enough space to store all the registers.
87 // The trampoline holds CFI information regarding the registers stored in the
88 // stack, which is then used by the unwinder to restore them.
89 #if defined(__x86_64__)
90 // In x86_64 the crashing function might also be using the red zone (128 bytes
91 // on top of their rsp).
92 constexpr size_t CFAOffset = 128 + sizeof(zx_thread_state_general_regs_t);
93 #elif defined(__aarch64__)
94 // In aarch64 we need to always have the stack pointer aligned to 16 bytes, so we
95 // make sure that we are keeping that same alignment.
96 constexpr size_t CFAOffset = (sizeof(zx_thread_state_general_regs_t) + 15) & -(uintptr_t)16;
99 // For the crash handler, we need to call Fuzzer::StaticCrashSignalCallback
100 // without POSIX signal handlers. To achieve this, we use an assembly function
101 // to add the necessary CFI unwinding information and a C function to bridge
102 // from that back into C++.
104 // FIXME: This works as a short-term solution, but this code really shouldn't be
105 // architecture dependent. A better long term solution is to implement remote
106 // unwinding and expose the necessary APIs through sanitizer_common and/or ASAN
107 // to allow the exception handling thread to gather the crash state directly.
109 // Alternatively, Fuchsia may in future actually implement basic signal
110 // handling for the machine trap signals.
111 #if defined(__x86_64__)
112 #define FOREACH_REGISTER(OP_REG, OP_NUM) \
131 #elif defined(__aarch64__)
132 #define FOREACH_REGISTER(OP_REG, OP_NUM) \
166 #error "Unsupported architecture for fuzzing on Fuchsia"
169 // Produces a CFI directive for the named or numbered register.
170 // The value used refers to an assembler immediate operand with the same name
171 // as the register (see ASM_OPERAND_REG).
172 #define CFI_OFFSET_REG(reg) ".cfi_offset " #reg ", %c[" #reg "]\n"
173 #define CFI_OFFSET_NUM(num) CFI_OFFSET_REG(x##num)
175 // Produces an assembler immediate operand for the named or numbered register.
176 // This operand contains the offset of the register relative to the CFA.
177 #define ASM_OPERAND_REG(reg) \
178 [reg] "i"(offsetof(zx_thread_state_general_regs_t, reg) - CFAOffset),
179 #define ASM_OPERAND_NUM(num) \
180 [x##num] "i"(offsetof(zx_thread_state_general_regs_t, r[num]) - CFAOffset),
182 // Trampoline to bridge from the assembly below to the static C++ crash
184 __attribute__((noreturn))
185 static void StaticCrashHandler() {
186 Fuzzer::StaticCrashSignalCallback();
192 // Creates the trampoline with the necessary CFI information to unwind through
193 // to the crashing call stack:
194 // * Defining the CFA so that it points to the stack pointer at the point
196 // * Storing all registers at the point of crash in the stack and refer to them
197 // via CFI information (relative to the CFA).
198 // * Setting the return column so the unwinder knows how to continue unwinding.
199 // * (x86_64) making sure rsp is aligned before calling StaticCrashHandler.
200 // * Calling StaticCrashHandler that will trigger the unwinder.
202 // The __attribute__((used)) is necessary because the function
203 // is never called; it's just a container around the assembly to allow it to
204 // use operands for compile-time computed constants.
205 __attribute__((used))
206 void MakeTrampoline() {
207 __asm__(".cfi_endproc\n"
208 ".pushsection .text.CrashTrampolineAsm\n"
209 ".type CrashTrampolineAsm,STT_FUNC\n"
210 "CrashTrampolineAsm:\n"
211 ".cfi_startproc simple\n"
212 ".cfi_signal_frame\n"
213 #if defined(__x86_64__)
214 ".cfi_return_column rip\n"
215 ".cfi_def_cfa rsp, %c[CFAOffset]\n"
216 FOREACH_REGISTER(CFI_OFFSET_REG, CFI_OFFSET_NUM)
218 ".cfi_def_cfa_register rbp\n"
220 "call %c[StaticCrashHandler]\n"
222 #elif defined(__aarch64__)
223 ".cfi_return_column 33\n"
224 ".cfi_def_cfa sp, %c[CFAOffset]\n"
225 FOREACH_REGISTER(CFI_OFFSET_REG, CFI_OFFSET_NUM)
226 ".cfi_offset 33, %c[pc]\n"
227 ".cfi_offset 30, %c[lr]\n"
228 "bl %c[StaticCrashHandler]\n"
231 #error "Unsupported architecture for fuzzing on Fuchsia"
234 ".size CrashTrampolineAsm, . - CrashTrampolineAsm\n"
238 : FOREACH_REGISTER(ASM_OPERAND_REG, ASM_OPERAND_NUM)
239 #if defined(__aarch64__)
243 [StaticCrashHandler] "i" (StaticCrashHandler),
244 [CFAOffset] "i" (CFAOffset));
247 void CrashHandler(zx_handle_t *Event) {
248 // This structure is used to ensure we close handles to objects we create in
250 struct ScopedHandle {
251 ~ScopedHandle() { _zx_handle_close(Handle); }
252 zx_handle_t Handle = ZX_HANDLE_INVALID;
255 // Create the exception channel. We need to claim to be a "debugger" so the
256 // kernel will allow us to modify and resume dying threads (see below). Once
257 // the channel is set, we can signal the main thread to continue and wait
258 // for the exception to arrive.
259 ScopedHandle Channel;
260 zx_handle_t Self = _zx_process_self();
261 ExitOnErr(_zx_task_create_exception_channel(
262 Self, ZX_EXCEPTION_CHANNEL_DEBUGGER, &Channel.Handle),
263 "_zx_task_create_exception_channel");
265 ExitOnErr(_zx_object_signal(*Event, 0, ZX_USER_SIGNAL_0),
266 "_zx_object_signal");
268 // This thread lives as long as the process in order to keep handling
269 // crashes. In practice, the first crashed thread to reach the end of the
270 // StaticCrashHandler will end the process.
272 ExitOnErr(_zx_object_wait_one(Channel.Handle, ZX_CHANNEL_READABLE,
273 ZX_TIME_INFINITE, nullptr),
274 "_zx_object_wait_one");
276 zx_exception_info_t ExceptionInfo;
277 ScopedHandle Exception;
278 ExitOnErr(_zx_channel_read(Channel.Handle, 0, &ExceptionInfo,
279 &Exception.Handle, sizeof(ExceptionInfo), 1,
283 // Ignore informational synthetic exceptions.
284 if (ZX_EXCP_THREAD_STARTING == ExceptionInfo.type ||
285 ZX_EXCP_THREAD_EXITING == ExceptionInfo.type ||
286 ZX_EXCP_PROCESS_STARTING == ExceptionInfo.type) {
290 // At this point, we want to get the state of the crashing thread, but
291 // libFuzzer and the sanitizers assume this will happen from that same
292 // thread via a POSIX signal handler. "Resurrecting" the thread in the
293 // middle of the appropriate callback is as simple as forcibly setting the
294 // instruction pointer/program counter, provided we NEVER EVER return from
295 // that function (since otherwise our stack will not be valid).
297 ExitOnErr(_zx_exception_get_thread(Exception.Handle, &Thread.Handle),
298 "_zx_exception_get_thread");
300 zx_thread_state_general_regs_t GeneralRegisters;
301 ExitOnErr(_zx_thread_read_state(Thread.Handle, ZX_THREAD_STATE_GENERAL_REGS,
303 sizeof(GeneralRegisters)),
304 "_zx_thread_read_state");
306 // To unwind properly, we need to push the crashing thread's register state
307 // onto the stack and jump into a trampoline with CFI instructions on how
309 #if defined(__x86_64__)
310 uintptr_t StackPtr = GeneralRegisters.rsp - CFAOffset;
311 __unsanitized_memcpy(reinterpret_cast<void *>(StackPtr), &GeneralRegisters,
312 sizeof(GeneralRegisters));
313 GeneralRegisters.rsp = StackPtr;
314 GeneralRegisters.rip = reinterpret_cast<zx_vaddr_t>(CrashTrampolineAsm);
316 #elif defined(__aarch64__)
317 uintptr_t StackPtr = GeneralRegisters.sp - CFAOffset;
318 __unsanitized_memcpy(reinterpret_cast<void *>(StackPtr), &GeneralRegisters,
319 sizeof(GeneralRegisters));
320 GeneralRegisters.sp = StackPtr;
321 GeneralRegisters.pc = reinterpret_cast<zx_vaddr_t>(CrashTrampolineAsm);
324 #error "Unsupported architecture for fuzzing on Fuchsia"
327 // Now force the crashing thread's state.
329 _zx_thread_write_state(Thread.Handle, ZX_THREAD_STATE_GENERAL_REGS,
330 &GeneralRegisters, sizeof(GeneralRegisters)),
331 "_zx_thread_write_state");
333 // Set the exception to HANDLED so it resumes the thread on close.
334 uint32_t ExceptionState = ZX_EXCEPTION_STATE_HANDLED;
335 ExitOnErr(_zx_object_set_property(Exception.Handle, ZX_PROP_EXCEPTION_STATE,
336 &ExceptionState, sizeof(ExceptionState)),
337 "zx_object_set_property");
343 // Platform specific functions.
344 void SetSignalHandler(const FuzzingOptions &Options) {
345 // Make sure information from libFuzzer and the sanitizers are easy to
346 // reassemble. `__sanitizer_log_write` has the added benefit of ensuring the
347 // DSO map is always available for the symbolizer.
348 // A uint64_t fits in 20 chars, so 64 is plenty.
350 memset(Buf, 0, sizeof(Buf));
351 snprintf(Buf, sizeof(Buf), "==%lu== INFO: libFuzzer starting.\n", GetPid());
352 if (EF->__sanitizer_log_write)
353 __sanitizer_log_write(Buf, sizeof(Buf));
356 // Set up alarm handler if needed.
357 if (Options.UnitTimeoutSec > 0) {
358 std::thread T(AlarmHandler, Options.UnitTimeoutSec / 2 + 1);
362 // Set up interrupt handler if needed.
363 if (Options.HandleInt || Options.HandleTerm) {
364 std::thread T(InterruptHandler);
368 // Early exit if no crash handler needed.
369 if (!Options.HandleSegv && !Options.HandleBus && !Options.HandleIll &&
370 !Options.HandleFpe && !Options.HandleAbrt)
373 // Set up the crash handler and wait until it is ready before proceeding.
375 ExitOnErr(_zx_event_create(0, &Event), "_zx_event_create");
377 std::thread T(CrashHandler, &Event);
379 _zx_object_wait_one(Event, ZX_USER_SIGNAL_0, ZX_TIME_INFINITE, nullptr);
380 _zx_handle_close(Event);
381 ExitOnErr(Status, "_zx_object_wait_one");
386 void SleepSeconds(int Seconds) {
387 _zx_nanosleep(_zx_deadline_after(ZX_SEC(Seconds)));
390 unsigned long GetPid() {
392 zx_info_handle_basic_t Info;
393 if ((rc = _zx_object_get_info(_zx_process_self(), ZX_INFO_HANDLE_BASIC, &Info,
394 sizeof(Info), NULL, NULL)) != ZX_OK) {
395 Printf("libFuzzer: unable to get info about self: %s\n",
396 _zx_status_get_string(rc));
402 size_t GetPeakRSSMb() {
404 zx_info_task_stats_t Info;
405 if ((rc = _zx_object_get_info(_zx_process_self(), ZX_INFO_TASK_STATS, &Info,
406 sizeof(Info), NULL, NULL)) != ZX_OK) {
407 Printf("libFuzzer: unable to get info about self: %s\n",
408 _zx_status_get_string(rc));
411 return (Info.mem_private_bytes + Info.mem_shared_bytes) >> 20;
414 template <typename Fn>
415 class RunOnDestruction {
417 explicit RunOnDestruction(Fn fn) : fn_(fn) {}
418 ~RunOnDestruction() { fn_(); }
424 template <typename Fn>
425 RunOnDestruction<Fn> at_scope_exit(Fn fn) {
426 return RunOnDestruction<Fn>(fn);
429 static fdio_spawn_action_t clone_fd_action(int localFd, int targetFd) {
431 .action = FDIO_SPAWN_ACTION_CLONE_FD,
435 .target_fd = targetFd,
440 int ExecuteCommand(const Command &Cmd) {
443 // Convert arguments to C array
444 auto Args = Cmd.getArguments();
445 size_t Argc = Args.size();
447 std::unique_ptr<const char *[]> Argv(new const char *[Argc + 1]);
448 for (size_t i = 0; i < Argc; ++i)
449 Argv[i] = Args[i].c_str();
450 Argv[Argc] = nullptr;
452 // Determine output. On Fuchsia, the fuzzer is typically run as a component
453 // that lacks a mutable working directory. Fortunately, when this is the case
454 // a mutable output directory must be specified using "-artifact_prefix=...",
455 // so write the log file(s) there.
456 // However, we don't want to apply this logic for absolute paths.
457 int FdOut = STDOUT_FILENO;
458 bool discardStdout = false;
459 bool discardStderr = false;
461 if (Cmd.hasOutputFile()) {
462 std::string Path = Cmd.getOutputFile();
463 if (Path == getDevNull()) {
464 // On Fuchsia, there's no "/dev/null" like-file, so we
465 // just don't copy the FDs into the spawned process.
466 discardStdout = true;
468 bool IsAbsolutePath = Path.length() > 1 && Path[0] == '/';
469 if (!IsAbsolutePath && Cmd.hasFlag("artifact_prefix"))
470 Path = Cmd.getFlagValue("artifact_prefix") + "/" + Path;
472 FdOut = open(Path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0);
474 Printf("libFuzzer: failed to open %s: %s\n", Path.c_str(),
480 auto CloseFdOut = at_scope_exit([FdOut]() {
481 if (FdOut != STDOUT_FILENO)
486 int FdErr = STDERR_FILENO;
487 if (Cmd.isOutAndErrCombined()) {
490 discardStderr = true;
493 // Clone the file descriptors into the new process
494 std::vector<fdio_spawn_action_t> SpawnActions;
495 SpawnActions.push_back(clone_fd_action(STDIN_FILENO, STDIN_FILENO));
498 SpawnActions.push_back(clone_fd_action(FdOut, STDOUT_FILENO));
500 SpawnActions.push_back(clone_fd_action(FdErr, STDERR_FILENO));
502 // Start the process.
503 char ErrorMsg[FDIO_SPAWN_ERR_MSG_MAX_LENGTH];
504 zx_handle_t ProcessHandle = ZX_HANDLE_INVALID;
505 rc = fdio_spawn_etc(ZX_HANDLE_INVALID,
506 FDIO_SPAWN_CLONE_ALL & (~FDIO_SPAWN_CLONE_STDIO), Argv[0],
507 Argv.get(), nullptr, SpawnActions.size(),
508 SpawnActions.data(), &ProcessHandle, ErrorMsg);
511 Printf("libFuzzer: failed to launch '%s': %s, %s\n", Argv[0], ErrorMsg,
512 _zx_status_get_string(rc));
515 auto CloseHandle = at_scope_exit([&]() { _zx_handle_close(ProcessHandle); });
517 // Now join the process and return the exit status.
518 if ((rc = _zx_object_wait_one(ProcessHandle, ZX_PROCESS_TERMINATED,
519 ZX_TIME_INFINITE, nullptr)) != ZX_OK) {
520 Printf("libFuzzer: failed to join '%s': %s\n", Argv[0],
521 _zx_status_get_string(rc));
525 zx_info_process_t Info;
526 if ((rc = _zx_object_get_info(ProcessHandle, ZX_INFO_PROCESS, &Info,
527 sizeof(Info), nullptr, nullptr)) != ZX_OK) {
528 Printf("libFuzzer: unable to get return code from '%s': %s\n", Argv[0],
529 _zx_status_get_string(rc));
533 return Info.return_code;
536 bool ExecuteCommand(const Command &BaseCmd, std::string *CmdOutput) {
537 auto LogFilePath = TempPath("SimPopenOut", ".txt");
538 Command Cmd(BaseCmd);
539 Cmd.setOutputFile(LogFilePath);
540 int Ret = ExecuteCommand(Cmd);
541 *CmdOutput = FileToString(LogFilePath);
542 RemoveFile(LogFilePath);
546 const void *SearchMemory(const void *Data, size_t DataLen, const void *Patt,
548 return memmem(Data, DataLen, Patt, PattLen);
551 // In fuchsia, accessing /dev/null is not supported. There's nothing
552 // similar to a file that discards everything that is written to it.
553 // The way of doing something similar in fuchsia is by using
554 // fdio_null_create and binding that to a file descriptor.
555 void DiscardOutput(int Fd) {
556 fdio_t *fdio_null = fdio_null_create();
557 if (fdio_null == nullptr) return;
558 int nullfd = fdio_bind_to_fd(fdio_null, -1, 0);
559 if (nullfd < 0) return;
563 } // namespace fuzzer
565 #endif // LIBFUZZER_FUCHSIA