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 <fbl/unique_fd.h>
21 #include <fcntl.h>
22 #include <launchpad/launchpad.h>
23 #include <string>
24 #include <thread>
25 #include <zircon/errors.h>
26 #include <zircon/status.h>
27 #include <zircon/syscalls.h>
28 #include <zircon/syscalls/port.h>
29 #include <zircon/types.h>
30 #include <zx/object.h>
31 #include <zx/port.h>
32 #include <zx/process.h>
33 #include <zx/time.h>
34 
35 namespace fuzzer {
36 
37 namespace {
38 
39 // A magic value for the Zircon exception port, chosen to spell 'FUZZING'
40 // when interpreted as a byte sequence on little-endian platforms.
41 const uint64_t kFuzzingCrash = 0x474e495a5a5546;
42 
43 void AlarmHandler(int Seconds) {
44   while (true) {
45     SleepSeconds(Seconds);
46     Fuzzer::StaticAlarmCallback();
47   }
48 }
49 
50 void InterruptHandler() {
51   // Ctrl-C sends ETX in Zircon.
52   while (getchar() != 0x03);
53   Fuzzer::StaticInterruptCallback();
54 }
55 
56 void CrashHandler(zx::port *Port) {
57   std::unique_ptr<zx::port> ExceptionPort(Port);
58   zx_port_packet_t Packet;
59   ExceptionPort->wait(ZX_TIME_INFINITE, &Packet, 0);
60   // Unbind as soon as possible so we don't receive exceptions from this thread.
61   if (zx_task_bind_exception_port(ZX_HANDLE_INVALID, ZX_HANDLE_INVALID,
62                                   kFuzzingCrash, 0) != ZX_OK) {
63     // Shouldn't happen; if it does the safest option is to just exit.
64     Printf("libFuzzer: unable to unbind exception port; aborting!\n");
65     exit(1);
66   }
67   if (Packet.key != kFuzzingCrash) {
68     Printf("libFuzzer: invalid crash key: %" PRIx64 "; aborting!\n",
69            Packet.key);
70     exit(1);
71   }
72   // CrashCallback should not return from this call
73   Fuzzer::StaticCrashSignalCallback();
74 }
75 
76 } // namespace
77 
78 // Platform specific functions.
79 void SetSignalHandler(const FuzzingOptions &Options) {
80   zx_status_t rc;
81 
82   // Set up alarm handler if needed.
83   if (Options.UnitTimeoutSec > 0) {
84     std::thread T(AlarmHandler, Options.UnitTimeoutSec / 2 + 1);
85     T.detach();
86   }
87 
88   // Set up interrupt handler if needed.
89   if (Options.HandleInt || Options.HandleTerm) {
90     std::thread T(InterruptHandler);
91     T.detach();
92   }
93 
94   // Early exit if no crash handler needed.
95   if (!Options.HandleSegv && !Options.HandleBus && !Options.HandleIll &&
96       !Options.HandleFpe && !Options.HandleAbrt)
97     return;
98 
99   // Create an exception port
100   zx::port *ExceptionPort = new zx::port();
101   if ((rc = zx::port::create(0, ExceptionPort)) != ZX_OK) {
102     Printf("libFuzzer: zx_port_create failed: %s\n", zx_status_get_string(rc));
103     exit(1);
104   }
105 
106   // Bind the port to receive exceptions from our process
107   if ((rc = zx_task_bind_exception_port(zx_process_self(), ExceptionPort->get(),
108                                         kFuzzingCrash, 0)) != ZX_OK) {
109     Printf("libFuzzer: unable to bind exception port: %s\n",
110            zx_status_get_string(rc));
111     exit(1);
112   }
113 
114   // Set up the crash handler.
115   std::thread T(CrashHandler, ExceptionPort);
116   T.detach();
117 }
118 
119 void SleepSeconds(int Seconds) {
120   zx::nanosleep(zx::deadline_after(ZX_SEC(Seconds)));
121 }
122 
123 unsigned long GetPid() {
124   zx_status_t rc;
125   zx_info_handle_basic_t Info;
126   if ((rc = zx_object_get_info(zx_process_self(), ZX_INFO_HANDLE_BASIC, &Info,
127                                sizeof(Info), NULL, NULL)) != ZX_OK) {
128     Printf("libFuzzer: unable to get info about self: %s\n",
129            zx_status_get_string(rc));
130     exit(1);
131   }
132   return Info.koid;
133 }
134 
135 size_t GetPeakRSSMb() {
136   zx_status_t rc;
137   zx_info_task_stats_t Info;
138   if ((rc = zx_object_get_info(zx_process_self(), ZX_INFO_TASK_STATS, &Info,
139                                sizeof(Info), NULL, NULL)) != ZX_OK) {
140     Printf("libFuzzer: unable to get info about self: %s\n",
141            zx_status_get_string(rc));
142     exit(1);
143   }
144   return (Info.mem_private_bytes + Info.mem_shared_bytes) >> 20;
145 }
146 
147 int ExecuteCommand(const Command &Cmd) {
148   zx_status_t rc;
149 
150   // Convert arguments to C array
151   auto Args = Cmd.getArguments();
152   size_t Argc = Args.size();
153   assert(Argc != 0);
154   std::unique_ptr<const char *[]> Argv(new const char *[Argc]);
155   for (size_t i = 0; i < Argc; ++i)
156     Argv[i] = Args[i].c_str();
157 
158   // Create the basic launchpad.  Clone everything except stdio.
159   launchpad_t *lp;
160   launchpad_create(ZX_HANDLE_INVALID, Argv[0], &lp);
161   launchpad_load_from_file(lp, Argv[0]);
162   launchpad_set_args(lp, Argc, Argv.get());
163   launchpad_clone(lp, LP_CLONE_ALL & (~LP_CLONE_FDIO_STDIO));
164 
165   // Determine stdout
166   int FdOut = STDOUT_FILENO;
167   fbl::unique_fd OutputFile;
168   if (Cmd.hasOutputFile()) {
169     auto Filename = Cmd.getOutputFile();
170     OutputFile.reset(open(Filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0));
171     if (!OutputFile) {
172       Printf("libFuzzer: failed to open %s: %s\n", Filename.c_str(),
173              strerror(errno));
174       return ZX_ERR_IO;
175     }
176     FdOut = OutputFile.get();
177   }
178 
179   // Determine stderr
180   int FdErr = STDERR_FILENO;
181   if (Cmd.isOutAndErrCombined())
182     FdErr = FdOut;
183 
184   // Clone the file descriptors into the new process
185   if ((rc = launchpad_clone_fd(lp, STDIN_FILENO, STDIN_FILENO)) != ZX_OK ||
186       (rc = launchpad_clone_fd(lp, FdOut, STDOUT_FILENO)) != ZX_OK ||
187       (rc = launchpad_clone_fd(lp, FdErr, STDERR_FILENO)) != ZX_OK) {
188     Printf("libFuzzer: failed to clone FDIO: %s\n", zx_status_get_string(rc));
189     return rc;
190   }
191 
192   // Start the process
193   zx_handle_t ProcessHandle = ZX_HANDLE_INVALID;
194   const char *ErrorMsg = nullptr;
195   if ((rc = launchpad_go(lp, &ProcessHandle, &ErrorMsg)) != ZX_OK) {
196     Printf("libFuzzer: failed to launch '%s': %s, %s\n", Argv[0], ErrorMsg,
197            zx_status_get_string(rc));
198     return rc;
199   }
200   zx::process Process(ProcessHandle);
201 
202   // Now join the process and return the exit status.
203   if ((rc = Process.wait_one(ZX_PROCESS_TERMINATED, ZX_TIME_INFINITE,
204                              nullptr)) != ZX_OK) {
205     Printf("libFuzzer: failed to join '%s': %s\n", Argv[0],
206            zx_status_get_string(rc));
207     return rc;
208   }
209 
210   zx_info_process_t Info;
211   if ((rc = Process.get_info(ZX_INFO_PROCESS, &Info, sizeof(Info), nullptr,
212                              nullptr)) != ZX_OK) {
213     Printf("libFuzzer: unable to get return code from '%s': %s\n", Argv[0],
214            zx_status_get_string(rc));
215     return rc;
216   }
217 
218   return Info.return_code;
219 }
220 
221 const void *SearchMemory(const void *Data, size_t DataLen, const void *Patt,
222                          size_t PattLen) {
223   return memmem(Data, DataLen, Patt, PattLen);
224 }
225 
226 } // namespace fuzzer
227 
228 #endif // LIBFUZZER_FUCHSIA
229