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 <fdio/spawn.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);
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 + 1]);
173   for (size_t i = 0; i < Argc; ++i)
174     Argv[i] = Args[i].c_str();
175   Argv[Argc] = nullptr;
176 
177   // Determine stdout
178   int FdOut = STDOUT_FILENO;
179 
180   if (Cmd.hasOutputFile()) {
181     auto Filename = Cmd.getOutputFile();
182     FdOut = open(Filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0);
183     if (FdOut == -1) {
184       Printf("libFuzzer: failed to open %s: %s\n", Filename.c_str(),
185              strerror(errno));
186       return ZX_ERR_IO;
187     }
188   }
189   auto CloseFdOut = at_scope_exit([&]() { close(FdOut); } );
190 
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
197   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   };
223 
224   // Start the process.
225   char ErrorMsg[FDIO_SPAWN_ERR_MSG_MAX_LENGTH];
226   zx_handle_t ProcessHandle = ZX_HANDLE_INVALID;
227   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) {
231     Printf("libFuzzer: failed to launch '%s': %s, %s\n", Argv[0], ErrorMsg,
232            _zx_status_get_string(rc));
233     return rc;
234   }
235   auto CloseHandle = at_scope_exit([&]() { _zx_handle_close(ProcessHandle); });
236 
237   // Now join the process and return the exit status.
238   if ((rc = _zx_object_wait_one(ProcessHandle, ZX_PROCESS_TERMINATED,
239                                 ZX_TIME_INFINITE, nullptr)) != ZX_OK) {
240     Printf("libFuzzer: failed to join '%s': %s\n", Argv[0],
241            _zx_status_get_string(rc));
242     return rc;
243   }
244 
245   zx_info_process_t Info;
246   if ((rc = _zx_object_get_info(ProcessHandle, ZX_INFO_PROCESS, &Info,
247                                 sizeof(Info), nullptr, nullptr)) != ZX_OK) {
248     Printf("libFuzzer: unable to get return code from '%s': %s\n", Argv[0],
249            _zx_status_get_string(rc));
250     return rc;
251   }
252 
253   return Info.return_code;
254 }
255 
256 const 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
264