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

Side by Side Diff: client/crash_report_database_win.cc

Issue 867363003: win: Implementation of CrashReportDatabase for Windows (Closed) Base URL: https://chromium.googlesource.com/crashpad/crashpad@master
Patch Set: validation on strings Created 5 years, 10 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
« no previous file with comments | « client/crash_report_database_test.cc ('k') | util/misc/uuid.h » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
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 "client/crash_report_database.h"
16
17 #include <rpc.h>
18 #include <time.h>
19 #include <windows.h>
20
21 #include <limits>
22
23 #include "base/files/file_path.h"
Mark Mentovai 2015/02/06 21:13:23 Since crash_report_database.h is the top #include
scottmg 2015/02/06 22:58:18 Done.
24 #include "base/logging.h"
25 #include "base/memory/scoped_ptr.h"
26 #include "base/numerics/safe_math.h"
27 #include "base/strings/stringprintf.h"
28 #include "base/strings/utf_string_conversions.h"
29 #include "util/misc/uuid.h"
30
31 namespace crashpad {
32
33 namespace {
34
35 const wchar_t kDatabaseDirectoryName[] = L"Crashpad";
36
37 const wchar_t kReportsDirectory[] = L"reports";
38 const wchar_t kMetadataFileName[] = L"metadata";
39 const wchar_t kMetadataTempFileName[] = L"metadata.tmp";
40 const wchar_t kMetadataMutexName[] = L"crashpad.metadata.lock";
41
42 const wchar_t kCrashReportFileExtension[] = L"dmp";
43
44 enum class ReportState : int {
45 //! \brief Just created, owned by caller and being written.
46 kNew,
47 //! \brief Fully filled out, owned by database.
48 kPending,
49 //! \brief In the process of uploading, owned by caller.
50 kUploading,
51 //! \brief Upload completed or skipped, owned by database.
52 kCompleted,
53
54 //! \brief Used during query to indicate a report in any state is acceptable.
55 //! Not a valid state for a report to be in.
56 kAny,
57 };
58
59 using OperationStatus = CrashReportDatabase::OperationStatus;
60
61 //! \brief Ensures that the node at path is a directory, and creates it if it
62 //! does not exist.
63 //!
64 //! \return If the path points to a file, rather than a directory, or the
65 //! directory could not be created, returns false. Otherwise, returns true,
66 //! indicating that path already was or now is a directory.
67 bool CreateOrEnsureDirectoryExists(const base::FilePath& path) {
68 if (CreateDirectory(path.value().c_str(), nullptr)) {
69 return true;
70 } else if (GetLastError() == ERROR_ALREADY_EXISTS) {
71 DWORD fileattr = GetFileAttributes(path.value().c_str());
72 if (fileattr == INVALID_FILE_ATTRIBUTES) {
73 PLOG(ERROR) << "GetFileAttributes";
74 return false;
75 }
76 if ((fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0)
77 return true;
78 LOG(ERROR) << "not a directory";
79 return false;
80 } else {
81 PLOG(ERROR) << "CreateDirectory";
82 return false;
83 }
84 }
85
86 //! \brief A private extension of the Report class that includes additional data
87 //! that's stored on disk in the metadata file.
88 struct ReportDisk : public CrashReportDatabase::Report {
89 //! \brief The current state of the report.
90 ReportState state;
91 };
92
93 //! \brief A private extension of the NewReport class to hold the UUID during
94 //! initial write. We don't store metadata in dump's file attributes, and
95 //! use the UUID to identify the dump on write completion.
96 struct NewReportDisk : public CrashReportDatabase::NewReport {
97 //! \brief The UUID for this crash report.
98 UUID uuid;
99 };
100
101 //! \brief Manages the metadata for the set of reports, handling serialization
102 //! to disk, and queries. Instances of this class should be created by using
103 //! CrashReportDatabaseWin::AcquireMetadata(), rather than direct
104 //! instantiation.
105 class Metadata {
106 public:
107 //! \param[in] base_dir Root of storage for data files.
108 //! \param[in] mutex_to_release An acquired mutex guarding access to the
109 //! metadata file. The lock is owned by this object and will be released
110 //! on destruction. The lifetime of the HANDLE is not owned.
111 Metadata(const base::FilePath& base_dir, HANDLE mutex_to_release);
112 ~Metadata();
113
114 //! \brief Reads the database from disk. May only be called once without an
115 //! interceding call to Write().
116 //!
117 //! \return true on success. If unsuccessful, the object is not in a usable
118 //! state.
119 bool Read();
120
121 //! \brief Flushes the database back to disk. It is not necessary to call this
122 //! method if the reports were not mutated, however, Read() may not be
123 //! called again until Write() is used.
124 //!
125 //! \return true on success.
126 bool Write();
127
128 //! \brief Adds a new report to the set. Write() must be called to persist
129 //! after adding new records.
Mark Mentovai 2015/02/06 21:13:23 Does Read() need to have been called first? If so,
scottmg 2015/02/06 22:58:17 Done with DCHECKs.
130 void AddNewRecord(const NewReportDisk& new_report);
131
132 //! \brief Finds all reports in a given state. The reports vector is only
Mark Mentovai 2015/02/06 21:13:23 “The \a reports vector”
scottmg 2015/02/06 22:58:18 Done.
133 //! valid when #kNoError is returned.
Mark Mentovai 2015/02/06 21:13:23 \param[out] reports should mention that reports mu
scottmg 2015/02/06 22:58:18 Done.
134 OperationStatus FindReports(
135 ReportState desired_state,
136 std::vector<const CrashReportDatabase::Report>* reports);
137
138 //! \brief Finds the report matching the given UUID and the desired state,
Mark Mentovai 2015/02/06 21:13:23 This isn’t exactly brief, and the first sentence i
scottmg 2015/02/06 22:58:18 Done.
139 //! returns a mutable pointer to it. Only valid if
140 //! CrashReportDatabase::kNoError is returned. If the report is mutated by
141 //! the caller, the caller is also responsible for calling Write() before
142 //! destruction to persist the changes.
143 //!
144 //! \param[in] uuid The report identifier.
145 //! \param[in] desired_state A specific state that the given report must be
146 //! in. If the report is located, but is in a different state,
147 //! CrashReportDatabase::kBusyError will be returned. If no filtering by
148 //! state is required, ReportState::kAny can be used.
149 //! \param[out] report_disk The found report, valid only if
150 //! CrashReportDatabase::kNoError is returned. Ownership is not
151 //! transferred to the caller.
152 OperationStatus FindSingleReport(const UUID& uuid,
153 ReportState desired_state,
154 ReportDisk** report_disk);
155
156 //! \brief Removes a single report identified by UUID. This removes both the
157 //! entry in the metadata database, as well as the on-disk report, if any.
158 //! Write() must be called to persist when CrashReportDatabase::kNoError
159 //! is returned.
160 //!
161 //! \param[in] uuid The report identifier.
162 OperationStatus RemoveByUUID(const UUID& uuid);
163
164 private:
165 //! \brief Confirms that the corresponding report actually exists on disk
166 //! (that is, the dump file has not been removed), and if desired_state
167 //! is not ReportState::kAny, confirms that the report is in the given
168 //! state.
169 static OperationStatus VerifyReport(const ReportDisk& report_win,
170 ReportState desired_state);
171
172 base::FilePath base_dir_;
173 bool loaded_;
174 HANDLE mutex_;
175 std::vector<ReportDisk> reports_;
176 };
177
178 Metadata::Metadata(const base::FilePath& base_dir, HANDLE mutex_to_release)
179 : base_dir_(base_dir),
180 loaded_(false),
181 mutex_(mutex_to_release),
182 reports_() {
183 }
184
185 Metadata::~Metadata() {
186 ReleaseMutex(mutex_);
187 }
188
189 // The format of the metadata file is a MetadataFileHeader, followed by a
190 // number of fixed size records of MetadataFileReportRecord, followed by a
191 // string table in UTF8 format, where each string is \0 terminated.
192
193 #pragma pack(push, 1)
194
195 struct MetadataFileHeader {
196 uint32_t magic;
197 uint32_t version;
198 uint32_t remaining_file_size;
Mark Mentovai 2015/02/06 21:13:23 Remaining after this field or this structure? (It’
scottmg 2015/02/06 22:58:18 Removed.
199 uint32_t num_records;
200 };
201
202 struct MetadataFileReportRecord {
203 UUID uuid; // UUID is a 16 byte, standard layout structure.
204 uint32_t file_path_index;
Mark Mentovai 2015/02/06 21:13:23 Are these byte indices into the file, or indices i
scottmg 2015/02/06 22:58:18 The format of file paths depends on how the CrashR
Mark Mentovai 2015/02/06 23:29:52 scottmg wrote:
scottmg 2015/02/07 01:21:58 OK. I've added a (failing) test, but haven't yet m
205 uint32_t id_index;
206 int64_t creation_time;
Mark Mentovai 2015/02/06 21:13:23 time_t epoch or something else? Same on line 208.
scottmg 2015/02/06 22:58:17 Done.
207 uint8_t uploaded;
Mark Mentovai 2015/02/06 21:13:24 0 or 1, or other values?
scottmg 2015/02/06 22:58:18 Done.
208 int64_t last_upload_attempt_time;
Mark Mentovai 2015/02/06 21:13:23 I know you’re pack(1), but let’s try to keep thing
scottmg 2015/02/06 22:58:17 Done.
209 int32_t upload_attempts;
210 int32_t state;
Mark Mentovai 2015/02/06 21:13:22 Reference ReportState if that’s what this means.
scottmg 2015/02/06 22:58:18 Done.
211 };
212
213 const uint32_t kMetadataFileHeaderMagic = 'CPAD';
214 const uint32_t kMetadataFileVersion = 1;
215
216 #pragma pack(pop)
217
218 uint32_t AddStringToTable(std::string* string_table, const std::string& str) {
219 uint32_t offset = base::checked_cast<uint32_t>(string_table->size());
220 *string_table += str;
221 *string_table += '\0';
222 return offset;
223 }
224
225 uint32_t AddStringToTable(std::string* string_table, const std::wstring& str) {
226 return AddStringToTable(string_table, base::UTF16ToUTF8(str));
227 }
228
229 bool Metadata::Read() {
230 DCHECK(!loaded_);
231 base::FilePath path = base_dir_.Append(kMetadataFileName);
232 auto input_file = ScopedFileHandle(LoggingOpenFileForRead(path));
233 // The file not existing is OK, we may not have created it yet.
234 if (input_file.get() == INVALID_HANDLE_VALUE) {
235 loaded_ = true;
236 return true;
237 }
238
239 MetadataFileHeader header;
240 if (!LoggingReadFile(input_file.get(), &header, sizeof(header)))
241 return false;
242 if (header.magic != kMetadataFileHeaderMagic ||
243 header.version != kMetadataFileVersion) {
244 return false;
Mark Mentovai 2015/02/06 21:13:23 I wonder about these “return false”s. If the metad
scottmg 2015/02/06 22:58:17 There's no recovery strategy. Any existing crash r
Mark Mentovai 2015/02/06 23:29:52 scottmg wrote:
scottmg 2015/02/07 01:21:57 Done.
245 }
246 scoped_ptr<uint8_t> buffer(new uint8_t[header.remaining_file_size]);
Mark Mentovai 2015/02/06 21:13:23 This needs to be scoped_ptr<uint8_t[]> because it’
scottmg 2015/02/06 22:58:17 Done.
247 if (!LoggingReadFile(
248 input_file.get(), buffer.get(), header.remaining_file_size)) {
249 return false;
250 }
251
252 auto records_size = base::CheckedNumeric<uint32_t>(header.num_records) *
253 sizeof(MetadataFileReportRecord);
254 if (!records_size.IsValid())
255 return false;
256
257 // Each record will have two NUL-terminated strings in the table.
Mark Mentovai 2015/02/06 21:13:23 They might be pooled, though. Maybe this writer do
scottmg 2015/02/06 22:58:18 True, removed.
Robert Sesek 2015/02/10 20:32:25 Even if the strings are pooled, though, the table
scottmg 2015/02/10 20:58:45 Done.
258 auto min_string_table_size =
259 base::CheckedNumeric<uint32_t>(header.num_records) * 2;
260 auto min_file_size = records_size + min_string_table_size;
261 if (!min_file_size.IsValid())
262 return false;
263
264 if (min_file_size.ValueOrDie() > header.remaining_file_size)
265 return false;
266
267 const char* string_table =
268 reinterpret_cast<const char*>(buffer.get() + records_size.ValueOrDie());
269 // Ensure the string table is \0 terminated.
270 if (buffer.get()[header.remaining_file_size - 1] != 0)
271 return false;
272
273 for (uint32_t i = 0; i < header.num_records; ++i) {
274 ReportDisk r;
275 const MetadataFileReportRecord* record =
Mark Mentovai 2015/02/06 21:13:23 Maybe it would have been better to have allocated
scottmg 2015/02/06 22:58:18 Sure. Done.
276 reinterpret_cast<const MetadataFileReportRecord*>(
277 buffer.get() + i * sizeof(MetadataFileReportRecord));
278 r.uuid = record->uuid;
279 size_t last_valid_index =
280 header.remaining_file_size - records_size.ValueOrDie() - 1;
281 if (record->file_path_index > last_valid_index ||
282 record->id_index > last_valid_index) {
283 return false;
284 }
285 r.file_path = base::FilePath(
286 base::UTF8ToUTF16(&string_table[record->file_path_index]));
287 r.id = &string_table[record->id_index];
288 r.creation_time = record->creation_time;
289 r.uploaded = record->uploaded;
290 r.last_upload_attempt_time = record->last_upload_attempt_time;
291 r.upload_attempts = record->upload_attempts;
292 r.state = static_cast<ReportState>(record->state);
293 reports_.push_back(r);
294 }
295 loaded_ = true;
296 return true;
297 }
298
299 bool Metadata::Write() {
300 DCHECK(loaded_);
301 base::FilePath path = base_dir_.Append(kMetadataTempFileName);
302
303 // Write data to a temporary file.
304 {
305 auto output_file = ScopedFileHandle(LoggingOpenFileForWrite(
306 path, FileWriteMode::kTruncateOrCreate, FilePermissions::kOwnerOnly));
307
308 // Build the records and string table we're going to write.
309 size_t num_records = reports_.size();
310 std::string string_table;
311 scoped_ptr<MetadataFileReportRecord[]> records(
312 new MetadataFileReportRecord[num_records]);
313 for (size_t i = 0; i < num_records; ++i) {
314 const ReportDisk& report = reports_[i];
315 MetadataFileReportRecord& record = records[i];
316 record.uuid = report.uuid;
317 record.file_path_index =
318 AddStringToTable(&string_table, report.file_path.value());
319 record.id_index = AddStringToTable(&string_table, report.id);
320 record.creation_time = report.creation_time;
321 record.uploaded = report.uploaded;
322 record.last_upload_attempt_time = report.last_upload_attempt_time;
323 record.upload_attempts = report.upload_attempts;
324 record.state = static_cast<uint32_t>(report.state);
325 }
326
327 // Now we have the size of the file, fill out the header.
328 MetadataFileHeader header;
329 header.magic = kMetadataFileHeaderMagic;
330 header.version = kMetadataFileVersion;
331 auto file_size = base::CheckedNumeric<uint32_t>(num_records) *
332 sizeof(MetadataFileReportRecord) +
333 string_table.size();
334 if (!file_size.IsValid())
335 return false;
336 header.remaining_file_size = file_size.ValueOrDie();
337 header.num_records = base::checked_cast<uint32_t>(num_records);
338
339 if (!LoggingWriteFile(output_file.get(), &header, sizeof(header)))
340 return false;
341 if (!LoggingWriteFile(output_file.get(),
342 records.get(),
343 num_records * sizeof(MetadataFileReportRecord))) {
344 return false;
345 }
346 if (!LoggingWriteFile(
347 output_file.get(), string_table.c_str(), string_table.size())) {
348 return false;
349 }
350 }
351
352 // While this is not guaranteed to be atomic, it is in practical cases. We
353 // aren't racing ourself here as we're holding the mutex here, we use
354 // MoveFileEx only to avoid corrupting data in case of failure during write.
355 bool result = MoveFileEx(path.value().c_str(),
356 base_dir_.Append(kMetadataFileName).value().c_str(),
357 MOVEFILE_REPLACE_EXISTING);
Mark Mentovai 2015/02/06 21:13:23 Because you’ve documented it to be safe to call Me
scottmg 2015/02/06 22:58:18 Oops, good point. Done. I don't like the interfac
358 loaded_ = !result;
359 return result;
360 }
361
362 void Metadata::AddNewRecord(const NewReportDisk& new_report) {
363 ReportDisk report;
364 report.uuid = new_report.uuid;
365 report.file_path = new_report.path;
366 report.state = ReportState::kNew;
367 reports_.push_back(report);
368 }
369
370 OperationStatus Metadata::FindReports(
371 ReportState desired_state,
372 std::vector<const CrashReportDatabase::Report>* reports) {
373 DCHECK(reports->empty());
374 for (const auto& report : reports_) {
375 if (report.state == desired_state) {
376 if (VerifyReport(report, desired_state) != CrashReportDatabase::kNoError)
377 continue;
378 reports->push_back(report);
379 }
380 }
381 return CrashReportDatabase::kNoError;
382 }
383
384 OperationStatus Metadata::FindSingleReport(const UUID& uuid,
385 ReportState desired_state,
386 ReportDisk** out_report) {
387 for (size_t i = 0; i < reports_.size(); ++i) {
388 if (reports_[i].uuid == uuid) {
389 OperationStatus os = VerifyReport(reports_[i], desired_state);
390 if (os != CrashReportDatabase::kNoError)
391 return os;
392 *out_report = &reports_[i];
393 return CrashReportDatabase::kNoError;
394 }
395 }
396 return CrashReportDatabase::kReportNotFound;
397 }
398
399 OperationStatus Metadata::RemoveByUUID(const UUID& uuid) {
400 for (size_t i = 0; i < reports_.size(); ++i) {
401 if (reports_[i].uuid == uuid) {
402 if (!DeleteFile(reports_[i].file_path.value().c_str())) {
403 PLOG(ERROR) << "DeleteFile " << reports_[i].file_path.value().c_str();
404 return CrashReportDatabase::kFileSystemError;
405 }
406 reports_.erase(reports_.begin() + i);
407 return CrashReportDatabase::kNoError;
408 }
409 }
410 return CrashReportDatabase::kReportNotFound;
411 }
412
413 // static
414 OperationStatus Metadata::VerifyReport(const ReportDisk& report_win,
Mark Mentovai 2015/02/06 21:13:23 Name this report_disk to match the type.
scottmg 2015/02/06 22:58:18 Done.
415 ReportState desired_state) {
416 if (desired_state != ReportState::kAny && report_win.state != desired_state)
417 return CrashReportDatabase::kBusyError;
418 if (GetFileAttributes(report_win.file_path.value().c_str()) ==
Mark Mentovai 2015/02/06 21:13:23 Since you’re already getting the attributes anyway
scottmg 2015/02/06 22:58:18 Done.
419 INVALID_FILE_ATTRIBUTES) {
420 return CrashReportDatabase::kReportNotFound;
421 }
422 return CrashReportDatabase::kNoError;
423 }
424
425 class CrashReportDatabaseWin : public CrashReportDatabase {
426 public:
427 explicit CrashReportDatabaseWin(const base::FilePath& path);
428 ~CrashReportDatabaseWin() override;
429
430 bool Initialize();
431
432 // CrashReportDatabase::
433 OperationStatus PrepareNewCrashReport(NewReport** report) override;
434 OperationStatus FinishedWritingCrashReport(NewReport* report,
435 UUID* uuid) override;
436 OperationStatus ErrorWritingCrashReport(NewReport* report) override;
437 OperationStatus LookUpCrashReport(const UUID& uuid, Report* report) override;
438 OperationStatus GetPendingReports(
439 std::vector<const Report>* reports) override;
440 OperationStatus GetCompletedReports(
441 std::vector<const Report>* reports) override;
442 OperationStatus GetReportForUploading(const UUID& uuid,
443 const Report** report) override;
444 OperationStatus RecordUploadAttempt(const Report* report,
445 bool successful,
446 const std::string& id) override;
447 OperationStatus SkipReportUpload(const UUID& uuid) override;
448
449 private:
450 scoped_ptr<Metadata> AcquireMetadata();
451
452 base::FilePath base_dir_;
453 ScopedKernelHANDLE mutex_;
454
455 DISALLOW_COPY_AND_ASSIGN(CrashReportDatabaseWin);
456 };
457
458 CrashReportDatabaseWin::CrashReportDatabaseWin(const base::FilePath& path)
459 : CrashReportDatabase(), base_dir_(path), mutex_() {
460 }
461
462 CrashReportDatabaseWin::~CrashReportDatabaseWin() {
463 }
464
465 bool CrashReportDatabaseWin::Initialize() {
466 // Check if the database already exists.
467 if (!CreateOrEnsureDirectoryExists(base_dir_))
468 return false;
469
470 // Create our reports subdirectory.
471 if (!CreateOrEnsureDirectoryExists(base_dir_.Append(kReportsDirectory)))
472 return false;
473
474 mutex_.reset(CreateMutex(nullptr, false, kMetadataMutexName));
Mark Mentovai 2015/02/06 21:13:23 Is this one systemwide mutex for all Crashpad data
scottmg 2015/02/06 22:58:17 Yes, system-wide, so only one metadata file can be
Mark Mentovai 2015/02/06 23:29:52 scottmg wrote:
scottmg 2015/02/07 01:21:57 Done.
475
476 // TODO(scottmg): When are completed reports pruned from disk? Delete here or
477 // maybe on Read().
478
479 return true;
480 }
481
482 OperationStatus CrashReportDatabaseWin::PrepareNewCrashReport(
Mark Mentovai 2015/02/06 21:13:23 I would have preferred it if this stage of the gam
scottmg 2015/02/06 22:58:17 I didn't like the extra error handling cases for m
483 NewReport** out_report) {
484 scoped_ptr<Metadata> metadata(AcquireMetadata());
485 if (!metadata)
486 return kFileSystemError;
487
488 scoped_ptr<NewReportDisk> report(new NewReportDisk());
489
490 ::UUID system_uuid;
491 if (UuidCreate(&system_uuid) != RPC_S_OK) {
492 return kFileSystemError;
493 }
494 static_assert(sizeof(system_uuid) == 16, "unexpected system uuid size");
495 static_assert(offsetof(::UUID, Data1) == 0, "unexpected uuid layout");
496 UUID uuid(reinterpret_cast<const uint8_t*>(&system_uuid.Data1));
497
498 report->uuid = uuid;
499 report->path =
500 base_dir_.Append(kReportsDirectory)
501 .Append(uuid.ToWideString() + L"." + kCrashReportFileExtension);
502 report->handle = LoggingOpenFileForWrite(report->path,
503 FileWriteMode::kTruncateOrCreate,
Mark Mentovai 2015/02/06 21:13:23 Shouldn’t we trust the uuid’s uniqueness and use k
scottmg 2015/02/06 22:58:18 Done.
504 FilePermissions::kOwnerOnly);
505 if (report->handle == INVALID_HANDLE_VALUE)
506 return kFileSystemError;
507
508 metadata->AddNewRecord(*report);
509 if (!metadata->Write())
510 return kDatabaseError;
511 *out_report = report.release();
512 return kNoError;
513 }
514
515 OperationStatus CrashReportDatabaseWin::FinishedWritingCrashReport(
516 NewReport* report,
517 UUID* uuid) {
518 // Take ownership of the report, and cast to our private version with UUID.
519 scoped_ptr<NewReportDisk> scoped_report(static_cast<NewReportDisk*>(report));
Mark Mentovai 2015/02/06 21:13:22 Too bad we don’t have down_cast<>.
520 // Take ownership of the file handle.
521 ScopedFileHandle handle(report->handle);
522
523 scoped_ptr<Metadata> metadata(AcquireMetadata());
524 if (!metadata)
525 return kFileSystemError;
526
527 ReportDisk* report_disk;
528 OperationStatus os = metadata->FindSingleReport(
529 scoped_report->uuid, ReportState::kNew, &report_disk);
530 if (os != kNoError)
531 return os;
532 report_disk->state = ReportState::kPending;
533 report_disk->creation_time = time(nullptr);
534 if (!metadata->Write())
535 return kDatabaseError;
536 *uuid = report_disk->uuid;
537 return kNoError;
538 }
539
540 OperationStatus CrashReportDatabaseWin::ErrorWritingCrashReport(
541 NewReport* report) {
542 // Close the outstanding handle.
543 LoggingCloseFile(report->handle);
544
545 // Take ownership of the report, and cast to our private version with UUID.
546 scoped_ptr<NewReportDisk> scoped_report(static_cast<NewReportDisk*>(report));
547
548 // Remove the report from the metadata and disk.
549 scoped_ptr<Metadata> metadata(AcquireMetadata());
550 if (!metadata)
551 return kFileSystemError;
552 OperationStatus os = metadata->RemoveByUUID(scoped_report->uuid);
553 if (os != kNoError)
554 return os;
555 if (!metadata->Write())
556 return kDatabaseError;
557
558 return kNoError;
559 }
560
561 OperationStatus CrashReportDatabaseWin::LookUpCrashReport(const UUID& uuid,
562 Report* report) {
563 scoped_ptr<Metadata> metadata(AcquireMetadata());
564 if (!metadata)
565 return kFileSystemError;
566
567 ReportDisk* report_disk;
568 OperationStatus os =
569 metadata->FindSingleReport(uuid, ReportState::kAny, &report_disk);
570 if (os != kNoError)
571 return os;
572 *report = *report_disk;
573 return kNoError;
574 }
575
576 OperationStatus CrashReportDatabaseWin::GetPendingReports(
577 std::vector<const Report>* reports) {
578 scoped_ptr<Metadata> metadata(AcquireMetadata());
579 if (!metadata)
580 return kFileSystemError;
581 return metadata->FindReports(ReportState::kPending, reports);
582 }
583
584 OperationStatus CrashReportDatabaseWin::GetCompletedReports(
585 std::vector<const Report>* reports) {
586 scoped_ptr<Metadata> metadata(AcquireMetadata());
587 if (!metadata)
588 return kFileSystemError;
589 return metadata->FindReports(ReportState::kCompleted, reports);
590 }
591
592 OperationStatus CrashReportDatabaseWin::GetReportForUploading(
593 const UUID& uuid,
594 const Report** report) {
595 scoped_ptr<Metadata> metadata(AcquireMetadata());
596 if (!metadata)
597 return kFileSystemError;
598
599 ReportDisk* report_disk;
600 OperationStatus os =
601 metadata->FindSingleReport(uuid, ReportState::kPending, &report_disk);
602 if (os != kNoError)
603 return os;
604 report_disk->state = ReportState::kUploading;
605 // Create a copy for passing back to client. This will be freed in
606 // RecordUploadAttempt.
607 *report = new Report(*report_disk);
608 if (!metadata->Write())
609 return kDatabaseError;
610 return kNoError;
611 }
612
613 OperationStatus CrashReportDatabaseWin::RecordUploadAttempt(
614 const Report* report,
615 bool successful,
616 const std::string& id) {
617 // Take ownership, allocated in GetReportForUploading.
618 scoped_ptr<const Report> upload_report(report);
619
620 scoped_ptr<Metadata> metadata(AcquireMetadata());
621 if (!metadata)
622 return kFileSystemError;
623
624 ReportDisk* report_disk;
625 OperationStatus os = metadata->FindSingleReport(
626 report->uuid, ReportState::kUploading, &report_disk);
627 if (os != kNoError)
628 return os;
629 report_disk->uploaded = successful;
630 report_disk->id = id;
631 report_disk->last_upload_attempt_time = time(nullptr);
632 report_disk->upload_attempts++;
633 report_disk->state =
634 successful ? ReportState::kCompleted : ReportState::kPending;
635 if (!metadata->Write())
636 return kDatabaseError;
637 return kNoError;
638 }
639
640 OperationStatus CrashReportDatabaseWin::SkipReportUpload(const UUID& uuid) {
641 scoped_ptr<Metadata> metadata(AcquireMetadata());
642 if (!metadata)
643 return kFileSystemError;
644
645 ReportDisk* report_disk;
646 OperationStatus os =
647 metadata->FindSingleReport(uuid, ReportState::kPending, &report_disk);
648 if (os != kNoError)
649 return os;
650 report_disk->state = ReportState::kCompleted;
651 if (!metadata->Write())
652 return kDatabaseError;
653 return kNoError;
654 }
655
656 scoped_ptr<Metadata> CrashReportDatabaseWin::AcquireMetadata() {
657 if (WaitForSingleObject(mutex_.get(), INFINITE) != WAIT_OBJECT_0)
Mark Mentovai 2015/02/06 21:13:23 Is WAIT_ABANDONED OK too?
scottmg 2015/02/06 22:58:17 Could be. Because we're INFINITE it would mean tha
Mark Mentovai 2015/02/06 23:29:52 scottmg wrote:
scottmg 2015/02/07 01:21:58 Switched to LockFileEx. Now the only way we'll fai
658 return nullptr;
Mark Mentovai 2015/02/06 21:13:22 PLOG something?
scottmg 2015/02/06 22:58:17 Done.
659 scoped_ptr<Metadata> metadata(new Metadata(base_dir_, mutex_.get()));
660 if (!metadata->Read()) {
661 LOG(ERROR) << "metadata file could not be loaded";
662 return nullptr;
663 }
664 return metadata;
665 }
666
667 } // namespace
668
669 // static
670 scoped_ptr<CrashReportDatabase> CrashReportDatabase::Initialize(
671 const base::FilePath& path) {
672 scoped_ptr<CrashReportDatabaseWin> database_win(
673 new CrashReportDatabaseWin(path.Append(kDatabaseDirectoryName)));
Mark Mentovai 2015/02/06 21:13:23 I think this append is crazy, but it matches what
scottmg 2015/02/06 22:58:17 I don't understand what's crazy about the append.
Mark Mentovai 2015/02/06 23:29:52 scottmg wrote:
scottmg 2015/02/07 01:21:58 I see. Well, Metadata takes only the file handle n
674 if (!database_win->Initialize())
675 database_win.reset();
676
677 return scoped_ptr<CrashReportDatabase>(database_win.release());
678 }
679
680 } // namespace crashpad
OLDNEW
« no previous file with comments | « client/crash_report_database_test.cc ('k') | util/misc/uuid.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698