blob: 3dacbd05c705863a5af6703ad7ea29bc2383bec8 [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>
phoseke7c6a592018-06-07 18:41:35 +000021#include <lib/fdio/spawn.h>
morehouse400262a2017-12-08 22:54:44 +000022#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);
phosek4b9efd12018-06-02 01:17:10 +0000172 std::unique_ptr<const char *[]> Argv(new const char *[Argc + 1]);
morehouse400262a2017-12-08 22:54:44 +0000173 for (size_t i = 0; i < Argc; ++i)
174 Argv[i] = Args[i].c_str();
phosek4b9efd12018-06-02 01:17:10 +0000175 Argv[Argc] = nullptr;
morehouse400262a2017-12-08 22:54:44 +0000176
177 // Determine stdout
178 int FdOut = STDOUT_FILENO;
phosekf9123762018-02-07 08:22:58 +0000179
morehouse400262a2017-12-08 22:54:44 +0000180 if (Cmd.hasOutputFile()) {
181 auto Filename = Cmd.getOutputFile();
phosekf9123762018-02-07 08:22:58 +0000182 FdOut = open(Filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0);
183 if (FdOut == -1) {
morehouse400262a2017-12-08 22:54:44 +0000184 Printf("libFuzzer: failed to open %s: %s\n", Filename.c_str(),
185 strerror(errno));
186 return ZX_ERR_IO;
187 }
morehouse400262a2017-12-08 22:54:44 +0000188 }
phosekf9123762018-02-07 08:22:58 +0000189 auto CloseFdOut = at_scope_exit([&]() { close(FdOut); } );
morehouse400262a2017-12-08 22:54:44 +0000190
191 // Determine stderr
192 int FdErr = STDERR_FILENO;
193 if (Cmd.isOutAndErrCombined())
194 FdErr = FdOut;
195
196 // Clone the file descriptors into the new process
phosek4b9efd12018-06-02 01:17:10 +0000197 fdio_spawn_action_t SpawnAction[] = {
198 {
199 .action = FDIO_SPAWN_ACTION_CLONE_FD,
200 .fd =
201 {
202 .local_fd = STDIN_FILENO,
203 .target_fd = STDIN_FILENO,
204 },
205 },
206 {
207 .action = FDIO_SPAWN_ACTION_CLONE_FD,
208 .fd =
209 {
210 .local_fd = FdOut,
211 .target_fd = STDOUT_FILENO,
212 },
213 },
214 {
215 .action = FDIO_SPAWN_ACTION_CLONE_FD,
216 .fd =
217 {
218 .local_fd = FdErr,
219 .target_fd = STDERR_FILENO,
220 },
221 },
222 };
morehouse400262a2017-12-08 22:54:44 +0000223
phosek4b9efd12018-06-02 01:17:10 +0000224 // Start the process.
225 char ErrorMsg[FDIO_SPAWN_ERR_MSG_MAX_LENGTH];
morehouse400262a2017-12-08 22:54:44 +0000226 zx_handle_t ProcessHandle = ZX_HANDLE_INVALID;
phosek4b9efd12018-06-02 01:17:10 +0000227 rc = fdio_spawn_etc(
228 ZX_HANDLE_INVALID, FDIO_SPAWN_CLONE_ALL & (~FDIO_SPAWN_CLONE_STDIO),
229 Argv[0], Argv.get(), nullptr, 3, SpawnAction, &ProcessHandle, ErrorMsg);
230 if (rc != ZX_OK) {
morehouse400262a2017-12-08 22:54:44 +0000231 Printf("libFuzzer: failed to launch '%s': %s, %s\n", Argv[0], ErrorMsg,
phosekf9123762018-02-07 08:22:58 +0000232 _zx_status_get_string(rc));
morehouse400262a2017-12-08 22:54:44 +0000233 return rc;
234 }
phosekf9123762018-02-07 08:22:58 +0000235 auto CloseHandle = at_scope_exit([&]() { _zx_handle_close(ProcessHandle); });
morehouse400262a2017-12-08 22:54:44 +0000236
237 // Now join the process and return the exit status.
phosekf9123762018-02-07 08:22:58 +0000238 if ((rc = _zx_object_wait_one(ProcessHandle, ZX_PROCESS_TERMINATED,
239 ZX_TIME_INFINITE, nullptr)) != ZX_OK) {
morehouse400262a2017-12-08 22:54:44 +0000240 Printf("libFuzzer: failed to join '%s': %s\n", Argv[0],
phosekf9123762018-02-07 08:22:58 +0000241 _zx_status_get_string(rc));
morehouse400262a2017-12-08 22:54:44 +0000242 return rc;
243 }
244
245 zx_info_process_t Info;
phosekf9123762018-02-07 08:22:58 +0000246 if ((rc = _zx_object_get_info(ProcessHandle, ZX_INFO_PROCESS, &Info,
247 sizeof(Info), nullptr, nullptr)) != ZX_OK) {
morehouse400262a2017-12-08 22:54:44 +0000248 Printf("libFuzzer: unable to get return code from '%s': %s\n", Argv[0],
phoseke81389f2018-05-26 01:02:34 +0000249 _zx_status_get_string(rc));
morehouse400262a2017-12-08 22:54:44 +0000250 return rc;
251 }
252
253 return Info.return_code;
254}
255
256const void *SearchMemory(const void *Data, size_t DataLen, const void *Patt,
257 size_t PattLen) {
258 return memmem(Data, DataLen, Patt, PattLen);
259}
260
261} // namespace fuzzer
262
263#endif // LIBFUZZER_FUCHSIA