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 "FuzzerDefs.h"
14 #include "FuzzerInternal.h"
15 #include "FuzzerUtil.h"
21 #include <lib/fdio/spawn.h>
23 #include <sys/select.h>
26 #include <zircon/errors.h>
27 #include <zircon/process.h>
28 #include <zircon/sanitizer.h>
29 #include <zircon/status.h>
30 #include <zircon/syscalls.h>
31 #include <zircon/syscalls/debug.h>
32 #include <zircon/syscalls/exception.h>
33 #include <zircon/syscalls/object.h>
34 #include <zircon/types.h>
38 // Given that Fuchsia doesn't have the POSIX signals that libFuzzer was written
39 // around, the general approach is to spin up dedicated threads to watch for
40 // each requested condition (alarm, interrupt, crash). Of these, the crash
41 // handler is the most involved, as it requires resuming the crashed thread in
42 // order to invoke the sanitizers to get the needed state.
44 // Forward declaration of assembly trampoline needed to resume crashed threads.
45 // This appears to have external linkage to C++, which is why it's not in the
46 // anonymous namespace. The assembly definition inside MakeTrampoline()
47 // actually defines the symbol with internal linkage only.
48 void CrashTrampolineAsm() __asm__("CrashTrampolineAsm");
52 // Helper function to handle Zircon syscall failures.
53 void ExitOnErr(zx_status_t Status, const char *Syscall) {
54 if (Status != ZX_OK) {
55 Printf("libFuzzer: %s failed: %s\n", Syscall,
56 _zx_status_get_string(Status));
61 void AlarmHandler(int Seconds) {
63 SleepSeconds(Seconds);
64 Fuzzer::StaticAlarmCallback();
68 void InterruptHandler() {
70 // Ctrl-C sends ETX in Zircon.
73 FD_SET(STDIN_FILENO, &readfds);
74 select(STDIN_FILENO + 1, &readfds, nullptr, nullptr, nullptr);
75 } while(!FD_ISSET(STDIN_FILENO, &readfds) || getchar() != 0x03);
76 Fuzzer::StaticInterruptCallback();
79 // For the crash handler, we need to call Fuzzer::StaticCrashSignalCallback
80 // without POSIX signal handlers. To achieve this, we use an assembly function
81 // to add the necessary CFI unwinding information and a C function to bridge
82 // from that back into C++.
84 // FIXME: This works as a short-term solution, but this code really shouldn't be
85 // architecture dependent. A better long term solution is to implement remote
86 // unwinding and expose the necessary APIs through sanitizer_common and/or ASAN
87 // to allow the exception handling thread to gather the crash state directly.
89 // Alternatively, Fuchsia may in future actually implement basic signal
90 // handling for the machine trap signals.
91 #if defined(__x86_64__)
92 #define FOREACH_REGISTER(OP_REG, OP_NUM) \
111 #elif defined(__aarch64__)
112 #define FOREACH_REGISTER(OP_REG, OP_NUM) \
147 #error "Unsupported architecture for fuzzing on Fuchsia"
150 // Produces a CFI directive for the named or numbered register.
151 #define CFI_OFFSET_REG(reg) ".cfi_offset " #reg ", %c[" #reg "]\n"
152 #define CFI_OFFSET_NUM(num) CFI_OFFSET_REG(r##num)
154 // Produces an assembler input operand for the named or numbered register.
155 #define ASM_OPERAND_REG(reg) \
156 [reg] "i"(offsetof(zx_thread_state_general_regs_t, reg)),
157 #define ASM_OPERAND_NUM(num) \
158 [r##num] "i"(offsetof(zx_thread_state_general_regs_t, r[num])),
160 // Trampoline to bridge from the assembly below to the static C++ crash
162 __attribute__((noreturn))
163 static void StaticCrashHandler() {
164 Fuzzer::StaticCrashSignalCallback();
170 // Creates the trampoline with the necessary CFI information to unwind through
171 // to the crashing call stack. The attribute is necessary because the function
172 // is never called; it's just a container around the assembly to allow it to
173 // use operands for compile-time computed constants.
174 __attribute__((used))
175 void MakeTrampoline() {
176 __asm__(".cfi_endproc\n"
177 ".pushsection .text.CrashTrampolineAsm\n"
178 ".type CrashTrampolineAsm,STT_FUNC\n"
179 "CrashTrampolineAsm:\n"
180 ".cfi_startproc simple\n"
181 ".cfi_signal_frame\n"
182 #if defined(__x86_64__)
183 ".cfi_return_column rip\n"
184 ".cfi_def_cfa rsp, 0\n"
185 FOREACH_REGISTER(CFI_OFFSET_REG, CFI_OFFSET_NUM)
186 "call %c[StaticCrashHandler]\n"
188 #elif defined(__aarch64__)
189 ".cfi_return_column 33\n"
190 ".cfi_def_cfa sp, 0\n"
191 ".cfi_offset 33, %c[pc]\n"
192 FOREACH_REGISTER(CFI_OFFSET_REG, CFI_OFFSET_NUM)
193 "bl %[StaticCrashHandler]\n"
195 #error "Unsupported architecture for fuzzing on Fuchsia"
198 ".size CrashTrampolineAsm, . - CrashTrampolineAsm\n"
202 : FOREACH_REGISTER(ASM_OPERAND_REG, ASM_OPERAND_NUM)
203 #if defined(__aarch64__)
206 [StaticCrashHandler] "i" (StaticCrashHandler));
209 void CrashHandler(zx_handle_t *Event) {
210 // This structure is used to ensure we close handles to objects we create in
212 struct ScopedHandle {
213 ~ScopedHandle() { _zx_handle_close(Handle); }
214 zx_handle_t Handle = ZX_HANDLE_INVALID;
217 // Create the exception channel. We need to claim to be a "debugger" so the
218 // kernel will allow us to modify and resume dying threads (see below). Once
219 // the channel is set, we can signal the main thread to continue and wait
220 // for the exception to arrive.
221 ScopedHandle Channel;
222 zx_handle_t Self = _zx_process_self();
223 ExitOnErr(_zx_task_create_exception_channel(
224 Self, ZX_EXCEPTION_CHANNEL_DEBUGGER, &Channel.Handle),
225 "_zx_task_create_exception_channel");
227 ExitOnErr(_zx_object_signal(*Event, 0, ZX_USER_SIGNAL_0),
228 "_zx_object_signal");
230 // This thread lives as long as the process in order to keep handling
231 // crashes. In practice, the first crashed thread to reach the end of the
232 // StaticCrashHandler will end the process.
234 ExitOnErr(_zx_object_wait_one(Channel.Handle, ZX_CHANNEL_READABLE,
235 ZX_TIME_INFINITE, nullptr),
236 "_zx_object_wait_one");
238 zx_exception_info_t ExceptionInfo;
239 ScopedHandle Exception;
240 ExitOnErr(_zx_channel_read(Channel.Handle, 0, &ExceptionInfo,
241 &Exception.Handle, sizeof(ExceptionInfo), 1,
245 // Ignore informational synthetic exceptions.
246 if (ZX_EXCP_THREAD_STARTING == ExceptionInfo.type ||
247 ZX_EXCP_THREAD_EXITING == ExceptionInfo.type ||
248 ZX_EXCP_PROCESS_STARTING == ExceptionInfo.type) {
252 // At this point, we want to get the state of the crashing thread, but
253 // libFuzzer and the sanitizers assume this will happen from that same
254 // thread via a POSIX signal handler. "Resurrecting" the thread in the
255 // middle of the appropriate callback is as simple as forcibly setting the
256 // instruction pointer/program counter, provided we NEVER EVER return from
257 // that function (since otherwise our stack will not be valid).
259 ExitOnErr(_zx_exception_get_thread(Exception.Handle, &Thread.Handle),
260 "_zx_exception_get_thread");
262 zx_thread_state_general_regs_t GeneralRegisters;
263 ExitOnErr(_zx_thread_read_state(Thread.Handle, ZX_THREAD_STATE_GENERAL_REGS,
265 sizeof(GeneralRegisters)),
266 "_zx_thread_read_state");
268 // To unwind properly, we need to push the crashing thread's register state
269 // onto the stack and jump into a trampoline with CFI instructions on how
271 #if defined(__x86_64__)
273 (GeneralRegisters.rsp - (128 + sizeof(GeneralRegisters))) &
275 __unsanitized_memcpy(reinterpret_cast<void *>(StackPtr), &GeneralRegisters,
276 sizeof(GeneralRegisters));
277 GeneralRegisters.rsp = StackPtr;
278 GeneralRegisters.rip = reinterpret_cast<zx_vaddr_t>(CrashTrampolineAsm);
280 #elif defined(__aarch64__)
282 (GeneralRegisters.sp - sizeof(GeneralRegisters)) & -(uintptr_t)16;
283 __unsanitized_memcpy(reinterpret_cast<void *>(StackPtr), &GeneralRegisters,
284 sizeof(GeneralRegisters));
285 GeneralRegisters.sp = StackPtr;
286 GeneralRegisters.pc = reinterpret_cast<zx_vaddr_t>(CrashTrampolineAsm);
289 #error "Unsupported architecture for fuzzing on Fuchsia"
292 // Now force the crashing thread's state.
294 _zx_thread_write_state(Thread.Handle, ZX_THREAD_STATE_GENERAL_REGS,
295 &GeneralRegisters, sizeof(GeneralRegisters)),
296 "_zx_thread_write_state");
298 // Set the exception to HANDLED so it resumes the thread on close.
299 uint32_t ExceptionState = ZX_EXCEPTION_STATE_HANDLED;
300 ExitOnErr(_zx_object_set_property(Exception.Handle, ZX_PROP_EXCEPTION_STATE,
301 &ExceptionState, sizeof(ExceptionState)),
302 "zx_object_set_property");
308 bool Mprotect(void *Ptr, size_t Size, bool AllowReadWrite) {
309 return false; // UNIMPLEMENTED
312 // Platform specific functions.
313 void SetSignalHandler(const FuzzingOptions &Options) {
314 // Set up alarm handler if needed.
315 if (Options.UnitTimeoutSec > 0) {
316 std::thread T(AlarmHandler, Options.UnitTimeoutSec / 2 + 1);
320 // Set up interrupt handler if needed.
321 if (Options.HandleInt || Options.HandleTerm) {
322 std::thread T(InterruptHandler);
326 // Early exit if no crash handler needed.
327 if (!Options.HandleSegv && !Options.HandleBus && !Options.HandleIll &&
328 !Options.HandleFpe && !Options.HandleAbrt)
331 // Set up the crash handler and wait until it is ready before proceeding.
333 ExitOnErr(_zx_event_create(0, &Event), "_zx_event_create");
335 std::thread T(CrashHandler, &Event);
337 _zx_object_wait_one(Event, ZX_USER_SIGNAL_0, ZX_TIME_INFINITE, nullptr);
338 _zx_handle_close(Event);
339 ExitOnErr(Status, "_zx_object_wait_one");
344 void SleepSeconds(int Seconds) {
345 _zx_nanosleep(_zx_deadline_after(ZX_SEC(Seconds)));
348 unsigned long GetPid() {
350 zx_info_handle_basic_t Info;
351 if ((rc = _zx_object_get_info(_zx_process_self(), ZX_INFO_HANDLE_BASIC, &Info,
352 sizeof(Info), NULL, NULL)) != ZX_OK) {
353 Printf("libFuzzer: unable to get info about self: %s\n",
354 _zx_status_get_string(rc));
360 size_t GetPeakRSSMb() {
362 zx_info_task_stats_t Info;
363 if ((rc = _zx_object_get_info(_zx_process_self(), ZX_INFO_TASK_STATS, &Info,
364 sizeof(Info), NULL, NULL)) != ZX_OK) {
365 Printf("libFuzzer: unable to get info about self: %s\n",
366 _zx_status_get_string(rc));
369 return (Info.mem_private_bytes + Info.mem_shared_bytes) >> 20;
372 template <typename Fn>
373 class RunOnDestruction {
375 explicit RunOnDestruction(Fn fn) : fn_(fn) {}
376 ~RunOnDestruction() { fn_(); }
382 template <typename Fn>
383 RunOnDestruction<Fn> at_scope_exit(Fn fn) {
384 return RunOnDestruction<Fn>(fn);
387 int ExecuteCommand(const Command &Cmd) {
390 // Convert arguments to C array
391 auto Args = Cmd.getArguments();
392 size_t Argc = Args.size();
394 std::unique_ptr<const char *[]> Argv(new const char *[Argc + 1]);
395 for (size_t i = 0; i < Argc; ++i)
396 Argv[i] = Args[i].c_str();
397 Argv[Argc] = nullptr;
399 // Determine output. On Fuchsia, the fuzzer is typically run as a component
400 // that lacks a mutable working directory. Fortunately, when this is the case
401 // a mutable output directory must be specified using "-artifact_prefix=...",
402 // so write the log file(s) there.
403 int FdOut = STDOUT_FILENO;
404 if (Cmd.hasOutputFile()) {
406 if (Cmd.hasFlag("artifact_prefix"))
407 Path = Cmd.getFlagValue("artifact_prefix") + "/" + Cmd.getOutputFile();
409 Path = Cmd.getOutputFile();
410 FdOut = open(Path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0);
412 Printf("libFuzzer: failed to open %s: %s\n", Path.c_str(),
417 auto CloseFdOut = at_scope_exit([FdOut]() {
418 if (FdOut != STDOUT_FILENO)
423 int FdErr = STDERR_FILENO;
424 if (Cmd.isOutAndErrCombined())
427 // Clone the file descriptors into the new process
428 fdio_spawn_action_t SpawnAction[] = {
430 .action = FDIO_SPAWN_ACTION_CLONE_FD,
433 .local_fd = STDIN_FILENO,
434 .target_fd = STDIN_FILENO,
438 .action = FDIO_SPAWN_ACTION_CLONE_FD,
442 .target_fd = STDOUT_FILENO,
446 .action = FDIO_SPAWN_ACTION_CLONE_FD,
450 .target_fd = STDERR_FILENO,
455 // Start the process.
456 char ErrorMsg[FDIO_SPAWN_ERR_MSG_MAX_LENGTH];
457 zx_handle_t ProcessHandle = ZX_HANDLE_INVALID;
459 ZX_HANDLE_INVALID, FDIO_SPAWN_CLONE_ALL & (~FDIO_SPAWN_CLONE_STDIO),
460 Argv[0], Argv.get(), nullptr, 3, SpawnAction, &ProcessHandle, ErrorMsg);
462 Printf("libFuzzer: failed to launch '%s': %s, %s\n", Argv[0], ErrorMsg,
463 _zx_status_get_string(rc));
466 auto CloseHandle = at_scope_exit([&]() { _zx_handle_close(ProcessHandle); });
468 // Now join the process and return the exit status.
469 if ((rc = _zx_object_wait_one(ProcessHandle, ZX_PROCESS_TERMINATED,
470 ZX_TIME_INFINITE, nullptr)) != ZX_OK) {
471 Printf("libFuzzer: failed to join '%s': %s\n", Argv[0],
472 _zx_status_get_string(rc));
476 zx_info_process_t Info;
477 if ((rc = _zx_object_get_info(ProcessHandle, ZX_INFO_PROCESS, &Info,
478 sizeof(Info), nullptr, nullptr)) != ZX_OK) {
479 Printf("libFuzzer: unable to get return code from '%s': %s\n", Argv[0],
480 _zx_status_get_string(rc));
484 return Info.return_code;
487 const void *SearchMemory(const void *Data, size_t DataLen, const void *Patt,
489 return memmem(Data, DataLen, Patt, PattLen);
492 } // namespace fuzzer
494 #endif // LIBFUZZER_FUCHSIA