#include "FuzzerPlatform.h"
#if LIBFUZZER_FUCHSIA
#include "FuzzerInternal.h"
#include "FuzzerUtil.h"
#include <cassert>
#include <cerrno>
#include <cinttypes>
#include <cstdint>
#include <fcntl.h>
#include <lib/fdio/fdio.h>
#include <lib/fdio/spawn.h>
#include <string>
#include <sys/select.h>
#include <thread>
#include <unistd.h>
#include <zircon/errors.h>
#include <zircon/process.h>
#include <zircon/sanitizer.h>
#include <zircon/status.h>
#include <zircon/syscalls.h>
#include <zircon/syscalls/debug.h>
#include <zircon/syscalls/exception.h>
#include <zircon/syscalls/object.h>
#include <zircon/types.h>
#include <vector>
namespace fuzzer {
void CrashTrampolineAsm() __asm__("CrashTrampolineAsm");
namespace {
std::thread SignalHandler;
zx_handle_t SignalHandlerEvent = ZX_HANDLE_INVALID;
void ExitOnErr(zx_status_t Status, const char *Syscall) {
if (Status != ZX_OK) {
Printf("libFuzzer: %s failed: %s\n", Syscall,
_zx_status_get_string(Status));
exit(1);
}
}
void AlarmHandler(int Seconds) {
while (true) {
SleepSeconds(Seconds);
Fuzzer::StaticAlarmCallback();
}
}
#if defined(__x86_64__)
#define FOREACH_REGISTER …
#elif defined(__aarch64__)
#define FOREACH_REGISTER …
#elif defined(__riscv)
#define FOREACH_REGISTER … \
#else
#error "Unsupported architecture for fuzzing on Fuchsia"
#endif
#define CFI_OFFSET_REG …
#define CFI_OFFSET_NUM …
#define ASM_OPERAND_REG …
#define ASM_OPERAND_NUM …
__attribute__((noreturn))
static void StaticCrashHandler() {
Fuzzer::StaticCrashSignalCallback();
for (;;) {
_Exit(1);
}
}
__attribute__((used))
void MakeTrampoline() {
__asm__(
".cfi_endproc\n"
".pushsection .text.CrashTrampolineAsm\n"
".type CrashTrampolineAsm,STT_FUNC\n"
"CrashTrampolineAsm:\n"
".cfi_startproc simple\n"
".cfi_signal_frame\n"
#if defined(__x86_64__)
".cfi_return_column rip\n"
".cfi_def_cfa rsp, 0\n"
FOREACH_REGISTER(CFI_OFFSET_REG, CFI_OFFSET_NUM)
"call %c[StaticCrashHandler]\n"
"ud2\n"
#elif defined(__aarch64__)
".cfi_return_column 33\n"
".cfi_def_cfa sp, 0\n"
FOREACH_REGISTER(CFI_OFFSET_REG, CFI_OFFSET_NUM)
".cfi_offset 33, %c[pc]\n"
".cfi_offset 30, %c[lr]\n"
"bl %c[StaticCrashHandler]\n"
"brk 1\n"
#elif defined(__riscv)
".cfi_return_column 64\n"
".cfi_def_cfa sp, 0\n"
".cfi_offset 64, %[pc]\n"
FOREACH_REGISTER(CFI_OFFSET_REG, CFI_OFFSET_NUM)
"call %c[StaticCrashHandler]\n"
"unimp\n"
#else
#error "Unsupported architecture for fuzzing on Fuchsia"
#endif
".cfi_endproc\n"
".size CrashTrampolineAsm, . - CrashTrampolineAsm\n"
".popsection\n"
".cfi_startproc\n"
:
: FOREACH_REGISTER(ASM_OPERAND_REG, ASM_OPERAND_NUM)
#if defined(__aarch64__) || defined(__riscv)
ASM_OPERAND_REG(pc)
#endif
#if defined(__aarch64__)
ASM_OPERAND_REG(lr)
#endif
[StaticCrashHandler] "i"(StaticCrashHandler));
}
void CrashHandler() {
assert(SignalHandlerEvent != ZX_HANDLE_INVALID);
struct ScopedHandle {
~ScopedHandle() { _zx_handle_close(Handle); }
zx_handle_t Handle = ZX_HANDLE_INVALID;
};
ScopedHandle Channel;
zx_handle_t Self = _zx_process_self();
ExitOnErr(_zx_task_create_exception_channel(
Self, ZX_EXCEPTION_CHANNEL_DEBUGGER, &Channel.Handle),
"_zx_task_create_exception_channel");
ExitOnErr(_zx_object_signal(SignalHandlerEvent, 0, ZX_USER_SIGNAL_0),
"_zx_object_signal");
while (true) {
zx_wait_item_t WaitItems[] = {
{
.handle = SignalHandlerEvent,
.waitfor = ZX_USER_SIGNAL_1,
.pending = 0,
},
{
.handle = Channel.Handle,
.waitfor = ZX_CHANNEL_READABLE | ZX_CHANNEL_PEER_CLOSED,
.pending = 0,
},
};
auto Status = _zx_object_wait_many(
WaitItems, sizeof(WaitItems) / sizeof(WaitItems[0]), ZX_TIME_INFINITE);
if (Status != ZX_OK || (WaitItems[1].pending & ZX_CHANNEL_READABLE) == 0) {
break;
}
zx_exception_info_t ExceptionInfo;
ScopedHandle Exception;
ExitOnErr(_zx_channel_read(Channel.Handle, 0, &ExceptionInfo,
&Exception.Handle, sizeof(ExceptionInfo), 1,
nullptr, nullptr),
"_zx_channel_read");
if (ZX_EXCP_THREAD_STARTING == ExceptionInfo.type ||
ZX_EXCP_THREAD_EXITING == ExceptionInfo.type ||
ZX_EXCP_PROCESS_STARTING == ExceptionInfo.type) {
continue;
}
ScopedHandle Thread;
ExitOnErr(_zx_exception_get_thread(Exception.Handle, &Thread.Handle),
"_zx_exception_get_thread");
zx_thread_state_general_regs_t GeneralRegisters;
ExitOnErr(_zx_thread_read_state(Thread.Handle, ZX_THREAD_STATE_GENERAL_REGS,
&GeneralRegisters,
sizeof(GeneralRegisters)),
"_zx_thread_read_state");
#if defined(__x86_64__)
uintptr_t StackPtr =
(GeneralRegisters.rsp - (128 + sizeof(GeneralRegisters))) &
-(uintptr_t)16;
__unsanitized_memcpy(reinterpret_cast<void *>(StackPtr), &GeneralRegisters,
sizeof(GeneralRegisters));
GeneralRegisters.rsp = StackPtr;
GeneralRegisters.rip = reinterpret_cast<zx_vaddr_t>(CrashTrampolineAsm);
#elif defined(__aarch64__) || defined(__riscv)
uintptr_t StackPtr =
(GeneralRegisters.sp - sizeof(GeneralRegisters)) & -(uintptr_t)16;
__unsanitized_memcpy(reinterpret_cast<void *>(StackPtr), &GeneralRegisters,
sizeof(GeneralRegisters));
GeneralRegisters.sp = StackPtr;
GeneralRegisters.pc = reinterpret_cast<zx_vaddr_t>(CrashTrampolineAsm);
#else
#error "Unsupported architecture for fuzzing on Fuchsia"
#endif
ExitOnErr(
_zx_thread_write_state(Thread.Handle, ZX_THREAD_STATE_GENERAL_REGS,
&GeneralRegisters, sizeof(GeneralRegisters)),
"_zx_thread_write_state");
uint32_t ExceptionState = ZX_EXCEPTION_STATE_HANDLED;
ExitOnErr(_zx_object_set_property(Exception.Handle, ZX_PROP_EXCEPTION_STATE,
&ExceptionState, sizeof(ExceptionState)),
"zx_object_set_property");
}
}
void StopSignalHandler() {
_zx_object_signal(SignalHandlerEvent, 0, ZX_USER_SIGNAL_1);
if (SignalHandler.joinable()) {
SignalHandler.join();
}
_zx_handle_close(SignalHandlerEvent);
}
}
void SetSignalHandler(const FuzzingOptions &Options) {
char Buf[64];
memset(Buf, 0, sizeof(Buf));
snprintf(Buf, sizeof(Buf), "==%lu== INFO: libFuzzer starting.\n", GetPid());
if (EF->__sanitizer_log_write)
__sanitizer_log_write(Buf, sizeof(Buf));
Printf("%s", Buf);
if (Options.HandleAlrm && Options.UnitTimeoutSec > 0) {
std::thread T(AlarmHandler, Options.UnitTimeoutSec / 2 + 1);
T.detach();
}
if (!Options.HandleSegv && !Options.HandleBus && !Options.HandleIll &&
!Options.HandleFpe && !Options.HandleAbrt)
return;
ExitOnErr(_zx_event_create(0, &SignalHandlerEvent), "_zx_event_create");
SignalHandler = std::thread(CrashHandler);
zx_status_t Status = _zx_object_wait_one(SignalHandlerEvent, ZX_USER_SIGNAL_0,
ZX_TIME_INFINITE, nullptr);
ExitOnErr(Status, "_zx_object_wait_one");
std::atexit(StopSignalHandler);
}
void SleepSeconds(int Seconds) {
_zx_nanosleep(_zx_deadline_after(ZX_SEC(Seconds)));
}
unsigned long GetPid() {
zx_status_t rc;
zx_info_handle_basic_t Info;
if ((rc = _zx_object_get_info(_zx_process_self(), ZX_INFO_HANDLE_BASIC, &Info,
sizeof(Info), NULL, NULL)) != ZX_OK) {
Printf("libFuzzer: unable to get info about self: %s\n",
_zx_status_get_string(rc));
exit(1);
}
return Info.koid;
}
size_t GetPeakRSSMb() {
zx_status_t rc;
zx_info_task_stats_t Info;
if ((rc = _zx_object_get_info(_zx_process_self(), ZX_INFO_TASK_STATS, &Info,
sizeof(Info), NULL, NULL)) != ZX_OK) {
Printf("libFuzzer: unable to get info about self: %s\n",
_zx_status_get_string(rc));
exit(1);
}
return (Info.mem_private_bytes + Info.mem_shared_bytes) >> 20;
}
template <typename Fn>
class RunOnDestruction {
public:
explicit RunOnDestruction(Fn fn) : fn_(fn) {}
~RunOnDestruction() { fn_(); }
private:
Fn fn_;
};
template <typename Fn>
RunOnDestruction<Fn> at_scope_exit(Fn fn) {
return RunOnDestruction<Fn>(fn);
}
static fdio_spawn_action_t clone_fd_action(int localFd, int targetFd) {
return {
.action = FDIO_SPAWN_ACTION_CLONE_FD,
.fd =
{
.local_fd = localFd,
.target_fd = targetFd,
},
};
}
int ExecuteCommand(const Command &Cmd) {
zx_status_t rc;
auto Args = Cmd.getArguments();
size_t Argc = Args.size();
assert(Argc != 0);
std::unique_ptr<const char *[]> Argv(new const char *[Argc + 1]);
for (size_t i = 0; i < Argc; ++i)
Argv[i] = Args[i].c_str();
Argv[Argc] = nullptr;
int FdOut = STDOUT_FILENO;
bool discardStdout = false;
bool discardStderr = false;
if (Cmd.hasOutputFile()) {
std::string Path = Cmd.getOutputFile();
if (Path == getDevNull()) {
discardStdout = true;
} else {
bool IsAbsolutePath = Path.length() > 1 && Path[0] == '/';
if (!IsAbsolutePath && Cmd.hasFlag("artifact_prefix"))
Path = Cmd.getFlagValue("artifact_prefix") + "/" + Path;
FdOut = open(Path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0);
if (FdOut == -1) {
Printf("libFuzzer: failed to open %s: %s\n", Path.c_str(),
strerror(errno));
return ZX_ERR_IO;
}
}
}
auto CloseFdOut = at_scope_exit([FdOut]() {
if (FdOut != STDOUT_FILENO)
close(FdOut);
});
int FdErr = STDERR_FILENO;
if (Cmd.isOutAndErrCombined()) {
FdErr = FdOut;
if (discardStdout)
discardStderr = true;
}
std::vector<fdio_spawn_action_t> SpawnActions;
SpawnActions.push_back(clone_fd_action(STDIN_FILENO, STDIN_FILENO));
if (!discardStdout)
SpawnActions.push_back(clone_fd_action(FdOut, STDOUT_FILENO));
if (!discardStderr)
SpawnActions.push_back(clone_fd_action(FdErr, STDERR_FILENO));
char ErrorMsg[FDIO_SPAWN_ERR_MSG_MAX_LENGTH];
zx_handle_t ProcessHandle = ZX_HANDLE_INVALID;
rc = fdio_spawn_etc(ZX_HANDLE_INVALID,
FDIO_SPAWN_CLONE_ALL & (~FDIO_SPAWN_CLONE_STDIO), Argv[0],
Argv.get(), nullptr, SpawnActions.size(),
SpawnActions.data(), &ProcessHandle, ErrorMsg);
if (rc != ZX_OK) {
Printf("libFuzzer: failed to launch '%s': %s, %s\n", Argv[0], ErrorMsg,
_zx_status_get_string(rc));
return rc;
}
auto CloseHandle = at_scope_exit([&]() { _zx_handle_close(ProcessHandle); });
if ((rc = _zx_object_wait_one(ProcessHandle, ZX_PROCESS_TERMINATED,
ZX_TIME_INFINITE, nullptr)) != ZX_OK) {
Printf("libFuzzer: failed to join '%s': %s\n", Argv[0],
_zx_status_get_string(rc));
return rc;
}
zx_info_process_t Info;
if ((rc = _zx_object_get_info(ProcessHandle, ZX_INFO_PROCESS, &Info,
sizeof(Info), nullptr, nullptr)) != ZX_OK) {
Printf("libFuzzer: unable to get return code from '%s': %s\n", Argv[0],
_zx_status_get_string(rc));
return rc;
}
return static_cast<int>(Info.return_code);
}
bool ExecuteCommand(const Command &BaseCmd, std::string *CmdOutput) {
auto LogFilePath = TempPath("SimPopenOut", ".txt");
Command Cmd(BaseCmd);
Cmd.setOutputFile(LogFilePath);
int Ret = ExecuteCommand(Cmd);
*CmdOutput = FileToString(LogFilePath);
RemoveFile(LogFilePath);
return Ret == 0;
}
const void *SearchMemory(const void *Data, size_t DataLen, const void *Patt,
size_t PattLen) {
return memmem(Data, DataLen, Patt, PattLen);
}
void DiscardOutput(int Fd) {
fdio_t *fdio_null = fdio_null_create();
if (fdio_null == nullptr) return;
int nullfd = fdio_bind_to_fd(fdio_null, -1, 0);
if (nullfd < 0) return;
dup2(nullfd, Fd);
}
size_t PageSize() {
static size_t PageSizeCached = _zx_system_get_page_size();
return PageSizeCached;
}
void SetThreadName(std::thread &thread, const std::string &name) {
if (zx_status_t s = zx_object_set_property(
thread.native_handle(), ZX_PROP_NAME, name.data(), name.size());
s != ZX_OK)
Printf("SetThreadName for name %s failed: %s", name.c_str(),
zx_status_get_string(s));
}
}
#endif