1 // Copyright 2014 The Crashpad Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include <fcntl.h>
16 #include <getopt.h>
17 #include <libgen.h>
18 #include <stdio.h>
19 #include <string.h>
20 #include <sys/types.h>
21 #include <unistd.h>
22 
23 #include <algorithm>
24 #include <string>
25 #include <vector>
26 
27 #include "base/files/scoped_file.h"
28 #include "base/logging.h"
29 #include "base/mac/mach_logging.h"
30 #include "tools/tool_support.h"
31 #include "util/mach/bootstrap.h"
32 #include "util/mach/exc_server_variants.h"
33 #include "util/mach/exception_behaviors.h"
34 #include "util/mach/exception_types.h"
35 #include "util/mach/mach_extensions.h"
36 #include "util/mach/mach_message.h"
37 #include "util/mach/mach_message_server.h"
38 #include "util/mach/symbolic_constants_mach.h"
39 #include "util/posix/symbolic_constants_posix.h"
40 #include "util/stdlib/string_number_conversion.h"
41 
42 namespace crashpad {
43 namespace {
44 
45 struct Options {
46   std::string file_path;
47   std::string mach_service;
48   FILE* file;
49   int timeout_secs;
50   bool has_timeout;
51   MachMessageServer::Persistent persistent;
52 };
53 
54 class ExceptionServer final : public UniversalMachExcServer::Interface {
55  public:
ExceptionServer(const Options & options,const std::string & me,int * exceptions_handled)56   ExceptionServer(const Options& options,
57                   const std::string& me,
58                   int* exceptions_handled)
59       : UniversalMachExcServer::Interface(),
60         options_(options),
61         me_(me),
62         exceptions_handled_(exceptions_handled) {}
63 
64   // UniversalMachExcServer::Interface:
CatchMachException(exception_behavior_t behavior,exception_handler_t exception_port,thread_t thread,task_t task,exception_type_t exception,const mach_exception_data_type_t * code,mach_msg_type_number_t code_count,thread_state_flavor_t * flavor,ConstThreadState old_state,mach_msg_type_number_t old_state_count,thread_state_t new_state,mach_msg_type_number_t * new_state_count,const mach_msg_trailer_t * trailer,bool * destroy_complex_request)65   virtual kern_return_t CatchMachException(
66       exception_behavior_t behavior,
67       exception_handler_t exception_port,
68       thread_t thread,
69       task_t task,
70       exception_type_t exception,
71       const mach_exception_data_type_t* code,
72       mach_msg_type_number_t code_count,
73       thread_state_flavor_t* flavor,
74       ConstThreadState old_state,
75       mach_msg_type_number_t old_state_count,
76       thread_state_t new_state,
77       mach_msg_type_number_t* new_state_count,
78       const mach_msg_trailer_t* trailer,
79       bool* destroy_complex_request) override {
80     *destroy_complex_request = true;
81     ++*exceptions_handled_;
82 
83     fprintf(options_.file,
84             "%s: behavior %s",
85             me_.c_str(),
86             ExceptionBehaviorToString(
87                 behavior, kUseFullName | kUnknownIsNumeric | kUseOr).c_str());
88 
89     kern_return_t kr;
90     if (ExceptionBehaviorHasIdentity(behavior)) {
91       // It’s not possible to call pid_for_task() once EXC_CORPSE_NOTIFY has
92       // been generated. It is possible to obtain the process ID by mapping the
93       // corpse kcdata area from the task’s address space at code[0] (size
94       // code[1]) and locating TASK_CRASHINFO_PID within that area. This area
95       // also includes TASK_CRASHINFO_CRASHED_THREADID which could be used
96       // instead of thread_info() below, and TASK_CRASHINFO_EXCEPTION_CODES
97       // which could be used to recover the exception codes passed to the
98       // EXC_CRASH handler. None of this is currently done because corpses are a
99       // new 10.11-only feature. See 10.11 <corpses/task_corpse.h> and
100       // <kern/kern_cdata.h>.
101       if (exception != EXC_CORPSE_NOTIFY) {
102         pid_t pid;
103         kr = pid_for_task(task, &pid);
104         if (kr != KERN_SUCCESS) {
105           fprintf(options_.file, "\n");
106           fflush(options_.file);
107           MACH_LOG(ERROR, kr) << "pid_for_task";
108           return KERN_FAILURE;
109         }
110         fprintf(options_.file, ", pid %d", pid);
111       }
112 
113       thread_identifier_info identifier_info;
114       mach_msg_type_number_t count = THREAD_IDENTIFIER_INFO_COUNT;
115       kr = thread_info(thread,
116                        THREAD_IDENTIFIER_INFO,
117                        reinterpret_cast<thread_info_t>(&identifier_info),
118                        &count);
119       if (kr != KERN_SUCCESS) {
120         fprintf(options_.file, "\n");
121         fflush(options_.file);
122         MACH_LOG(ERROR, kr) << "thread_info";
123         return KERN_FAILURE;
124       }
125       fprintf(options_.file, ", thread %lld", identifier_info.thread_id);
126     }
127 
128     fprintf(
129         options_.file,
130         ", exception %s, codes[%d]",
131         ExceptionToString(exception, kUseFullName | kUnknownIsNumeric).c_str(),
132         code_count);
133 
134     for (size_t index = 0; index < code_count; ++index) {
135       fprintf(options_.file,
136               "%s %#llx",
137               index != 0 ? "," : "",
138               code[index]);
139     }
140 
141     if (exception == EXC_CRASH) {
142       mach_exception_code_t original_code_0;
143       int signal;
144       exception_type_t original_exception =
145           ExcCrashRecoverOriginalException(code[0], &original_code_0, &signal);
146       fprintf(options_.file,
147               ", original exception %s, original code[0] %lld, signal %s",
148               ExceptionToString(original_exception,
149                                 kUseFullName | kUnknownIsNumeric).c_str(),
150               original_code_0,
151               SignalToString(signal, kUseFullName | kUnknownIsNumeric).c_str());
152     }
153 
154     if (ExceptionBehaviorHasState(behavior)) {
155       std::string flavor_string =
156           ThreadStateFlavorToString(*flavor, kUseFullName | kUnknownIsNumeric);
157       fprintf(options_.file,
158               ", flavor %s, old_state_count %d",
159               flavor_string.c_str(),
160               old_state_count);
161     }
162 
163     fprintf(options_.file, "\n");
164     fflush(options_.file);
165 
166     if (exception != EXC_CRASH && exception != kMachExceptionSimulated) {
167       // Find another handler.
168       return KERN_FAILURE;
169     }
170 
171     ExcServerCopyState(
172         behavior, old_state, old_state_count, new_state, new_state_count);
173 
174     return ExcServerSuccessfulReturnValue(exception, behavior, false);
175   }
176 
177  private:
178   const Options& options_;
179   const std::string& me_;
180   int* exceptions_handled_;
181 };
182 
Usage(const std::string & me)183 void Usage(const std::string& me) {
184   fprintf(stderr,
185 "Usage: %s -m SERVICE [OPTION]...\n"
186 "Catch Mach exceptions and display information about them.\n"
187 "\n"
188 "  -f, --file=FILE             append information to FILE instead of stdout\n"
189 "  -m, --mach-service=SERVICE  register SERVICE with the bootstrap server\n"
190 "  -p, --persistent            continue processing exceptions after the first\n"
191 "  -t, --timeout=TIMEOUT       run for a maximum of TIMEOUT seconds\n"
192 "      --help                  display this help and exit\n"
193 "      --version               output version information and exit\n",
194           me.c_str());
195   ToolSupport::UsageTail(me);
196 }
197 
CatchExceptionToolMain(int argc,char * argv[])198 int CatchExceptionToolMain(int argc, char* argv[]) {
199   const std::string me(basename(argv[0]));
200 
201   enum OptionFlags {
202     // “Short” (single-character) options.
203     kOptionFile = 'f',
204     kOptionMachService = 'm',
205     kOptionPersistent = 'p',
206     kOptionTimeout = 't',
207 
208     // Long options without short equivalents.
209     kOptionLastChar = 255,
210 
211     // Standard options.
212     kOptionHelp = -2,
213     kOptionVersion = -3,
214   };
215 
216   Options options = {};
217 
218   static constexpr option long_options[] = {
219       {"file", required_argument, nullptr, kOptionFile},
220       {"mach-service", required_argument, nullptr, kOptionMachService},
221       {"persistent", no_argument, nullptr, kOptionPersistent},
222       {"timeout", required_argument, nullptr, kOptionTimeout},
223       {"help", no_argument, nullptr, kOptionHelp},
224       {"version", no_argument, nullptr, kOptionVersion},
225       {nullptr, 0, nullptr, 0},
226   };
227 
228   int opt;
229   while ((opt = getopt_long(argc, argv, "f:m:pt:", long_options, nullptr)) !=
230          -1) {
231     switch (opt) {
232       case kOptionFile:
233         options.file_path = optarg;
234         break;
235       case kOptionMachService:
236         options.mach_service = optarg;
237         break;
238       case kOptionPersistent:
239         options.persistent = MachMessageServer::kPersistent;
240         break;
241       case kOptionTimeout:
242         if (!StringToNumber(optarg, &options.timeout_secs) ||
243             options.timeout_secs < 0) {
244           ToolSupport::UsageHint(me, "-t requires a zero or positive TIMEOUT");
245           return EXIT_FAILURE;
246         }
247         options.has_timeout = true;
248         break;
249       case kOptionHelp:
250         Usage(me);
251         return EXIT_SUCCESS;
252       case kOptionVersion:
253         ToolSupport::Version(me);
254         return EXIT_SUCCESS;
255       default:
256         ToolSupport::UsageHint(me, nullptr);
257         return EXIT_FAILURE;
258     }
259   }
260   argc -= optind;
261   argv += optind;
262 
263   if (options.mach_service.empty()) {
264     ToolSupport::UsageHint(me, "-m is required");
265     return EXIT_FAILURE;
266   }
267 
268   base::mac::ScopedMachReceiveRight
269       service_port(BootstrapCheckIn(options.mach_service));
270   if (service_port == kMachPortNull) {
271     return EXIT_FAILURE;
272   }
273 
274   base::ScopedFILE file_owner;
275   if (options.file_path.empty()) {
276     options.file = stdout;
277   } else {
278     file_owner.reset(fopen(options.file_path.c_str(), "a"));
279     if (!file_owner.get()) {
280       PLOG(ERROR) << "fopen " << options.file_path;
281       return EXIT_FAILURE;
282     }
283     options.file = file_owner.get();
284     if (fcntl(fileno(options.file), F_SETFD, FD_CLOEXEC) == -1) {
285       PLOG(ERROR) << "fcntl " << options.file_path;
286       return EXIT_FAILURE;
287     }
288   }
289 
290   int exceptions_handled = 0;
291   ExceptionServer exception_server(options, me, &exceptions_handled);
292   UniversalMachExcServer universal_mach_exc_server(&exception_server);
293 
294   // Assume that if persistent mode has been requested, it’s desirable to ignore
295   // large messages and keep running.
296   MachMessageServer::ReceiveLarge receive_large =
297       (options.persistent == MachMessageServer::kPersistent)
298           ? MachMessageServer::kReceiveLargeIgnore
299           : MachMessageServer::kReceiveLargeError;
300 
301   mach_msg_timeout_t timeout_ms;
302   if (!options.has_timeout) {
303     timeout_ms = kMachMessageTimeoutWaitIndefinitely;
304   } else if (options.timeout_secs == 0) {
305     timeout_ms = kMachMessageTimeoutNonblocking;
306   } else {
307     timeout_ms = options.timeout_secs * 1000;
308   }
309 
310   mach_msg_return_t mr = MachMessageServer::Run(&universal_mach_exc_server,
311                                                 service_port.get(),
312                                                 MACH_MSG_OPTION_NONE,
313                                                 options.persistent,
314                                                 receive_large,
315                                                 timeout_ms);
316   if (mr == MACH_RCV_TIMED_OUT && options.has_timeout && options.persistent &&
317       exceptions_handled) {
318     // This is not an error: when exiting on timeout during persistent
319     // processing and at least one exception was handled, it’s considered a
320     // success.
321   } else if (mr != MACH_MSG_SUCCESS) {
322     MACH_LOG(ERROR, mr) << "MachMessageServer::Run";
323     return EXIT_FAILURE;
324   }
325 
326   return EXIT_SUCCESS;
327 }
328 
329 }  // namespace
330 }  // namespace crashpad
331 
main(int argc,char * argv[])332 int main(int argc, char* argv[]) {
333   return crashpad::CatchExceptionToolMain(argc, argv);
334 }
335