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" 11 12 #if LIBFUZZER_FUCHSIA 13 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> 36 37 #include <vector> 38 39 namespace fuzzer { 40 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. 46 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"); 52 53 namespace { 54 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)); 60 exit(1); 61 } 62 } 63 64 void AlarmHandler(int Seconds) { 65 while (true) { 66 SleepSeconds(Seconds); 67 Fuzzer::StaticAlarmCallback(); 68 } 69 } 70 71 // For the crash handler, we need to call Fuzzer::StaticCrashSignalCallback 72 // without POSIX signal handlers. To achieve this, we use an assembly function 73 // to add the necessary CFI unwinding information and a C function to bridge 74 // from that back into C++. 75 76 // FIXME: This works as a short-term solution, but this code really shouldn't be 77 // architecture dependent. A better long term solution is to implement remote 78 // unwinding and expose the necessary APIs through sanitizer_common and/or ASAN 79 // to allow the exception handling thread to gather the crash state directly. 80 // 81 // Alternatively, Fuchsia may in future actually implement basic signal 82 // handling for the machine trap signals. 83 #if defined(__x86_64__) 84 #define FOREACH_REGISTER(OP_REG, OP_NUM) \ 85 OP_REG(rax) \ 86 OP_REG(rbx) \ 87 OP_REG(rcx) \ 88 OP_REG(rdx) \ 89 OP_REG(rsi) \ 90 OP_REG(rdi) \ 91 OP_REG(rbp) \ 92 OP_REG(rsp) \ 93 OP_REG(r8) \ 94 OP_REG(r9) \ 95 OP_REG(r10) \ 96 OP_REG(r11) \ 97 OP_REG(r12) \ 98 OP_REG(r13) \ 99 OP_REG(r14) \ 100 OP_REG(r15) \ 101 OP_REG(rip) 102 103 #elif defined(__aarch64__) 104 #define FOREACH_REGISTER(OP_REG, OP_NUM) \ 105 OP_NUM(0) \ 106 OP_NUM(1) \ 107 OP_NUM(2) \ 108 OP_NUM(3) \ 109 OP_NUM(4) \ 110 OP_NUM(5) \ 111 OP_NUM(6) \ 112 OP_NUM(7) \ 113 OP_NUM(8) \ 114 OP_NUM(9) \ 115 OP_NUM(10) \ 116 OP_NUM(11) \ 117 OP_NUM(12) \ 118 OP_NUM(13) \ 119 OP_NUM(14) \ 120 OP_NUM(15) \ 121 OP_NUM(16) \ 122 OP_NUM(17) \ 123 OP_NUM(18) \ 124 OP_NUM(19) \ 125 OP_NUM(20) \ 126 OP_NUM(21) \ 127 OP_NUM(22) \ 128 OP_NUM(23) \ 129 OP_NUM(24) \ 130 OP_NUM(25) \ 131 OP_NUM(26) \ 132 OP_NUM(27) \ 133 OP_NUM(28) \ 134 OP_NUM(29) \ 135 OP_REG(sp) 136 137 #else 138 #error "Unsupported architecture for fuzzing on Fuchsia" 139 #endif 140 141 // Produces a CFI directive for the named or numbered register. 142 // The value used refers to an assembler immediate operand with the same name 143 // as the register (see ASM_OPERAND_REG). 144 #define CFI_OFFSET_REG(reg) ".cfi_offset " #reg ", %c[" #reg "]\n" 145 #define CFI_OFFSET_NUM(num) CFI_OFFSET_REG(x##num) 146 147 // Produces an assembler immediate operand for the named or numbered register. 148 // This operand contains the offset of the register relative to the CFA. 149 #define ASM_OPERAND_REG(reg) \ 150 [reg] "i"(offsetof(zx_thread_state_general_regs_t, reg)), 151 #define ASM_OPERAND_NUM(num) \ 152 [x##num] "i"(offsetof(zx_thread_state_general_regs_t, r[num])), 153 154 // Trampoline to bridge from the assembly below to the static C++ crash 155 // callback. 156 __attribute__((noreturn)) 157 static void StaticCrashHandler() { 158 Fuzzer::StaticCrashSignalCallback(); 159 for (;;) { 160 _Exit(1); 161 } 162 } 163 164 // This trampoline function has the necessary CFI information to unwind 165 // and get a backtrace: 166 // * The stack contains a copy of all the registers at the point of crash, 167 // the code has CFI directives specifying how to restore them. 168 // * A call to StaticCrashHandler, which will print the stacktrace and exit 169 // the fuzzer, generating a crash artifact. 170 // 171 // The __attribute__((used)) 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__( 177 ".cfi_endproc\n" 178 ".pushsection .text.CrashTrampolineAsm\n" 179 ".type CrashTrampolineAsm,STT_FUNC\n" 180 "CrashTrampolineAsm:\n" 181 ".cfi_startproc simple\n" 182 ".cfi_signal_frame\n" 183 #if defined(__x86_64__) 184 ".cfi_return_column rip\n" 185 ".cfi_def_cfa rsp, 0\n" 186 FOREACH_REGISTER(CFI_OFFSET_REG, CFI_OFFSET_NUM) 187 "call %c[StaticCrashHandler]\n" 188 "ud2\n" 189 #elif defined(__aarch64__) 190 ".cfi_return_column 33\n" 191 ".cfi_def_cfa sp, 0\n" 192 FOREACH_REGISTER(CFI_OFFSET_REG, CFI_OFFSET_NUM) 193 ".cfi_offset 33, %c[pc]\n" 194 ".cfi_offset 30, %c[lr]\n" 195 "bl %c[StaticCrashHandler]\n" 196 "brk 1\n" 197 #else 198 #error "Unsupported architecture for fuzzing on Fuchsia" 199 #endif 200 ".cfi_endproc\n" 201 ".size CrashTrampolineAsm, . - CrashTrampolineAsm\n" 202 ".popsection\n" 203 ".cfi_startproc\n" 204 : // No outputs 205 : FOREACH_REGISTER(ASM_OPERAND_REG, ASM_OPERAND_NUM) 206 #if defined(__aarch64__) 207 ASM_OPERAND_REG(pc) ASM_OPERAND_REG(lr) 208 #endif 209 [StaticCrashHandler] "i"(StaticCrashHandler)); 210 } 211 212 void CrashHandler(zx_handle_t *Event) { 213 // This structure is used to ensure we close handles to objects we create in 214 // this handler. 215 struct ScopedHandle { 216 ~ScopedHandle() { _zx_handle_close(Handle); } 217 zx_handle_t Handle = ZX_HANDLE_INVALID; 218 }; 219 220 // Create the exception channel. We need to claim to be a "debugger" so the 221 // kernel will allow us to modify and resume dying threads (see below). Once 222 // the channel is set, we can signal the main thread to continue and wait 223 // for the exception to arrive. 224 ScopedHandle Channel; 225 zx_handle_t Self = _zx_process_self(); 226 ExitOnErr(_zx_task_create_exception_channel( 227 Self, ZX_EXCEPTION_CHANNEL_DEBUGGER, &Channel.Handle), 228 "_zx_task_create_exception_channel"); 229 230 ExitOnErr(_zx_object_signal(*Event, 0, ZX_USER_SIGNAL_0), 231 "_zx_object_signal"); 232 233 // This thread lives as long as the process in order to keep handling 234 // crashes. In practice, the first crashed thread to reach the end of the 235 // StaticCrashHandler will end the process. 236 while (true) { 237 ExitOnErr(_zx_object_wait_one(Channel.Handle, ZX_CHANNEL_READABLE, 238 ZX_TIME_INFINITE, nullptr), 239 "_zx_object_wait_one"); 240 241 zx_exception_info_t ExceptionInfo; 242 ScopedHandle Exception; 243 ExitOnErr(_zx_channel_read(Channel.Handle, 0, &ExceptionInfo, 244 &Exception.Handle, sizeof(ExceptionInfo), 1, 245 nullptr, nullptr), 246 "_zx_channel_read"); 247 248 // Ignore informational synthetic exceptions. 249 if (ZX_EXCP_THREAD_STARTING == ExceptionInfo.type || 250 ZX_EXCP_THREAD_EXITING == ExceptionInfo.type || 251 ZX_EXCP_PROCESS_STARTING == ExceptionInfo.type) { 252 continue; 253 } 254 255 // At this point, we want to get the state of the crashing thread, but 256 // libFuzzer and the sanitizers assume this will happen from that same 257 // thread via a POSIX signal handler. "Resurrecting" the thread in the 258 // middle of the appropriate callback is as simple as forcibly setting the 259 // instruction pointer/program counter, provided we NEVER EVER return from 260 // that function (since otherwise our stack will not be valid). 261 ScopedHandle Thread; 262 ExitOnErr(_zx_exception_get_thread(Exception.Handle, &Thread.Handle), 263 "_zx_exception_get_thread"); 264 265 zx_thread_state_general_regs_t GeneralRegisters; 266 ExitOnErr(_zx_thread_read_state(Thread.Handle, ZX_THREAD_STATE_GENERAL_REGS, 267 &GeneralRegisters, 268 sizeof(GeneralRegisters)), 269 "_zx_thread_read_state"); 270 271 // To unwind properly, we need to push the crashing thread's register state 272 // onto the stack and jump into a trampoline with CFI instructions on how 273 // to restore it. 274 #if defined(__x86_64__) 275 uintptr_t StackPtr = 276 (GeneralRegisters.rsp - (128 + sizeof(GeneralRegisters))) & 277 -(uintptr_t)16; 278 __unsanitized_memcpy(reinterpret_cast<void *>(StackPtr), &GeneralRegisters, 279 sizeof(GeneralRegisters)); 280 GeneralRegisters.rsp = StackPtr; 281 GeneralRegisters.rip = reinterpret_cast<zx_vaddr_t>(CrashTrampolineAsm); 282 283 #elif defined(__aarch64__) 284 uintptr_t StackPtr = 285 (GeneralRegisters.sp - sizeof(GeneralRegisters)) & -(uintptr_t)16; 286 __unsanitized_memcpy(reinterpret_cast<void *>(StackPtr), &GeneralRegisters, 287 sizeof(GeneralRegisters)); 288 GeneralRegisters.sp = StackPtr; 289 GeneralRegisters.pc = reinterpret_cast<zx_vaddr_t>(CrashTrampolineAsm); 290 291 #else 292 #error "Unsupported architecture for fuzzing on Fuchsia" 293 #endif 294 295 // Now force the crashing thread's state. 296 ExitOnErr( 297 _zx_thread_write_state(Thread.Handle, ZX_THREAD_STATE_GENERAL_REGS, 298 &GeneralRegisters, sizeof(GeneralRegisters)), 299 "_zx_thread_write_state"); 300 301 // Set the exception to HANDLED so it resumes the thread on close. 302 uint32_t ExceptionState = ZX_EXCEPTION_STATE_HANDLED; 303 ExitOnErr(_zx_object_set_property(Exception.Handle, ZX_PROP_EXCEPTION_STATE, 304 &ExceptionState, sizeof(ExceptionState)), 305 "zx_object_set_property"); 306 } 307 } 308 309 } // namespace 310 311 // Platform specific functions. 312 void SetSignalHandler(const FuzzingOptions &Options) { 313 // Make sure information from libFuzzer and the sanitizers are easy to 314 // reassemble. `__sanitizer_log_write` has the added benefit of ensuring the 315 // DSO map is always available for the symbolizer. 316 // A uint64_t fits in 20 chars, so 64 is plenty. 317 char Buf[64]; 318 memset(Buf, 0, sizeof(Buf)); 319 snprintf(Buf, sizeof(Buf), "==%lu== INFO: libFuzzer starting.\n", GetPid()); 320 if (EF->__sanitizer_log_write) 321 __sanitizer_log_write(Buf, sizeof(Buf)); 322 Printf("%s", Buf); 323 324 // Set up alarm handler if needed. 325 if (Options.HandleAlrm && Options.UnitTimeoutSec > 0) { 326 std::thread T(AlarmHandler, Options.UnitTimeoutSec / 2 + 1); 327 T.detach(); 328 } 329 330 // Options.HandleInt and Options.HandleTerm are not supported on Fuchsia 331 332 // Early exit if no crash handler needed. 333 if (!Options.HandleSegv && !Options.HandleBus && !Options.HandleIll && 334 !Options.HandleFpe && !Options.HandleAbrt) 335 return; 336 337 // Set up the crash handler and wait until it is ready before proceeding. 338 zx_handle_t Event; 339 ExitOnErr(_zx_event_create(0, &Event), "_zx_event_create"); 340 341 std::thread T(CrashHandler, &Event); 342 zx_status_t Status = 343 _zx_object_wait_one(Event, ZX_USER_SIGNAL_0, ZX_TIME_INFINITE, nullptr); 344 _zx_handle_close(Event); 345 ExitOnErr(Status, "_zx_object_wait_one"); 346 347 T.detach(); 348 } 349 350 void SleepSeconds(int Seconds) { 351 _zx_nanosleep(_zx_deadline_after(ZX_SEC(Seconds))); 352 } 353 354 unsigned long GetPid() { 355 zx_status_t rc; 356 zx_info_handle_basic_t Info; 357 if ((rc = _zx_object_get_info(_zx_process_self(), ZX_INFO_HANDLE_BASIC, &Info, 358 sizeof(Info), NULL, NULL)) != ZX_OK) { 359 Printf("libFuzzer: unable to get info about self: %s\n", 360 _zx_status_get_string(rc)); 361 exit(1); 362 } 363 return Info.koid; 364 } 365 366 size_t GetPeakRSSMb() { 367 zx_status_t rc; 368 zx_info_task_stats_t Info; 369 if ((rc = _zx_object_get_info(_zx_process_self(), ZX_INFO_TASK_STATS, &Info, 370 sizeof(Info), NULL, NULL)) != ZX_OK) { 371 Printf("libFuzzer: unable to get info about self: %s\n", 372 _zx_status_get_string(rc)); 373 exit(1); 374 } 375 return (Info.mem_private_bytes + Info.mem_shared_bytes) >> 20; 376 } 377 378 template <typename Fn> 379 class RunOnDestruction { 380 public: 381 explicit RunOnDestruction(Fn fn) : fn_(fn) {} 382 ~RunOnDestruction() { fn_(); } 383 384 private: 385 Fn fn_; 386 }; 387 388 template <typename Fn> 389 RunOnDestruction<Fn> at_scope_exit(Fn fn) { 390 return RunOnDestruction<Fn>(fn); 391 } 392 393 static fdio_spawn_action_t clone_fd_action(int localFd, int targetFd) { 394 return { 395 .action = FDIO_SPAWN_ACTION_CLONE_FD, 396 .fd = 397 { 398 .local_fd = localFd, 399 .target_fd = targetFd, 400 }, 401 }; 402 } 403 404 int ExecuteCommand(const Command &Cmd) { 405 zx_status_t rc; 406 407 // Convert arguments to C array 408 auto Args = Cmd.getArguments(); 409 size_t Argc = Args.size(); 410 assert(Argc != 0); 411 std::unique_ptr<const char *[]> Argv(new const char *[Argc + 1]); 412 for (size_t i = 0; i < Argc; ++i) 413 Argv[i] = Args[i].c_str(); 414 Argv[Argc] = nullptr; 415 416 // Determine output. On Fuchsia, the fuzzer is typically run as a component 417 // that lacks a mutable working directory. Fortunately, when this is the case 418 // a mutable output directory must be specified using "-artifact_prefix=...", 419 // so write the log file(s) there. 420 // However, we don't want to apply this logic for absolute paths. 421 int FdOut = STDOUT_FILENO; 422 bool discardStdout = false; 423 bool discardStderr = false; 424 425 if (Cmd.hasOutputFile()) { 426 std::string Path = Cmd.getOutputFile(); 427 if (Path == getDevNull()) { 428 // On Fuchsia, there's no "/dev/null" like-file, so we 429 // just don't copy the FDs into the spawned process. 430 discardStdout = true; 431 } else { 432 bool IsAbsolutePath = Path.length() > 1 && Path[0] == '/'; 433 if (!IsAbsolutePath && Cmd.hasFlag("artifact_prefix")) 434 Path = Cmd.getFlagValue("artifact_prefix") + "/" + Path; 435 436 FdOut = open(Path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0); 437 if (FdOut == -1) { 438 Printf("libFuzzer: failed to open %s: %s\n", Path.c_str(), 439 strerror(errno)); 440 return ZX_ERR_IO; 441 } 442 } 443 } 444 auto CloseFdOut = at_scope_exit([FdOut]() { 445 if (FdOut != STDOUT_FILENO) 446 close(FdOut); 447 }); 448 449 // Determine stderr 450 int FdErr = STDERR_FILENO; 451 if (Cmd.isOutAndErrCombined()) { 452 FdErr = FdOut; 453 if (discardStdout) 454 discardStderr = true; 455 } 456 457 // Clone the file descriptors into the new process 458 std::vector<fdio_spawn_action_t> SpawnActions; 459 SpawnActions.push_back(clone_fd_action(STDIN_FILENO, STDIN_FILENO)); 460 461 if (!discardStdout) 462 SpawnActions.push_back(clone_fd_action(FdOut, STDOUT_FILENO)); 463 if (!discardStderr) 464 SpawnActions.push_back(clone_fd_action(FdErr, STDERR_FILENO)); 465 466 // Start the process. 467 char ErrorMsg[FDIO_SPAWN_ERR_MSG_MAX_LENGTH]; 468 zx_handle_t ProcessHandle = ZX_HANDLE_INVALID; 469 rc = fdio_spawn_etc(ZX_HANDLE_INVALID, 470 FDIO_SPAWN_CLONE_ALL & (~FDIO_SPAWN_CLONE_STDIO), Argv[0], 471 Argv.get(), nullptr, SpawnActions.size(), 472 SpawnActions.data(), &ProcessHandle, ErrorMsg); 473 474 if (rc != ZX_OK) { 475 Printf("libFuzzer: failed to launch '%s': %s, %s\n", Argv[0], ErrorMsg, 476 _zx_status_get_string(rc)); 477 return rc; 478 } 479 auto CloseHandle = at_scope_exit([&]() { _zx_handle_close(ProcessHandle); }); 480 481 // Now join the process and return the exit status. 482 if ((rc = _zx_object_wait_one(ProcessHandle, ZX_PROCESS_TERMINATED, 483 ZX_TIME_INFINITE, nullptr)) != ZX_OK) { 484 Printf("libFuzzer: failed to join '%s': %s\n", Argv[0], 485 _zx_status_get_string(rc)); 486 return rc; 487 } 488 489 zx_info_process_t Info; 490 if ((rc = _zx_object_get_info(ProcessHandle, ZX_INFO_PROCESS, &Info, 491 sizeof(Info), nullptr, nullptr)) != ZX_OK) { 492 Printf("libFuzzer: unable to get return code from '%s': %s\n", Argv[0], 493 _zx_status_get_string(rc)); 494 return rc; 495 } 496 497 return static_cast<int>(Info.return_code); 498 } 499 500 bool ExecuteCommand(const Command &BaseCmd, std::string *CmdOutput) { 501 auto LogFilePath = TempPath("SimPopenOut", ".txt"); 502 Command Cmd(BaseCmd); 503 Cmd.setOutputFile(LogFilePath); 504 int Ret = ExecuteCommand(Cmd); 505 *CmdOutput = FileToString(LogFilePath); 506 RemoveFile(LogFilePath); 507 return Ret == 0; 508 } 509 510 const void *SearchMemory(const void *Data, size_t DataLen, const void *Patt, 511 size_t PattLen) { 512 return memmem(Data, DataLen, Patt, PattLen); 513 } 514 515 // In fuchsia, accessing /dev/null is not supported. There's nothing 516 // similar to a file that discards everything that is written to it. 517 // The way of doing something similar in fuchsia is by using 518 // fdio_null_create and binding that to a file descriptor. 519 void DiscardOutput(int Fd) { 520 fdio_t *fdio_null = fdio_null_create(); 521 if (fdio_null == nullptr) return; 522 int nullfd = fdio_bind_to_fd(fdio_null, -1, 0); 523 if (nullfd < 0) return; 524 dup2(nullfd, Fd); 525 } 526 527 } // namespace fuzzer 528 529 #endif // LIBFUZZER_FUCHSIA 530