OLD | NEW |
---|---|
(Empty) | |
1 // Copyright 2016 The Chromium Authors. All rights reserved. | |
scottmg
2017/01/06 18:29:04
2017
Sigurður Ásgeirsson
2017/01/06 20:59:11
Done.
| |
2 // Use of this source code is governed by a BSD-style license that can be | |
3 // found in the LICENSE file. | |
4 | |
5 #include "components/crash/content/app/fallback_crash_handler_win.h" | |
6 | |
7 #include <dbghelp.h> | |
8 | |
9 #include <algorithm> | |
10 #include <map> | |
11 #include <vector> | |
12 | |
13 #include "base/command_line.h" | |
14 #include "base/files/file.h" | |
15 #include "base/files/file_util.h" | |
16 #include "base/numerics/safe_conversions.h" | |
17 #include "base/process/process_handle.h" | |
18 #include "base/strings/string_number_conversions.h" | |
19 #include "base/win/scoped_handle.h" | |
20 #include "base/win/win_util.h" | |
21 #include "third_party/crashpad/crashpad/client/crash_report_database.h" | |
22 #include "third_party/crashpad/crashpad/client/settings.h" | |
23 #include "third_party/crashpad/crashpad/minidump/minidump_extensions.h" | |
24 | |
25 namespace crash_reporter { | |
26 | |
27 namespace { | |
28 | |
29 using StringStringMap = std::map<std::string, std::string>; | |
30 | |
31 class MinidumpUpdater { | |
32 public: | |
33 using FilePosition = uint32_t; | |
34 | |
35 MinidumpUpdater(); | |
36 | |
37 // Reads the existing directory from |file|. | |
38 bool Initialize(base::File* file); | |
39 | |
40 // Appends the simple dictionary with |crash_keys| to the file, and updates | |
41 // the CrashpadInfo with its location. | |
42 bool AppendSimpleDictionary(const StringStringMap& crash_keys); | |
43 | |
44 private: | |
45 // Writes |data_len| bytes from |data| to the file at the current location. | |
46 bool WriteData(const void* data, size_t data_len); | |
47 bool WriteAndAdvance(const void* data, | |
48 size_t data_len, | |
49 FilePosition* position); | |
50 | |
51 base::File* file_; | |
52 std::vector<MINIDUMP_DIRECTORY> directory_; | |
53 }; | |
54 | |
55 MinidumpUpdater::MinidumpUpdater() : file_(nullptr) {} | |
56 | |
57 bool MinidumpUpdater::Initialize(base::File* file) { | |
58 DCHECK(file && file->IsValid()); | |
59 DCHECK(!file_); | |
60 | |
61 // Read the file header. | |
62 MINIDUMP_HEADER header = {}; | |
63 int bytes_read = | |
64 file->Read(0, reinterpret_cast<char*>(&header), sizeof(header)); | |
65 if (bytes_read != sizeof(header)) | |
66 return false; | |
67 if (header.Signature != MINIDUMP_SIGNATURE || header.NumberOfStreams == 0) | |
68 return false; | |
69 | |
70 // Read the stream directory. | |
71 directory_.resize(header.NumberOfStreams); | |
72 int bytes_to_read = header.NumberOfStreams * sizeof(directory_[0]); | |
73 bytes_read = | |
74 file->Read(header.StreamDirectoryRva, | |
75 reinterpret_cast<char*>(&directory_.at(0)), bytes_to_read); | |
76 if (bytes_read != bytes_to_read) | |
77 return false; | |
78 | |
79 // CrashPad has some fairly unreasonable checking on the minidump header and | |
80 // directory. Match with those checks for now to allow Crashpad to read the | |
81 // CrashpadInfo and upload these dumps. | |
82 | |
83 // Start by removing any unused directory entries. | |
84 // TODO(siggi): Fix Crashpad to ignore unused streams. | |
85 directory_.erase(std::remove_if(directory_.begin(), directory_.end(), | |
86 [](const MINIDUMP_DIRECTORY& entry) { | |
87 return entry.StreamType == UnusedStream; | |
88 })); | |
89 | |
90 // Update the header. | |
91 // TODO(siggi): Fix Crashpad's version checking. | |
92 header.Version = MINIDUMP_VERSION; | |
93 header.NumberOfStreams = base::saturated_cast<ULONG32>(directory_.size()); | |
94 | |
95 // Write back the potentially shortened and packed dictionary. | |
96 int bytes_to_write = header.NumberOfStreams * sizeof(directory_[0]); | |
97 int bytes_written = | |
98 file->Write(header.StreamDirectoryRva, | |
99 reinterpret_cast<char*>(&directory_.at(0)), bytes_to_write); | |
100 if (bytes_written != bytes_to_write) | |
101 return false; | |
102 | |
103 // Write back the header. | |
104 bytes_written = | |
105 file->Write(0, reinterpret_cast<char*>(&header), sizeof(header)); | |
106 if (bytes_written != sizeof(header)) | |
107 return false; | |
108 | |
109 // Success, stash the file. | |
110 file_ = file; | |
111 | |
112 return true; | |
113 } | |
114 | |
115 bool MinidumpUpdater::AppendSimpleDictionary( | |
116 const StringStringMap& crash_keys) { | |
117 DCHECK(file_); | |
118 | |
119 // Start by finding the Crashpad directory entry and reading the CrashpadInfo. | |
120 FilePosition crashpad_info_pos = 0; | |
121 crashpad::MinidumpCrashpadInfo crashpad_info; | |
122 for (const auto& entry : directory_) { | |
123 if (entry.StreamType != crashpad::kMinidumpStreamTypeCrashpadInfo) | |
124 continue; | |
125 | |
126 // This file is freshly written, so it must contain the same version | |
127 // CrashpadInfo structure this code compiled against. | |
128 if (entry.Location.DataSize != sizeof(crashpad_info)) | |
129 return false; | |
130 | |
131 crashpad_info_pos = entry.Location.Rva; | |
132 break; | |
133 } | |
134 | |
135 // No CrashpadInfo directory entry found. | |
136 if (crashpad_info_pos == 0) | |
137 return false; | |
138 | |
139 int bytes_read = | |
140 file_->Read(crashpad_info_pos, reinterpret_cast<char*>(&crashpad_info), | |
141 sizeof(crashpad_info)); | |
142 if (bytes_read != sizeof(crashpad_info)) | |
143 return false; | |
144 | |
145 if (crashpad_info.version != crashpad::MinidumpCrashpadInfo::kVersion) | |
146 return false; | |
147 | |
148 // Seek to the tail of the file, where we're going to extend it. | |
149 FilePosition next_available_byte = file_->Seek(base::File::FROM_END, 0); | |
150 if (next_available_byte == -1) | |
151 return false; | |
152 | |
153 // Write the key/value pairs and collect their locations. | |
154 std::vector<crashpad::MinidumpSimpleStringDictionaryEntry> entries; | |
155 for (const auto& kv : crash_keys) { | |
156 crashpad::MinidumpSimpleStringDictionaryEntry entry = {0}; | |
157 | |
158 entry.key = next_available_byte; | |
159 uint32_t key_len = base::saturated_cast<uint32_t>(kv.first.size()); | |
160 if (!WriteAndAdvance(&key_len, sizeof(key_len), &next_available_byte) || | |
161 !WriteAndAdvance(&kv.first.at(0), key_len, &next_available_byte)) { | |
162 return false; | |
163 } | |
164 | |
165 entry.value = next_available_byte; | |
166 uint32_t value_len = base::saturated_cast<uint32_t>(kv.second.size()); | |
167 if (!WriteAndAdvance(&value_len, sizeof(value_len), &next_available_byte) || | |
168 !WriteAndAdvance(&kv.second.at(0), value_len, &next_available_byte)) { | |
169 return false; | |
170 } | |
171 | |
172 entries.push_back(entry); | |
173 } | |
174 | |
175 // Write the dictionary array itself - note the array is count-prefixed. | |
176 FilePosition dict_pos = next_available_byte; | |
177 uint32_t entry_count = base::saturated_cast<uint32_t>(entries.size()); | |
178 if (!WriteAndAdvance(&entry_count, sizeof(entry_count), | |
179 &next_available_byte) || | |
180 !WriteAndAdvance(&entries.at(0), entry_count * sizeof(entries[0]), | |
181 &next_available_byte)) { | |
182 return false; | |
183 } | |
184 | |
185 // Touch up the CrashpadInfo and write it back to the file. | |
186 crashpad_info.simple_annotations.DataSize = next_available_byte - dict_pos; | |
187 crashpad_info.simple_annotations.Rva = dict_pos; | |
188 | |
189 int bytes_written = file_->Write( | |
190 crashpad_info_pos, reinterpret_cast<const char*>(&crashpad_info), | |
191 sizeof(crashpad_info)); | |
192 if (bytes_written != sizeof(crashpad_info)) | |
193 return false; | |
194 | |
195 return true; | |
196 } | |
197 | |
198 bool MinidumpUpdater::WriteData(const void* data, size_t data_len) { | |
199 DCHECK(file_); | |
200 DCHECK(data); | |
201 DCHECK_NE(0U, data_len); | |
202 | |
203 if (data_len > INT_MAX) | |
204 return false; | |
205 | |
206 int bytes_to_write = static_cast<int>(data_len); | |
207 int written_bytes = file_->WriteAtCurrentPos( | |
208 reinterpret_cast<const char*>(data), bytes_to_write); | |
209 if (written_bytes == -1) | |
210 return false; | |
211 | |
212 return true; | |
213 } | |
214 | |
215 bool MinidumpUpdater::WriteAndAdvance(const void* data, | |
216 size_t data_len, | |
217 FilePosition* position) { | |
218 DCHECK(position); | |
219 DCHECK_EQ(file_->Seek(base::File::FROM_CURRENT, 0), *position); | |
220 | |
221 if (!WriteData(data, data_len)) | |
222 return false; | |
223 | |
224 *position += base::saturated_cast<FilePosition>(data_len); | |
225 return true; | |
226 } | |
227 | |
228 // Writes a minidump file to for |process| to |dump_file| with embedded | |
229 // CrashpadInfo, containing |crash_keys|, |client_id| and |report_id|. | |
230 // The |dump_file| must be open for read as well as write. | |
231 bool MiniDumpWriteDumpWithCrashpadInfo(const base::Process& process, | |
232 uint32_t minidump_type, | |
233 MINIDUMP_EXCEPTION_INFORMATION* exc_info, | |
234 const StringStringMap& crash_keys, | |
235 const crashpad::UUID& client_id, | |
236 const crashpad::UUID& report_id, | |
237 base::File* dump_file) { | |
238 DCHECK(process.IsValid()); | |
239 DCHECK(exc_info); | |
240 DCHECK(dump_file && dump_file->IsValid()); | |
241 | |
242 // The CrashpadInfo structure and its associated directory entry are injected | |
243 // into the minidump, to minimize the work to patching up the dump. | |
244 crashpad::MinidumpCrashpadInfo crashpad_info; | |
245 crashpad_info.version = crashpad::MinidumpCrashpadInfo::kVersion; | |
246 crashpad_info.client_id = client_id; | |
247 crashpad_info.report_id = report_id; | |
248 | |
249 MINIDUMP_USER_STREAM crashpad_info_stream = { | |
250 crashpad::kMinidumpStreamTypeCrashpadInfo, // Type | |
251 sizeof(crashpad_info), // BufferSize | |
252 &crashpad_info // Buffer | |
253 }; | |
254 MINIDUMP_USER_STREAM_INFORMATION user_stream_info = { | |
255 1, // UserStreamCount | |
256 &crashpad_info_stream // UserStreamArray | |
257 }; | |
258 | |
259 // Write the minidump to the provided dump file. | |
260 if (!MiniDumpWriteDump( | |
261 process.Handle(), // Process handle. | |
262 process.Pid(), // Process Id. | |
263 dump_file->GetPlatformFile(), // File handle. | |
264 static_cast<MINIDUMP_TYPE>(minidump_type), // Minidump type. | |
265 exc_info, // Exception Param | |
266 &user_stream_info, // UserStreamParam, | |
267 nullptr)) { // CallbackParam | |
268 return false; | |
269 } | |
270 | |
271 // Retouch the minidump to make it Crashpad compatible. | |
272 MinidumpUpdater updater; | |
273 if (!updater.Initialize(dump_file)) | |
274 return false; | |
275 if (!updater.AppendSimpleDictionary(crash_keys)) | |
276 return false; | |
277 | |
278 return true; | |
279 } | |
280 | |
281 // Appends the full contents of |source| to |dest| at te. | |
282 bool AppendFileContents(base::File* source, base::PlatformFile dest) { | |
283 DCHECK(source && source->IsValid()); | |
284 DCHECK_NE(base::kInvalidPlatformFile, dest); | |
285 | |
286 // Rewind the source | |
287 if (source->Seek(base::File::FROM_BEGIN, 0) == -1) | |
288 return false; | |
289 | |
290 std::vector<char> buf; | |
291 buf.resize(1024); | |
292 while (true) { | |
293 int bytes_read = | |
294 source->ReadAtCurrentPos(&buf.at(0), static_cast<int>(buf.size())); | |
295 if (bytes_read == -1) | |
296 return false; | |
297 if (bytes_read == 0) | |
298 break; | |
299 | |
300 DWORD bytes_written = 0; | |
301 // Due to handle instrumentation, the destination can't be wrapped in | |
302 // a base::File, so we go basic Win32 API here. | |
303 if (!WriteFile(dest, &buf.at(0), bytes_read, &bytes_written, nullptr) || | |
304 static_cast<int>(bytes_written) != bytes_read) { | |
305 return false; | |
306 } | |
307 } | |
308 | |
309 return true; | |
310 } | |
311 | |
312 } // namespace | |
313 | |
314 FallbackCrashHandler::FallbackCrashHandler() | |
315 : thread_id_(base::kInvalidThreadId), exc_ptrs_(nullptr) {} | |
316 | |
317 FallbackCrashHandler::~FallbackCrashHandler() {} | |
318 | |
319 bool FallbackCrashHandler::ParseCommandLine(base::CommandLine* cmd_line) { | |
320 // Retrieve the handle to the process to dump. | |
321 unsigned uint_process = 0; | |
322 if (!base::StringToUint(cmd_line->GetSwitchValueASCII("process"), | |
323 &uint_process)) { | |
324 return false; | |
325 } | |
326 | |
327 // Before taking ownership of the supposed handle, see whether it's really | |
328 // a process handle. | |
329 base::ProcessHandle process_handle = base::win::Uint32ToHandle(uint_process); | |
330 if (base::GetProcId(process_handle) == base::kNullProcessId) | |
331 return false; | |
332 | |
333 // Retrieve the thread id argument. | |
334 unsigned thread_id = 0; | |
335 if (!base::StringToUint(cmd_line->GetSwitchValueASCII("thread"), | |
336 &thread_id)) { | |
337 return false; | |
338 } | |
339 | |
340 // Retrieve the "exception-pointers" argument. | |
341 uint64_t uint_exc_ptrs = 0; | |
342 if (!base::StringToUint64(cmd_line->GetSwitchValueASCII("exception-pointers"), | |
343 &uint_exc_ptrs)) { | |
344 return false; | |
345 } | |
346 exc_ptrs_ = reinterpret_cast<EXCEPTION_POINTERS*>( | |
347 static_cast<uintptr_t>(uint_exc_ptrs)); | |
348 | |
349 // Retrieve the "database" argument. | |
350 database_dir_ = cmd_line->GetSwitchValuePath("database"); | |
351 if (database_dir_.empty()) | |
352 return false; | |
353 | |
354 // Everything checks out, take ownership of the process handle. | |
355 process_ = base::Process(process_handle); | |
356 | |
357 return true; | |
358 } | |
359 | |
360 bool FallbackCrashHandler::GenerateCrashDump() { | |
361 std::unique_ptr<crashpad::CrashReportDatabase> database = | |
362 crashpad::CrashReportDatabase::InitializeWithoutCreating(database_dir_); | |
363 | |
364 if (!database) | |
365 return false; | |
366 | |
367 crashpad::CrashReportDatabase::NewReport* report = nullptr; | |
368 crashpad::CrashReportDatabase::OperationStatus status = | |
369 database->PrepareNewCrashReport(&report); | |
370 if (status != crashpad::CrashReportDatabase::kNoError) | |
371 return false; | |
372 | |
373 // Make sure we release the report on early exit. | |
374 crashpad::CrashReportDatabase::CallErrorWritingCrashReport on_error( | |
375 database.get(), report); | |
376 | |
377 // TODO(siggi): Go big on the detail here for Canary/Dev channels. | |
378 uint32_t minidump_type = MiniDumpWithUnloadedModules | | |
379 MiniDumpWithProcessThreadData | | |
380 MiniDumpWithThreadInfo; | |
381 | |
382 MINIDUMP_EXCEPTION_INFORMATION exc_info = {}; | |
383 exc_info.ThreadId = thread_id_; | |
384 exc_info.ExceptionPointers = exc_ptrs_; | |
385 exc_info.ClientPointers = TRUE; // ExceptionPointers in client. | |
386 | |
387 // Write mandatory crash keys. These will be read by crashpad and used as | |
388 // http request parameters for the upload. Keys and values should match | |
389 // server side configuration. | |
390 // TODO(siggi): Grab these parameters from chrome_elf. | |
391 // DO NOT SUBMIT | |
392 std::map<std::string, std::string> crash_keys = { | |
393 {"prod", "minidump_info.product_name"}, | |
394 {"ver", "minidump_info.version_number"}, | |
395 {"channel", "minidump_info.channel_name"}, | |
396 {"plat", "minidump_info.platform"}, | |
397 {"ptype", "crashpad_handler"}}; | |
398 | |
399 crashpad::UUID client_id; | |
400 crashpad::Settings* settings = database->GetSettings(); | |
401 if (settings) { | |
402 // If GetSettings() or GetClientID() fails client_id will be left at its | |
403 // default value, all zeroes, which is appropriate. | |
404 settings->GetClientID(&client_id); | |
405 } | |
406 | |
407 base::FilePath dump_file_path; | |
408 if (!base::CreateTemporaryFile(&dump_file_path)) | |
409 return false; | |
410 | |
411 // Open the file with delete on close, to try and ensure it's cleaned up on | |
412 // any kind of failure. | |
413 base::File dump_file(dump_file_path, base::File::FLAG_OPEN | | |
414 base::File::FLAG_READ | | |
415 base::File::FLAG_WRITE | | |
416 base::File::FLAG_DELETE_ON_CLOSE); | |
417 if (!dump_file.IsValid()) | |
418 return false; | |
419 | |
420 // Write the minidump to the temp file, and then copy the data to the | |
421 // Crashpad-provided handle, as the latter is only open for write. | |
422 if (!MiniDumpWriteDumpWithCrashpadInfo(process_, minidump_type, &exc_info, | |
423 crash_keys, client_id, report->uuid, | |
424 &dump_file) || | |
425 !AppendFileContents(&dump_file, report->handle)) { | |
426 return false; | |
427 } | |
428 | |
429 on_error.Disarm(); | |
430 | |
431 crashpad::UUID report_id = {}; | |
432 status = database->FinishedWritingCrashReport(report, &report_id); | |
433 if (status != crashpad::CrashReportDatabase::kNoError) | |
434 return false; | |
435 | |
436 return true; | |
437 } | |
438 | |
439 } // namespace crash_reporter | |
OLD | NEW |