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 // The signal handler thread uses Zircon exceptions to resume crashed threads
56 // into libFuzzer's POSIX signal handlers. The associated event is used to
57 // signal when the thread is running, and when it should stop.
58 std::thread SignalHandler
;
59 zx_handle_t SignalHandlerEvent
= ZX_HANDLE_INVALID
;
61 // Helper function to handle Zircon syscall failures.
62 void ExitOnErr(zx_status_t Status
, const char *Syscall
) {
63 if (Status
!= ZX_OK
) {
64 Printf("libFuzzer: %s failed: %s\n", Syscall
,
65 _zx_status_get_string(Status
));
70 void AlarmHandler(int Seconds
) {
72 SleepSeconds(Seconds
);
73 Fuzzer::StaticAlarmCallback();
77 // For the crash handler, we need to call Fuzzer::StaticCrashSignalCallback
78 // without POSIX signal handlers. To achieve this, we use an assembly function
79 // to add the necessary CFI unwinding information and a C function to bridge
80 // from that back into C++.
82 // FIXME: This works as a short-term solution, but this code really shouldn't be
83 // architecture dependent. A better long term solution is to implement remote
84 // unwinding and expose the necessary APIs through sanitizer_common and/or ASAN
85 // to allow the exception handling thread to gather the crash state directly.
87 // Alternatively, Fuchsia may in future actually implement basic signal
88 // handling for the machine trap signals.
89 #if defined(__x86_64__)
91 #define FOREACH_REGISTER(OP_REG, OP_NUM) \
110 #elif defined(__aarch64__)
112 #define FOREACH_REGISTER(OP_REG, OP_NUM) \
145 #elif defined(__riscv)
147 #define FOREACH_REGISTER(OP_REG, OP_NUM) \
181 #error "Unsupported architecture for fuzzing on Fuchsia"
184 // Produces a CFI directive for the named or numbered register.
185 // The value used refers to an assembler immediate operand with the same name
186 // as the register (see ASM_OPERAND_REG).
187 #define CFI_OFFSET_REG(reg) ".cfi_offset " #reg ", %c[" #reg "]\n"
188 #define CFI_OFFSET_NUM(num) CFI_OFFSET_REG(x##num)
190 // Produces an assembler immediate operand for the named or numbered register.
191 // This operand contains the offset of the register relative to the CFA.
192 #define ASM_OPERAND_REG(reg) \
193 [reg] "i"(offsetof(zx_thread_state_general_regs_t, reg)),
194 #define ASM_OPERAND_NUM(num) \
195 [x##num] "i"(offsetof(zx_thread_state_general_regs_t, r[num])),
197 // Trampoline to bridge from the assembly below to the static C++ crash
199 __attribute__((noreturn
))
200 static void StaticCrashHandler() {
201 Fuzzer::StaticCrashSignalCallback();
207 // This trampoline function has the necessary CFI information to unwind
208 // and get a backtrace:
209 // * The stack contains a copy of all the registers at the point of crash,
210 // the code has CFI directives specifying how to restore them.
211 // * A call to StaticCrashHandler, which will print the stacktrace and exit
212 // the fuzzer, generating a crash artifact.
214 // The __attribute__((used)) is necessary because the function
215 // is never called; it's just a container around the assembly to allow it to
216 // use operands for compile-time computed constants.
217 __attribute__((used
))
218 void MakeTrampoline() {
221 ".pushsection .text.CrashTrampolineAsm\n"
222 ".type CrashTrampolineAsm,STT_FUNC\n"
223 "CrashTrampolineAsm:\n"
224 ".cfi_startproc simple\n"
225 ".cfi_signal_frame\n"
226 #if defined(__x86_64__)
227 ".cfi_return_column rip\n"
228 ".cfi_def_cfa rsp, 0\n"
229 FOREACH_REGISTER(CFI_OFFSET_REG
, CFI_OFFSET_NUM
)
230 "call %c[StaticCrashHandler]\n"
232 #elif defined(__aarch64__)
233 ".cfi_return_column 33\n"
234 ".cfi_def_cfa sp, 0\n"
235 FOREACH_REGISTER(CFI_OFFSET_REG
, CFI_OFFSET_NUM
)
236 ".cfi_offset 33, %c[pc]\n"
237 ".cfi_offset 30, %c[lr]\n"
238 "bl %c[StaticCrashHandler]\n"
240 #elif defined(__riscv)
241 ".cfi_return_column 64\n"
242 ".cfi_def_cfa sp, 0\n"
243 ".cfi_offset 64, %[pc]\n"
244 FOREACH_REGISTER(CFI_OFFSET_REG
, CFI_OFFSET_NUM
)
245 "call %c[StaticCrashHandler]\n"
248 #error "Unsupported architecture for fuzzing on Fuchsia"
251 ".size CrashTrampolineAsm, . - CrashTrampolineAsm\n"
255 : FOREACH_REGISTER(ASM_OPERAND_REG
, ASM_OPERAND_NUM
)
256 #if defined(__aarch64__) || defined(__riscv)
259 #if defined(__aarch64__)
262 [StaticCrashHandler
] "i"(StaticCrashHandler
));
265 void CrashHandler() {
266 assert(SignalHandlerEvent
!= ZX_HANDLE_INVALID
);
268 // This structure is used to ensure we close handles to objects we create in
270 struct ScopedHandle
{
271 ~ScopedHandle() { _zx_handle_close(Handle
); }
272 zx_handle_t Handle
= ZX_HANDLE_INVALID
;
275 // Create the exception channel. We need to claim to be a "debugger" so the
276 // kernel will allow us to modify and resume dying threads (see below). Once
277 // the channel is set, we can signal the main thread to continue and wait
278 // for the exception to arrive.
279 ScopedHandle Channel
;
280 zx_handle_t Self
= _zx_process_self();
281 ExitOnErr(_zx_task_create_exception_channel(
282 Self
, ZX_EXCEPTION_CHANNEL_DEBUGGER
, &Channel
.Handle
),
283 "_zx_task_create_exception_channel");
285 ExitOnErr(_zx_object_signal(SignalHandlerEvent
, 0, ZX_USER_SIGNAL_0
),
286 "_zx_object_signal");
288 // This thread lives as long as the process in order to keep handling
289 // crashes. In practice, the first crashed thread to reach the end of the
290 // StaticCrashHandler will end the process.
292 zx_wait_item_t WaitItems
[] = {
294 .handle
= SignalHandlerEvent
,
295 .waitfor
= ZX_SIGNAL_HANDLE_CLOSED
,
299 .handle
= Channel
.Handle
,
300 .waitfor
= ZX_CHANNEL_READABLE
| ZX_CHANNEL_PEER_CLOSED
,
304 auto Status
= _zx_object_wait_many(
305 WaitItems
, sizeof(WaitItems
) / sizeof(WaitItems
[0]), ZX_TIME_INFINITE
);
306 if (Status
!= ZX_OK
|| (WaitItems
[1].pending
& ZX_CHANNEL_READABLE
) == 0) {
310 zx_exception_info_t ExceptionInfo
;
311 ScopedHandle Exception
;
312 ExitOnErr(_zx_channel_read(Channel
.Handle
, 0, &ExceptionInfo
,
313 &Exception
.Handle
, sizeof(ExceptionInfo
), 1,
317 // Ignore informational synthetic exceptions.
318 if (ZX_EXCP_THREAD_STARTING
== ExceptionInfo
.type
||
319 ZX_EXCP_THREAD_EXITING
== ExceptionInfo
.type
||
320 ZX_EXCP_PROCESS_STARTING
== ExceptionInfo
.type
) {
324 // At this point, we want to get the state of the crashing thread, but
325 // libFuzzer and the sanitizers assume this will happen from that same
326 // thread via a POSIX signal handler. "Resurrecting" the thread in the
327 // middle of the appropriate callback is as simple as forcibly setting the
328 // instruction pointer/program counter, provided we NEVER EVER return from
329 // that function (since otherwise our stack will not be valid).
331 ExitOnErr(_zx_exception_get_thread(Exception
.Handle
, &Thread
.Handle
),
332 "_zx_exception_get_thread");
334 zx_thread_state_general_regs_t GeneralRegisters
;
335 ExitOnErr(_zx_thread_read_state(Thread
.Handle
, ZX_THREAD_STATE_GENERAL_REGS
,
337 sizeof(GeneralRegisters
)),
338 "_zx_thread_read_state");
340 // To unwind properly, we need to push the crashing thread's register state
341 // onto the stack and jump into a trampoline with CFI instructions on how
343 #if defined(__x86_64__)
346 (GeneralRegisters
.rsp
- (128 + sizeof(GeneralRegisters
))) &
348 __unsanitized_memcpy(reinterpret_cast<void *>(StackPtr
), &GeneralRegisters
,
349 sizeof(GeneralRegisters
));
350 GeneralRegisters
.rsp
= StackPtr
;
351 GeneralRegisters
.rip
= reinterpret_cast<zx_vaddr_t
>(CrashTrampolineAsm
);
353 #elif defined(__aarch64__) || defined(__riscv)
356 (GeneralRegisters
.sp
- sizeof(GeneralRegisters
)) & -(uintptr_t)16;
357 __unsanitized_memcpy(reinterpret_cast<void *>(StackPtr
), &GeneralRegisters
,
358 sizeof(GeneralRegisters
));
359 GeneralRegisters
.sp
= StackPtr
;
360 GeneralRegisters
.pc
= reinterpret_cast<zx_vaddr_t
>(CrashTrampolineAsm
);
363 #error "Unsupported architecture for fuzzing on Fuchsia"
366 // Now force the crashing thread's state.
368 _zx_thread_write_state(Thread
.Handle
, ZX_THREAD_STATE_GENERAL_REGS
,
369 &GeneralRegisters
, sizeof(GeneralRegisters
)),
370 "_zx_thread_write_state");
372 // Set the exception to HANDLED so it resumes the thread on close.
373 uint32_t ExceptionState
= ZX_EXCEPTION_STATE_HANDLED
;
374 ExitOnErr(_zx_object_set_property(Exception
.Handle
, ZX_PROP_EXCEPTION_STATE
,
375 &ExceptionState
, sizeof(ExceptionState
)),
376 "zx_object_set_property");
380 void StopSignalHandler() {
381 _zx_handle_close(SignalHandlerEvent
);
382 if (SignalHandler
.joinable()) {
383 SignalHandler
.join();
389 // Platform specific functions.
390 void SetSignalHandler(const FuzzingOptions
&Options
) {
391 // Make sure information from libFuzzer and the sanitizers are easy to
392 // reassemble. `__sanitizer_log_write` has the added benefit of ensuring the
393 // DSO map is always available for the symbolizer.
394 // A uint64_t fits in 20 chars, so 64 is plenty.
396 memset(Buf
, 0, sizeof(Buf
));
397 snprintf(Buf
, sizeof(Buf
), "==%lu== INFO: libFuzzer starting.\n", GetPid());
398 if (EF
->__sanitizer_log_write
)
399 __sanitizer_log_write(Buf
, sizeof(Buf
));
402 // Set up alarm handler if needed.
403 if (Options
.HandleAlrm
&& Options
.UnitTimeoutSec
> 0) {
404 std::thread
T(AlarmHandler
, Options
.UnitTimeoutSec
/ 2 + 1);
408 // Options.HandleInt and Options.HandleTerm are not supported on Fuchsia
410 // Early exit if no crash handler needed.
411 if (!Options
.HandleSegv
&& !Options
.HandleBus
&& !Options
.HandleIll
&&
412 !Options
.HandleFpe
&& !Options
.HandleAbrt
)
415 // Set up the crash handler and wait until it is ready before proceeding.
416 ExitOnErr(_zx_event_create(0, &SignalHandlerEvent
), "_zx_event_create");
418 SignalHandler
= std::thread(CrashHandler
);
419 zx_status_t Status
= _zx_object_wait_one(SignalHandlerEvent
, ZX_USER_SIGNAL_0
,
420 ZX_TIME_INFINITE
, nullptr);
421 ExitOnErr(Status
, "_zx_object_wait_one");
423 std::atexit(StopSignalHandler
);
426 void SleepSeconds(int Seconds
) {
427 _zx_nanosleep(_zx_deadline_after(ZX_SEC(Seconds
)));
430 unsigned long GetPid() {
432 zx_info_handle_basic_t Info
;
433 if ((rc
= _zx_object_get_info(_zx_process_self(), ZX_INFO_HANDLE_BASIC
, &Info
,
434 sizeof(Info
), NULL
, NULL
)) != ZX_OK
) {
435 Printf("libFuzzer: unable to get info about self: %s\n",
436 _zx_status_get_string(rc
));
442 size_t GetPeakRSSMb() {
444 zx_info_task_stats_t Info
;
445 if ((rc
= _zx_object_get_info(_zx_process_self(), ZX_INFO_TASK_STATS
, &Info
,
446 sizeof(Info
), NULL
, NULL
)) != ZX_OK
) {
447 Printf("libFuzzer: unable to get info about self: %s\n",
448 _zx_status_get_string(rc
));
451 return (Info
.mem_private_bytes
+ Info
.mem_shared_bytes
) >> 20;
454 template <typename Fn
>
455 class RunOnDestruction
{
457 explicit RunOnDestruction(Fn fn
) : fn_(fn
) {}
458 ~RunOnDestruction() { fn_(); }
464 template <typename Fn
>
465 RunOnDestruction
<Fn
> at_scope_exit(Fn fn
) {
466 return RunOnDestruction
<Fn
>(fn
);
469 static fdio_spawn_action_t
clone_fd_action(int localFd
, int targetFd
) {
471 .action
= FDIO_SPAWN_ACTION_CLONE_FD
,
475 .target_fd
= targetFd
,
480 int ExecuteCommand(const Command
&Cmd
) {
483 // Convert arguments to C array
484 auto Args
= Cmd
.getArguments();
485 size_t Argc
= Args
.size();
487 std::unique_ptr
<const char *[]> Argv(new const char *[Argc
+ 1]);
488 for (size_t i
= 0; i
< Argc
; ++i
)
489 Argv
[i
] = Args
[i
].c_str();
490 Argv
[Argc
] = nullptr;
492 // Determine output. On Fuchsia, the fuzzer is typically run as a component
493 // that lacks a mutable working directory. Fortunately, when this is the case
494 // a mutable output directory must be specified using "-artifact_prefix=...",
495 // so write the log file(s) there.
496 // However, we don't want to apply this logic for absolute paths.
497 int FdOut
= STDOUT_FILENO
;
498 bool discardStdout
= false;
499 bool discardStderr
= false;
501 if (Cmd
.hasOutputFile()) {
502 std::string Path
= Cmd
.getOutputFile();
503 if (Path
== getDevNull()) {
504 // On Fuchsia, there's no "/dev/null" like-file, so we
505 // just don't copy the FDs into the spawned process.
506 discardStdout
= true;
508 bool IsAbsolutePath
= Path
.length() > 1 && Path
[0] == '/';
509 if (!IsAbsolutePath
&& Cmd
.hasFlag("artifact_prefix"))
510 Path
= Cmd
.getFlagValue("artifact_prefix") + "/" + Path
;
512 FdOut
= open(Path
.c_str(), O_WRONLY
| O_CREAT
| O_TRUNC
, 0);
514 Printf("libFuzzer: failed to open %s: %s\n", Path
.c_str(),
520 auto CloseFdOut
= at_scope_exit([FdOut
]() {
521 if (FdOut
!= STDOUT_FILENO
)
526 int FdErr
= STDERR_FILENO
;
527 if (Cmd
.isOutAndErrCombined()) {
530 discardStderr
= true;
533 // Clone the file descriptors into the new process
534 std::vector
<fdio_spawn_action_t
> SpawnActions
;
535 SpawnActions
.push_back(clone_fd_action(STDIN_FILENO
, STDIN_FILENO
));
538 SpawnActions
.push_back(clone_fd_action(FdOut
, STDOUT_FILENO
));
540 SpawnActions
.push_back(clone_fd_action(FdErr
, STDERR_FILENO
));
542 // Start the process.
543 char ErrorMsg
[FDIO_SPAWN_ERR_MSG_MAX_LENGTH
];
544 zx_handle_t ProcessHandle
= ZX_HANDLE_INVALID
;
545 rc
= fdio_spawn_etc(ZX_HANDLE_INVALID
,
546 FDIO_SPAWN_CLONE_ALL
& (~FDIO_SPAWN_CLONE_STDIO
), Argv
[0],
547 Argv
.get(), nullptr, SpawnActions
.size(),
548 SpawnActions
.data(), &ProcessHandle
, ErrorMsg
);
551 Printf("libFuzzer: failed to launch '%s': %s, %s\n", Argv
[0], ErrorMsg
,
552 _zx_status_get_string(rc
));
555 auto CloseHandle
= at_scope_exit([&]() { _zx_handle_close(ProcessHandle
); });
557 // Now join the process and return the exit status.
558 if ((rc
= _zx_object_wait_one(ProcessHandle
, ZX_PROCESS_TERMINATED
,
559 ZX_TIME_INFINITE
, nullptr)) != ZX_OK
) {
560 Printf("libFuzzer: failed to join '%s': %s\n", Argv
[0],
561 _zx_status_get_string(rc
));
565 zx_info_process_t Info
;
566 if ((rc
= _zx_object_get_info(ProcessHandle
, ZX_INFO_PROCESS
, &Info
,
567 sizeof(Info
), nullptr, nullptr)) != ZX_OK
) {
568 Printf("libFuzzer: unable to get return code from '%s': %s\n", Argv
[0],
569 _zx_status_get_string(rc
));
573 return static_cast<int>(Info
.return_code
);
576 bool ExecuteCommand(const Command
&BaseCmd
, std::string
*CmdOutput
) {
577 auto LogFilePath
= TempPath("SimPopenOut", ".txt");
578 Command
Cmd(BaseCmd
);
579 Cmd
.setOutputFile(LogFilePath
);
580 int Ret
= ExecuteCommand(Cmd
);
581 *CmdOutput
= FileToString(LogFilePath
);
582 RemoveFile(LogFilePath
);
586 const void *SearchMemory(const void *Data
, size_t DataLen
, const void *Patt
,
588 return memmem(Data
, DataLen
, Patt
, PattLen
);
591 // In fuchsia, accessing /dev/null is not supported. There's nothing
592 // similar to a file that discards everything that is written to it.
593 // The way of doing something similar in fuchsia is by using
594 // fdio_null_create and binding that to a file descriptor.
595 void DiscardOutput(int Fd
) {
596 fdio_t
*fdio_null
= fdio_null_create();
597 if (fdio_null
== nullptr) return;
598 int nullfd
= fdio_bind_to_fd(fdio_null
, -1, 0);
599 if (nullfd
< 0) return;
604 static size_t PageSizeCached
= _zx_system_get_page_size();
605 return PageSizeCached
;
608 void SetThreadName(std::thread
&thread
, const std::string
&name
) {
612 } // namespace fuzzer
614 #endif // LIBFUZZER_FUCHSIA