Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(25)

Side by Side Diff: components/crash/content/app/fallback_crash_handler_win.cc

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

Powered by Google App Engine
This is Rietveld 408576698