File: crash_verification.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (314 lines) | stat: -rw-r--r-- 11,414 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/allocation_recorder/testing/crash_verification.h"

#include <algorithm>
#include <filesystem>
#include <iostream>
#include <iterator>
#include <memory>
#include <set>
#include <vector>

#include "base/debug/debugging_buildflags.h"
#include "base/files/file_path.h"
#include "base/functional/callback.h"
#include "base/threading/platform_thread.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "components/allocation_recorder/internal/internal.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/crashpad/crashpad/client/crash_report_database.h"
#include "third_party/crashpad/crashpad/snapshot/minidump/minidump_stream.h"
#include "third_party/crashpad/crashpad/snapshot/minidump/process_snapshot_minidump.h"
#include "third_party/crashpad/crashpad/util/misc/uuid.h"

#if BUILDFLAG(ENABLE_ALLOCATION_STACK_TRACE_RECORDER)
#include "components/allocation_recorder/crash_handler/memory_operation_report.pb.h"
#endif

using testing::AssertionFailure;
using testing::AssertionResult;
using testing::AssertionSuccess;

namespace crashpad {
void PrintTo(const CrashReportDatabase::OperationStatus status,
             std::ostream* os) {
  switch (status) {
    case CrashReportDatabase::kNoError:
      *os << "CrashReportDatabase::OperationStatus::kNoError";
      break;
    case CrashReportDatabase::kReportNotFound:
      *os << "CrashReportDatabase::OperationStatus::kReportNotFound";
      break;
    case CrashReportDatabase::kFileSystemError:
      *os << "CrashReportDatabase::OperationStatus::kFileSystemError";
      break;
    case CrashReportDatabase::kDatabaseError:
      *os << "CrashReportDatabase::OperationStatus::kDatabaseError";
      break;
    case CrashReportDatabase::kBusyError:
      *os << "CrashReportDatabase::OperationStatus::kBusyError";
      break;
    case CrashReportDatabase::kCannotRequestUpload:
      *os << "CrashReportDatabase::OperationStatus::kCannotRequestUpload";
      break;
  }
}
}  // namespace crashpad

namespace {

class CrashpadIntegration {
 public:
  CrashpadIntegration() = default;
  ~CrashpadIntegration() {
    if (crash_report_database_) {
      ShutDown();
    }
  }

  void SetUp(const base::FilePath& crashpad_database_path);
  void ShutDown();

  // Get all MinidumpStreams whose stream type equals
  // |allocation_recorder::internal::kStreamDataType|.
  std::vector<const crashpad::MinidumpStream*> GetAllocationRecorderStreams();

  void CheckHasNoAllocationRecorderStream();

#if BUILDFLAG(ENABLE_ALLOCATION_STACK_TRACE_RECORDER)
  void GetPayload(allocation_recorder::Payload& payload);
#endif

 private:
  void CrashDatabaseHasReport();
  void ReportHasProcessSnapshot();

#if BUILDFLAG(ENABLE_ALLOCATION_STACK_TRACE_RECORDER)
  void GetAllocationRecorderStream(
      const crashpad::MinidumpStream*& allocation_recorder_stream);
#endif

  // Try and read the created report from the database of crash reports. Errors
  // such as failure to read the list of pending reports will always result in a
  // fatal error.
  void TryReadCreatedReport();

  base::FilePath database_dir_;

  std::unique_ptr<crashpad::CrashReportDatabase> crash_report_database_;

  std::unique_ptr<crashpad::CrashReportDatabase::Report> report_;
  std::unique_ptr<crashpad::ProcessSnapshotMinidump> minidump_process_snapshot_;
};

void CrashpadIntegration::SetUp(const base::FilePath& crashpad_database_path) {
  database_dir_ = crashpad_database_path;

  crash_report_database_ =
      crashpad::CrashReportDatabase::InitializeWithoutCreating(database_dir_);
  ASSERT_NE(crash_report_database_, nullptr)
      << "Failed to load crash database. database='" << database_dir_ << '\'';

  std::vector<crashpad::CrashReportDatabase::Report> reports;
  ASSERT_EQ(crashpad::CrashReportDatabase::kNoError,
            crash_report_database_->GetPendingReports(&reports))
      << "Failed to read list of old pending reports. database='"
      << database_dir_ << '\'';
  ASSERT_EQ(reports.size(), std::size_t{0})
      << "Expected no reports at setup time."
      << "Please choose a unique temporary crashpad_database_path.";
}

void CrashpadIntegration::ShutDown() {
  if (report_) {
    const auto report_deletion_result =
        crash_report_database_->DeleteReport(report_->uuid);
    EXPECT_EQ(crashpad::CrashReportDatabase::kNoError, report_deletion_result);
  }

  minidump_process_snapshot_ = {};
  report_ = {};
  crash_report_database_ = {};
  database_dir_ = {};
}

void CrashpadIntegration::CrashDatabaseHasReport() {
  // The Crashpad report might not have been written yet. Try to read the report
  // multiple times without asserting success. Only in the very last try we
  // assert that a new report is present.
  constexpr auto maximum_total_retry_duration = base::Seconds(5);
  constexpr auto wait_time_between_retries = base::Milliseconds(200);

  const auto time_out_to_last_nonfatal_try =
      base::Time::Now() + maximum_total_retry_duration;

  while (base::Time::Now() <= time_out_to_last_nonfatal_try) {
    ASSERT_NO_FATAL_FAILURE(TryReadCreatedReport());

    if (report_) {
      return;
    }

    base::PlatformThreadBase::Sleep(wait_time_between_retries);
  }

  ASSERT_NO_FATAL_FAILURE(TryReadCreatedReport());
  ASSERT_NE(report_, nullptr)
      << "Found no new report. database='" << database_dir_ << '\'';
}

void CrashpadIntegration::ReportHasProcessSnapshot() {
  crashpad::FileReader file_reader;

  minidump_process_snapshot_ =
      std::make_unique<crashpad::ProcessSnapshotMinidump>();

  ASSERT_TRUE(file_reader.Open(report_->file_path))
      << "Failed to open dump file. path='" << report_->file_path << '\'';

  ASSERT_TRUE(minidump_process_snapshot_->Initialize(&file_reader))
      << "Failed to initialize process snapshot "
         "from report file. path='"
      << report_->file_path << '\'';
}

std::vector<const crashpad::MinidumpStream*>
CrashpadIntegration::GetAllocationRecorderStreams() {
  const auto stream_has_correct_type_predicate =
      [](const crashpad::MinidumpStream* const stream) {
        return stream && stream->stream_type() ==
                             allocation_recorder::internal::kStreamDataType;
      };

  const auto& custom_minidump_streams =
      minidump_process_snapshot_->CustomMinidumpStreams();

  std::vector<const crashpad::MinidumpStream*> allocation_recorder_streams;

  std::copy_if(std::begin(custom_minidump_streams),
               std::end(custom_minidump_streams),
               std::back_inserter(allocation_recorder_streams),
               stream_has_correct_type_predicate);

  return allocation_recorder_streams;
}

void CrashpadIntegration::TryReadCreatedReport() {
  std::vector<crashpad::CrashReportDatabase::Report> reports;
  ASSERT_EQ(crashpad::CrashReportDatabase::kNoError,
            crash_report_database_->GetPendingReports(&reports))
      << "Failed to read list of pending reports. database='" << database_dir_
      << '\'';
  ASSERT_EQ(reports.size(), std::size_t{1});
  report_ = std::make_unique<crashpad::CrashReportDatabase::Report>(reports[0]);
}

void CrashpadIntegration::CheckHasNoAllocationRecorderStream() {
  ASSERT_NO_FATAL_FAILURE(CrashDatabaseHasReport());
  ASSERT_NO_FATAL_FAILURE(ReportHasProcessSnapshot());

  const auto allocation_recorder_streams = GetAllocationRecorderStreams();

  EXPECT_EQ(std::size(allocation_recorder_streams), 0ul)
      << "Found at least one allocation recorder stream.";
}

#if BUILDFLAG(ENABLE_ALLOCATION_STACK_TRACE_RECORDER)
void CrashpadIntegration::GetAllocationRecorderStream(
    const crashpad::MinidumpStream*& allocation_recorder_stream) {
  const auto allocation_recorder_streams = GetAllocationRecorderStreams();

  ASSERT_EQ(std::size(allocation_recorder_streams), 1ul)
      << "Didn't find expected number of allocation recorder streams.";
  ASSERT_NE(allocation_recorder_streams.front(), nullptr)
      << "The only allocation recorder stream is nullptr.";

  allocation_recorder_stream = allocation_recorder_streams.front();
}

void CrashpadIntegration::GetPayload(allocation_recorder::Payload& payload) {
  ASSERT_NO_FATAL_FAILURE(CrashDatabaseHasReport());
  ASSERT_NO_FATAL_FAILURE(ReportHasProcessSnapshot());

  const crashpad::MinidumpStream* allocation_recorder_stream;
  ASSERT_NO_FATAL_FAILURE(
      GetAllocationRecorderStream(allocation_recorder_stream));
  const std::vector<uint8_t>& data = allocation_recorder_stream->data();

  ASSERT_TRUE(payload.ParseFromArray(std::data(data), std::size(data)))
      << "Failed to parse recorder information "
         "from recorder stream.";
}
#endif
}  // namespace

namespace allocation_recorder::testing {

#if BUILDFLAG(ENABLE_ALLOCATION_STACK_TRACE_RECORDER)
void VerifyCrashCreatesCrashpadReportWithAllocationRecorderStream(
    const base::FilePath& crashpad_database_path,
    base::OnceClosure crash_function,
    base::OnceCallback<void(const allocation_recorder::Payload& payload)>
        payload_verification) {
  ASSERT_TRUE(crash_function);
  CrashpadIntegration crashpad_integration;
  ASSERT_NO_FATAL_FAILURE(crashpad_integration.SetUp(crashpad_database_path));
  ASSERT_NO_FATAL_FAILURE(std::move(crash_function).Run());

  allocation_recorder::Payload payload;
  ASSERT_NO_FATAL_FAILURE(crashpad_integration.GetPayload(payload));

  if (payload_verification) {
    ASSERT_NO_FATAL_FAILURE(std::move(payload_verification).Run(payload));
  }
  ASSERT_NO_FATAL_FAILURE(crashpad_integration.ShutDown());
}

void VerifyPayload(const bool expect_report_with_content,
                   const allocation_recorder::Payload& payload) {
  if (expect_report_with_content) {
    if (payload.has_processing_failures()) {
      const auto& failures = payload.processing_failures();
      const auto& messages = failures.messages();
      ASSERT_GT(messages.size(), 0);
      FAIL() << "Payload has unexpected processing failure:\n" << messages[0];
    }
    ASSERT_TRUE(payload.has_operation_report());
    const auto& operation_report = payload.operation_report();

    ASSERT_TRUE(operation_report.has_statistics());
    const auto& statistics = operation_report.statistics();

    EXPECT_GT(operation_report.memory_operations_size(), 0);
    EXPECT_GT(statistics.total_number_of_operations(), 0ul);

#if BUILDFLAG(ENABLE_ALLOCATION_TRACE_RECORDER_FULL_REPORTING)
    EXPECT_TRUE(statistics.has_total_number_of_collisions());
#endif
  } else {
    ASSERT_TRUE(payload.has_processing_failures());
    const auto& failures = payload.processing_failures();
    const auto& messages = failures.messages();
    ASSERT_EQ(messages.size(), 1);
    ASSERT_EQ(
        messages[0],
        "No annotation found! required-name=allocation-recorder-crash-info");
  }
}
#else
void VerifyCrashCreatesCrashpadReportWithoutAllocationRecorderStream(
    const base::FilePath& crashpad_database_path,
    base::OnceClosure crash_function) {
  ASSERT_TRUE(crash_function);
  CrashpadIntegration crashpad_integration;
  ASSERT_NO_FATAL_FAILURE(crashpad_integration.SetUp(crashpad_database_path));
  ASSERT_NO_FATAL_FAILURE(std::move(crash_function).Run());
  ASSERT_NO_FATAL_FAILURE(crashpad_integration.ShutDown());
}
#endif  // BUILDFLAG(ENABLE_ALLOCATION_STACK_TRACE_RECORDER)

}  // namespace allocation_recorder::testing