blob: 73974e5f815ae0e6436a639461ea9ded1e270dc8 [file] [log] [blame]
morehouse400262a2017-12-08 22:54:44 +00001//===- FuzzerUtilFuchsia.cpp - Misc utils for Fuchsia. --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9// Misc utils implementation using Fuchsia/Zircon APIs.
10//===----------------------------------------------------------------------===//
11#include "FuzzerDefs.h"
12
13#if LIBFUZZER_FUCHSIA
14
15#include "FuzzerInternal.h"
16#include "FuzzerUtil.h"
17#include <cerrno>
18#include <cinttypes>
19#include <cstdint>
morehouse400262a2017-12-08 22:54:44 +000020#include <fcntl.h>
21#include <launchpad/launchpad.h>
22#include <string>
23#include <thread>
phosekf9123762018-02-07 08:22:58 +000024#include <unistd.h>
morehouse400262a2017-12-08 22:54:44 +000025#include <zircon/errors.h>
phosekf9123762018-02-07 08:22:58 +000026#include <zircon/process.h>
morehouse400262a2017-12-08 22:54:44 +000027#include <zircon/status.h>
28#include <zircon/syscalls.h>
29#include <zircon/syscalls/port.h>
30#include <zircon/types.h>
morehouse400262a2017-12-08 22:54:44 +000031
32namespace fuzzer {
33
34namespace {
35
36// A magic value for the Zircon exception port, chosen to spell 'FUZZING'
37// when interpreted as a byte sequence on little-endian platforms.
38const uint64_t kFuzzingCrash = 0x474e495a5a5546;
39
40void AlarmHandler(int Seconds) {
41 while (true) {
42 SleepSeconds(Seconds);
43 Fuzzer::StaticAlarmCallback();
44 }
45}
46
47void InterruptHandler() {
phosek1631e452018-04-19 14:01:46 +000048 fd_set readfds;
morehouse400262a2017-12-08 22:54:44 +000049 // Ctrl-C sends ETX in Zircon.
phosek1631e452018-04-19 14:01:46 +000050 do {
51 FD_ZERO(&readfds);
52 FD_SET(STDIN_FILENO, &readfds);
53 select(STDIN_FILENO + 1, &readfds, nullptr, nullptr, nullptr);
54 } while(!FD_ISSET(STDIN_FILENO, &readfds) || getchar() != 0x03);
morehouse400262a2017-12-08 22:54:44 +000055 Fuzzer::StaticInterruptCallback();
56}
57
phosekf9123762018-02-07 08:22:58 +000058void CrashHandler(zx_handle_t *Port) {
59 std::unique_ptr<zx_handle_t> ExceptionPort(Port);
morehouse400262a2017-12-08 22:54:44 +000060 zx_port_packet_t Packet;
phosekf9123762018-02-07 08:22:58 +000061 _zx_port_wait(*ExceptionPort, ZX_TIME_INFINITE, &Packet, 1);
morehouse400262a2017-12-08 22:54:44 +000062 // Unbind as soon as possible so we don't receive exceptions from this thread.
phosekf9123762018-02-07 08:22:58 +000063 if (_zx_task_bind_exception_port(ZX_HANDLE_INVALID, ZX_HANDLE_INVALID,
64 kFuzzingCrash, 0) != ZX_OK) {
morehouse400262a2017-12-08 22:54:44 +000065 // Shouldn't happen; if it does the safest option is to just exit.
66 Printf("libFuzzer: unable to unbind exception port; aborting!\n");
67 exit(1);
68 }
69 if (Packet.key != kFuzzingCrash) {
70 Printf("libFuzzer: invalid crash key: %" PRIx64 "; aborting!\n",
71 Packet.key);
72 exit(1);
73 }
74 // CrashCallback should not return from this call
75 Fuzzer::StaticCrashSignalCallback();
76}
77
78} // namespace
79
80// Platform specific functions.
81void SetSignalHandler(const FuzzingOptions &Options) {
82 zx_status_t rc;
83
84 // Set up alarm handler if needed.
85 if (Options.UnitTimeoutSec > 0) {
86 std::thread T(AlarmHandler, Options.UnitTimeoutSec / 2 + 1);
87 T.detach();
88 }
89
90 // Set up interrupt handler if needed.
91 if (Options.HandleInt || Options.HandleTerm) {
92 std::thread T(InterruptHandler);
93 T.detach();
94 }
95
96 // Early exit if no crash handler needed.
97 if (!Options.HandleSegv && !Options.HandleBus && !Options.HandleIll &&
98 !Options.HandleFpe && !Options.HandleAbrt)
99 return;
100
101 // Create an exception port
phosekf9123762018-02-07 08:22:58 +0000102 zx_handle_t *ExceptionPort = new zx_handle_t;
103 if ((rc = _zx_port_create(0, ExceptionPort)) != ZX_OK) {
104 Printf("libFuzzer: zx_port_create failed: %s\n", _zx_status_get_string(rc));
morehouse400262a2017-12-08 22:54:44 +0000105 exit(1);
106 }
107
108 // Bind the port to receive exceptions from our process
phosekf9123762018-02-07 08:22:58 +0000109 if ((rc = _zx_task_bind_exception_port(_zx_process_self(), *ExceptionPort,
110 kFuzzingCrash, 0)) != ZX_OK) {
morehouse400262a2017-12-08 22:54:44 +0000111 Printf("libFuzzer: unable to bind exception port: %s\n",
112 zx_status_get_string(rc));
113 exit(1);
114 }
115
116 // Set up the crash handler.
117 std::thread T(CrashHandler, ExceptionPort);
118 T.detach();
119}
120
121void SleepSeconds(int Seconds) {
phosekf9123762018-02-07 08:22:58 +0000122 _zx_nanosleep(_zx_deadline_after(ZX_SEC(Seconds)));
morehouse400262a2017-12-08 22:54:44 +0000123}
124
125unsigned long GetPid() {
126 zx_status_t rc;
127 zx_info_handle_basic_t Info;
phosekf9123762018-02-07 08:22:58 +0000128 if ((rc = zx_object_get_info(_zx_process_self(), ZX_INFO_HANDLE_BASIC, &Info,
morehouse400262a2017-12-08 22:54:44 +0000129 sizeof(Info), NULL, NULL)) != ZX_OK) {
130 Printf("libFuzzer: unable to get info about self: %s\n",
131 zx_status_get_string(rc));
132 exit(1);
133 }
134 return Info.koid;
135}
136
137size_t GetPeakRSSMb() {
138 zx_status_t rc;
139 zx_info_task_stats_t Info;
phosekf9123762018-02-07 08:22:58 +0000140 if ((rc = _zx_object_get_info(_zx_process_self(), ZX_INFO_TASK_STATS, &Info,
morehouse400262a2017-12-08 22:54:44 +0000141 sizeof(Info), NULL, NULL)) != ZX_OK) {
142 Printf("libFuzzer: unable to get info about self: %s\n",
phosekf9123762018-02-07 08:22:58 +0000143 _zx_status_get_string(rc));
morehouse400262a2017-12-08 22:54:44 +0000144 exit(1);
145 }
146 return (Info.mem_private_bytes + Info.mem_shared_bytes) >> 20;
147}
148
phosekf9123762018-02-07 08:22:58 +0000149template <typename Fn>
150class RunOnDestruction {
151 public:
152 explicit RunOnDestruction(Fn fn) : fn_(fn) {}
153 ~RunOnDestruction() { fn_(); }
154
155 private:
156 Fn fn_;
157};
158
159template <typename Fn>
160RunOnDestruction<Fn> at_scope_exit(Fn fn) {
161 return RunOnDestruction<Fn>(fn);
162}
163
morehouse400262a2017-12-08 22:54:44 +0000164int ExecuteCommand(const Command &Cmd) {
165 zx_status_t rc;
166
167 // Convert arguments to C array
168 auto Args = Cmd.getArguments();
169 size_t Argc = Args.size();
170 assert(Argc != 0);
171 std::unique_ptr<const char *[]> Argv(new const char *[Argc]);
172 for (size_t i = 0; i < Argc; ++i)
173 Argv[i] = Args[i].c_str();
174
175 // Create the basic launchpad. Clone everything except stdio.
176 launchpad_t *lp;
177 launchpad_create(ZX_HANDLE_INVALID, Argv[0], &lp);
178 launchpad_load_from_file(lp, Argv[0]);
179 launchpad_set_args(lp, Argc, Argv.get());
180 launchpad_clone(lp, LP_CLONE_ALL & (~LP_CLONE_FDIO_STDIO));
181
182 // Determine stdout
183 int FdOut = STDOUT_FILENO;
phosekf9123762018-02-07 08:22:58 +0000184
morehouse400262a2017-12-08 22:54:44 +0000185 if (Cmd.hasOutputFile()) {
186 auto Filename = Cmd.getOutputFile();
phosekf9123762018-02-07 08:22:58 +0000187 FdOut = open(Filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0);
188 if (FdOut == -1) {
morehouse400262a2017-12-08 22:54:44 +0000189 Printf("libFuzzer: failed to open %s: %s\n", Filename.c_str(),
190 strerror(errno));
191 return ZX_ERR_IO;
192 }
morehouse400262a2017-12-08 22:54:44 +0000193 }
phosekf9123762018-02-07 08:22:58 +0000194 auto CloseFdOut = at_scope_exit([&]() { close(FdOut); } );
morehouse400262a2017-12-08 22:54:44 +0000195
196 // Determine stderr
197 int FdErr = STDERR_FILENO;
198 if (Cmd.isOutAndErrCombined())
199 FdErr = FdOut;
200
201 // Clone the file descriptors into the new process
202 if ((rc = launchpad_clone_fd(lp, STDIN_FILENO, STDIN_FILENO)) != ZX_OK ||
203 (rc = launchpad_clone_fd(lp, FdOut, STDOUT_FILENO)) != ZX_OK ||
204 (rc = launchpad_clone_fd(lp, FdErr, STDERR_FILENO)) != ZX_OK) {
phosekf9123762018-02-07 08:22:58 +0000205 Printf("libFuzzer: failed to clone FDIO: %s\n", _zx_status_get_string(rc));
morehouse400262a2017-12-08 22:54:44 +0000206 return rc;
207 }
208
209 // Start the process
210 zx_handle_t ProcessHandle = ZX_HANDLE_INVALID;
211 const char *ErrorMsg = nullptr;
212 if ((rc = launchpad_go(lp, &ProcessHandle, &ErrorMsg)) != ZX_OK) {
213 Printf("libFuzzer: failed to launch '%s': %s, %s\n", Argv[0], ErrorMsg,
phosekf9123762018-02-07 08:22:58 +0000214 _zx_status_get_string(rc));
morehouse400262a2017-12-08 22:54:44 +0000215 return rc;
216 }
phosekf9123762018-02-07 08:22:58 +0000217 auto CloseHandle = at_scope_exit([&]() { _zx_handle_close(ProcessHandle); });
morehouse400262a2017-12-08 22:54:44 +0000218
219 // Now join the process and return the exit status.
phosekf9123762018-02-07 08:22:58 +0000220 if ((rc = _zx_object_wait_one(ProcessHandle, ZX_PROCESS_TERMINATED,
221 ZX_TIME_INFINITE, nullptr)) != ZX_OK) {
morehouse400262a2017-12-08 22:54:44 +0000222 Printf("libFuzzer: failed to join '%s': %s\n", Argv[0],
phosekf9123762018-02-07 08:22:58 +0000223 _zx_status_get_string(rc));
morehouse400262a2017-12-08 22:54:44 +0000224 return rc;
225 }
226
227 zx_info_process_t Info;
phosekf9123762018-02-07 08:22:58 +0000228 if ((rc = _zx_object_get_info(ProcessHandle, ZX_INFO_PROCESS, &Info,
229 sizeof(Info), nullptr, nullptr)) != ZX_OK) {
morehouse400262a2017-12-08 22:54:44 +0000230 Printf("libFuzzer: unable to get return code from '%s': %s\n", Argv[0],
231 zx_status_get_string(rc));
232 return rc;
233 }
234
235 return Info.return_code;
236}
237
238const void *SearchMemory(const void *Data, size_t DataLen, const void *Patt,
239 size_t PattLen) {
240 return memmem(Data, DataLen, Patt, PattLen);
241}
242
243} // namespace fuzzer
244
245#endif // LIBFUZZER_FUCHSIA