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

Side by Side Diff: client/crash_report_database_win.cc

Issue 913273002: win: Implementation of CrashReportDatabase for Windows (for C++ Windows readability review) (Closed) Base URL: https://chromium.googlesource.com/crashpad/crashpad@master
Patch Set: more fixes 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
1 // Copyright 2015 The Crashpad Authors. All rights reserved. 1 // Copyright 2015 The Crashpad Authors. All rights reserved.
2 // 2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); 3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with 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 5 // You may obtain a copy of the License at
6 // 6 //
7 // http://www.apache.org/licenses/LICENSE-2.0 7 // http://www.apache.org/licenses/LICENSE-2.0
8 // 8 //
9 // Unless required by applicable law or agreed to in writing, software 9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, 10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and 12 // See the License for the specific language governing permissions and
13 // limitations under the License. 13 // limitations under the License.
14 14
15 #include "client/crash_report_database.h" 15 #include "client/crash_report_database.h"
16 16
17 #include <rpc.h> 17 #include <rpc.h>
18 #include <string.h> 18 #include <string.h>
19 #include <time.h> 19 #include <time.h>
20 #include <windows.h> 20 #include <windows.h>
21 21
22 #include "base/logging.h" 22 #include "base/logging.h"
23 #include "base/numerics/safe_math.h" 23 #include "base/numerics/safe_math.h"
24 #include "base/strings/string16.h"
24 #include "base/strings/stringprintf.h" 25 #include "base/strings/stringprintf.h"
25 #include "base/strings/utf_string_conversions.h" 26 #include "base/strings/utf_string_conversions.h"
26 27
27 namespace crashpad { 28 namespace crashpad {
28 29
29 namespace { 30 namespace {
30 31
31 const wchar_t kDatabaseDirectoryName[] = L"Crashpad"; 32 const wchar_t kDatabaseDirectoryName[] = L"Crashpad";
32 33
33 const wchar_t kReportsDirectory[] = L"reports"; 34 const wchar_t kReportsDirectory[] = L"reports";
34 const wchar_t kMetadataFileName[] = L"metadata"; 35 const wchar_t kMetadataFileName[] = L"metadata";
35 36
36 const wchar_t kCrashReportFileExtension[] = L"dmp"; 37 const wchar_t kCrashReportFileExtension[] = L"dmp";
37 38
38 enum class ReportState : int { 39 const uint32_t kMetadataFileHeaderMagic = 'CPAD';
40 const uint32_t kMetadataFileVersion = 1;
41
42 using OperationStatus = CrashReportDatabase::OperationStatus;
43
44 // Helpers ---------------------------------------------------------------------
45
46 // Adds a string to the string table and returns the byte index where it was
47 // added.
48 uint32_t AddStringToTable(std::string* string_table, const std::string& str) {
49 uint32_t offset = base::checked_cast<uint32_t>(string_table->size());
50 *string_table += str;
51 *string_table += '\0';
52 return offset;
53 }
54
55 // Converts |str| to UTF8, adds the result to the string table and returns the
56 // byte index where it was added.
57 uint32_t AddStringToTable(std::string* string_table,
58 const base::string16& str) {
59 return AddStringToTable(string_table, base::UTF16ToUTF8(str));
60 }
61
62 // Reads from the current file position to EOF and returns as a string of bytes.
63 std::string ReadRestOfFileAsString(FileHandle file) {
64 FileOffset read_from = LoggingSeekFile(file, 0, SEEK_CUR);
65 FileOffset end = LoggingSeekFile(file, 0, SEEK_END);
66 FileOffset original = LoggingSeekFile(file, read_from, SEEK_SET);
67 if (read_from == -1 || end == -1 || original == -1 || read_from == end)
68 return std::string();
69 DCHECK_EQ(read_from, original);
70 DCHECK_GT(end, read_from);
71 size_t data_length = static_cast<size_t>(end - read_from);
72 std::string buffer(data_length, '\0');
73 return LoggingReadFile(file, &buffer[0], data_length) ? buffer
74 : std::string();
75 }
76
77 // Helper structures, and conversions ------------------------------------------
78
79 // The format of the on disk metadata file is a MetadataFileHeader, followed by
80 // a number of fixed size records of MetadataFileReportRecord, followed by a
81 // string table in UTF8 format, where each string is \0 terminated.
82 struct MetadataFileHeader {
83 uint32_t magic;
84 uint32_t version;
85 uint32_t num_records;
86 uint32_t padding;
87 };
88
89 struct ReportDisk;
90
91 struct MetadataFileReportRecord {
92 UUID uuid; // UUID is a 16 byte, standard layout structure.
93 uint32_t file_path_index; // Index into string table. File name is relative
94 // to the reports directory when on disk.
95 uint32_t id_index; // Index into string table.
96 int64_t creation_time; // Holds a time_t.
97 int64_t last_upload_attempt_time; // Holds a time_t.
Peter Kasting 2015/02/14 00:50:22 Up to you whether you like this better: ... i
scottmg 2015/02/14 01:12:20 Sure.
98 int32_t upload_attempts;
99 int32_t state; // A ReportState.
100 uint8_t uploaded; // Boolean, 0 or 1.
101 uint8_t padding[7];
102
103 MetadataFileReportRecord() {}
104
105 // Constructs from a ReportDisk, adding to |string_table| and storing indices
106 // as strings into that table.
107 MetadataFileReportRecord(const ReportDisk& report, std::string* string_table);
108 };
109
110 enum class ReportState {
39 //! \brief Created and filled out by caller, owned by database. 111 //! \brief Created and filled out by caller, owned by database.
40 kPending, 112 kPending,
41 //! \brief In the process of uploading, owned by caller. 113 //! \brief In the process of uploading, owned by caller.
42 kUploading, 114 kUploading,
43 //! \brief Upload completed or skipped, owned by database. 115 //! \brief Upload completed or skipped, owned by database.
44 kCompleted, 116 kCompleted,
45 }; 117 };
46 118
47 using OperationStatus = CrashReportDatabase::OperationStatus;
48
49 //! \brief Ensures that the node at path is a directory, and creates it if it
50 //! does not exist.
51 //!
52 //! \return If the path points to a file, rather than a directory, or the
53 //! directory could not be created, returns `false`. Otherwise, returns
54 //! `true`, indicating that path already was or now is a directory.
55 bool CreateOrEnsureDirectoryExists(const base::FilePath& path) {
56 if (CreateDirectory(path.value().c_str(), nullptr)) {
57 return true;
58 } else if (GetLastError() == ERROR_ALREADY_EXISTS) {
59 DWORD fileattr = GetFileAttributes(path.value().c_str());
60 if (fileattr == INVALID_FILE_ATTRIBUTES) {
61 PLOG(ERROR) << "GetFileAttributes";
62 return false;
63 }
64 if ((fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0)
65 return true;
66 LOG(ERROR) << "not a directory";
67 return false;
68 } else {
69 PLOG(ERROR) << "CreateDirectory";
70 return false;
71 }
72 }
73
74 //! \brief A private extension of the Report class that includes additional data 119 //! \brief A private extension of the Report class that includes additional data
75 //! that's stored on disk in the metadata file. 120 //! that's stored on disk in the metadata file.
76 struct ReportDisk : public CrashReportDatabase::Report { 121 struct ReportDisk : public CrashReportDatabase::Report {
77 //! \brief The current state of the report. 122 //! \brief The current state of the report.
78 ReportState state; 123 ReportState state;
124
125 ReportDisk(const MetadataFileReportRecord& record,
126 const base::FilePath& report_dir,
127 const std::string& string_table);
128
129 ReportDisk(const UUID& uuid,
130 const base::FilePath& path,
131 time_t creation_tim,
132 ReportState state);
79 }; 133 };
80 134
135 MetadataFileReportRecord::MetadataFileReportRecord(const ReportDisk& report,
136 std::string* string_table) {
137 uuid = report.uuid;
Peter Kasting 2015/02/14 00:50:22 Nit: Prefer to use the constructor initializer lis
scottmg 2015/02/14 01:12:20 Done.
138 file_path_index =
139 AddStringToTable(string_table, report.file_path.BaseName().value());
140 id_index = AddStringToTable(string_table, report.id);
141 creation_time = report.creation_time;
142 last_upload_attempt_time = report.last_upload_attempt_time;
143 upload_attempts = report.upload_attempts;
144 state = static_cast<uint32_t>(report.state);
145 uploaded = report.uploaded;
146 memset(&padding, 0, sizeof(padding));
147 }
148
149 ReportDisk::ReportDisk(const MetadataFileReportRecord& record,
150 const base::FilePath& report_dir,
151 const std::string& string_table) : Report() {
Peter Kasting 2015/02/14 00:50:22 Kinda suprised that clang-format (I assume) put ":
scottmg 2015/02/14 01:12:20 Apparently I didn't hit my format button there for
152 uuid = record.uuid;
153 file_path = report_dir.Append(
154 base::UTF8ToUTF16(&string_table[record.file_path_index]));
155 id = &string_table[record.id_index];
156 creation_time = record.creation_time;
157 uploaded = record.uploaded;
158 last_upload_attempt_time = record.last_upload_attempt_time;
159 upload_attempts = record.upload_attempts;
160 state = static_cast<ReportState>(record.state);
161 }
162
163 ReportDisk::ReportDisk(const UUID& uuid,
164 const base::FilePath& path,
165 time_t creation_time,
166 ReportState state)
167 : Report() {
168 this->uuid = uuid;
169 this->file_path = path;
170 this->creation_time = creation_time;
171 this->state = state;
172 }
173
81 //! \brief A private extension of the NewReport class to hold the UUID during 174 //! \brief A private extension of the NewReport class to hold the UUID during
82 //! initial write. We don't store metadata in dump's file attributes, and 175 //! initial write. We don't store metadata in dump's file attributes, so we
83 //! use the UUID to identify the dump on write completion. 176 //! use the UUID to identify the dump on write completion.
84 struct NewReportDisk : public CrashReportDatabase::NewReport { 177 struct NewReportDisk : public CrashReportDatabase::NewReport {
85 //! \brief The UUID for this crash report. 178 //! \brief The UUID for this crash report.
86 UUID uuid; 179 UUID uuid;
87 }; 180 };
88 181
182 // Metadata --------------------------------------------------------------------
183
89 //! \brief Manages the metadata for the set of reports, handling serialization 184 //! \brief Manages the metadata for the set of reports, handling serialization
90 //! to disk, and queries. Instances of this class should be created by using 185 //! to disk, and queries.
91 //! CrashReportDatabaseWin::AcquireMetadata().
92 class Metadata { 186 class Metadata {
93 public: 187 public:
94 //! \brief Writes any changes if necessary, unlocks and closes the file 188 //! \brief Writes any changes if necessary, unlocks and closes the file
95 //! handle. 189 //! handle.
96 ~Metadata(); 190 ~Metadata();
97 191
192 static scoped_ptr<Metadata> Create(const base::FilePath& metadata_file,
193 const base::FilePath& report_dir);
194
98 //! \brief Adds a new report to the set. 195 //! \brief Adds a new report to the set.
99 //! 196 //!
100 //! \param[in] new_report_disk The record to add. The #state field must be set 197 //! \param[in] new_report_disk The record to add. The #state field must be set
101 //! to kPending. 198 //! to kPending.
102 void AddNewRecord(const ReportDisk& new_report_disk); 199 void AddNewRecord(const ReportDisk& new_report_disk);
103 200
104 //! \brief Finds all reports in a given state. The \a reports vector is only 201 //! \brief Finds all reports in a given state. The \a reports vector is only
105 //! valid when CrashReportDatabase::kNoError is returned. 202 //! valid when CrashReportDatabase::kNoError is returned.
106 //! 203 //!
107 //! \param[in] desired_state The state to match. 204 //! \param[in] desired_state The state to match.
108 //! \param[out] reports Matching reports, must be empty on entry. 205 //! \param[out] reports Matching reports, must be empty on entry.
109 OperationStatus FindReports( 206 OperationStatus FindReports(
110 ReportState desired_state, 207 ReportState desired_state,
111 std::vector<const CrashReportDatabase::Report>* reports); 208 std::vector<const CrashReportDatabase::Report>* reports) const;
112 209
113 //! \brief Finds the report matching the given UUID. 210 //! \brief Finds the report matching the given UUID.
114 //! 211 //!
115 //! The returned report is only valid if CrashReportDatabase::kNoError is 212 //! The returned report is only valid if CrashReportDatabase::kNoError is
116 //! returned. 213 //! returned.
117 //! 214 //!
118 //! \param[in] uuid The report identifier. 215 //! \param[in] uuid The report identifier.
119 //! \param[out] report_disk The found report, valid only if 216 //! \param[out] report_disk The found report, valid only if
120 //! CrashReportDatabase::kNoError is returned. Ownership is not 217 //! CrashReportDatabase::kNoError is returned. Ownership is not
121 //! transferred to the caller, and the report may not be modified. 218 //! transferred to the caller, and the report may not be modified.
122 OperationStatus FindSingleReport(const UUID& uuid, 219 OperationStatus FindSingleReport(const UUID& uuid,
123 const ReportDisk** report_disk); 220 const ReportDisk** report_disk) const;
124 221
125 //! \brief Finds a single report matching the given UUID and in the desired 222 //! \brief Finds a single report matching the given UUID and in the desired
126 //! state and calls the client-supplied mutator to modify the report. 223 //! state, and returns a mutable ReportDisk* if found.
127 //! 224 //!
128 //! The mutator object must have an operator()(ReportDisk*) which makes the 225 //! This marks the metadata as dirty, and on destruction, changes will be
129 //! desired changes. 226 //! written to disk via Write().
130 //! 227 //!
131 //! \return #kNoError on success. #kReportNotFound if there was no report with 228 //! \return #kNoError on success. #kReportNotFound if there was no report with
132 //! the specified UUID. #kBusyError if the report was not in the specified 229 //! the specified UUID. #kBusyError if the report was not in the specified
133 //! state. 230 //! state.
134 template <class T> 231 OperationStatus FindSingleReportAndMarkDirty(const UUID& uuid,
135 OperationStatus MutateSingleReport(const UUID& uuid, 232 ReportState desired_state,
136 ReportState desired_state, 233 ReportDisk** report_disk);
137 const T& mutator);
138 234
139 private: 235 private:
140 static scoped_ptr<Metadata> Create(const base::FilePath& metadata_file,
141 const base::FilePath& report_dir);
142 friend class CrashReportDatabaseWin;
143
144 Metadata(FileHandle handle, const base::FilePath& report_dir); 236 Metadata(FileHandle handle, const base::FilePath& report_dir);
145 237
146 bool Rewind(); 238 bool Rewind();
147 239
148 void Read(); 240 void Read();
149 void Write(); 241 void Write();
150 242
151 //! \brief Confirms that the corresponding report actually exists on disk 243 //! \brief Confirms that the corresponding report actually exists on disk
152 //! (that is, the dump file has not been removed), that the report is in 244 //! (that is, the dump file has not been removed), and that the report is
153 //! the given state. 245 //! in the given state.
154 static OperationStatus VerifyReport(const ReportDisk& report_disk, 246 static OperationStatus VerifyReport(const ReportDisk& report_disk,
155 ReportState desired_state); 247 ReportState desired_state);
156 //! \brief Confirms that the corresponding report actually exists on disk 248 //! \brief Confirms that the corresponding report actually exists on disk
157 //! (that is, the dump file has not been removed). 249 //! (that is, the dump file has not been removed).
158 static OperationStatus VerifyReportAnyState(const ReportDisk& report_disk); 250 static OperationStatus VerifyReportAnyState(const ReportDisk& report_disk);
159 251
160 ScopedFileHandle handle_; 252 ScopedFileHandle handle_;
161 const base::FilePath report_dir_; 253 const base::FilePath report_dir_;
162 bool dirty_; //! \brief Is a Write() required on destruction? 254 bool dirty_; //! \brief True when a Write() is required on destruction.
163 std::vector<ReportDisk> reports_; 255 std::vector<ReportDisk> reports_;
164 256
165 DISALLOW_COPY_AND_ASSIGN(Metadata); 257 DISALLOW_COPY_AND_ASSIGN(Metadata);
166 }; 258 };
167 259
168 Metadata::Metadata(FileHandle handle, const base::FilePath& report_dir)
169 : handle_(handle), report_dir_(report_dir), dirty_(false), reports_() {
170 }
171
172 Metadata::~Metadata() { 260 Metadata::~Metadata() {
173 if (dirty_) 261 if (dirty_)
174 Write(); 262 Write();
175 // Not actually async, UnlockFileEx requires the Offset fields. 263 // Not actually async, UnlockFileEx requires the Offset fields.
176 OVERLAPPED overlapped = {0}; 264 OVERLAPPED overlapped = {0};
177 if (!UnlockFileEx(handle_.get(), 0, MAXDWORD, MAXDWORD, &overlapped)) 265 if (!UnlockFileEx(handle_.get(), 0, MAXDWORD, MAXDWORD, &overlapped))
178 PLOG(ERROR) << "UnlockFileEx"; 266 PLOG(ERROR) << "UnlockFileEx";
179 } 267 }
180 268
181 // The format of the metadata file is a MetadataFileHeader, followed by a
182 // number of fixed size records of MetadataFileReportRecord, followed by a
183 // string table in UTF8 format, where each string is \0 terminated.
184
185 #pragma pack(push, 1)
186
187 struct MetadataFileHeader {
188 uint32_t magic;
189 uint32_t version;
190 uint32_t num_records;
191 uint32_t padding;
192 };
193
194 struct MetadataFileReportRecord {
195 UUID uuid; // UUID is a 16 byte, standard layout structure.
196 uint32_t file_path_index; // Index into string table. File name is relative
197 // to the reports directory when on disk.
198 uint32_t id_index; // Index into string table.
199 int64_t creation_time; // Holds a time_t.
200 int64_t last_upload_attempt_time; // Holds a time_t.
201 int32_t upload_attempts;
202 int32_t state; // A ReportState.
203 uint8_t uploaded; // Boolean, 0 or 1.
204 uint8_t padding[7];
205 };
206
207 const uint32_t kMetadataFileHeaderMagic = 'CPAD';
208 const uint32_t kMetadataFileVersion = 1;
209
210 #pragma pack(pop)
211
212 // Reads from the current file position to EOF and returns as uint8_t[].
213 std::string ReadRestOfFileAsString(FileHandle file) {
214 FileOffset read_from = LoggingSeekFile(file, 0, SEEK_CUR);
215 FileOffset end = LoggingSeekFile(file, 0, SEEK_END);
216 FileOffset original = LoggingSeekFile(file, read_from, SEEK_SET);
217 if (read_from == -1 || end == -1 || original == -1)
218 return std::string();
219 DCHECK_EQ(read_from, original);
220 DCHECK_GE(end, read_from);
221 size_t data_length = static_cast<size_t>(end - read_from);
222 std::string buffer(data_length, '\0');
223 if (!LoggingReadFile(file, &buffer[0], data_length))
224 return std::string();
225 return buffer;
226 }
227
228 uint32_t AddStringToTable(std::string* string_table, const std::string& str) {
229 uint32_t offset = base::checked_cast<uint32_t>(string_table->size());
230 *string_table += str;
231 *string_table += '\0';
232 return offset;
233 }
234
235 uint32_t AddStringToTable(std::string* string_table, const std::wstring& str) {
236 return AddStringToTable(string_table, base::UTF16ToUTF8(str));
237 }
238
239 // static 269 // static
240 scoped_ptr<Metadata> Metadata::Create(const base::FilePath& metadata_file, 270 scoped_ptr<Metadata> Metadata::Create(const base::FilePath& metadata_file,
241 const base::FilePath& report_dir) { 271 const base::FilePath& report_dir) {
242 // It is important that dwShareMode be non-zero so that concurrent access to 272 // It is important that dwShareMode be non-zero so that concurrent access to
243 // this file results in a successful open. This allows us to get to LockFileEx 273 // this file results in a successful open. This allows us to get to LockFileEx
244 // which then blocks to guard access. 274 // which then blocks to guard access.
245 FileHandle handle = CreateFile(metadata_file.value().c_str(), 275 FileHandle handle = CreateFile(metadata_file.value().c_str(),
246 GENERIC_READ | GENERIC_WRITE, 276 GENERIC_READ | GENERIC_WRITE,
247 FILE_SHARE_READ | FILE_SHARE_WRITE, 277 FILE_SHARE_READ | FILE_SHARE_WRITE,
248 nullptr, 278 nullptr,
(...skipping 16 matching lines...) Expand all
265 295
266 scoped_ptr<Metadata> metadata(new Metadata(handle, report_dir)); 296 scoped_ptr<Metadata> metadata(new Metadata(handle, report_dir));
267 // If Read() fails, for whatever reason (corruption, etc.) metadata will not 297 // If Read() fails, for whatever reason (corruption, etc.) metadata will not
268 // have been modified and will be in a clean empty state. We continue on and 298 // have been modified and will be in a clean empty state. We continue on and
269 // return an empty database to hopefully recover. This means that existing 299 // return an empty database to hopefully recover. This means that existing
270 // crash reports have been orphaned. 300 // crash reports have been orphaned.
271 metadata->Read(); 301 metadata->Read();
272 return metadata; 302 return metadata;
273 } 303 }
274 304
305 void Metadata::AddNewRecord(const ReportDisk& new_report_disk) {
306 DCHECK(new_report_disk.state == ReportState::kPending);
307 reports_.push_back(new_report_disk);
308 dirty_ = true;
309 }
310
311 OperationStatus Metadata::FindReports(
312 ReportState desired_state,
313 std::vector<const CrashReportDatabase::Report>* reports) const {
314 DCHECK(reports->empty());
315 for (const auto& report : reports_) {
316 if (report.state == desired_state &&
317 VerifyReport(report, desired_state) == CrashReportDatabase::kNoError) {
318 reports->push_back(report);
319 }
320 }
321 return CrashReportDatabase::kNoError;
322 }
323
324 OperationStatus Metadata::FindSingleReport(
325 const UUID& uuid,
326 const ReportDisk** out_report) const {
327 auto report_iter = std::find_if(
328 reports_.begin(), reports_.end(), [uuid](const ReportDisk& report) {
329 return report.uuid == uuid;
330 });
331 if (report_iter == reports_.end())
332 return CrashReportDatabase::kReportNotFound;
333 OperationStatus os = VerifyReportAnyState(*report_iter);
334 if (os == CrashReportDatabase::kNoError)
335 *out_report = &*report_iter;
336 return os;
337 }
338
339 OperationStatus Metadata::FindSingleReportAndMarkDirty(
340 const UUID& uuid,
341 ReportState desired_state,
342 ReportDisk** report_disk) {
343 auto report_iter = std::find_if(
344 reports_.begin(), reports_.end(), [uuid](const ReportDisk& report) {
345 return report.uuid == uuid;
346 });
347 if (report_iter == reports_.end())
348 return CrashReportDatabase::kReportNotFound;
349 OperationStatus os = VerifyReport(*report_iter, desired_state);
350 if (os == CrashReportDatabase::kNoError) {
351 dirty_ = true;
352 *report_disk = &*report_iter;
353 }
354 return os;
355 }
356
357 Metadata::Metadata(FileHandle handle, const base::FilePath& report_dir)
358 : handle_(handle), report_dir_(report_dir), dirty_(false), reports_() {
359 }
360
275 bool Metadata::Rewind() { 361 bool Metadata::Rewind() {
276 FileOffset result = LoggingSeekFile(handle_.get(), 0, SEEK_SET); 362 FileOffset result = LoggingSeekFile(handle_.get(), 0, SEEK_SET);
277 DCHECK_EQ(result, 0); 363 DCHECK_EQ(result, 0);
278 return result == 0; 364 return result == 0;
279 } 365 }
280 366
281 void Metadata::Read() { 367 void Metadata::Read() {
282 FileOffset length = LoggingSeekFile(handle_.get(), 0, SEEK_END); 368 FileOffset length = LoggingSeekFile(handle_.get(), 0, SEEK_END);
283 if (length <= 0) // Failed, or empty: Abort. 369 if (length <= 0) // Failed, or empty: Abort.
284 return; 370 return;
285 if (!Rewind()) { 371 if (!Rewind()) {
286 LOG(ERROR) << "failed to rewind to read"; 372 LOG(ERROR) << "failed to rewind to read";
287 return; 373 return;
288 } 374 }
289 375
290 MetadataFileHeader header; 376 MetadataFileHeader header;
291 if (!LoggingReadFile(handle_.get(), &header, sizeof(header))) { 377 if (!LoggingReadFile(handle_.get(), &header, sizeof(header))) {
292 LOG(ERROR) << "failed to read header"; 378 LOG(ERROR) << "failed to read header";
293 return; 379 return;
294 } 380 }
295 if (header.magic != kMetadataFileHeaderMagic || 381 if (header.magic != kMetadataFileHeaderMagic ||
296 header.version != kMetadataFileVersion) { 382 header.version != kMetadataFileVersion) {
297 LOG(ERROR) << "unexpected header"; 383 LOG(ERROR) << "unexpected header";
298 return; 384 return;
299 } 385 }
300 386
301 auto records_size = base::CheckedNumeric<uint32_t>(header.num_records) * 387 base::CheckedNumeric<uint32_t> records_size =
302 sizeof(MetadataFileReportRecord); 388 base::CheckedNumeric<uint32_t>(header.num_records) *
389 sizeof(MetadataFileReportRecord);
303 if (!records_size.IsValid()) { 390 if (!records_size.IsValid()) {
304 LOG(ERROR) << "record size out of range"; 391 LOG(ERROR) << "record size out of range";
305 return; 392 return;
306 } 393 }
307 394
308 scoped_ptr<MetadataFileReportRecord[]> records( 395 std::vector<MetadataFileReportRecord> records(header.num_records);
309 new MetadataFileReportRecord[header.num_records]); 396 if (!LoggingReadFile(handle_.get(), &records[0], records_size.ValueOrDie())) {
310 if (!LoggingReadFile(
311 handle_.get(), records.get(), records_size.ValueOrDie())) {
312 LOG(ERROR) << "failed to read records"; 397 LOG(ERROR) << "failed to read records";
313 return; 398 return;
314 } 399 }
315 400
316 std::string string_table = ReadRestOfFileAsString(handle_.get()); 401 std::string string_table = ReadRestOfFileAsString(handle_.get());
317 if (string_table.empty() || string_table.back() != '\0') { 402 if (string_table.empty() || string_table.back() != '\0') {
318 LOG(ERROR) << "bad string table"; 403 LOG(ERROR) << "bad string table";
319 return; 404 return;
320 } 405 }
321 for (uint32_t i = 0; i < header.num_records; ++i) { 406
322 ReportDisk r; 407 std::vector<ReportDisk> reports;
323 const MetadataFileReportRecord* record = &records[i]; 408 for (const auto& record : records) {
324 r.uuid = record->uuid; 409 if (record.file_path_index >= string_table.size() ||
325 if (record->file_path_index >= string_table.size() || 410 record.id_index >= string_table.size()) {
326 record->id_index >= string_table.size()) {
327 reports_.clear();
328 LOG(ERROR) << "invalid string table index"; 411 LOG(ERROR) << "invalid string table index";
329 return; 412 return;
330 } 413 }
331 r.file_path = report_dir_.Append( 414 reports.push_back(ReportDisk(record, report_dir_, string_table));
332 base::UTF8ToUTF16(&string_table[record->file_path_index]));
333 r.id = &string_table[record->id_index];
334 r.creation_time = record->creation_time;
335 r.uploaded = record->uploaded;
336 r.last_upload_attempt_time = record->last_upload_attempt_time;
337 r.upload_attempts = record->upload_attempts;
338 r.state = static_cast<ReportState>(record->state);
339 reports_.push_back(r);
340 } 415 }
416 reports_.swap(reports);
341 } 417 }
342 418
343 void Metadata::Write() { 419 void Metadata::Write() {
344 if (!Rewind()) { 420 if (!Rewind()) {
345 LOG(ERROR) << "failed to rewind to write"; 421 LOG(ERROR) << "failed to rewind to write";
346 return; 422 return;
347 } 423 }
348 424
349 // Truncate to ensure that a partial write doesn't cause a mix of old and new 425 // Truncate to ensure that a partial write doesn't cause a mix of old and new
350 // data causing an incorrect interpretation on read. 426 // data causing an incorrect interpretation on read.
351 if (!SetEndOfFile(handle_.get())) { 427 if (!SetEndOfFile(handle_.get())) {
352 PLOG(ERROR) << "failed to truncate"; 428 PLOG(ERROR) << "failed to truncate";
353 return; 429 return;
354 } 430 }
355 431
356 size_t num_records = reports_.size(); 432 size_t num_records = reports_.size();
357 433
358 // Fill and write out the header. 434 // Fill and write out the header.
359 MetadataFileHeader header = {0}; 435 MetadataFileHeader header = {0};
360 header.magic = kMetadataFileHeaderMagic; 436 header.magic = kMetadataFileHeaderMagic;
361 header.version = kMetadataFileVersion; 437 header.version = kMetadataFileVersion;
362 header.num_records = base::checked_cast<uint32_t>(num_records); 438 header.num_records = base::checked_cast<uint32_t>(num_records);
363 if (!LoggingWriteFile(handle_.get(), &header, sizeof(header))) { 439 if (!LoggingWriteFile(handle_.get(), &header, sizeof(header))) {
364 LOG(ERROR) << "failed to write header"; 440 LOG(ERROR) << "failed to write header";
365 return; 441 return;
366 } 442 }
367 443
368 // Build the records and string table we're going to write. 444 // Build the records and string table we're going to write.
369 std::string string_table; 445 std::string string_table;
370 scoped_ptr<MetadataFileReportRecord[]> records( 446 std::vector<MetadataFileReportRecord> records;
371 new MetadataFileReportRecord[num_records]); 447 records.reserve(num_records);
372 memset(records.get(), 0, sizeof(MetadataFileReportRecord) * num_records); 448 for (const auto& report : reports_) {
373 for (size_t i = 0; i < num_records; ++i) {
374 const ReportDisk& report = reports_[i];
375 MetadataFileReportRecord& record = records[i];
376 record.uuid = report.uuid;
377 const base::FilePath& path = report.file_path; 449 const base::FilePath& path = report.file_path;
378 if (path.DirName() != report_dir_) { 450 if (path.DirName() != report_dir_) {
379 LOG(ERROR) << path.value().c_str() << " expected to start with " 451 LOG(ERROR) << path.value().c_str() << " expected to start with "
380 << report_dir_.value().c_str(); 452 << report_dir_.value().c_str();
381 return; 453 return;
382 } 454 }
383 record.file_path_index = 455 records.push_back(MetadataFileReportRecord(report, &string_table));
384 AddStringToTable(&string_table, path.BaseName().value().c_str());
385 record.id_index = AddStringToTable(&string_table, report.id);
386 record.creation_time = report.creation_time;
387 record.uploaded = report.uploaded;
388 record.last_upload_attempt_time = report.last_upload_attempt_time;
389 record.upload_attempts = report.upload_attempts;
390 record.state = static_cast<uint32_t>(report.state);
391 } 456 }
392 457
393 if (!LoggingWriteFile(handle_.get(), 458 if (!LoggingWriteFile(handle_.get(),
394 records.get(), 459 &records[0],
395 num_records * sizeof(MetadataFileReportRecord))) { 460 records.size() * sizeof(MetadataFileReportRecord))) {
396 LOG(ERROR) << "failed to write records"; 461 LOG(ERROR) << "failed to write records";
397 return; 462 return;
398 } 463 }
399 if (!LoggingWriteFile( 464 if (!LoggingWriteFile(
400 handle_.get(), string_table.c_str(), string_table.size())) { 465 handle_.get(), string_table.c_str(), string_table.size())) {
401 LOG(ERROR) << "failed to write string table"; 466 LOG(ERROR) << "failed to write string table";
402 return; 467 return;
403 } 468 }
404 } 469 }
405 470
406 void Metadata::AddNewRecord(const ReportDisk& new_report_disk) {
407 DCHECK(new_report_disk.state == ReportState::kPending);
408 reports_.push_back(new_report_disk);
409 dirty_ = true;
410 }
411
412 OperationStatus Metadata::FindReports(
413 ReportState desired_state,
414 std::vector<const CrashReportDatabase::Report>* reports) {
415 DCHECK(reports->empty());
416 for (const auto& report : reports_) {
417 if (report.state == desired_state) {
418 if (VerifyReport(report, desired_state) != CrashReportDatabase::kNoError)
419 continue;
420 reports->push_back(report);
421 }
422 }
423 return CrashReportDatabase::kNoError;
424 }
425
426 OperationStatus Metadata::FindSingleReport(const UUID& uuid,
427 const ReportDisk** out_report) {
428 for (size_t i = 0; i < reports_.size(); ++i) {
429 if (reports_[i].uuid == uuid) {
430 OperationStatus os = VerifyReportAnyState(reports_[i]);
431 if (os != CrashReportDatabase::kNoError)
432 return os;
433 *out_report = &reports_[i];
434 return CrashReportDatabase::kNoError;
435 }
436 }
437 return CrashReportDatabase::kReportNotFound;
438 }
439
440 template <class T>
441 OperationStatus Metadata::MutateSingleReport(
442 const UUID& uuid,
443 ReportState desired_state,
444 const T& mutator) {
445 for (size_t i = 0; i < reports_.size(); ++i) {
446 if (reports_[i].uuid == uuid) {
447 OperationStatus os = VerifyReport(reports_[i], desired_state);
448 if (os != CrashReportDatabase::kNoError)
449 return os;
450 mutator(&reports_[i]);
451 dirty_ = true;
452 return CrashReportDatabase::kNoError;
453 }
454 }
455 return CrashReportDatabase::kReportNotFound;
456 }
457
458 // static 471 // static
459 OperationStatus Metadata::VerifyReportAnyState(const ReportDisk& report_disk) { 472 OperationStatus Metadata::VerifyReportAnyState(const ReportDisk& report_disk) {
460 DWORD fileattr = GetFileAttributes(report_disk.file_path.value().c_str()); 473 DWORD fileattr = GetFileAttributes(report_disk.file_path.value().c_str());
461 if (fileattr == INVALID_FILE_ATTRIBUTES) 474 if (fileattr == INVALID_FILE_ATTRIBUTES)
462 return CrashReportDatabase::kReportNotFound; 475 return CrashReportDatabase::kReportNotFound;
463 if ((fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0) 476 return (fileattr & FILE_ATTRIBUTE_DIRECTORY)
464 return CrashReportDatabase::kFileSystemError; 477 ? CrashReportDatabase::kFileSystemError
465 return CrashReportDatabase::kNoError; 478 : CrashReportDatabase::kNoError;
466 } 479 }
467 480
468 // static 481 // static
469 OperationStatus Metadata::VerifyReport(const ReportDisk& report_disk, 482 OperationStatus Metadata::VerifyReport(const ReportDisk& report_disk,
470 ReportState desired_state) { 483 ReportState desired_state) {
471 if (report_disk.state != desired_state) 484 return (report_disk.state == desired_state)
472 return CrashReportDatabase::kBusyError; 485 ? VerifyReportAnyState(report_disk)
473 return VerifyReportAnyState(report_disk); 486 : CrashReportDatabase::kBusyError;
474 } 487 }
475 488
489 //! \brief Ensures that the node at path is a directory, and creates it if it
490 //! does not exist.
491 //!
492 //! \return If the path points to a file, rather than a directory, or the
493 //! directory could not be created, returns `false`. Otherwise, returns
494 //! `true`, indicating that path already was or now is a directory.
495 bool CreateDirectoryIfNecessary(const base::FilePath& path) {
496 if (CreateDirectory(path.value().c_str(), nullptr))
497 return true;
498 if (GetLastError() != ERROR_ALREADY_EXISTS) {
499 PLOG(ERROR) << "CreateDirectory";
500 return false;
501 }
502 DWORD fileattr = GetFileAttributes(path.value().c_str());
503 if (fileattr == INVALID_FILE_ATTRIBUTES) {
504 PLOG(ERROR) << "GetFileAttributes";
505 return false;
506 }
507 if ((fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0)
508 return true;
509 LOG(ERROR) << "not a directory";
510 return false;
511 }
512
513 // CrashReportDatabaseWin ------------------------------------------------------
514
476 class CrashReportDatabaseWin : public CrashReportDatabase { 515 class CrashReportDatabaseWin : public CrashReportDatabase {
477 public: 516 public:
478 explicit CrashReportDatabaseWin(const base::FilePath& path); 517 explicit CrashReportDatabaseWin(const base::FilePath& path);
479 ~CrashReportDatabaseWin() override; 518 ~CrashReportDatabaseWin() override;
480 519
481 bool Initialize(); 520 bool Initialize();
482 521
483 // CrashReportDatabase: 522 // CrashReportDatabase:
484 OperationStatus PrepareNewCrashReport(NewReport** report) override; 523 OperationStatus PrepareNewCrashReport(NewReport** report) override;
485 OperationStatus FinishedWritingCrashReport(NewReport* report, 524 OperationStatus FinishedWritingCrashReport(NewReport* report,
(...skipping 20 matching lines...) Expand all
506 }; 545 };
507 546
508 CrashReportDatabaseWin::CrashReportDatabaseWin(const base::FilePath& path) 547 CrashReportDatabaseWin::CrashReportDatabaseWin(const base::FilePath& path)
509 : CrashReportDatabase(), base_dir_(path) { 548 : CrashReportDatabase(), base_dir_(path) {
510 } 549 }
511 550
512 CrashReportDatabaseWin::~CrashReportDatabaseWin() { 551 CrashReportDatabaseWin::~CrashReportDatabaseWin() {
513 } 552 }
514 553
515 bool CrashReportDatabaseWin::Initialize() { 554 bool CrashReportDatabaseWin::Initialize() {
516 // Check if the database already exists. 555 // Ensure the database and report subdirectories exist.
517 if (!CreateOrEnsureDirectoryExists(base_dir_)) 556 if (!CreateDirectoryIfNecessary(base_dir_) ||
518 return false; 557 !CreateDirectoryIfNecessary(base_dir_.Append(kReportsDirectory)))
519
520 // Create our reports subdirectory.
521 if (!CreateOrEnsureDirectoryExists(base_dir_.Append(kReportsDirectory)))
522 return false; 558 return false;
523 559
524 // TODO(scottmg): When are completed reports pruned from disk? Delete here or 560 // TODO(scottmg): When are completed reports pruned from disk? Delete here or
525 // maybe on AcquireMetadata(). 561 // maybe on AcquireMetadata().
526 562
527 return true; 563 return true;
528 } 564 }
529 565
530 OperationStatus CrashReportDatabaseWin::PrepareNewCrashReport( 566 OperationStatus CrashReportDatabaseWin::PrepareNewCrashReport(
531 NewReport** out_report) { 567 NewReport** report) {
532 scoped_ptr<NewReportDisk> report(new NewReportDisk());
533
534 ::UUID system_uuid; 568 ::UUID system_uuid;
535 if (UuidCreate(&system_uuid) != RPC_S_OK) { 569 if (UuidCreate(&system_uuid) != RPC_S_OK)
536 return kFileSystemError; 570 return kFileSystemError;
537 }
538 static_assert(sizeof(system_uuid) == 16, "unexpected system uuid size"); 571 static_assert(sizeof(system_uuid) == 16, "unexpected system uuid size");
539 static_assert(offsetof(::UUID, Data1) == 0, "unexpected uuid layout"); 572 static_assert(offsetof(::UUID, Data1) == 0, "unexpected uuid layout");
540 UUID uuid(reinterpret_cast<const uint8_t*>(&system_uuid.Data1)); 573 UUID uuid(reinterpret_cast<const uint8_t*>(&system_uuid.Data1));
541 574
542 report->uuid = uuid; 575 scoped_ptr<NewReportDisk> new_report(new NewReportDisk());
543 report->path = 576 new_report->uuid = uuid;
577 new_report->path =
544 base_dir_.Append(kReportsDirectory) 578 base_dir_.Append(kReportsDirectory)
545 .Append(uuid.ToWideString() + L"." + kCrashReportFileExtension); 579 .Append(uuid.ToString16() + L"." + kCrashReportFileExtension);
546 report->handle = LoggingOpenFileForWrite( 580 new_report->handle = LoggingOpenFileForWrite(new_report->path,
547 report->path, FileWriteMode::kCreateOrFail, FilePermissions::kOwnerOnly); 581 FileWriteMode::kCreateOrFail,
548 if (report->handle == INVALID_HANDLE_VALUE) 582 FilePermissions::kOwnerOnly);
583 if (new_report->handle == INVALID_HANDLE_VALUE)
549 return kFileSystemError; 584 return kFileSystemError;
550 585
551 *out_report = report.release(); 586 *report = new_report.release();
552 return kNoError; 587 return kNoError;
553 } 588 }
554 589
555 OperationStatus CrashReportDatabaseWin::FinishedWritingCrashReport( 590 OperationStatus CrashReportDatabaseWin::FinishedWritingCrashReport(
556 NewReport* report, 591 NewReport* report,
557 UUID* uuid) { 592 UUID* uuid) {
558 // Take ownership of the report, and cast to our private version with UUID. 593 // Take ownership of the report, and cast to our private version with UUID.
559 scoped_ptr<NewReportDisk> scoped_report(static_cast<NewReportDisk*>(report)); 594 scoped_ptr<NewReportDisk> scoped_report(static_cast<NewReportDisk*>(report));
560 // Take ownership of the file handle. 595 // Take ownership of the file handle.
561 ScopedFileHandle handle(report->handle); 596 ScopedFileHandle handle(report->handle);
562 597
563 scoped_ptr<Metadata> metadata(AcquireMetadata()); 598 scoped_ptr<Metadata> metadata(AcquireMetadata());
564 if (!metadata) 599 if (!metadata)
565 return kDatabaseError; 600 return kDatabaseError;
566 ReportDisk report_disk; 601 metadata->AddNewRecord(ReportDisk(scoped_report->uuid,
567 report_disk.uuid = scoped_report->uuid; 602 scoped_report->path,
568 report_disk.file_path = scoped_report->path; 603 time(nullptr),
569 report_disk.creation_time = time(nullptr); 604 ReportState::kPending));
570 report_disk.state = ReportState::kPending; 605 *uuid = scoped_report->uuid;
571 metadata->AddNewRecord(report_disk);
572 *uuid = report_disk.uuid;
573 return kNoError; 606 return kNoError;
574 } 607 }
575 608
576 OperationStatus CrashReportDatabaseWin::ErrorWritingCrashReport( 609 OperationStatus CrashReportDatabaseWin::ErrorWritingCrashReport(
577 NewReport* report) { 610 NewReport* report) {
578 // Take ownership of the report, and cast to our private version with UUID. 611 // Take ownership of the report, and cast to our private version with UUID.
579 scoped_ptr<NewReportDisk> scoped_report(static_cast<NewReportDisk*>(report)); 612 scoped_ptr<NewReportDisk> scoped_report(static_cast<NewReportDisk*>(report));
580 613
581 // Close the outstanding handle. 614 // Close the outstanding handle.
582 LoggingCloseFile(report->handle); 615 LoggingCloseFile(report->handle);
583 616
584 // We failed to write, so remove the dump file. There's no entry in the 617 // We failed to write, so remove the dump file. There's no entry in the
585 // metadata table yet. 618 // metadata table yet.
586 if (!DeleteFile(scoped_report->path.value().c_str())) { 619 if (!DeleteFile(scoped_report->path.value().c_str())) {
587 PLOG(ERROR) << "DeleteFile " << scoped_report->path.value().c_str(); 620 PLOG(ERROR) << "DeleteFile " << scoped_report->path.value().c_str();
588 return CrashReportDatabase::kFileSystemError; 621 return CrashReportDatabase::kFileSystemError;
589 } 622 }
590 623
591 return kNoError; 624 return kNoError;
592 } 625 }
593 626
594 OperationStatus CrashReportDatabaseWin::LookUpCrashReport(const UUID& uuid, 627 OperationStatus CrashReportDatabaseWin::LookUpCrashReport(const UUID& uuid,
595 Report* report) { 628 Report* report) {
596 scoped_ptr<Metadata> metadata(AcquireMetadata()); 629 scoped_ptr<Metadata> metadata(AcquireMetadata());
597 if (!metadata) 630 if (!metadata)
598 return kDatabaseError; 631 return kDatabaseError;
599 // Find and return a copy of the matching report. 632 // Find and return a copy of the matching report.
600 const ReportDisk* report_disk; 633 const ReportDisk* report_disk;
601 OperationStatus os = metadata->FindSingleReport(uuid, &report_disk); 634 OperationStatus os = metadata->FindSingleReport(uuid, &report_disk);
602 if (os != kNoError) 635 if (os == kNoError)
603 return os; 636 *report = *report_disk;
604 *report = *report_disk;
605 return kNoError; 637 return kNoError;
606 } 638 }
607 639
608 OperationStatus CrashReportDatabaseWin::GetPendingReports( 640 OperationStatus CrashReportDatabaseWin::GetPendingReports(
609 std::vector<const Report>* reports) { 641 std::vector<const Report>* reports) {
610 scoped_ptr<Metadata> metadata(AcquireMetadata()); 642 scoped_ptr<Metadata> metadata(AcquireMetadata());
611 if (!metadata) 643 return metadata ? metadata->FindReports(ReportState::kPending, reports)
612 return kDatabaseError; 644 : kDatabaseError;
613 return metadata->FindReports(ReportState::kPending, reports);
614 } 645 }
615 646
616 OperationStatus CrashReportDatabaseWin::GetCompletedReports( 647 OperationStatus CrashReportDatabaseWin::GetCompletedReports(
617 std::vector<const Report>* reports) { 648 std::vector<const Report>* reports) {
618 scoped_ptr<Metadata> metadata(AcquireMetadata()); 649 scoped_ptr<Metadata> metadata(AcquireMetadata());
619 if (!metadata) 650 return metadata ? metadata->FindReports(ReportState::kCompleted, reports)
620 return kDatabaseError; 651 : kDatabaseError;
621 return metadata->FindReports(ReportState::kCompleted, reports);
622 } 652 }
623 653
624 OperationStatus CrashReportDatabaseWin::GetReportForUploading( 654 OperationStatus CrashReportDatabaseWin::GetReportForUploading(
625 const UUID& uuid, 655 const UUID& uuid,
626 const Report** report) { 656 const Report** report) {
627 scoped_ptr<Metadata> metadata(AcquireMetadata()); 657 scoped_ptr<Metadata> metadata(AcquireMetadata());
628 if (!metadata) 658 if (!metadata)
629 return kDatabaseError; 659 return kDatabaseError;
630 // TODO(scottmg): After returning this report to the client, there is no way 660 // TODO(scottmg): After returning this report to the client, there is no way
631 // to reap this report if the uploader fails to call RecordUploadAttempt() or 661 // to reap this report if the uploader fails to call RecordUploadAttempt() or
632 // SkipReportUpload() (if it crashed or was otherwise buggy). To resolve this, 662 // SkipReportUpload() (if it crashed or was otherwise buggy). To resolve this,
633 // one possibility would be to change the interface to be FileHandle based, so 663 // one possibility would be to change the interface to be FileHandle based, so
634 // that instead of giving the file_path back to the client and changing state 664 // that instead of giving the file_path back to the client and changing state
635 // to kUploading, we return an exclusive access handle, and use that as the 665 // to kUploading, we return an exclusive access handle, and use that as the
636 // signal that the upload is pending, rather than an update to state in the 666 // signal that the upload is pending, rather than an update to state in the
637 // metadata. Alternatively, there could be a "garbage collection" at startup 667 // metadata. Alternatively, there could be a "garbage collection" at startup
638 // where any reports that are orphaned in the kUploading state are either 668 // where any reports that are orphaned in the kUploading state are either
639 // reset to kPending to retry, or discarded. 669 // reset to kPending to retry, or discarded.
640 return metadata->MutateSingleReport( 670 ReportDisk* report_disk;
641 uuid, ReportState::kPending, [report](ReportDisk* report_disk) { 671 OperationStatus os = metadata->FindSingleReportAndMarkDirty(
642 report_disk->state = ReportState::kUploading; 672 uuid, ReportState::kPending, &report_disk);
643 // Create a copy for passing back to client. This will be freed in 673 if (os == CrashReportDatabase::kNoError) {
644 // RecordUploadAttempt. 674 report_disk->state = ReportState::kUploading;
645 *report = new Report(*report_disk); 675 // Create a copy for passing back to client. This will be freed in
646 }); 676 // RecordUploadAttempt.
677 *report = new Report(*report_disk);
678 }
679 return os;
647 } 680 }
648 681
649 OperationStatus CrashReportDatabaseWin::RecordUploadAttempt( 682 OperationStatus CrashReportDatabaseWin::RecordUploadAttempt(
650 const Report* report, 683 const Report* report,
651 bool successful, 684 bool successful,
652 const std::string& id) { 685 const std::string& id) {
653 // Take ownership, allocated in GetReportForUploading. 686 // Take ownership, allocated in GetReportForUploading.
654 scoped_ptr<const Report> upload_report(report); 687 scoped_ptr<const Report> upload_report(report);
655 scoped_ptr<Metadata> metadata(AcquireMetadata()); 688 scoped_ptr<Metadata> metadata(AcquireMetadata());
656 if (!metadata) 689 if (!metadata)
657 return kDatabaseError; 690 return kDatabaseError;
658 return metadata->MutateSingleReport( 691 ReportDisk* report_disk;
659 report->uuid, 692 OperationStatus os = metadata->FindSingleReportAndMarkDirty(
660 ReportState::kUploading, 693 report->uuid, ReportState::kUploading, &report_disk);
661 [successful, id](ReportDisk* report_disk) { 694 if (os == CrashReportDatabaseWin::kNoError) {
662 report_disk->uploaded = successful; 695 report_disk->uploaded = successful;
663 report_disk->id = id; 696 report_disk->id = id;
664 report_disk->last_upload_attempt_time = time(nullptr); 697 report_disk->last_upload_attempt_time = time(nullptr);
665 report_disk->upload_attempts++; 698 report_disk->upload_attempts++;
666 report_disk->state = 699 report_disk->state =
667 successful ? ReportState::kCompleted : ReportState::kPending; 700 successful ? ReportState::kCompleted : ReportState::kPending;
668 }); 701 }
702 return os;
669 } 703 }
670 704
671 OperationStatus CrashReportDatabaseWin::SkipReportUpload(const UUID& uuid) { 705 OperationStatus CrashReportDatabaseWin::SkipReportUpload(const UUID& uuid) {
672 scoped_ptr<Metadata> metadata(AcquireMetadata()); 706 scoped_ptr<Metadata> metadata(AcquireMetadata());
673 if (!metadata) 707 if (!metadata)
674 return kDatabaseError; 708 return kDatabaseError;
675 return metadata->MutateSingleReport( 709 ReportDisk* report_disk;
676 uuid, ReportState::kPending, [](ReportDisk* report_disk) { 710 OperationStatus os = metadata->FindSingleReportAndMarkDirty(
677 report_disk->state = ReportState::kCompleted; 711 uuid, ReportState::kPending, &report_disk);
678 }); 712 if (os == CrashReportDatabase::kNoError)
713 report_disk->state = ReportState::kCompleted;
714 return os;
679 } 715 }
680 716
681 scoped_ptr<Metadata> CrashReportDatabaseWin::AcquireMetadata() { 717 scoped_ptr<Metadata> CrashReportDatabaseWin::AcquireMetadata() {
682 base::FilePath metadata_file = base_dir_.Append(kMetadataFileName); 718 base::FilePath metadata_file = base_dir_.Append(kMetadataFileName);
683 return Metadata::Create(metadata_file, base_dir_.Append(kReportsDirectory)); 719 return Metadata::Create(metadata_file, base_dir_.Append(kReportsDirectory));
684 } 720 }
685 721
686 } // namespace 722 } // namespace
687 723
688 // static 724 // static
689 scoped_ptr<CrashReportDatabase> CrashReportDatabase::Initialize( 725 scoped_ptr<CrashReportDatabase> CrashReportDatabase::Initialize(
690 const base::FilePath& path) { 726 const base::FilePath& path) {
691 scoped_ptr<CrashReportDatabaseWin> database_win( 727 scoped_ptr<CrashReportDatabaseWin> database_win(
692 new CrashReportDatabaseWin(path.Append(kDatabaseDirectoryName))); 728 new CrashReportDatabaseWin(path.Append(kDatabaseDirectoryName)));
693 if (!database_win->Initialize()) 729 return database_win->Initialize() ? database_win.Pass()
694 database_win.reset(); 730 : scoped_ptr<CrashReportDatabaseWin>();
695
696 return scoped_ptr<CrashReportDatabase>(database_win.release());
697 } 731 }
698 732
699 } // namespace crashpad 733 } // 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