Run DCE after a LoopFlatten test to reduce spurious output [nfc]
[llvm-project.git] / compiler-rt / lib / fuzzer / FuzzerUtilFuchsia.cpp
blobcfb81cd3f780bbca08cf3ee939ff8688febfefa8
1 //===- FuzzerUtilFuchsia.cpp - Misc utils for Fuchsia. --------------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 // Misc utils implementation using Fuchsia/Zircon APIs.
9 //===----------------------------------------------------------------------===//
10 #include "FuzzerPlatform.h"
12 #if LIBFUZZER_FUCHSIA
14 #include "FuzzerInternal.h"
15 #include "FuzzerUtil.h"
16 #include <cassert>
17 #include <cerrno>
18 #include <cinttypes>
19 #include <cstdint>
20 #include <fcntl.h>
21 #include <lib/fdio/fdio.h>
22 #include <lib/fdio/spawn.h>
23 #include <string>
24 #include <sys/select.h>
25 #include <thread>
26 #include <unistd.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>
37 #include <vector>
39 namespace fuzzer {
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");
53 namespace {
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));
66 exit(1);
70 void AlarmHandler(int Seconds) {
71 while (true) {
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) \
92 OP_REG(rax) \
93 OP_REG(rbx) \
94 OP_REG(rcx) \
95 OP_REG(rdx) \
96 OP_REG(rsi) \
97 OP_REG(rdi) \
98 OP_REG(rbp) \
99 OP_REG(rsp) \
100 OP_REG(r8) \
101 OP_REG(r9) \
102 OP_REG(r10) \
103 OP_REG(r11) \
104 OP_REG(r12) \
105 OP_REG(r13) \
106 OP_REG(r14) \
107 OP_REG(r15) \
108 OP_REG(rip)
110 #elif defined(__aarch64__)
112 #define FOREACH_REGISTER(OP_REG, OP_NUM) \
113 OP_NUM(0) \
114 OP_NUM(1) \
115 OP_NUM(2) \
116 OP_NUM(3) \
117 OP_NUM(4) \
118 OP_NUM(5) \
119 OP_NUM(6) \
120 OP_NUM(7) \
121 OP_NUM(8) \
122 OP_NUM(9) \
123 OP_NUM(10) \
124 OP_NUM(11) \
125 OP_NUM(12) \
126 OP_NUM(13) \
127 OP_NUM(14) \
128 OP_NUM(15) \
129 OP_NUM(16) \
130 OP_NUM(17) \
131 OP_NUM(18) \
132 OP_NUM(19) \
133 OP_NUM(20) \
134 OP_NUM(21) \
135 OP_NUM(22) \
136 OP_NUM(23) \
137 OP_NUM(24) \
138 OP_NUM(25) \
139 OP_NUM(26) \
140 OP_NUM(27) \
141 OP_NUM(28) \
142 OP_NUM(29) \
143 OP_REG(sp)
145 #elif defined(__riscv)
147 #define FOREACH_REGISTER(OP_REG, OP_NUM) \
148 OP_REG(ra) \
149 OP_REG(sp) \
150 OP_REG(gp) \
151 OP_REG(tp) \
152 OP_REG(t0) \
153 OP_REG(t1) \
154 OP_REG(t2) \
155 OP_REG(s0) \
156 OP_REG(s1) \
157 OP_REG(a0) \
158 OP_REG(a1) \
159 OP_REG(a2) \
160 OP_REG(a3) \
161 OP_REG(a4) \
162 OP_REG(a5) \
163 OP_REG(a6) \
164 OP_REG(a7) \
165 OP_REG(s2) \
166 OP_REG(s3) \
167 OP_REG(s4) \
168 OP_REG(s5) \
169 OP_REG(s6) \
170 OP_REG(s7) \
171 OP_REG(s8) \
172 OP_REG(s9) \
173 OP_REG(s10) \
174 OP_REG(s11) \
175 OP_REG(t3) \
176 OP_REG(t4) \
177 OP_REG(t5) \
178 OP_REG(t6) \
180 #else
181 #error "Unsupported architecture for fuzzing on Fuchsia"
182 #endif
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
198 // callback.
199 __attribute__((noreturn))
200 static void StaticCrashHandler() {
201 Fuzzer::StaticCrashSignalCallback();
202 for (;;) {
203 _Exit(1);
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() {
219 __asm__(
220 ".cfi_endproc\n"
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"
231 "ud2\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"
239 "brk 1\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"
246 "unimp\n"
247 #else
248 #error "Unsupported architecture for fuzzing on Fuchsia"
249 #endif
250 ".cfi_endproc\n"
251 ".size CrashTrampolineAsm, . - CrashTrampolineAsm\n"
252 ".popsection\n"
253 ".cfi_startproc\n"
254 : // No outputs
255 : FOREACH_REGISTER(ASM_OPERAND_REG, ASM_OPERAND_NUM)
256 #if defined(__aarch64__) || defined(__riscv)
257 ASM_OPERAND_REG(pc)
258 #endif
259 #if defined(__aarch64__)
260 ASM_OPERAND_REG(lr)
261 #endif
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
269 // this handler.
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.
291 while (true) {
292 zx_wait_item_t WaitItems[] = {
294 .handle = SignalHandlerEvent,
295 .waitfor = ZX_SIGNAL_HANDLE_CLOSED,
296 .pending = 0,
299 .handle = Channel.Handle,
300 .waitfor = ZX_CHANNEL_READABLE | ZX_CHANNEL_PEER_CLOSED,
301 .pending = 0,
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) {
307 break;
310 zx_exception_info_t ExceptionInfo;
311 ScopedHandle Exception;
312 ExitOnErr(_zx_channel_read(Channel.Handle, 0, &ExceptionInfo,
313 &Exception.Handle, sizeof(ExceptionInfo), 1,
314 nullptr, nullptr),
315 "_zx_channel_read");
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) {
321 continue;
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).
330 ScopedHandle Thread;
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,
336 &GeneralRegisters,
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
342 // to restore it.
343 #if defined(__x86_64__)
345 uintptr_t StackPtr =
346 (GeneralRegisters.rsp - (128 + sizeof(GeneralRegisters))) &
347 -(uintptr_t)16;
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)
355 uintptr_t StackPtr =
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);
362 #else
363 #error "Unsupported architecture for fuzzing on Fuchsia"
364 #endif
366 // Now force the crashing thread's state.
367 ExitOnErr(
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();
387 } // namespace
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.
395 char Buf[64];
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));
400 Printf("%s", Buf);
402 // Set up alarm handler if needed.
403 if (Options.HandleAlrm && Options.UnitTimeoutSec > 0) {
404 std::thread T(AlarmHandler, Options.UnitTimeoutSec / 2 + 1);
405 T.detach();
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)
413 return;
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() {
431 zx_status_t rc;
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));
437 exit(1);
439 return Info.koid;
442 size_t GetPeakRSSMb() {
443 zx_status_t rc;
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));
449 exit(1);
451 return (Info.mem_private_bytes + Info.mem_shared_bytes) >> 20;
454 template <typename Fn>
455 class RunOnDestruction {
456 public:
457 explicit RunOnDestruction(Fn fn) : fn_(fn) {}
458 ~RunOnDestruction() { fn_(); }
460 private:
461 Fn 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) {
470 return {
471 .action = FDIO_SPAWN_ACTION_CLONE_FD,
472 .fd =
474 .local_fd = localFd,
475 .target_fd = targetFd,
480 int ExecuteCommand(const Command &Cmd) {
481 zx_status_t rc;
483 // Convert arguments to C array
484 auto Args = Cmd.getArguments();
485 size_t Argc = Args.size();
486 assert(Argc != 0);
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;
507 } else {
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);
513 if (FdOut == -1) {
514 Printf("libFuzzer: failed to open %s: %s\n", Path.c_str(),
515 strerror(errno));
516 return ZX_ERR_IO;
520 auto CloseFdOut = at_scope_exit([FdOut]() {
521 if (FdOut != STDOUT_FILENO)
522 close(FdOut);
525 // Determine stderr
526 int FdErr = STDERR_FILENO;
527 if (Cmd.isOutAndErrCombined()) {
528 FdErr = FdOut;
529 if (discardStdout)
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));
537 if (!discardStdout)
538 SpawnActions.push_back(clone_fd_action(FdOut, STDOUT_FILENO));
539 if (!discardStderr)
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);
550 if (rc != ZX_OK) {
551 Printf("libFuzzer: failed to launch '%s': %s, %s\n", Argv[0], ErrorMsg,
552 _zx_status_get_string(rc));
553 return 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));
562 return 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));
570 return 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);
583 return Ret == 0;
586 const void *SearchMemory(const void *Data, size_t DataLen, const void *Patt,
587 size_t PattLen) {
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;
600 dup2(nullfd, Fd);
603 size_t PageSize() {
604 static size_t PageSizeCached = _zx_system_get_page_size();
605 return PageSizeCached;
608 void SetThreadName(std::thread &thread, const std::string &name) {
609 // TODO ?
612 } // namespace fuzzer
614 #endif // LIBFUZZER_FUCHSIA