1 // Copyright 2015 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 "handler/mac/crash_report_exception_handler.h"
16
17 #include <utility>
18 #include <vector>
19
20 #include "base/logging.h"
21 #include "base/mac/mach_logging.h"
22 #include "base/mac/scoped_mach_port.h"
23 #include "base/strings/stringprintf.h"
24 #include "client/settings.h"
25 #include "handler/mac/file_limit_annotation.h"
26 #include "minidump/minidump_file_writer.h"
27 #include "minidump/minidump_user_extension_stream_data_source.h"
28 #include "snapshot/crashpad_info_client_options.h"
29 #include "snapshot/mac/process_snapshot_mac.h"
30 #include "util/file/file_writer.h"
31 #include "util/mach/bootstrap.h"
32 #include "util/mach/exc_client_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/scoped_task_suspend.h"
38 #include "util/mach/symbolic_constants_mach.h"
39 #include "util/misc/metrics.h"
40 #include "util/misc/tri_state.h"
41 #include "util/misc/uuid.h"
42
43 namespace crashpad {
44
CrashReportExceptionHandler(CrashReportDatabase * database,CrashReportUploadThread * upload_thread,const std::map<std::string,std::string> * process_annotations,const UserStreamDataSources * user_stream_data_sources)45 CrashReportExceptionHandler::CrashReportExceptionHandler(
46 CrashReportDatabase* database,
47 CrashReportUploadThread* upload_thread,
48 const std::map<std::string, std::string>* process_annotations,
49 const UserStreamDataSources* user_stream_data_sources)
50 : database_(database),
51 upload_thread_(upload_thread),
52 process_annotations_(process_annotations),
53 user_stream_data_sources_(user_stream_data_sources) {}
54
~CrashReportExceptionHandler()55 CrashReportExceptionHandler::~CrashReportExceptionHandler() {
56 }
57
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)58 kern_return_t CrashReportExceptionHandler::CatchMachException(
59 exception_behavior_t behavior,
60 exception_handler_t exception_port,
61 thread_t thread,
62 task_t task,
63 exception_type_t exception,
64 const mach_exception_data_type_t* code,
65 mach_msg_type_number_t code_count,
66 thread_state_flavor_t* flavor,
67 ConstThreadState old_state,
68 mach_msg_type_number_t old_state_count,
69 thread_state_t new_state,
70 mach_msg_type_number_t* new_state_count,
71 const mach_msg_trailer_t* trailer,
72 bool* destroy_complex_request) {
73 RecordFileLimitAnnotation();
74 Metrics::ExceptionEncountered();
75 Metrics::ExceptionCode(ExceptionCodeForMetrics(exception, code[0]));
76 *destroy_complex_request = true;
77
78 // The expected behavior is EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES,
79 // but it’s possible to deal with any exception behavior as long as it
80 // carries identity information (valid thread and task ports).
81 if (!ExceptionBehaviorHasIdentity(behavior)) {
82 LOG(ERROR) << base::StringPrintf(
83 "unexpected exception behavior %s, rejecting",
84 ExceptionBehaviorToString(
85 behavior, kUseFullName | kUnknownIsNumeric | kUseOr).c_str());
86 Metrics::ExceptionCaptureResult(
87 Metrics::CaptureResult::kUnexpectedExceptionBehavior);
88 return KERN_FAILURE;
89 } else if (behavior != (EXCEPTION_STATE_IDENTITY | kMachExceptionCodes)) {
90 LOG(WARNING) << base::StringPrintf(
91 "unexpected exception behavior %s, proceeding",
92 ExceptionBehaviorToString(
93 behavior, kUseFullName | kUnknownIsNumeric | kUseOr).c_str());
94 }
95
96 if (task == mach_task_self()) {
97 LOG(ERROR) << "cannot suspend myself";
98 Metrics::ExceptionCaptureResult(
99 Metrics::CaptureResult::kFailedDueToSuspendSelf);
100 return KERN_FAILURE;
101 }
102
103 ScopedTaskSuspend suspend(task);
104
105 ProcessSnapshotMac process_snapshot;
106 if (!process_snapshot.Initialize(task)) {
107 Metrics::ExceptionCaptureResult(Metrics::CaptureResult::kSnapshotFailed);
108 return KERN_FAILURE;
109 }
110
111 // Check for suspicious message sources. A suspicious exception message comes
112 // from a source other than the kernel or the process that the exception
113 // purportedly occurred in.
114 //
115 // TODO(mark): Consider exceptions outside of the range (0, 32) from the
116 // kernel to be suspicious, and exceptions other than kMachExceptionSimulated
117 // from the process itself to be suspicious.
118 const pid_t pid = process_snapshot.ProcessID();
119 pid_t audit_pid = AuditPIDFromMachMessageTrailer(trailer);
120 if (audit_pid != -1 && audit_pid != 0) {
121 if (audit_pid != pid) {
122 LOG(WARNING) << "exception for pid " << pid << " sent by pid "
123 << audit_pid;
124 }
125 }
126
127 CrashpadInfoClientOptions client_options;
128 process_snapshot.GetCrashpadOptions(&client_options);
129
130 if (client_options.crashpad_handler_behavior != TriState::kDisabled &&
131 !IsExceptionNonfatalResource(exception, code[0], pid)) {
132 // Non-fatal resource exceptions are never user-visible and are not
133 // currently of interest to Crashpad.
134
135 if (!process_snapshot.InitializeException(behavior,
136 thread,
137 exception,
138 code,
139 code_count,
140 *flavor,
141 old_state,
142 old_state_count)) {
143 Metrics::ExceptionCaptureResult(
144 Metrics::CaptureResult::kExceptionInitializationFailed);
145 return KERN_FAILURE;
146 }
147
148 UUID client_id;
149 Settings* const settings = database_->GetSettings();
150 if (settings) {
151 // If GetSettings() or GetClientID() fails, something else will log a
152 // message and client_id will be left at its default value, all zeroes,
153 // which is appropriate.
154 settings->GetClientID(&client_id);
155 }
156
157 process_snapshot.SetClientID(client_id);
158 process_snapshot.SetAnnotationsSimpleMap(*process_annotations_);
159
160 std::unique_ptr<CrashReportDatabase::NewReport> new_report;
161 CrashReportDatabase::OperationStatus database_status =
162 database_->PrepareNewCrashReport(&new_report);
163 if (database_status != CrashReportDatabase::kNoError) {
164 Metrics::ExceptionCaptureResult(
165 Metrics::CaptureResult::kPrepareNewCrashReportFailed);
166 return KERN_FAILURE;
167 }
168
169 process_snapshot.SetReportID(new_report->ReportID());
170
171 MinidumpFileWriter minidump;
172 minidump.InitializeFromSnapshot(&process_snapshot);
173 AddUserExtensionStreams(
174 user_stream_data_sources_, &process_snapshot, &minidump);
175
176 if (!minidump.WriteEverything(new_report->Writer())) {
177 Metrics::ExceptionCaptureResult(
178 Metrics::CaptureResult::kMinidumpWriteFailed);
179 return KERN_FAILURE;
180 }
181
182 UUID uuid;
183 database_status =
184 database_->FinishedWritingCrashReport(std::move(new_report), &uuid);
185 if (database_status != CrashReportDatabase::kNoError) {
186 Metrics::ExceptionCaptureResult(
187 Metrics::CaptureResult::kFinishedWritingCrashReportFailed);
188 return KERN_FAILURE;
189 }
190
191 if (upload_thread_) {
192 upload_thread_->ReportPending(uuid);
193 }
194 }
195
196 if (client_options.system_crash_reporter_forwarding != TriState::kDisabled &&
197 (exception == EXC_CRASH ||
198 exception == EXC_RESOURCE ||
199 exception == EXC_GUARD)) {
200 // Don’t forward simulated exceptions such as kMachExceptionSimulated to the
201 // system crash reporter. Only forward the types of exceptions that it would
202 // receive under normal conditions. Although the system crash reporter is
203 // able to deal with other exceptions including simulated ones, forwarding
204 // them to the system crash reporter could present the system’s crash UI for
205 // processes that haven’t actually crashed, and could result in reports not
206 // actually associated with crashes being sent to the operating system
207 // vendor.
208 base::mac::ScopedMachSendRight
209 system_crash_reporter_handler(SystemCrashReporterHandler());
210 if (system_crash_reporter_handler.get()) {
211 // Make copies of mutable out parameters so that the system crash reporter
212 // can’t influence the state returned by this method.
213 thread_state_flavor_t flavor_forward = *flavor;
214 mach_msg_type_number_t new_state_forward_count = *new_state_count;
215 std::vector<natural_t> new_state_forward(
216 new_state, new_state + new_state_forward_count);
217
218 // The system crash reporter requires the behavior to be
219 // EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES. It uses the identity
220 // parameters but doesn’t appear to use the state parameters, including
221 // |flavor|, and doesn’t care if they are 0 or invalid. As long as an
222 // identity is available (checked above), any other exception behavior is
223 // converted to what the system crash reporter wants, with the caveat that
224 // problems may arise if the state wasn’t available and the system crash
225 // reporter changes in the future to use it. However, normally, the state
226 // will be available.
227 kern_return_t kr = UniversalExceptionRaise(
228 EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES,
229 system_crash_reporter_handler.get(),
230 thread,
231 task,
232 exception,
233 code,
234 code_count,
235 &flavor_forward,
236 old_state,
237 old_state_count,
238 new_state_forward_count ? &new_state_forward[0] : nullptr,
239 &new_state_forward_count);
240 MACH_LOG_IF(WARNING, kr != KERN_SUCCESS, kr) << "UniversalExceptionRaise";
241 }
242 }
243
244 ExcServerCopyState(
245 behavior, old_state, old_state_count, new_state, new_state_count);
246
247 Metrics::ExceptionCaptureResult(Metrics::CaptureResult::kSuccess);
248 return ExcServerSuccessfulReturnValue(exception, behavior, false);
249 }
250
251 } // namespace crashpad
252