1 //===- 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>
20 #include <fcntl.h>
21 #include <launchpad/launchpad.h>
22 #include <string>
23 #include <sys/select.h>
24 #include <thread>
25 #include <unistd.h>
26 #include <zircon/errors.h>
27 #include <zircon/process.h>
28 #include <zircon/status.h>
29 #include <zircon/syscalls.h>
30 #include <zircon/syscalls/port.h>
31 #include <zircon/types.h>
32 
33 namespace fuzzer {
34 
35 namespace {
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.
39 const uint64_t kFuzzingCrash = 0x474e495a5a5546;
40 
41 void AlarmHandler(int Seconds) {
42   while (true) {
43     SleepSeconds(Seconds);
44     Fuzzer::StaticAlarmCallback();
45   }
46 }
47 
48 void InterruptHandler() {
49   fd_set readfds;
50   // Ctrl-C sends ETX in Zircon.
51   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);
56   Fuzzer::StaticInterruptCallback();
57 }
58 
59 void CrashHandler(zx_handle_t *Port) {
60   std::unique_ptr<zx_handle_t> ExceptionPort(Port);
61   zx_port_packet_t Packet;
62   _zx_port_wait(*ExceptionPort, ZX_TIME_INFINITE, &Packet, 1);
63   // Unbind as soon as possible so we don't receive exceptions from this thread.
64   if (_zx_task_bind_exception_port(ZX_HANDLE_INVALID, ZX_HANDLE_INVALID,
65                                    kFuzzingCrash, 0) != ZX_OK) {
66     // 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.
82 void 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
103   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));
106     exit(1);
107   }
108 
109   // Bind the port to receive exceptions from our process
110   if ((rc = _zx_task_bind_exception_port(_zx_process_self(), *ExceptionPort,
111                                          kFuzzingCrash, 0)) != ZX_OK) {
112     Printf("libFuzzer: unable to bind exception port: %s\n",
113            zx_status_get_string(rc));
114     exit(1);
115   }
116 
117   // Set up the crash handler.
118   std::thread T(CrashHandler, ExceptionPort);
119   T.detach();
120 }
121 
122 void SleepSeconds(int Seconds) {
123   _zx_nanosleep(_zx_deadline_after(ZX_SEC(Seconds)));
124 }
125 
126 unsigned long GetPid() {
127   zx_status_t rc;
128   zx_info_handle_basic_t Info;
129   if ((rc = zx_object_get_info(_zx_process_self(), ZX_INFO_HANDLE_BASIC, &Info,
130                                sizeof(Info), NULL, NULL)) != ZX_OK) {
131     Printf("libFuzzer: unable to get info about self: %s\n",
132            zx_status_get_string(rc));
133     exit(1);
134   }
135   return Info.koid;
136 }
137 
138 size_t GetPeakRSSMb() {
139   zx_status_t rc;
140   zx_info_task_stats_t Info;
141   if ((rc = _zx_object_get_info(_zx_process_self(), ZX_INFO_TASK_STATS, &Info,
142                                sizeof(Info), NULL, NULL)) != ZX_OK) {
143     Printf("libFuzzer: unable to get info about self: %s\n",
144            _zx_status_get_string(rc));
145     exit(1);
146   }
147   return (Info.mem_private_bytes + Info.mem_shared_bytes) >> 20;
148 }
149 
150 template <typename Fn>
151 class RunOnDestruction {
152  public:
153   explicit RunOnDestruction(Fn fn) : fn_(fn) {}
154   ~RunOnDestruction() { fn_(); }
155 
156  private:
157   Fn fn_;
158 };
159 
160 template <typename Fn>
161 RunOnDestruction<Fn> at_scope_exit(Fn fn) {
162   return RunOnDestruction<Fn>(fn);
163 }
164 
165 int 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;
185 
186   if (Cmd.hasOutputFile()) {
187     auto Filename = Cmd.getOutputFile();
188     FdOut = open(Filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0);
189     if (FdOut == -1) {
190       Printf("libFuzzer: failed to open %s: %s\n", Filename.c_str(),
191              strerror(errno));
192       return ZX_ERR_IO;
193     }
194   }
195   auto CloseFdOut = at_scope_exit([&]() { close(FdOut); } );
196 
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) {
206     Printf("libFuzzer: failed to clone FDIO: %s\n", _zx_status_get_string(rc));
207     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,
215            _zx_status_get_string(rc));
216     return rc;
217   }
218   auto CloseHandle = at_scope_exit([&]() { _zx_handle_close(ProcessHandle); });
219 
220   // Now join the process and return the exit status.
221   if ((rc = _zx_object_wait_one(ProcessHandle, ZX_PROCESS_TERMINATED,
222                                 ZX_TIME_INFINITE, nullptr)) != ZX_OK) {
223     Printf("libFuzzer: failed to join '%s': %s\n", Argv[0],
224            _zx_status_get_string(rc));
225     return rc;
226   }
227 
228   zx_info_process_t Info;
229   if ((rc = _zx_object_get_info(ProcessHandle, ZX_INFO_PROCESS, &Info,
230                                 sizeof(Info), nullptr, nullptr)) != ZX_OK) {
231     Printf("libFuzzer: unable to get return code from '%s': %s\n", Argv[0],
232            zx_status_get_string(rc));
233     return rc;
234   }
235 
236   return Info.return_code;
237 }
238 
239 const 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
247