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 "FuzzerDefs.h" 11 12 #if LIBFUZZER_FUCHSIA 13 14 #include "FuzzerInternal.h" 15 #include "FuzzerUtil.h" 16 #include <cerrno> 17 #include <cinttypes> 18 #include <cstdint> 19 #include <fcntl.h> 20 #include <lib/fdio/spawn.h> 21 #include <string> 22 #include <sys/select.h> 23 #include <thread> 24 #include <unistd.h> 25 #include <zircon/errors.h> 26 #include <zircon/process.h> 27 #include <zircon/sanitizer.h> 28 #include <zircon/status.h> 29 #include <zircon/syscalls.h> 30 #include <zircon/syscalls/debug.h> 31 #include <zircon/syscalls/exception.h> 32 #include <zircon/syscalls/port.h> 33 #include <zircon/types.h> 34 35 namespace fuzzer { 36 37 // Given that Fuchsia doesn't have the POSIX signals that libFuzzer was written 38 // around, the general approach is to spin up dedicated threads to watch for 39 // each requested condition (alarm, interrupt, crash). Of these, the crash 40 // handler is the most involved, as it requires resuming the crashed thread in 41 // order to invoke the sanitizers to get the needed state. 42 43 // Forward declaration of assembly trampoline needed to resume crashed threads. 44 // This appears to have external linkage to C++, which is why it's not in the 45 // anonymous namespace. The assembly definition inside MakeTrampoline() 46 // actually defines the symbol with internal linkage only. 47 void CrashTrampolineAsm() __asm__("CrashTrampolineAsm"); 48 49 namespace { 50 51 // A magic value for the Zircon exception port, chosen to spell 'FUZZING' 52 // when interpreted as a byte sequence on little-endian platforms. 53 const uint64_t kFuzzingCrash = 0x474e495a5a5546; 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 void InterruptHandler() { 72 fd_set readfds; 73 // Ctrl-C sends ETX in Zircon. 74 do { 75 FD_ZERO(&readfds); 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(); 80 } 81 82 // For the crash handler, we need to call Fuzzer::StaticCrashSignalCallback 83 // without POSIX signal handlers. To achieve this, we use an assembly function 84 // to add the necessary CFI unwinding information and a C function to bridge 85 // from that back into C++. 86 87 // FIXME: This works as a short-term solution, but this code really shouldn't be 88 // architecture dependent. A better long term solution is to implement remote 89 // unwinding and expose the necessary APIs through sanitizer_common and/or ASAN 90 // to allow the exception handling thread to gather the crash state directly. 91 // 92 // Alternatively, Fuchsia may in future actually implement basic signal 93 // handling for the machine trap signals. 94 #if defined(__x86_64__) 95 #define FOREACH_REGISTER(OP_REG, OP_NUM) \ 96 OP_REG(rax) \ 97 OP_REG(rbx) \ 98 OP_REG(rcx) \ 99 OP_REG(rdx) \ 100 OP_REG(rsi) \ 101 OP_REG(rdi) \ 102 OP_REG(rbp) \ 103 OP_REG(rsp) \ 104 OP_REG(r8) \ 105 OP_REG(r9) \ 106 OP_REG(r10) \ 107 OP_REG(r11) \ 108 OP_REG(r12) \ 109 OP_REG(r13) \ 110 OP_REG(r14) \ 111 OP_REG(r15) \ 112 OP_REG(rip) 113 114 #elif defined(__aarch64__) 115 #define FOREACH_REGISTER(OP_REG, OP_NUM) \ 116 OP_NUM(0) \ 117 OP_NUM(1) \ 118 OP_NUM(2) \ 119 OP_NUM(3) \ 120 OP_NUM(4) \ 121 OP_NUM(5) \ 122 OP_NUM(6) \ 123 OP_NUM(7) \ 124 OP_NUM(8) \ 125 OP_NUM(9) \ 126 OP_NUM(10) \ 127 OP_NUM(11) \ 128 OP_NUM(12) \ 129 OP_NUM(13) \ 130 OP_NUM(14) \ 131 OP_NUM(15) \ 132 OP_NUM(16) \ 133 OP_NUM(17) \ 134 OP_NUM(18) \ 135 OP_NUM(19) \ 136 OP_NUM(20) \ 137 OP_NUM(21) \ 138 OP_NUM(22) \ 139 OP_NUM(23) \ 140 OP_NUM(24) \ 141 OP_NUM(25) \ 142 OP_NUM(26) \ 143 OP_NUM(27) \ 144 OP_NUM(28) \ 145 OP_NUM(29) \ 146 OP_NUM(30) \ 147 OP_REG(sp) 148 149 #else 150 #error "Unsupported architecture for fuzzing on Fuchsia" 151 #endif 152 153 // Produces a CFI directive for the named or numbered register. 154 #define CFI_OFFSET_REG(reg) ".cfi_offset " #reg ", %c[" #reg "]\n" 155 #define CFI_OFFSET_NUM(num) CFI_OFFSET_REG(r##num) 156 157 // Produces an assembler input operand for the named or numbered register. 158 #define ASM_OPERAND_REG(reg) \ 159 [reg] "i"(offsetof(zx_thread_state_general_regs_t, reg)), 160 #define ASM_OPERAND_NUM(num) \ 161 [r##num] "i"(offsetof(zx_thread_state_general_regs_t, r[num])), 162 163 // Trampoline to bridge from the assembly below to the static C++ crash 164 // callback. 165 __attribute__((noreturn)) 166 static void StaticCrashHandler() { 167 Fuzzer::StaticCrashSignalCallback(); 168 for (;;) { 169 _Exit(1); 170 } 171 } 172 173 // Creates the trampoline with the necessary CFI information to unwind through 174 // to the crashing call stack. The attribute is necessary because the function 175 // is never called; it's just a container around the assembly to allow it to 176 // use operands for compile-time computed constants. 177 __attribute__((used)) 178 void MakeTrampoline() { 179 __asm__(".cfi_endproc\n" 180 ".pushsection .text.CrashTrampolineAsm\n" 181 ".type CrashTrampolineAsm,STT_FUNC\n" 182 "CrashTrampolineAsm:\n" 183 ".cfi_startproc simple\n" 184 ".cfi_signal_frame\n" 185 #if defined(__x86_64__) 186 ".cfi_return_column rip\n" 187 ".cfi_def_cfa rsp, 0\n" 188 FOREACH_REGISTER(CFI_OFFSET_REG, CFI_OFFSET_NUM) 189 "call %c[StaticCrashHandler]\n" 190 "ud2\n" 191 #elif defined(__aarch64__) 192 ".cfi_return_column 33\n" 193 ".cfi_def_cfa sp, 0\n" 194 ".cfi_offset 33, %c[pc]\n" 195 FOREACH_REGISTER(CFI_OFFSET_REG, CFI_OFFSET_NUM) 196 "bl %[StaticCrashHandler]\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) 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 and bind the exception port. We need to claim to be a "debugger" so 221 // the kernel will allow us to modify and resume dying threads (see below). 222 // Once the port is set, we can signal the main thread to continue and wait 223 // for the exception to arrive. 224 ScopedHandle Port; 225 ExitOnErr(_zx_port_create(0, &Port.Handle), "_zx_port_create"); 226 zx_handle_t Self = _zx_process_self(); 227 228 ExitOnErr(_zx_task_bind_exception_port(Self, Port.Handle, kFuzzingCrash, 229 ZX_EXCEPTION_PORT_DEBUGGER), 230 "_zx_task_bind_exception_port"); 231 232 ExitOnErr(_zx_object_signal(*Event, 0, ZX_USER_SIGNAL_0), 233 "_zx_object_signal"); 234 235 zx_port_packet_t Packet; 236 ExitOnErr(_zx_port_wait(Port.Handle, ZX_TIME_INFINITE, &Packet), 237 "_zx_port_wait"); 238 239 // At this point, we want to get the state of the crashing thread, but 240 // libFuzzer and the sanitizers assume this will happen from that same thread 241 // via a POSIX signal handler. "Resurrecting" the thread in the middle of the 242 // appropriate callback is as simple as forcibly setting the instruction 243 // pointer/program counter, provided we NEVER EVER return from that function 244 // (since otherwise our stack will not be valid). 245 ScopedHandle Thread; 246 ExitOnErr(_zx_object_get_child(Self, Packet.exception.tid, 247 ZX_RIGHT_SAME_RIGHTS, &Thread.Handle), 248 "_zx_object_get_child"); 249 250 zx_thread_state_general_regs_t GeneralRegisters; 251 ExitOnErr(_zx_thread_read_state(Thread.Handle, ZX_THREAD_STATE_GENERAL_REGS, 252 &GeneralRegisters, sizeof(GeneralRegisters)), 253 "_zx_thread_read_state"); 254 255 // To unwind properly, we need to push the crashing thread's register state 256 // onto the stack and jump into a trampoline with CFI instructions on how 257 // to restore it. 258 #if defined(__x86_64__) 259 uintptr_t StackPtr = 260 (GeneralRegisters.rsp - (128 + sizeof(GeneralRegisters))) & 261 -(uintptr_t)16; 262 __unsanitized_memcpy(reinterpret_cast<void *>(StackPtr), &GeneralRegisters, 263 sizeof(GeneralRegisters)); 264 GeneralRegisters.rsp = StackPtr; 265 GeneralRegisters.rip = reinterpret_cast<zx_vaddr_t>(CrashTrampolineAsm); 266 267 #elif defined(__aarch64__) 268 uintptr_t StackPtr = 269 (GeneralRegisters.sp - sizeof(GeneralRegisters)) & -(uintptr_t)16; 270 __unsanitized_memcpy(reinterpret_cast<void *>(StackPtr), &GeneralRegisters, 271 sizeof(GeneralRegisters)); 272 GeneralRegisters.sp = StackPtr; 273 GeneralRegisters.pc = reinterpret_cast<zx_vaddr_t>(CrashTrampolineAsm); 274 275 #else 276 #error "Unsupported architecture for fuzzing on Fuchsia" 277 #endif 278 279 // Now force the crashing thread's state. 280 ExitOnErr(_zx_thread_write_state(Thread.Handle, ZX_THREAD_STATE_GENERAL_REGS, 281 &GeneralRegisters, sizeof(GeneralRegisters)), 282 "_zx_thread_write_state"); 283 284 ExitOnErr(_zx_task_resume_from_exception(Thread.Handle, Port.Handle, 0), 285 "_zx_task_resume_from_exception"); 286 } 287 288 } // namespace 289 290 bool Mprotect(void *Ptr, size_t Size, bool AllowReadWrite) { 291 return false; // UNIMPLEMENTED 292 } 293 294 // Platform specific functions. 295 void SetSignalHandler(const FuzzingOptions &Options) { 296 // Set up alarm handler if needed. 297 if (Options.UnitTimeoutSec > 0) { 298 std::thread T(AlarmHandler, Options.UnitTimeoutSec / 2 + 1); 299 T.detach(); 300 } 301 302 // Set up interrupt handler if needed. 303 if (Options.HandleInt || Options.HandleTerm) { 304 std::thread T(InterruptHandler); 305 T.detach(); 306 } 307 308 // Early exit if no crash handler needed. 309 if (!Options.HandleSegv && !Options.HandleBus && !Options.HandleIll && 310 !Options.HandleFpe && !Options.HandleAbrt) 311 return; 312 313 // Set up the crash handler and wait until it is ready before proceeding. 314 zx_handle_t Event; 315 ExitOnErr(_zx_event_create(0, &Event), "_zx_event_create"); 316 317 std::thread T(CrashHandler, &Event); 318 zx_status_t Status = 319 _zx_object_wait_one(Event, ZX_USER_SIGNAL_0, ZX_TIME_INFINITE, nullptr); 320 _zx_handle_close(Event); 321 ExitOnErr(Status, "_zx_object_wait_one"); 322 323 T.detach(); 324 } 325 326 void SleepSeconds(int Seconds) { 327 _zx_nanosleep(_zx_deadline_after(ZX_SEC(Seconds))); 328 } 329 330 unsigned long GetPid() { 331 zx_status_t rc; 332 zx_info_handle_basic_t Info; 333 if ((rc = _zx_object_get_info(_zx_process_self(), ZX_INFO_HANDLE_BASIC, &Info, 334 sizeof(Info), NULL, NULL)) != ZX_OK) { 335 Printf("libFuzzer: unable to get info about self: %s\n", 336 _zx_status_get_string(rc)); 337 exit(1); 338 } 339 return Info.koid; 340 } 341 342 size_t GetPeakRSSMb() { 343 zx_status_t rc; 344 zx_info_task_stats_t Info; 345 if ((rc = _zx_object_get_info(_zx_process_self(), ZX_INFO_TASK_STATS, &Info, 346 sizeof(Info), NULL, NULL)) != ZX_OK) { 347 Printf("libFuzzer: unable to get info about self: %s\n", 348 _zx_status_get_string(rc)); 349 exit(1); 350 } 351 return (Info.mem_private_bytes + Info.mem_shared_bytes) >> 20; 352 } 353 354 template <typename Fn> 355 class RunOnDestruction { 356 public: 357 explicit RunOnDestruction(Fn fn) : fn_(fn) {} 358 ~RunOnDestruction() { fn_(); } 359 360 private: 361 Fn fn_; 362 }; 363 364 template <typename Fn> 365 RunOnDestruction<Fn> at_scope_exit(Fn fn) { 366 return RunOnDestruction<Fn>(fn); 367 } 368 369 int ExecuteCommand(const Command &Cmd) { 370 zx_status_t rc; 371 372 // Convert arguments to C array 373 auto Args = Cmd.getArguments(); 374 size_t Argc = Args.size(); 375 assert(Argc != 0); 376 std::unique_ptr<const char *[]> Argv(new const char *[Argc + 1]); 377 for (size_t i = 0; i < Argc; ++i) 378 Argv[i] = Args[i].c_str(); 379 Argv[Argc] = nullptr; 380 381 // Determine output. On Fuchsia, the fuzzer is typically run as a component 382 // that lacks a mutable working directory. Fortunately, when this is the case 383 // a mutable output directory must be specified using "-artifact_prefix=...", 384 // so write the log file(s) there. 385 int FdOut = STDOUT_FILENO; 386 if (Cmd.hasOutputFile()) { 387 std::string Path; 388 if (Cmd.hasFlag("artifact_prefix")) 389 Path = Cmd.getFlagValue("artifact_prefix") + "/" + Cmd.getOutputFile(); 390 else 391 Path = Cmd.getOutputFile(); 392 FdOut = open(Path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0); 393 if (FdOut == -1) { 394 Printf("libFuzzer: failed to open %s: %s\n", Path.c_str(), 395 strerror(errno)); 396 return ZX_ERR_IO; 397 } 398 } 399 auto CloseFdOut = at_scope_exit([FdOut]() { 400 if (FdOut != STDOUT_FILENO) 401 close(FdOut); 402 }); 403 404 // Determine stderr 405 int FdErr = STDERR_FILENO; 406 if (Cmd.isOutAndErrCombined()) 407 FdErr = FdOut; 408 409 // Clone the file descriptors into the new process 410 fdio_spawn_action_t SpawnAction[] = { 411 { 412 .action = FDIO_SPAWN_ACTION_CLONE_FD, 413 .fd = 414 { 415 .local_fd = STDIN_FILENO, 416 .target_fd = STDIN_FILENO, 417 }, 418 }, 419 { 420 .action = FDIO_SPAWN_ACTION_CLONE_FD, 421 .fd = 422 { 423 .local_fd = FdOut, 424 .target_fd = STDOUT_FILENO, 425 }, 426 }, 427 { 428 .action = FDIO_SPAWN_ACTION_CLONE_FD, 429 .fd = 430 { 431 .local_fd = FdErr, 432 .target_fd = STDERR_FILENO, 433 }, 434 }, 435 }; 436 437 // Start the process. 438 char ErrorMsg[FDIO_SPAWN_ERR_MSG_MAX_LENGTH]; 439 zx_handle_t ProcessHandle = ZX_HANDLE_INVALID; 440 rc = fdio_spawn_etc( 441 ZX_HANDLE_INVALID, FDIO_SPAWN_CLONE_ALL & (~FDIO_SPAWN_CLONE_STDIO), 442 Argv[0], Argv.get(), nullptr, 3, SpawnAction, &ProcessHandle, ErrorMsg); 443 if (rc != ZX_OK) { 444 Printf("libFuzzer: failed to launch '%s': %s, %s\n", Argv[0], ErrorMsg, 445 _zx_status_get_string(rc)); 446 return rc; 447 } 448 auto CloseHandle = at_scope_exit([&]() { _zx_handle_close(ProcessHandle); }); 449 450 // Now join the process and return the exit status. 451 if ((rc = _zx_object_wait_one(ProcessHandle, ZX_PROCESS_TERMINATED, 452 ZX_TIME_INFINITE, nullptr)) != ZX_OK) { 453 Printf("libFuzzer: failed to join '%s': %s\n", Argv[0], 454 _zx_status_get_string(rc)); 455 return rc; 456 } 457 458 zx_info_process_t Info; 459 if ((rc = _zx_object_get_info(ProcessHandle, ZX_INFO_PROCESS, &Info, 460 sizeof(Info), nullptr, nullptr)) != ZX_OK) { 461 Printf("libFuzzer: unable to get return code from '%s': %s\n", Argv[0], 462 _zx_status_get_string(rc)); 463 return rc; 464 } 465 466 return Info.return_code; 467 } 468 469 const void *SearchMemory(const void *Data, size_t DataLen, const void *Patt, 470 size_t PattLen) { 471 return memmem(Data, DataLen, Patt, PattLen); 472 } 473 474 } // namespace fuzzer 475 476 #endif // LIBFUZZER_FUCHSIA 477