blob: d51850eefe42bd2f45b7f7876548a24bc3cbe3ba [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>
phosek00c73322018-04-20 00:41:06 +000023#include <sys/select.h>
morehouse400262a2017-12-08 22:54:44 +000024#include <thread>
phosekf9123762018-02-07 08:22:58 +000025#include <unistd.h>
morehouse400262a2017-12-08 22:54:44 +000026#include <zircon/errors.h>
phosekf9123762018-02-07 08:22:58 +000027#include <zircon/process.h>
morehouse400262a2017-12-08 22:54:44 +000028#include <zircon/status.h>
29#include <zircon/syscalls.h>
30#include <zircon/syscalls/port.h>
31#include <zircon/types.h>
morehouse400262a2017-12-08 22:54:44 +000032
33namespace fuzzer {
34
35namespace {
36
37// A magic value for the Zircon exception port, chosen to spell 'FUZZING'
38// when interpreted as a byte sequence on little-endian platforms.
39const uint64_t kFuzzingCrash = 0x474e495a5a5546;
40
41void AlarmHandler(int Seconds) {
42 while (true) {
43 SleepSeconds(Seconds);
44 Fuzzer::StaticAlarmCallback();
45 }
46}
47
48void InterruptHandler() {
phosek1631e452018-04-19 14:01:46 +000049 fd_set readfds;
morehouse400262a2017-12-08 22:54:44 +000050 // Ctrl-C sends ETX in Zircon.
phosek1631e452018-04-19 14:01:46 +000051 do {
52 FD_ZERO(&readfds);
53 FD_SET(STDIN_FILENO, &readfds);
54 select(STDIN_FILENO + 1, &readfds, nullptr, nullptr, nullptr);
55 } while(!FD_ISSET(STDIN_FILENO, &readfds) || getchar() != 0x03);
morehouse400262a2017-12-08 22:54:44 +000056 Fuzzer::StaticInterruptCallback();
57}
58
phosekf9123762018-02-07 08:22:58 +000059void CrashHandler(zx_handle_t *Port) {
60 std::unique_ptr<zx_handle_t> ExceptionPort(Port);
morehouse400262a2017-12-08 22:54:44 +000061 zx_port_packet_t Packet;
phoseke81389f2018-05-26 01:02:34 +000062 _zx_port_wait(*ExceptionPort, ZX_TIME_INFINITE, &Packet);
morehouse400262a2017-12-08 22:54:44 +000063 // Unbind as soon as possible so we don't receive exceptions from this thread.
phosekf9123762018-02-07 08:22:58 +000064 if (_zx_task_bind_exception_port(ZX_HANDLE_INVALID, ZX_HANDLE_INVALID,
65 kFuzzingCrash, 0) != ZX_OK) {
morehouse400262a2017-12-08 22:54:44 +000066 // Shouldn't happen; if it does the safest option is to just exit.
67 Printf("libFuzzer: unable to unbind exception port; aborting!\n");
68 exit(1);
69 }
70 if (Packet.key != kFuzzingCrash) {
71 Printf("libFuzzer: invalid crash key: %" PRIx64 "; aborting!\n",
72 Packet.key);
73 exit(1);
74 }
75 // CrashCallback should not return from this call
76 Fuzzer::StaticCrashSignalCallback();
77}
78
79} // namespace
80
81// Platform specific functions.
82void SetSignalHandler(const FuzzingOptions &Options) {
83 zx_status_t rc;
84
85 // Set up alarm handler if needed.
86 if (Options.UnitTimeoutSec > 0) {
87 std::thread T(AlarmHandler, Options.UnitTimeoutSec / 2 + 1);
88 T.detach();
89 }
90
91 // Set up interrupt handler if needed.
92 if (Options.HandleInt || Options.HandleTerm) {
93 std::thread T(InterruptHandler);
94 T.detach();
95 }
96
97 // Early exit if no crash handler needed.
98 if (!Options.HandleSegv && !Options.HandleBus && !Options.HandleIll &&
99 !Options.HandleFpe && !Options.HandleAbrt)
100 return;
101
102 // Create an exception port
phosekf9123762018-02-07 08:22:58 +0000103 zx_handle_t *ExceptionPort = new zx_handle_t;
104 if ((rc = _zx_port_create(0, ExceptionPort)) != ZX_OK) {
105 Printf("libFuzzer: zx_port_create failed: %s\n", _zx_status_get_string(rc));
morehouse400262a2017-12-08 22:54:44 +0000106 exit(1);
107 }
108
109 // Bind the port to receive exceptions from our process
phosekf9123762018-02-07 08:22:58 +0000110 if ((rc = _zx_task_bind_exception_port(_zx_process_self(), *ExceptionPort,
111 kFuzzingCrash, 0)) != ZX_OK) {
morehouse400262a2017-12-08 22:54:44 +0000112 Printf("libFuzzer: unable to bind exception port: %s\n",
phoseke81389f2018-05-26 01:02:34 +0000113 _zx_status_get_string(rc));
morehouse400262a2017-12-08 22:54:44 +0000114 exit(1);
115 }
116
117 // Set up the crash handler.
118 std::thread T(CrashHandler, ExceptionPort);
119 T.detach();
120}
121
122void SleepSeconds(int Seconds) {
phosekf9123762018-02-07 08:22:58 +0000123 _zx_nanosleep(_zx_deadline_after(ZX_SEC(Seconds)));
morehouse400262a2017-12-08 22:54:44 +0000124}
125
126unsigned long GetPid() {
127 zx_status_t rc;
128 zx_info_handle_basic_t Info;
phoseke81389f2018-05-26 01:02:34 +0000129 if ((rc = _zx_object_get_info(_zx_process_self(), ZX_INFO_HANDLE_BASIC, &Info,
morehouse400262a2017-12-08 22:54:44 +0000130 sizeof(Info), NULL, NULL)) != ZX_OK) {
131 Printf("libFuzzer: unable to get info about self: %s\n",
phoseke81389f2018-05-26 01:02:34 +0000132 _zx_status_get_string(rc));
morehouse400262a2017-12-08 22:54:44 +0000133 exit(1);
134 }
135 return Info.koid;
136}
137
138size_t GetPeakRSSMb() {
139 zx_status_t rc;
140 zx_info_task_stats_t Info;
phosekf9123762018-02-07 08:22:58 +0000141 if ((rc = _zx_object_get_info(_zx_process_self(), ZX_INFO_TASK_STATS, &Info,
morehouse400262a2017-12-08 22:54:44 +0000142 sizeof(Info), NULL, NULL)) != ZX_OK) {
143 Printf("libFuzzer: unable to get info about self: %s\n",
phosekf9123762018-02-07 08:22:58 +0000144 _zx_status_get_string(rc));
morehouse400262a2017-12-08 22:54:44 +0000145 exit(1);
146 }
147 return (Info.mem_private_bytes + Info.mem_shared_bytes) >> 20;
148}
149
phosekf9123762018-02-07 08:22:58 +0000150template <typename Fn>
151class RunOnDestruction {
152 public:
153 explicit RunOnDestruction(Fn fn) : fn_(fn) {}
154 ~RunOnDestruction() { fn_(); }
155
156 private:
157 Fn fn_;
158};
159
160template <typename Fn>
161RunOnDestruction<Fn> at_scope_exit(Fn fn) {
162 return RunOnDestruction<Fn>(fn);
163}
164
morehouse400262a2017-12-08 22:54:44 +0000165int ExecuteCommand(const Command &Cmd) {
166 zx_status_t rc;
167
168 // Convert arguments to C array
169 auto Args = Cmd.getArguments();
170 size_t Argc = Args.size();
171 assert(Argc != 0);
172 std::unique_ptr<const char *[]> Argv(new const char *[Argc]);
173 for (size_t i = 0; i < Argc; ++i)
174 Argv[i] = Args[i].c_str();
175
176 // Create the basic launchpad. Clone everything except stdio.
177 launchpad_t *lp;
178 launchpad_create(ZX_HANDLE_INVALID, Argv[0], &lp);
179 launchpad_load_from_file(lp, Argv[0]);
180 launchpad_set_args(lp, Argc, Argv.get());
181 launchpad_clone(lp, LP_CLONE_ALL & (~LP_CLONE_FDIO_STDIO));
182
183 // Determine stdout
184 int FdOut = STDOUT_FILENO;
phosekf9123762018-02-07 08:22:58 +0000185
morehouse400262a2017-12-08 22:54:44 +0000186 if (Cmd.hasOutputFile()) {
187 auto Filename = Cmd.getOutputFile();
phosekf9123762018-02-07 08:22:58 +0000188 FdOut = open(Filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0);
189 if (FdOut == -1) {
morehouse400262a2017-12-08 22:54:44 +0000190 Printf("libFuzzer: failed to open %s: %s\n", Filename.c_str(),
191 strerror(errno));
192 return ZX_ERR_IO;
193 }
morehouse400262a2017-12-08 22:54:44 +0000194 }
phosekf9123762018-02-07 08:22:58 +0000195 auto CloseFdOut = at_scope_exit([&]() { close(FdOut); } );
morehouse400262a2017-12-08 22:54:44 +0000196
197 // Determine stderr
198 int FdErr = STDERR_FILENO;
199 if (Cmd.isOutAndErrCombined())
200 FdErr = FdOut;
201
202 // Clone the file descriptors into the new process
203 if ((rc = launchpad_clone_fd(lp, STDIN_FILENO, STDIN_FILENO)) != ZX_OK ||
204 (rc = launchpad_clone_fd(lp, FdOut, STDOUT_FILENO)) != ZX_OK ||
205 (rc = launchpad_clone_fd(lp, FdErr, STDERR_FILENO)) != ZX_OK) {
phosekf9123762018-02-07 08:22:58 +0000206 Printf("libFuzzer: failed to clone FDIO: %s\n", _zx_status_get_string(rc));
morehouse400262a2017-12-08 22:54:44 +0000207 return rc;
208 }
209
210 // Start the process
211 zx_handle_t ProcessHandle = ZX_HANDLE_INVALID;
212 const char *ErrorMsg = nullptr;
213 if ((rc = launchpad_go(lp, &ProcessHandle, &ErrorMsg)) != ZX_OK) {
214 Printf("libFuzzer: failed to launch '%s': %s, %s\n", Argv[0], ErrorMsg,
phosekf9123762018-02-07 08:22:58 +0000215 _zx_status_get_string(rc));
morehouse400262a2017-12-08 22:54:44 +0000216 return rc;
217 }
phosekf9123762018-02-07 08:22:58 +0000218 auto CloseHandle = at_scope_exit([&]() { _zx_handle_close(ProcessHandle); });
morehouse400262a2017-12-08 22:54:44 +0000219
220 // Now join the process and return the exit status.
phosekf9123762018-02-07 08:22:58 +0000221 if ((rc = _zx_object_wait_one(ProcessHandle, ZX_PROCESS_TERMINATED,
222 ZX_TIME_INFINITE, nullptr)) != ZX_OK) {
morehouse400262a2017-12-08 22:54:44 +0000223 Printf("libFuzzer: failed to join '%s': %s\n", Argv[0],
phosekf9123762018-02-07 08:22:58 +0000224 _zx_status_get_string(rc));
morehouse400262a2017-12-08 22:54:44 +0000225 return rc;
226 }
227
228 zx_info_process_t Info;
phosekf9123762018-02-07 08:22:58 +0000229 if ((rc = _zx_object_get_info(ProcessHandle, ZX_INFO_PROCESS, &Info,
230 sizeof(Info), nullptr, nullptr)) != ZX_OK) {
morehouse400262a2017-12-08 22:54:44 +0000231 Printf("libFuzzer: unable to get return code from '%s': %s\n", Argv[0],
phoseke81389f2018-05-26 01:02:34 +0000232 _zx_status_get_string(rc));
morehouse400262a2017-12-08 22:54:44 +0000233 return rc;
234 }
235
236 return Info.return_code;
237}
238
239const void *SearchMemory(const void *Data, size_t DataLen, const void *Patt,
240 size_t PattLen) {
241 return memmem(Data, DataLen, Patt, PattLen);
242}
243
244} // namespace fuzzer
245
246#endif // LIBFUZZER_FUCHSIA