diff --git a/DEPS b/DEPS index 190f5a30..aefedbc9 100644 --- a/DEPS +++ b/DEPS @@ -38,7 +38,7 @@ deps = { 'crashpad/third_party/mini_chromium/mini_chromium': Var('chromium_git') + '/chromium/mini_chromium@' + - '9e0d322ae9f87acbe17c4ced025319b4964bf0b7', + '62e6015f633dd4acb1610db15a064889315cadaa', 'crashpad/third_party/zlib/zlib': Var('chromium_git') + '/chromium/src/third_party/zlib@' + '13dc246a58e4b72104d35f9b1809af95221ebda7', diff --git a/build/gyp_crashpad_android.py b/build/gyp_crashpad_android.py index 852839aa..a6ad1b43 100755 --- a/build/gyp_crashpad_android.py +++ b/build/gyp_crashpad_android.py @@ -1,4 +1,5 @@ #!/usr/bin/env python +# coding: utf-8 # Copyright 2017 The Crashpad Authors. All rights reserved. # @@ -18,6 +19,7 @@ import argparse import glob import gyp_crashpad import os +import re import subprocess import sys @@ -31,7 +33,7 @@ def main(args): default='clang', choices=('clang', 'gcc'), help='The compiler to use, clang by default') - (parsed, extra_args) = parser.parse_known_args(args) + (parsed, extra_command_line_args) = parser.parse_known_args(args) NDK_ERROR=( 'NDK must be a valid standalone NDK toolchain.\n' + @@ -55,8 +57,11 @@ def main(args): ndk_bin_dir = os.path.join(parsed.ndk, 'bin') + clang_path = os.path.join(ndk_bin_dir, 'clang') + extra_args = [] + if parsed.compiler == 'clang': - os.environ['CC_target'] = os.path.join(ndk_bin_dir, 'clang') + os.environ['CC_target'] = clang_path os.environ['CXX_target'] = os.path.join(ndk_bin_dir, 'clang++') elif parsed.compiler == 'gcc': os.environ['CC_target'] = os.path.join(ndk_bin_dir, @@ -64,6 +69,27 @@ def main(args): os.environ['CXX_target'] = os.path.join(ndk_bin_dir, '%s-g++' % arch_triplet) + # Unlike the Clang build, when using GCC with “unified headers,” + # __ANDROID_API__ isn’t set automatically and must be pushed in to the + # build. Fish the correct value out of the Clang wrapper script. If unified + # headers are not being used, the Clang wrapper won’t mention + # __ANDROID_API__, but the standalone toolchain’s will + # #define it for both Clang and GCC. + # + # Unified headers are the way of the future, according to + # https://android.googlesource.com/platform/ndk/+/ndk-r14/CHANGELOG.md and + # https://android.googlesource.com/platform/ndk/+/master/docs/UnifiedHeaders.md. + with open(clang_path, 'r') as file: + clang_script_contents = file.read() + matches = re.finditer(r'\s-D__ANDROID_API__=([\d]+)\s', + clang_script_contents) + match = next(matches, None) + if match: + android_api = int(match.group(1)) + extra_args.extend(['-D', 'android_api_level=%d' % android_api]) + if next(matches, None): + raise AssertionError('__ANDROID_API__ defined too many times') + for tool in ('ar', 'nm', 'readelf'): os.environ['%s_target' % tool.upper()] = ( os.path.join(ndk_bin_dir, '%s-%s' % (arch_triplet, tool))) @@ -72,7 +98,9 @@ def main(args): ['-D', 'OS=android', '-D', 'target_arch=%s' % arch, '-D', 'clang=%d' % (1 if parsed.compiler == 'clang' else 0), - '-f', 'ninja-android'] + extra_args) + '-f', 'ninja-android'] + + extra_args + + extra_command_line_args) if __name__ == '__main__': diff --git a/build/run_tests.py b/build/run_tests.py index 00b40f6b..c5cbb03b 100755 --- a/build/run_tests.py +++ b/build/run_tests.py @@ -38,6 +38,11 @@ def main(args): 'crashpad_test_test', 'crashpad_util_test', ] + + if sys.platform == 'win32': + tests.append('crashpad_handler_test') + tests = sorted(tests) + for test in tests: print '-' * 80 print test diff --git a/client/capture_context_mac_test.cc b/client/capture_context_mac_test.cc index 1904b2b6..ca52961e 100644 --- a/client/capture_context_mac_test.cc +++ b/client/capture_context_mac_test.cc @@ -35,11 +35,11 @@ namespace { // gtest assertions. void SanityCheckContext(const NativeCPUContext& context) { #if defined(ARCH_CPU_X86) - ASSERT_EQ(x86_THREAD_STATE32, context.tsh.flavor); - ASSERT_EQ(implicit_cast(x86_THREAD_STATE32_COUNT), context.tsh.count); + ASSERT_EQ(context.tsh.flavor, x86_THREAD_STATE32); + ASSERT_EQ(context.tsh.count, implicit_cast(x86_THREAD_STATE32_COUNT)); #elif defined(ARCH_CPU_X86_64) - ASSERT_EQ(x86_THREAD_STATE64, context.tsh.flavor); - ASSERT_EQ(implicit_cast(x86_THREAD_STATE64_COUNT), context.tsh.count); + ASSERT_EQ(context.tsh.flavor, x86_THREAD_STATE64); + ASSERT_EQ(context.tsh.count, implicit_cast(x86_THREAD_STATE64_COUNT)); #endif #if defined(ARCH_CPU_X86_FAMILY) @@ -57,18 +57,18 @@ void SanityCheckContext(const NativeCPUContext& context) { // 3.4.3 “EFLAGS Register”, and AMD Architecture Programmer’s Manual, Volume // 2: System Programming (24593-3.24), 3.1.6 “RFLAGS Register”. #if defined(ARCH_CPU_X86) - EXPECT_EQ(0u, context.uts.ts32.__cs & ~0xffff); - EXPECT_EQ(0u, context.uts.ts32.__ds & ~0xffff); - EXPECT_EQ(0u, context.uts.ts32.__es & ~0xffff); - EXPECT_EQ(0u, context.uts.ts32.__fs & ~0xffff); - EXPECT_EQ(0u, context.uts.ts32.__gs & ~0xffff); - EXPECT_EQ(0u, context.uts.ts32.__ss & ~0xffff); - EXPECT_EQ(2u, context.uts.ts32.__eflags & 0xffc0802a); + EXPECT_EQ(context.uts.ts32.__cs & ~0xffff, 0u); + EXPECT_EQ(context.uts.ts32.__ds & ~0xffff, 0u); + EXPECT_EQ(context.uts.ts32.__es & ~0xffff, 0u); + EXPECT_EQ(context.uts.ts32.__fs & ~0xffff, 0u); + EXPECT_EQ(context.uts.ts32.__gs & ~0xffff, 0u); + EXPECT_EQ(context.uts.ts32.__ss & ~0xffff, 0u); + EXPECT_EQ(context.uts.ts32.__eflags & 0xffc0802a, 2u); #elif defined(ARCH_CPU_X86_64) - EXPECT_EQ(0u, context.uts.ts64.__cs & ~UINT64_C(0xffff)); - EXPECT_EQ(0u, context.uts.ts64.__fs & ~UINT64_C(0xffff)); - EXPECT_EQ(0u, context.uts.ts64.__gs & ~UINT64_C(0xffff)); - EXPECT_EQ(2u, context.uts.ts64.__rflags & UINT64_C(0xffffffffffc0802a)); + EXPECT_EQ(context.uts.ts64.__cs & ~UINT64_C(0xffff), 0u); + EXPECT_EQ(context.uts.ts64.__fs & ~UINT64_C(0xffff), 0u); + EXPECT_EQ(context.uts.ts64.__gs & ~UINT64_C(0xffff), 0u); + EXPECT_EQ(context.uts.ts64.__rflags & UINT64_C(0xffffffffffc0802a), 2u); #endif #endif } @@ -141,7 +141,7 @@ void TestCaptureContext() { ASSERT_NO_FATAL_FAILURE(SanityCheckContext(context_2)); } - EXPECT_EQ(sp, StackPointerFromContext(context_2)); + EXPECT_EQ(StackPointerFromContext(context_2), sp); EXPECT_GT(ProgramCounterFromContext(context_2), pc); } diff --git a/client/client_test.gyp b/client/client_test.gyp index dec8f603..ffafcdbd 100644 --- a/client/client_test.gyp +++ b/client/client_test.gyp @@ -22,6 +22,7 @@ 'type': 'executable', 'dependencies': [ 'client.gyp:crashpad_client', + '../compat/compat.gyp:crashpad_compat', '../handler/handler.gyp:crashpad_handler', '../test/test.gyp:crashpad_gmock_main', '../test/test.gyp:crashpad_test', diff --git a/client/crash_report_database.h b/client/crash_report_database.h index 3768cb23..62117899 100644 --- a/client/crash_report_database.h +++ b/client/crash_report_database.h @@ -144,6 +144,11 @@ class CrashReportDatabase { kNoError = 0, //! \brief The report that was requested could not be located. + //! + //! This may occur when the report is present in the database but not in a + //! state appropriate for the requested operation, for example, if + //! GetReportForUploading() is called to obtain report that’s already in the + //! completed state. kReportNotFound, //! \brief An error occured while performing a file operation on a crash diff --git a/client/crash_report_database_mac.mm b/client/crash_report_database_mac.mm index 0d074cba..3cc2d7fe 100644 --- a/client/crash_report_database_mac.mm +++ b/client/crash_report_database_mac.mm @@ -17,6 +17,7 @@ #include #include #import +#include #include #include #include @@ -146,6 +147,17 @@ class CrashReportDatabaseMac : public CrashReportDatabase { OperationStatus RequestUpload(const UUID& uuid) override; private: + //! \brief Report states for use with LocateCrashReport(). + //! + //! ReportState may be considered to be a bitfield. + enum ReportState : uint8_t { + kReportStateWrite = 1 << 0, // in kWriteDirectory + kReportStatePending = 1 << 1, // in kUploadPendingDirectory + kReportStateCompleted = 1 << 2, // in kCompletedDirectory + kReportStateAny = + kReportStateWrite | kReportStatePending | kReportStateCompleted, + }; + //! \brief A private extension of the Report class that maintains bookkeeping //! information of the database. struct UploadReport : public Report { @@ -157,10 +169,12 @@ class CrashReportDatabaseMac : public CrashReportDatabase { //! \brief Locates a crash report in the database by UUID. //! //! \param[in] uuid The UUID of the crash report to locate. + //! \param[in] desired_state The state of the report to locate, composed of + //! ReportState values. //! //! \return The full path to the report file, or an empty path if it cannot be //! found. - base::FilePath LocateCrashReport(const UUID& uuid); + base::FilePath LocateCrashReport(const UUID& uuid, uint8_t desired_state); //! \brief Obtains an exclusive advisory lock on a file. //! @@ -392,7 +406,7 @@ CrashReportDatabaseMac::LookUpCrashReport(const UUID& uuid, CrashReportDatabase::Report* report) { INITIALIZATION_STATE_DCHECK_VALID(initialized_); - base::FilePath path = LocateCrashReport(uuid); + base::FilePath path = LocateCrashReport(uuid, kReportStateAny); if (path.empty()) return kReportNotFound; @@ -429,7 +443,7 @@ CrashReportDatabaseMac::GetReportForUploading(const UUID& uuid, const Report** report) { INITIALIZATION_STATE_DCHECK_VALID(initialized_); - base::FilePath report_path = LocateCrashReport(uuid); + base::FilePath report_path = LocateCrashReport(uuid, kReportStatePending); if (report_path.empty()) return kReportNotFound; @@ -459,7 +473,8 @@ CrashReportDatabaseMac::RecordUploadAttempt(const Report* report, DCHECK(report); DCHECK(successful || id.empty()); - base::FilePath report_path = LocateCrashReport(report->uuid); + base::FilePath report_path = + LocateCrashReport(report->uuid, kReportStatePending); if (report_path.empty()) return kReportNotFound; @@ -513,7 +528,7 @@ CrashReportDatabase::OperationStatus CrashReportDatabaseMac::SkipReportUpload( Metrics::CrashUploadSkipped(reason); - base::FilePath report_path = LocateCrashReport(uuid); + base::FilePath report_path = LocateCrashReport(uuid, kReportStatePending); if (report_path.empty()) return kReportNotFound; @@ -528,7 +543,7 @@ CrashReportDatabase::OperationStatus CrashReportDatabaseMac::DeleteReport( const UUID& uuid) { INITIALIZATION_STATE_DCHECK_VALID(initialized_); - base::FilePath report_path = LocateCrashReport(uuid); + base::FilePath report_path = LocateCrashReport(uuid, kReportStateAny); if (report_path.empty()) return kReportNotFound; @@ -544,11 +559,25 @@ CrashReportDatabase::OperationStatus CrashReportDatabaseMac::DeleteReport( return kNoError; } -base::FilePath CrashReportDatabaseMac::LocateCrashReport(const UUID& uuid) { +base::FilePath CrashReportDatabaseMac::LocateCrashReport( + const UUID& uuid, + uint8_t desired_state) { const std::string target_uuid = uuid.ToString(); - for (size_t i = 0; i < arraysize(kReportDirectories); ++i) { + + std::vector report_directories; + if (desired_state & kReportStateWrite) { + report_directories.push_back(kWriteDirectory); + } + if (desired_state & kReportStatePending) { + report_directories.push_back(kUploadPendingDirectory); + } + if (desired_state & kReportStateCompleted) { + report_directories.push_back(kCompletedDirectory); + } + + for (const std::string& report_directory : report_directories) { base::FilePath path = - base_dir_.Append(kReportDirectories[i]) + base_dir_.Append(report_directory) .Append(target_uuid + "." + kCrashReportFileExtension); // Test if the path exists. @@ -573,7 +602,8 @@ CrashReportDatabase::OperationStatus CrashReportDatabaseMac::RequestUpload( const UUID& uuid) { INITIALIZATION_STATE_DCHECK_VALID(initialized_); - base::FilePath report_path = LocateCrashReport(uuid); + base::FilePath report_path = + LocateCrashReport(uuid, kReportStatePending | kReportStateCompleted); if (report_path.empty()) return kReportNotFound; diff --git a/client/crash_report_database_test.cc b/client/crash_report_database_test.cc index 72804643..da44ebfb 100644 --- a/client/crash_report_database_test.cc +++ b/client/crash_report_database_test.cc @@ -49,17 +49,17 @@ class CrashReportDatabaseTest : public testing::Test { void CreateCrashReport(CrashReportDatabase::Report* report) { CrashReportDatabase::NewReport* new_report = nullptr; - ASSERT_EQ(CrashReportDatabase::kNoError, - db_->PrepareNewCrashReport(&new_report)); + ASSERT_EQ(db_->PrepareNewCrashReport(&new_report), + CrashReportDatabase::kNoError); const char kTest[] = "test"; ASSERT_TRUE(LoggingWriteFile(new_report->handle, kTest, sizeof(kTest))); UUID uuid; - EXPECT_EQ(CrashReportDatabase::kNoError, - db_->FinishedWritingCrashReport(new_report, &uuid)); + EXPECT_EQ(db_->FinishedWritingCrashReport(new_report, &uuid), + CrashReportDatabase::kNoError); - EXPECT_EQ(CrashReportDatabase::kNoError, - db_->LookUpCrashReport(uuid, report)); + EXPECT_EQ(db_->LookUpCrashReport(uuid, report), + CrashReportDatabase::kNoError); ExpectPreparedCrashReport(*report); ASSERT_TRUE(FileExists(report->file_path)); } @@ -71,14 +71,14 @@ class CrashReportDatabaseTest : public testing::Test { ASSERT_TRUE(settings->GetLastUploadAttemptTime(×[0])); const CrashReportDatabase::Report* report = nullptr; - ASSERT_EQ(CrashReportDatabase::kNoError, - db_->GetReportForUploading(uuid, &report)); - EXPECT_NE(UUID(), report->uuid); + ASSERT_EQ(db_->GetReportForUploading(uuid, &report), + CrashReportDatabase::kNoError); + EXPECT_NE(report->uuid, UUID()); EXPECT_FALSE(report->file_path.empty()); EXPECT_TRUE(FileExists(report->file_path)) << report->file_path.value(); EXPECT_GT(report->creation_time, 0); - EXPECT_EQ(CrashReportDatabase::kNoError, - db_->RecordUploadAttempt(report, successful, id)); + EXPECT_EQ(db_->RecordUploadAttempt(report, successful, id), + CrashReportDatabase::kNoError); ASSERT_TRUE(settings->GetLastUploadAttemptTime(×[1])); EXPECT_NE(times[1], 0); @@ -86,14 +86,14 @@ class CrashReportDatabaseTest : public testing::Test { } void ExpectPreparedCrashReport(const CrashReportDatabase::Report& report) { - EXPECT_NE(UUID(), report.uuid); + EXPECT_NE(report.uuid, UUID()); EXPECT_FALSE(report.file_path.empty()); EXPECT_TRUE(FileExists(report.file_path)) << report.file_path.value(); EXPECT_TRUE(report.id.empty()); EXPECT_GT(report.creation_time, 0); EXPECT_FALSE(report.uploaded); - EXPECT_EQ(0, report.last_upload_attempt_time); - EXPECT_EQ(0, report.upload_attempts); + EXPECT_EQ(report.last_upload_attempt_time, 0); + EXPECT_EQ(report.upload_attempts, 0); EXPECT_FALSE(report.upload_explicitly_requested); } @@ -107,8 +107,8 @@ class CrashReportDatabaseTest : public testing::Test { CrashReportDatabase::OperationStatus os = db()->RequestUpload(uuid); CrashReportDatabase::Report report; - EXPECT_EQ(CrashReportDatabase::kNoError, - db_->LookUpCrashReport(uuid, &report)); + EXPECT_EQ(db_->LookUpCrashReport(uuid, &report), + CrashReportDatabase::kNoError); return os; } @@ -132,7 +132,7 @@ TEST_F(CrashReportDatabaseTest, Initialize) { time_t last_upload_attempt_time; ASSERT_TRUE(settings->GetLastUploadAttemptTime(&last_upload_attempt_time)); - EXPECT_EQ(0, last_upload_attempt_time); + EXPECT_EQ(last_upload_attempt_time, 0); // Close and reopen the database at the same path. ResetDatabase(); @@ -143,10 +143,10 @@ TEST_F(CrashReportDatabaseTest, Initialize) { settings = db->GetSettings(); ASSERT_TRUE(settings->GetClientID(&client_ids[1])); - EXPECT_EQ(client_ids[0], client_ids[1]); + EXPECT_EQ(client_ids[1], client_ids[0]); ASSERT_TRUE(settings->GetLastUploadAttemptTime(&last_upload_attempt_time)); - EXPECT_EQ(0, last_upload_attempt_time); + EXPECT_EQ(last_upload_attempt_time, 0); // Check that the database can also be opened by the method that is permitted // to create it. @@ -156,16 +156,16 @@ TEST_F(CrashReportDatabaseTest, Initialize) { settings = db->GetSettings(); ASSERT_TRUE(settings->GetClientID(&client_ids[2])); - EXPECT_EQ(client_ids[0], client_ids[2]); + EXPECT_EQ(client_ids[2], client_ids[0]); ASSERT_TRUE(settings->GetLastUploadAttemptTime(&last_upload_attempt_time)); - EXPECT_EQ(0, last_upload_attempt_time); + EXPECT_EQ(last_upload_attempt_time, 0); std::vector reports; - EXPECT_EQ(CrashReportDatabase::kNoError, db->GetPendingReports(&reports)); + EXPECT_EQ(db->GetPendingReports(&reports), CrashReportDatabase::kNoError); EXPECT_TRUE(reports.empty()); reports.clear(); - EXPECT_EQ(CrashReportDatabase::kNoError, db->GetCompletedReports(&reports)); + EXPECT_EQ(db->GetCompletedReports(&reports), CrashReportDatabase::kNoError); EXPECT_TRUE(reports.empty()); // InitializeWithoutCreating() shouldn’t create a nonexistent database. @@ -177,38 +177,38 @@ TEST_F(CrashReportDatabaseTest, Initialize) { TEST_F(CrashReportDatabaseTest, NewCrashReport) { CrashReportDatabase::NewReport* new_report; - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->PrepareNewCrashReport(&new_report)); + EXPECT_EQ(db()->PrepareNewCrashReport(&new_report), + CrashReportDatabase::kNoError); UUID expect_uuid = new_report->uuid; EXPECT_TRUE(FileExists(new_report->path)) << new_report->path.value(); UUID uuid; - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->FinishedWritingCrashReport(new_report, &uuid)); - EXPECT_EQ(expect_uuid, uuid); + EXPECT_EQ(db()->FinishedWritingCrashReport(new_report, &uuid), + CrashReportDatabase::kNoError); + EXPECT_EQ(uuid, expect_uuid); CrashReportDatabase::Report report; - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->LookUpCrashReport(uuid, &report)); + EXPECT_EQ(db()->LookUpCrashReport(uuid, &report), + CrashReportDatabase::kNoError); ExpectPreparedCrashReport(report); std::vector reports; - EXPECT_EQ(CrashReportDatabase::kNoError, db()->GetPendingReports(&reports)); - ASSERT_EQ(1u, reports.size()); - EXPECT_EQ(report.uuid, reports[0].uuid); + EXPECT_EQ(db()->GetPendingReports(&reports), CrashReportDatabase::kNoError); + ASSERT_EQ(reports.size(), 1u); + EXPECT_EQ(reports[0].uuid, report.uuid); reports.clear(); - EXPECT_EQ(CrashReportDatabase::kNoError, db()->GetCompletedReports(&reports)); + EXPECT_EQ(db()->GetCompletedReports(&reports), CrashReportDatabase::kNoError); EXPECT_TRUE(reports.empty()); } TEST_F(CrashReportDatabaseTest, ErrorWritingCrashReport) { CrashReportDatabase::NewReport* new_report = nullptr; - ASSERT_EQ(CrashReportDatabase::kNoError, - db()->PrepareNewCrashReport(&new_report)); + ASSERT_EQ(db()->PrepareNewCrashReport(&new_report), + CrashReportDatabase::kNoError); base::FilePath new_report_path = new_report->path; EXPECT_TRUE(FileExists(new_report_path)) << new_report_path.value(); - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->ErrorWritingCrashReport(new_report)); + EXPECT_EQ(db()->ErrorWritingCrashReport(new_report), + CrashReportDatabase::kNoError); EXPECT_FALSE(FileExists(new_report_path)) << new_report_path.value(); } @@ -223,14 +223,14 @@ TEST_F(CrashReportDatabaseTest, LookUpCrashReport) { { CrashReportDatabase::Report report; - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->LookUpCrashReport(uuid, &report)); - EXPECT_EQ(uuid, report.uuid); - EXPECT_NE(std::string::npos, report.file_path.value().find(path().value())); - EXPECT_EQ(std::string(), report.id); + EXPECT_EQ(db()->LookUpCrashReport(uuid, &report), + CrashReportDatabase::kNoError); + EXPECT_EQ(report.uuid, uuid); + EXPECT_NE(report.file_path.value().find(path().value()), std::string::npos); + EXPECT_EQ(report.id, std::string()); EXPECT_FALSE(report.uploaded); - EXPECT_EQ(0, report.last_upload_attempt_time); - EXPECT_EQ(0, report.upload_attempts); + EXPECT_EQ(report.last_upload_attempt_time, 0); + EXPECT_EQ(report.upload_attempts, 0); EXPECT_FALSE(report.upload_explicitly_requested); } @@ -238,14 +238,14 @@ TEST_F(CrashReportDatabaseTest, LookUpCrashReport) { { CrashReportDatabase::Report report; - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->LookUpCrashReport(uuid, &report)); - EXPECT_EQ(uuid, report.uuid); - EXPECT_NE(std::string::npos, report.file_path.value().find(path().value())); - EXPECT_EQ("test", report.id); + EXPECT_EQ(db()->LookUpCrashReport(uuid, &report), + CrashReportDatabase::kNoError); + EXPECT_EQ(report.uuid, uuid); + EXPECT_NE(report.file_path.value().find(path().value()), std::string::npos); + EXPECT_EQ(report.id, "test"); EXPECT_TRUE(report.uploaded); - EXPECT_NE(0, report.last_upload_attempt_time); - EXPECT_EQ(1, report.upload_attempts); + EXPECT_NE(report.last_upload_attempt_time, 0); + EXPECT_EQ(report.upload_attempts, 1); EXPECT_FALSE(report.upload_explicitly_requested); } } @@ -261,76 +261,76 @@ TEST_F(CrashReportDatabaseTest, RecordUploadAttempt) { UploadReport(reports[2].uuid, true, "abc123"); std::vector query(3); - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->LookUpCrashReport(reports[0].uuid, &query[0])); - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->LookUpCrashReport(reports[1].uuid, &query[1])); - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->LookUpCrashReport(reports[2].uuid, &query[2])); + EXPECT_EQ(db()->LookUpCrashReport(reports[0].uuid, &query[0]), + CrashReportDatabase::kNoError); + EXPECT_EQ(db()->LookUpCrashReport(reports[1].uuid, &query[1]), + CrashReportDatabase::kNoError); + EXPECT_EQ(db()->LookUpCrashReport(reports[2].uuid, &query[2]), + CrashReportDatabase::kNoError); - EXPECT_EQ(std::string(), query[0].id); - EXPECT_EQ(std::string(), query[1].id); - EXPECT_EQ("abc123", query[2].id); + EXPECT_EQ(query[0].id, std::string()); + EXPECT_EQ(query[1].id, std::string()); + EXPECT_EQ(query[2].id, "abc123"); EXPECT_FALSE(query[0].uploaded); EXPECT_FALSE(query[1].uploaded); EXPECT_TRUE(query[2].uploaded); - EXPECT_EQ(0, query[0].last_upload_attempt_time); - EXPECT_NE(0, query[1].last_upload_attempt_time); - EXPECT_NE(0, query[2].last_upload_attempt_time); + EXPECT_EQ(query[0].last_upload_attempt_time, 0); + EXPECT_NE(query[1].last_upload_attempt_time, 0); + EXPECT_NE(query[2].last_upload_attempt_time, 0); - EXPECT_EQ(0, query[0].upload_attempts); - EXPECT_EQ(1, query[1].upload_attempts); - EXPECT_EQ(1, query[2].upload_attempts); + EXPECT_EQ(query[0].upload_attempts, 0); + EXPECT_EQ(query[1].upload_attempts, 1); + EXPECT_EQ(query[2].upload_attempts, 1); // Attempt to upload and fail again. UploadReport(reports[1].uuid, false, std::string()); time_t report_2_upload_time = query[2].last_upload_attempt_time; - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->LookUpCrashReport(reports[0].uuid, &query[0])); - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->LookUpCrashReport(reports[1].uuid, &query[1])); - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->LookUpCrashReport(reports[2].uuid, &query[2])); + EXPECT_EQ(db()->LookUpCrashReport(reports[0].uuid, &query[0]), + CrashReportDatabase::kNoError); + EXPECT_EQ(db()->LookUpCrashReport(reports[1].uuid, &query[1]), + CrashReportDatabase::kNoError); + EXPECT_EQ(db()->LookUpCrashReport(reports[2].uuid, &query[2]), + CrashReportDatabase::kNoError); EXPECT_FALSE(query[0].uploaded); EXPECT_FALSE(query[1].uploaded); EXPECT_TRUE(query[2].uploaded); - EXPECT_EQ(0, query[0].last_upload_attempt_time); + EXPECT_EQ(query[0].last_upload_attempt_time, 0); EXPECT_GE(query[1].last_upload_attempt_time, report_2_upload_time); - EXPECT_EQ(report_2_upload_time, query[2].last_upload_attempt_time); + EXPECT_EQ(query[2].last_upload_attempt_time, report_2_upload_time); - EXPECT_EQ(0, query[0].upload_attempts); - EXPECT_EQ(2, query[1].upload_attempts); - EXPECT_EQ(1, query[2].upload_attempts); + EXPECT_EQ(query[0].upload_attempts, 0); + EXPECT_EQ(query[1].upload_attempts, 2); + EXPECT_EQ(query[2].upload_attempts, 1); // Third time's the charm: upload and succeed. UploadReport(reports[1].uuid, true, "666hahaha"); time_t report_1_upload_time = query[1].last_upload_attempt_time; - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->LookUpCrashReport(reports[0].uuid, &query[0])); - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->LookUpCrashReport(reports[1].uuid, &query[1])); - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->LookUpCrashReport(reports[2].uuid, &query[2])); + EXPECT_EQ(db()->LookUpCrashReport(reports[0].uuid, &query[0]), + CrashReportDatabase::kNoError); + EXPECT_EQ(db()->LookUpCrashReport(reports[1].uuid, &query[1]), + CrashReportDatabase::kNoError); + EXPECT_EQ(db()->LookUpCrashReport(reports[2].uuid, &query[2]), + CrashReportDatabase::kNoError); EXPECT_FALSE(query[0].uploaded); EXPECT_TRUE(query[1].uploaded); EXPECT_TRUE(query[2].uploaded); - EXPECT_EQ(0, query[0].last_upload_attempt_time); + EXPECT_EQ(query[0].last_upload_attempt_time, 0); EXPECT_GE(query[1].last_upload_attempt_time, report_1_upload_time); - EXPECT_EQ(report_2_upload_time, query[2].last_upload_attempt_time); + EXPECT_EQ(query[2].last_upload_attempt_time, report_2_upload_time); - EXPECT_EQ(0, query[0].upload_attempts); - EXPECT_EQ(3, query[1].upload_attempts); - EXPECT_EQ(1, query[2].upload_attempts); + EXPECT_EQ(query[0].upload_attempts, 0); + EXPECT_EQ(query[1].upload_attempts, 3); + EXPECT_EQ(query[2].upload_attempts, 1); } // This test covers both query functions since they are related. @@ -349,52 +349,52 @@ TEST_F(CrashReportDatabaseTest, GetCompletedAndNotUploadedReports) { const UUID& report_4_uuid = reports[4].uuid; std::vector pending; - EXPECT_EQ(CrashReportDatabase::kNoError, db()->GetPendingReports(&pending)); + EXPECT_EQ(db()->GetPendingReports(&pending), CrashReportDatabase::kNoError); std::vector completed; - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->GetCompletedReports(&completed)); + EXPECT_EQ(db()->GetCompletedReports(&completed), + CrashReportDatabase::kNoError); - EXPECT_EQ(reports.size(), pending.size()); - EXPECT_EQ(0u, completed.size()); + EXPECT_EQ(pending.size(), reports.size()); + EXPECT_EQ(completed.size(), 0u); // Upload one report successfully. UploadReport(report_1_uuid, true, "report1"); pending.clear(); - EXPECT_EQ(CrashReportDatabase::kNoError, db()->GetPendingReports(&pending)); + EXPECT_EQ(db()->GetPendingReports(&pending), CrashReportDatabase::kNoError); completed.clear(); - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->GetCompletedReports(&completed)); + EXPECT_EQ(db()->GetCompletedReports(&completed), + CrashReportDatabase::kNoError); - EXPECT_EQ(4u, pending.size()); - ASSERT_EQ(1u, completed.size()); + EXPECT_EQ(pending.size(), 4u); + ASSERT_EQ(completed.size(), 1u); for (const auto& report : pending) { - EXPECT_NE(report_1_uuid, report.uuid); + EXPECT_NE(report.uuid, report_1_uuid); EXPECT_FALSE(report.file_path.empty()); } - EXPECT_EQ(report_1_uuid, completed[0].uuid); - EXPECT_EQ("report1", completed[0].id); - EXPECT_EQ(true, completed[0].uploaded); + EXPECT_EQ(completed[0].uuid, report_1_uuid); + EXPECT_EQ(completed[0].id, "report1"); + EXPECT_EQ(completed[0].uploaded, true); EXPECT_GT(completed[0].last_upload_attempt_time, 0); - EXPECT_EQ(1, completed[0].upload_attempts); + EXPECT_EQ(completed[0].upload_attempts, 1); // Fail to upload one report. UploadReport(report_2_uuid, false, std::string()); pending.clear(); - EXPECT_EQ(CrashReportDatabase::kNoError, db()->GetPendingReports(&pending)); + EXPECT_EQ(db()->GetPendingReports(&pending), CrashReportDatabase::kNoError); completed.clear(); - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->GetCompletedReports(&completed)); + EXPECT_EQ(db()->GetCompletedReports(&completed), + CrashReportDatabase::kNoError); - EXPECT_EQ(4u, pending.size()); - ASSERT_EQ(1u, completed.size()); + EXPECT_EQ(pending.size(), 4u); + ASSERT_EQ(completed.size(), 1u); for (const auto& report : pending) { if (report.upload_attempts != 0) { - EXPECT_EQ(report_2_uuid, report.uuid); + EXPECT_EQ(report.uuid, report_2_uuid); EXPECT_GT(report.last_upload_attempt_time, 0); EXPECT_FALSE(report.uploaded); EXPECT_TRUE(report.id.empty()); @@ -406,25 +406,25 @@ TEST_F(CrashReportDatabaseTest, GetCompletedAndNotUploadedReports) { UploadReport(report_4_uuid, true, "report_4"); pending.clear(); - EXPECT_EQ(CrashReportDatabase::kNoError, db()->GetPendingReports(&pending)); + EXPECT_EQ(db()->GetPendingReports(&pending), CrashReportDatabase::kNoError); completed.clear(); - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->GetCompletedReports(&completed)); + EXPECT_EQ(db()->GetCompletedReports(&completed), + CrashReportDatabase::kNoError); - EXPECT_EQ(3u, pending.size()); - ASSERT_EQ(2u, completed.size()); + EXPECT_EQ(pending.size(), 3u); + ASSERT_EQ(completed.size(), 2u); // Succeed the failed report. UploadReport(report_2_uuid, true, "report 2"); pending.clear(); - EXPECT_EQ(CrashReportDatabase::kNoError, db()->GetPendingReports(&pending)); + EXPECT_EQ(db()->GetPendingReports(&pending), CrashReportDatabase::kNoError); completed.clear(); - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->GetCompletedReports(&completed)); + EXPECT_EQ(db()->GetCompletedReports(&completed), + CrashReportDatabase::kNoError); - EXPECT_EQ(2u, pending.size()); - ASSERT_EQ(3u, completed.size()); + EXPECT_EQ(pending.size(), 2u); + ASSERT_EQ(completed.size(), 3u); for (const auto& report : pending) { EXPECT_TRUE(report.uuid == report_0_uuid || report.uuid == report_3_uuid); @@ -432,26 +432,26 @@ TEST_F(CrashReportDatabaseTest, GetCompletedAndNotUploadedReports) { } // Skip upload for one report. - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->SkipReportUpload( - report_3_uuid, Metrics::CrashSkippedReason::kUploadsDisabled)); + EXPECT_EQ(db()->SkipReportUpload( + report_3_uuid, Metrics::CrashSkippedReason::kUploadsDisabled), + CrashReportDatabase::kNoError); pending.clear(); - EXPECT_EQ(CrashReportDatabase::kNoError, db()->GetPendingReports(&pending)); + EXPECT_EQ(db()->GetPendingReports(&pending), CrashReportDatabase::kNoError); completed.clear(); - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->GetCompletedReports(&completed)); + EXPECT_EQ(db()->GetCompletedReports(&completed), + CrashReportDatabase::kNoError); - ASSERT_EQ(1u, pending.size()); - ASSERT_EQ(4u, completed.size()); + ASSERT_EQ(pending.size(), 1u); + ASSERT_EQ(completed.size(), 4u); - EXPECT_EQ(report_0_uuid, pending[0].uuid); + EXPECT_EQ(pending[0].uuid, report_0_uuid); for (const auto& report : completed) { if (report.uuid == report_3_uuid) { EXPECT_FALSE(report.uploaded); - EXPECT_EQ(0, report.upload_attempts); - EXPECT_EQ(0, report.last_upload_attempt_time); + EXPECT_EQ(report.upload_attempts, 0); + EXPECT_EQ(report.last_upload_attempt_time, 0); } else { EXPECT_TRUE(report.uploaded); EXPECT_GT(report.upload_attempts, 0); @@ -466,58 +466,74 @@ TEST_F(CrashReportDatabaseTest, DuelingUploads) { CreateCrashReport(&report); const CrashReportDatabase::Report* upload_report; - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->GetReportForUploading(report.uuid, &upload_report)); + EXPECT_EQ(db()->GetReportForUploading(report.uuid, &upload_report), + CrashReportDatabase::kNoError); const CrashReportDatabase::Report* upload_report_2 = nullptr; - EXPECT_EQ(CrashReportDatabase::kBusyError, - db()->GetReportForUploading(report.uuid, &upload_report_2)); + EXPECT_EQ(db()->GetReportForUploading(report.uuid, &upload_report_2), + CrashReportDatabase::kBusyError); EXPECT_FALSE(upload_report_2); - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->RecordUploadAttempt(upload_report, true, std::string())); + EXPECT_EQ(db()->RecordUploadAttempt(upload_report, true, std::string()), + CrashReportDatabase::kNoError); +} + +TEST_F(CrashReportDatabaseTest, UploadAlreadyUploaded) { + CrashReportDatabase::Report report; + CreateCrashReport(&report); + + const CrashReportDatabase::Report* upload_report; + EXPECT_EQ(db()->GetReportForUploading(report.uuid, &upload_report), + CrashReportDatabase::kNoError); + EXPECT_EQ(db()->RecordUploadAttempt(upload_report, true, std::string()), + CrashReportDatabase::kNoError); + + const CrashReportDatabase::Report* upload_report_2 = nullptr; + EXPECT_EQ(db()->GetReportForUploading(report.uuid, &upload_report_2), + CrashReportDatabase::kReportNotFound); + EXPECT_FALSE(upload_report_2); } TEST_F(CrashReportDatabaseTest, MoveDatabase) { CrashReportDatabase::NewReport* new_report; - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->PrepareNewCrashReport(&new_report)); + EXPECT_EQ(db()->PrepareNewCrashReport(&new_report), + CrashReportDatabase::kNoError); EXPECT_TRUE(FileExists(new_report->path)) << new_report->path.value(); UUID uuid; - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->FinishedWritingCrashReport(new_report, &uuid)); + EXPECT_EQ(db()->FinishedWritingCrashReport(new_report, &uuid), + CrashReportDatabase::kNoError); RelocateDatabase(); CrashReportDatabase::Report report; - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->LookUpCrashReport(uuid, &report)); + EXPECT_EQ(db()->LookUpCrashReport(uuid, &report), + CrashReportDatabase::kNoError); ExpectPreparedCrashReport(report); EXPECT_TRUE(FileExists(report.file_path)) << report.file_path.value(); } TEST_F(CrashReportDatabaseTest, ReportRemoved) { CrashReportDatabase::NewReport* new_report; - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->PrepareNewCrashReport(&new_report)); + EXPECT_EQ(db()->PrepareNewCrashReport(&new_report), + CrashReportDatabase::kNoError); EXPECT_TRUE(FileExists(new_report->path)) << new_report->path.value(); UUID uuid; - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->FinishedWritingCrashReport(new_report, &uuid)); + EXPECT_EQ(db()->FinishedWritingCrashReport(new_report, &uuid), + CrashReportDatabase::kNoError); CrashReportDatabase::Report report; - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->LookUpCrashReport(uuid, &report)); + EXPECT_EQ(db()->LookUpCrashReport(uuid, &report), + CrashReportDatabase::kNoError); #if defined(OS_WIN) - EXPECT_EQ(0, _wunlink(report.file_path.value().c_str())); + EXPECT_EQ(_wunlink(report.file_path.value().c_str()), 0); #else - EXPECT_EQ(0, unlink(report.file_path.value().c_str())) + EXPECT_EQ(unlink(report.file_path.value().c_str()), 0) << ErrnoMessage("unlink"); #endif - EXPECT_EQ(CrashReportDatabase::kReportNotFound, - db()->LookUpCrashReport(uuid, &report)); + EXPECT_EQ(db()->LookUpCrashReport(uuid, &report), + CrashReportDatabase::kReportNotFound); } TEST_F(CrashReportDatabaseTest, DeleteReport) { @@ -539,34 +555,34 @@ TEST_F(CrashReportDatabaseTest, DeleteReport) { UploadReport(keep_completed.uuid, true, "1"); UploadReport(delete_completed.uuid, true, "2"); - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->LookUpCrashReport(keep_completed.uuid, &keep_completed)); - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->LookUpCrashReport(delete_completed.uuid, &delete_completed)); + EXPECT_EQ(db()->LookUpCrashReport(keep_completed.uuid, &keep_completed), + CrashReportDatabase::kNoError); + EXPECT_EQ(db()->LookUpCrashReport(delete_completed.uuid, &delete_completed), + CrashReportDatabase::kNoError); EXPECT_TRUE(FileExists(keep_completed.file_path)); EXPECT_TRUE(FileExists(delete_completed.file_path)); - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->DeleteReport(delete_pending.uuid)); + EXPECT_EQ(db()->DeleteReport(delete_pending.uuid), + CrashReportDatabase::kNoError); EXPECT_FALSE(FileExists(delete_pending.file_path)); - EXPECT_EQ(CrashReportDatabase::kReportNotFound, - db()->LookUpCrashReport(delete_pending.uuid, &delete_pending)); - EXPECT_EQ(CrashReportDatabase::kReportNotFound, - db()->DeleteReport(delete_pending.uuid)); + EXPECT_EQ(db()->LookUpCrashReport(delete_pending.uuid, &delete_pending), + CrashReportDatabase::kReportNotFound); + EXPECT_EQ(db()->DeleteReport(delete_pending.uuid), + CrashReportDatabase::kReportNotFound); - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->DeleteReport(delete_completed.uuid)); + EXPECT_EQ(db()->DeleteReport(delete_completed.uuid), + CrashReportDatabase::kNoError); EXPECT_FALSE(FileExists(delete_completed.file_path)); - EXPECT_EQ(CrashReportDatabase::kReportNotFound, - db()->LookUpCrashReport(delete_completed.uuid, &delete_completed)); - EXPECT_EQ(CrashReportDatabase::kReportNotFound, - db()->DeleteReport(delete_completed.uuid)); + EXPECT_EQ(db()->LookUpCrashReport(delete_completed.uuid, &delete_completed), + CrashReportDatabase::kReportNotFound); + EXPECT_EQ(db()->DeleteReport(delete_completed.uuid), + CrashReportDatabase::kReportNotFound); - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->LookUpCrashReport(keep_pending.uuid, &keep_pending)); - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->LookUpCrashReport(keep_completed.uuid, &keep_completed)); + EXPECT_EQ(db()->LookUpCrashReport(keep_pending.uuid, &keep_pending), + CrashReportDatabase::kNoError); + EXPECT_EQ(db()->LookUpCrashReport(keep_completed.uuid, &keep_completed), + CrashReportDatabase::kNoError); } TEST_F(CrashReportDatabaseTest, DeleteReportEmptyingDatabase) { @@ -577,20 +593,20 @@ TEST_F(CrashReportDatabaseTest, DeleteReportEmptyingDatabase) { UploadReport(report.uuid, true, "1"); - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->LookUpCrashReport(report.uuid, &report)); + EXPECT_EQ(db()->LookUpCrashReport(report.uuid, &report), + CrashReportDatabase::kNoError); EXPECT_TRUE(FileExists(report.file_path)); // This causes an empty database to be written, make sure this is handled. - EXPECT_EQ(CrashReportDatabase::kNoError, db()->DeleteReport(report.uuid)); + EXPECT_EQ(db()->DeleteReport(report.uuid), CrashReportDatabase::kNoError); EXPECT_FALSE(FileExists(report.file_path)); } TEST_F(CrashReportDatabaseTest, ReadEmptyDatabase) { CrashReportDatabase::Report report; CreateCrashReport(&report); - EXPECT_EQ(CrashReportDatabase::kNoError, db()->DeleteReport(report.uuid)); + EXPECT_EQ(db()->DeleteReport(report.uuid), CrashReportDatabase::kNoError); // Deleting and the creating another report causes an empty database to be // loaded. Make sure this is handled. @@ -608,22 +624,22 @@ TEST_F(CrashReportDatabaseTest, RequestUpload) { const UUID& report_1_uuid = reports[1].uuid; // Skipped report gets back to pending state after RequestUpload is called. - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->SkipReportUpload( - report_1_uuid, Metrics::CrashSkippedReason::kUploadsDisabled)); + EXPECT_EQ(db()->SkipReportUpload( + report_1_uuid, Metrics::CrashSkippedReason::kUploadsDisabled), + CrashReportDatabase::kNoError); std::vector pending_reports; CrashReportDatabase::OperationStatus os = db()->GetPendingReports(&pending_reports); - EXPECT_EQ(CrashReportDatabase::kNoError, os); - ASSERT_EQ(1u, pending_reports.size()); - EXPECT_EQ(pending_reports[0].uuid, report_0_uuid); + EXPECT_EQ(os, CrashReportDatabase::kNoError); + ASSERT_EQ(pending_reports.size(), 1u); + EXPECT_EQ(report_0_uuid, pending_reports[0].uuid); pending_reports.clear(); - EXPECT_EQ(CrashReportDatabase::kNoError, RequestUpload(report_1_uuid)); + EXPECT_EQ(RequestUpload(report_1_uuid), CrashReportDatabase::kNoError); os = db()->GetPendingReports(&pending_reports); - EXPECT_EQ(CrashReportDatabase::kNoError, os); - ASSERT_EQ(2u, pending_reports.size()); + EXPECT_EQ(os, CrashReportDatabase::kNoError); + ASSERT_EQ(pending_reports.size(), 2u); // Check individual reports. const CrashReportDatabase::Report* expicitly_requested_report; @@ -636,35 +652,35 @@ TEST_F(CrashReportDatabaseTest, RequestUpload) { expicitly_requested_report = &pending_reports[0]; } - EXPECT_EQ(report_0_uuid, pending_report->uuid); + EXPECT_EQ(pending_report->uuid, report_0_uuid); EXPECT_FALSE(pending_report->upload_explicitly_requested); - EXPECT_EQ(report_1_uuid, expicitly_requested_report->uuid); + EXPECT_EQ(expicitly_requested_report->uuid, report_1_uuid); EXPECT_TRUE(expicitly_requested_report->upload_explicitly_requested); // Explicitly requested reports will not have upload_explicitly_requested bit // after getting skipped. - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->SkipReportUpload( - report_1_uuid, Metrics::CrashSkippedReason::kUploadsDisabled)); + EXPECT_EQ(db()->SkipReportUpload( + report_1_uuid, Metrics::CrashSkippedReason::kUploadsDisabled), + CrashReportDatabase::kNoError); CrashReportDatabase::Report report; - EXPECT_EQ(CrashReportDatabase::kNoError, - db()->LookUpCrashReport(report_1_uuid, &report)); + EXPECT_EQ(db()->LookUpCrashReport(report_1_uuid, &report), + CrashReportDatabase::kNoError); EXPECT_FALSE(report.upload_explicitly_requested); // Pending report gets correctly affected after RequestUpload is called. pending_reports.clear(); - EXPECT_EQ(CrashReportDatabase::kNoError, RequestUpload(report_0_uuid)); + EXPECT_EQ(RequestUpload(report_0_uuid), CrashReportDatabase::kNoError); os = db()->GetPendingReports(&pending_reports); - EXPECT_EQ(CrashReportDatabase::kNoError, os); - EXPECT_EQ(1u, pending_reports.size()); - EXPECT_EQ(pending_reports[0].uuid, report_0_uuid); + EXPECT_EQ(os, CrashReportDatabase::kNoError); + EXPECT_EQ(pending_reports.size(), 1u); + EXPECT_EQ(report_0_uuid, pending_reports[0].uuid); EXPECT_TRUE(pending_reports[0].upload_explicitly_requested); // Already uploaded report cannot be requested for the new upload. UploadReport(report_0_uuid, true, "1"); - EXPECT_EQ(CrashReportDatabase::kCannotRequestUpload, - RequestUpload(report_0_uuid)); + EXPECT_EQ(RequestUpload(report_0_uuid), + CrashReportDatabase::kCannotRequestUpload); } } // namespace diff --git a/client/crash_report_database_win.cc b/client/crash_report_database_win.cc index 6629d25d..a97b1cf0 100644 --- a/client/crash_report_database_win.cc +++ b/client/crash_report_database_win.cc @@ -242,8 +242,9 @@ class Metadata { //! written to disk via Write(). //! //! \return #kNoError on success. #kReportNotFound if there was no report with - //! the specified UUID. #kBusyError if the report was not in the specified - //! state. + //! the specified UUID, or if the report was not in the specified state + //! and was not uploading. #kBusyError if the report was not in the + //! specified state and was uploading. OperationStatus FindSingleReportAndMarkDirty(const UUID& uuid, ReportState desired_state, ReportDisk** report_disk); @@ -530,9 +531,13 @@ OperationStatus Metadata::VerifyReportAnyState(const ReportDisk& report_disk) { // static OperationStatus Metadata::VerifyReport(const ReportDisk& report_disk, ReportState desired_state) { - return (report_disk.state == desired_state) - ? VerifyReportAnyState(report_disk) - : CrashReportDatabase::kBusyError; + if (report_disk.state == desired_state) { + return VerifyReportAnyState(report_disk); + } + + return report_disk.state == ReportState::kUploading + ? CrashReportDatabase::kBusyError + : CrashReportDatabase::kReportNotFound; } bool EnsureDirectory(const base::FilePath& path) { @@ -876,7 +881,7 @@ OperationStatus CrashReportDatabaseWin::RequestUpload(const UUID& uuid) { // TODO(gayane): Search for the report only once regardless of its state. OperationStatus os = metadata->FindSingleReportAndMarkDirty( uuid, ReportState::kCompleted, &report_disk); - if (os == kBusyError) { + if (os == kReportNotFound) { os = metadata->FindSingleReportAndMarkDirty( uuid, ReportState::kPending, &report_disk); } diff --git a/client/crashpad_client_win_test.cc b/client/crashpad_client_win_test.cc index 47e7add9..7e5093f2 100644 --- a/client/crashpad_client_win_test.cc +++ b/client/crashpad_client_win_test.cc @@ -14,25 +14,31 @@ #include "client/crashpad_client.h" +#include + #include "base/files/file_path.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" +#include "base/logging.h" #include "gtest/gtest.h" -#include "test/paths.h" +#include "test/test_paths.h" #include "test/scoped_temp_dir.h" #include "test/win/win_multiprocess.h" +#include "test/win/win_multiprocess_with_temp_dir.h" +#include "util/win/scoped_handle.h" #include "util/win/termination_codes.h" namespace crashpad { namespace test { namespace { -void StartAndUseHandler() { - ScopedTempDir temp_dir; - base::FilePath handler_path = Paths::Executable().DirName().Append( +void StartAndUseHandler(const base::FilePath& temp_dir) { + base::FilePath handler_path = TestPaths::Executable().DirName().Append( FILE_PATH_LITERAL("crashpad_handler.com")); + CrashpadClient client; ASSERT_TRUE(client.StartHandler(handler_path, - temp_dir.path(), + temp_dir, base::FilePath(), "", std::map(), @@ -42,9 +48,9 @@ void StartAndUseHandler() { ASSERT_TRUE(client.WaitForHandlerStart(INFINITE)); } -class StartWithInvalidHandles final : public WinMultiprocess { +class StartWithInvalidHandles final : public WinMultiprocessWithTempDir { public: - StartWithInvalidHandles() : WinMultiprocess() {} + StartWithInvalidHandles() : WinMultiprocessWithTempDir() {} ~StartWithInvalidHandles() {} private: @@ -56,7 +62,7 @@ class StartWithInvalidHandles final : public WinMultiprocess { SetStdHandle(STD_OUTPUT_HANDLE, INVALID_HANDLE_VALUE); SetStdHandle(STD_ERROR_HANDLE, INVALID_HANDLE_VALUE); - StartAndUseHandler(); + StartAndUseHandler(GetTempDirPath()); SetStdHandle(STD_OUTPUT_HANDLE, original_stdout); SetStdHandle(STD_ERROR_HANDLE, original_stderr); @@ -64,12 +70,12 @@ class StartWithInvalidHandles final : public WinMultiprocess { }; TEST(CrashpadClient, StartWithInvalidHandles) { - WinMultiprocess::Run(); + WinMultiprocessWithTempDir::Run(); } -class StartWithSameStdoutStderr final : public WinMultiprocess { +class StartWithSameStdoutStderr final : public WinMultiprocessWithTempDir { public: - StartWithSameStdoutStderr() : WinMultiprocess() {} + StartWithSameStdoutStderr() : WinMultiprocessWithTempDir() {} ~StartWithSameStdoutStderr() {} private: @@ -80,19 +86,19 @@ class StartWithSameStdoutStderr final : public WinMultiprocess { HANDLE original_stderr = GetStdHandle(STD_ERROR_HANDLE); SetStdHandle(STD_OUTPUT_HANDLE, original_stderr); - StartAndUseHandler(); + StartAndUseHandler(GetTempDirPath()); SetStdHandle(STD_OUTPUT_HANDLE, original_stdout); } }; TEST(CrashpadClient, StartWithSameStdoutStderr) { - WinMultiprocess::Run(); + WinMultiprocessWithTempDir::Run(); } void StartAndUseBrokenHandler(CrashpadClient* client) { ScopedTempDir temp_dir; - base::FilePath handler_path = Paths::Executable().DirName().Append( + base::FilePath handler_path = TestPaths::Executable().DirName().Append( FILE_PATH_LITERAL("fake_handler_that_crashes_at_startup.exe")); ASSERT_TRUE(client->StartHandler(handler_path, temp_dir.path(), diff --git a/client/crashpad_info.h b/client/crashpad_info.h index 0462eaf9..77c9097a 100644 --- a/client/crashpad_info.h +++ b/client/crashpad_info.h @@ -96,10 +96,19 @@ struct CrashpadInfo { //! SimpleStringDictionary object. It is the caller’s responsibility to //! ensure that this pointer remains valid while it is in effect for a //! CrashpadInfo object. + //! + //! \sa simple_annotations() void set_simple_annotations(SimpleStringDictionary* simple_annotations) { simple_annotations_ = simple_annotations; } + //! \return The simple annotations dictionary. + //! + //! \sa set_simple_annotations() + SimpleStringDictionary* simple_annotations() const { + return simple_annotations_; + } + //! \brief Enables or disables Crashpad handler processing. //! //! When handling an exception, the Crashpad handler will scan all modules in diff --git a/client/prune_crash_reports_test.cc b/client/prune_crash_reports_test.cc index 7772d20d..14eb2e0b 100644 --- a/client/prune_crash_reports_test.cc +++ b/client/prune_crash_reports_test.cc @@ -185,9 +185,9 @@ TEST(PruneCrashReports, BinaryCondition) { auto rhs = new StaticCondition(test.rhs_value); BinaryPruneCondition condition(test.op, lhs, rhs); CrashReportDatabase::Report report; - EXPECT_EQ(test.cond_result, condition.ShouldPruneReport(report)); - EXPECT_EQ(test.lhs_executed, lhs->did_execute()); - EXPECT_EQ(test.rhs_executed, rhs->did_execute()); + EXPECT_EQ(condition.ShouldPruneReport(report), test.cond_result); + EXPECT_EQ(lhs->did_execute(), test.lhs_executed); + EXPECT_EQ(rhs->did_execute(), test.rhs_executed); } } diff --git a/client/settings_test.cc b/client/settings_test.cc index 08c24b4c..866e58d7 100644 --- a/client/settings_test.cc +++ b/client/settings_test.cc @@ -62,13 +62,13 @@ class SettingsTest : public testing::Test { TEST_F(SettingsTest, ClientID) { UUID client_id; EXPECT_TRUE(settings()->GetClientID(&client_id)); - EXPECT_NE(UUID(), client_id); + EXPECT_NE(client_id, UUID()); Settings local_settings(settings_path()); EXPECT_TRUE(local_settings.Initialize()); UUID actual; EXPECT_TRUE(local_settings.GetClientID(&actual)); - EXPECT_EQ(client_id, actual); + EXPECT_EQ(actual, client_id); } TEST_F(SettingsTest, UploadsEnabled) { @@ -100,18 +100,18 @@ TEST_F(SettingsTest, LastUploadAttemptTime) { time_t actual = -1; EXPECT_TRUE(settings()->GetLastUploadAttemptTime(&actual)); // Default value is 0. - EXPECT_EQ(0, actual); + EXPECT_EQ(actual, 0); const time_t expected = time(nullptr); EXPECT_TRUE(settings()->SetLastUploadAttemptTime(expected)); EXPECT_TRUE(settings()->GetLastUploadAttemptTime(&actual)); - EXPECT_EQ(expected, actual); + EXPECT_EQ(actual, expected); Settings local_settings(settings_path()); EXPECT_TRUE(local_settings.Initialize()); actual = -1; EXPECT_TRUE(local_settings.GetLastUploadAttemptTime(&actual)); - EXPECT_EQ(expected, actual); + EXPECT_EQ(actual, expected); } // The following tests write a corrupt settings file and test the recovery @@ -129,13 +129,13 @@ TEST_F(SettingsTest, BadFileOnGet) { UUID client_id; EXPECT_TRUE(settings()->GetClientID(&client_id)); - EXPECT_NE(UUID(), client_id); + EXPECT_NE(client_id, UUID()); Settings local_settings(settings_path()); EXPECT_TRUE(local_settings.Initialize()); UUID actual; EXPECT_TRUE(local_settings.GetClientID(&actual)); - EXPECT_EQ(client_id, actual); + EXPECT_EQ(actual, client_id); } TEST_F(SettingsTest, BadFileOnSet) { @@ -154,10 +154,10 @@ TEST_F(SettingsTest, UnlinkFile) { EXPECT_TRUE(settings()->SetLastUploadAttemptTime(time(nullptr))); #if defined(OS_WIN) - EXPECT_EQ(0, _wunlink(settings_path().value().c_str())) + EXPECT_EQ(_wunlink(settings_path().value().c_str()), 0) << ErrnoMessage("_wunlink"); #else - EXPECT_EQ(0, unlink(settings_path().value().c_str())) + EXPECT_EQ(unlink(settings_path().value().c_str()), 0) << ErrnoMessage("unlink"); #endif @@ -165,7 +165,7 @@ TEST_F(SettingsTest, UnlinkFile) { EXPECT_TRUE(local_settings.Initialize()); UUID new_client_id; EXPECT_TRUE(local_settings.GetClientID(&new_client_id)); - EXPECT_NE(client_id, new_client_id); + EXPECT_NE(new_client_id, client_id); // Check that all values are reset. bool enabled = true; @@ -174,7 +174,7 @@ TEST_F(SettingsTest, UnlinkFile) { time_t time = -1; EXPECT_TRUE(local_settings.GetLastUploadAttemptTime(&time)); - EXPECT_EQ(0, time); + EXPECT_EQ(time, 0); } } // namespace diff --git a/client/simple_address_range_bag_test.cc b/client/simple_address_range_bag_test.cc index 0598d294..ac81a1f4 100644 --- a/client/simple_address_range_bag_test.cc +++ b/client/simple_address_range_bag_test.cc @@ -32,13 +32,13 @@ TEST(SimpleAddressRangeBag, Entry) { bag.Insert(reinterpret_cast(0x1000), 200); entry = TestBag::Iterator(bag).Next(); ASSERT_TRUE(entry); - EXPECT_EQ(entry->base, 0x1000u); - EXPECT_EQ(entry->size, 200u); + EXPECT_EQ(0x1000u, entry->base); + EXPECT_EQ(200u, entry->size); bag.Remove(reinterpret_cast(0x1000), 200); EXPECT_FALSE(entry->is_active()); - EXPECT_EQ(entry->base, 0u); - EXPECT_EQ(entry->size, 0u); + EXPECT_EQ(0u, entry->base); + EXPECT_EQ(0u, entry->size); } TEST(SimpleAddressRangeBag, SimpleAddressRangeBag) { @@ -48,24 +48,24 @@ TEST(SimpleAddressRangeBag, SimpleAddressRangeBag) { EXPECT_TRUE(bag.Insert(reinterpret_cast(0x2000), 20)); EXPECT_TRUE(bag.Insert(CheckedRange(0x3000, 30))); - EXPECT_EQ(bag.GetCount(), 3u); + EXPECT_EQ(3u, bag.GetCount()); // Duplicates added too. EXPECT_TRUE(bag.Insert(CheckedRange(0x3000, 30))); EXPECT_TRUE(bag.Insert(CheckedRange(0x3000, 30))); - EXPECT_EQ(bag.GetCount(), 5u); + EXPECT_EQ(5u, bag.GetCount()); // Can be removed 3 times, but not the 4th time. EXPECT_TRUE(bag.Remove(CheckedRange(0x3000, 30))); EXPECT_TRUE(bag.Remove(CheckedRange(0x3000, 30))); EXPECT_TRUE(bag.Remove(CheckedRange(0x3000, 30))); - EXPECT_EQ(bag.GetCount(), 2u); + EXPECT_EQ(2u, bag.GetCount()); EXPECT_FALSE(bag.Remove(CheckedRange(0x3000, 30))); - EXPECT_EQ(bag.GetCount(), 2u); + EXPECT_EQ(2u, bag.GetCount()); EXPECT_TRUE(bag.Remove(reinterpret_cast(0x1000), 10)); EXPECT_TRUE(bag.Remove(reinterpret_cast(0x2000), 20)); - EXPECT_EQ(bag.GetCount(), 0u); + EXPECT_EQ(0u, bag.GetCount()); } TEST(SimpleAddressRangeBag, CopyAndAssign) { @@ -74,24 +74,24 @@ TEST(SimpleAddressRangeBag, CopyAndAssign) { EXPECT_TRUE(bag.Insert(CheckedRange(3, 4))); EXPECT_TRUE(bag.Insert(CheckedRange(5, 6))); EXPECT_TRUE(bag.Remove(CheckedRange(3, 4))); - EXPECT_EQ(2u, bag.GetCount()); + EXPECT_EQ(bag.GetCount(), 2u); // Test copy. TSimpleAddressRangeBag<10> bag_copy(bag); - EXPECT_EQ(2u, bag_copy.GetCount()); + EXPECT_EQ(bag_copy.GetCount(), 2u); EXPECT_TRUE(bag_copy.Remove(CheckedRange(1, 2))); EXPECT_TRUE(bag_copy.Remove(CheckedRange(5, 6))); - EXPECT_EQ(0u, bag_copy.GetCount()); - EXPECT_EQ(2u, bag.GetCount()); + EXPECT_EQ(bag_copy.GetCount(), 0u); + EXPECT_EQ(bag.GetCount(), 2u); // Test assign. TSimpleAddressRangeBag<10> bag_assign; bag_assign = bag; - EXPECT_EQ(2u, bag_assign.GetCount()); + EXPECT_EQ(bag_assign.GetCount(), 2u); EXPECT_TRUE(bag_assign.Remove(CheckedRange(1, 2))); EXPECT_TRUE(bag_assign.Remove(CheckedRange(5, 6))); - EXPECT_EQ(0u, bag_assign.GetCount()); - EXPECT_EQ(2u, bag.GetCount()); + EXPECT_EQ(bag_assign.GetCount(), 0u); + EXPECT_EQ(bag.GetCount(), 2u); } // Running out of space shouldn't crash. @@ -100,7 +100,7 @@ TEST(SimpleAddressRangeBag, OutOfSpace) { EXPECT_TRUE(bag.Insert(CheckedRange(1, 2))); EXPECT_TRUE(bag.Insert(CheckedRange(3, 4))); EXPECT_FALSE(bag.Insert(CheckedRange(5, 6))); - EXPECT_EQ(2u, bag.GetCount()); + EXPECT_EQ(bag.GetCount(), 2u); EXPECT_FALSE(bag.Remove(CheckedRange(5, 6))); } diff --git a/client/simple_string_dictionary_test.cc b/client/simple_string_dictionary_test.cc index 69e892b4..6d827b8f 100644 --- a/client/simple_string_dictionary_test.cc +++ b/client/simple_string_dictionary_test.cc @@ -46,8 +46,8 @@ TEST(SimpleStringDictionary, Entry) { // Clear the entry and verify the key and value are empty strings. map.RemoveKey("key1"); EXPECT_FALSE(entry->is_active()); - EXPECT_EQ(strlen(entry->key), 0u); - EXPECT_EQ(strlen(entry->value), 0u); + EXPECT_EQ(0u, strlen(entry->key)); + EXPECT_EQ(0u, strlen(entry->value)); } TEST(SimpleStringDictionary, SimpleStringDictionary) { @@ -62,7 +62,7 @@ TEST(SimpleStringDictionary, SimpleStringDictionary) { EXPECT_NE(dict.GetValueForKey("key1"), "value1"); EXPECT_NE(dict.GetValueForKey("key2"), "value2"); EXPECT_NE(dict.GetValueForKey("key3"), "value3"); - EXPECT_EQ(dict.GetCount(), 3u); + EXPECT_EQ(3u, dict.GetCount()); // try an unknown key EXPECT_FALSE(dict.GetValueForKey("key4")); @@ -85,11 +85,11 @@ TEST(SimpleStringDictionary, CopyAndAssign) { map.SetKeyValue("two", "b"); map.SetKeyValue("three", "c"); map.RemoveKey("two"); - EXPECT_EQ(2u, map.GetCount()); + EXPECT_EQ(map.GetCount(), 2u); // Test copy. TSimpleStringDictionary<10, 10, 10> map_copy(map); - EXPECT_EQ(2u, map_copy.GetCount()); + EXPECT_EQ(map_copy.GetCount(), 2u); EXPECT_STREQ("a", map_copy.GetValueForKey("one")); EXPECT_STREQ("c", map_copy.GetValueForKey("three")); map_copy.SetKeyValue("four", "d"); @@ -99,7 +99,7 @@ TEST(SimpleStringDictionary, CopyAndAssign) { // Test assign. TSimpleStringDictionary<10, 10, 10> map_assign; map_assign = map; - EXPECT_EQ(2u, map_assign.GetCount()); + EXPECT_EQ(map_assign.GetCount(), 2u); EXPECT_STREQ("a", map_assign.GetValueForKey("one")); EXPECT_STREQ("c", map_assign.GetValueForKey("three")); map_assign.SetKeyValue("four", "d"); @@ -129,7 +129,7 @@ TEST(SimpleStringDictionary, Iterator) { // We'll keep track of the number of key/value pairs we think should be in the // dictionary - int expectedDictionarySize = 0; + int expected_dictionary_size = 0; // Set a bunch of key/value pairs like key0/value0, key1/value1, ... for (int i = 0; i < kPartitionIndex; ++i) { @@ -137,7 +137,7 @@ TEST(SimpleStringDictionary, Iterator) { sprintf(value, "value%d", i); dict->SetKeyValue(key, value); } - expectedDictionarySize = kPartitionIndex; + expected_dictionary_size = kPartitionIndex; // set a couple of the keys twice (with the same value) - should be nop dict->SetKeyValue("key2", "value2"); @@ -149,7 +149,7 @@ TEST(SimpleStringDictionary, Iterator) { dict->RemoveKey("key18"); dict->RemoveKey("key23"); dict->RemoveKey("key31"); - expectedDictionarySize -= 4; // we just removed four key/value pairs + expected_dictionary_size -= 4; // we just removed four key/value pairs // Set some more key/value pairs like key59/value59, key60/value60, ... for (int i = kPartitionIndex; i < kDictionaryCapacity; ++i) { @@ -157,7 +157,7 @@ TEST(SimpleStringDictionary, Iterator) { sprintf(value, "value%d", i); dict->SetKeyValue(key, value); } - expectedDictionarySize += kDictionaryCapacity - kPartitionIndex; + expected_dictionary_size += kDictionaryCapacity - kPartitionIndex; // Now create an iterator on the dictionary SimpleStringDictionary::Iterator iter(*dict); @@ -170,35 +170,36 @@ TEST(SimpleStringDictionary, Iterator) { int count[kDictionaryCapacity]; memset(count, 0, sizeof(count)); - int totalCount = 0; + int total_count = 0; for (;;) { const SimpleStringDictionary::Entry* entry = iter.Next(); if (!entry) break; - totalCount++; + total_count++; - // Extract keyNumber from a string of the form key - int keyNumber; - sscanf(entry->key, "key%d", &keyNumber); + // Extract key_number from a string of the form key + int key_number; + sscanf(entry->key, "key%d", &key_number); - // Extract valueNumber from a string of the form value - int valueNumber; - sscanf(entry->value, "value%d", &valueNumber); + // Extract value_number from a string of the form value + int value_number; + sscanf(entry->value, "value%d", &value_number); // The value number should equal the key number since that's how we set them - EXPECT_EQ(keyNumber, valueNumber); + EXPECT_EQ(value_number, key_number); - // Key and value numbers should be in proper range: 0 <= keyNumber < + // Key and value numbers should be in proper range: 0 <= key_number < // kDictionaryCapacity - bool isKeyInGoodRange = (keyNumber >= 0 && keyNumber < kDictionaryCapacity); - bool isValueInGoodRange = - (valueNumber >= 0 && valueNumber < kDictionaryCapacity); - EXPECT_TRUE(isKeyInGoodRange); - EXPECT_TRUE(isValueInGoodRange); + bool key_in_good_range = + key_number >= 0 && key_number < kDictionaryCapacity; + bool value_in_good_range = + value_number >= 0 && value_number < kDictionaryCapacity; + EXPECT_TRUE(key_in_good_range); + EXPECT_TRUE(value_in_good_range); - if (isKeyInGoodRange && isValueInGoodRange) { - ++count[keyNumber]; + if (key_in_good_range && value_in_good_range) { + ++count[key_number]; } } @@ -207,12 +208,12 @@ TEST(SimpleStringDictionary, Iterator) { for (size_t i = 0; i < kDictionaryCapacity; ++i) { // Skip over key7, key18, key23, and key31, since we removed them if (!(i == 7 || i == 18 || i == 23 || i == 31)) { - EXPECT_EQ(count[i], 1); + EXPECT_EQ(1, count[i]); } } // Make sure the number of iterations matches the expected dictionary size. - EXPECT_EQ(totalCount, expectedDictionarySize); + EXPECT_EQ(total_count, expected_dictionary_size); } TEST(SimpleStringDictionary, AddRemove) { @@ -221,22 +222,22 @@ TEST(SimpleStringDictionary, AddRemove) { map.SetKeyValue("mike", "pink"); map.SetKeyValue("mark", "allays"); - EXPECT_EQ(3u, map.GetCount()); + EXPECT_EQ(map.GetCount(), 3u); EXPECT_STREQ("ert", map.GetValueForKey("rob")); EXPECT_STREQ("pink", map.GetValueForKey("mike")); EXPECT_STREQ("allays", map.GetValueForKey("mark")); map.RemoveKey("mike"); - EXPECT_EQ(2u, map.GetCount()); + EXPECT_EQ(map.GetCount(), 2u); EXPECT_FALSE(map.GetValueForKey("mike")); map.SetKeyValue("mark", "mal"); - EXPECT_EQ(2u, map.GetCount()); + EXPECT_EQ(map.GetCount(), 2u); EXPECT_STREQ("mal", map.GetValueForKey("mark")); map.RemoveKey("mark"); - EXPECT_EQ(1u, map.GetCount()); + EXPECT_EQ(map.GetCount(), 1u); EXPECT_FALSE(map.GetValueForKey("mark")); } @@ -246,7 +247,7 @@ TEST(SimpleStringDictionary, OutOfSpace) { map.SetKeyValue("a", "1"); map.SetKeyValue("b", "2"); map.SetKeyValue("c", "3"); - EXPECT_EQ(2u, map.GetCount()); + EXPECT_EQ(map.GetCount(), 2u); EXPECT_FALSE(map.GetValueForKey("c")); } @@ -262,7 +263,7 @@ TEST(SimpleStringDictionaryDeathTest, NullKey) { ASSERT_DEATH_CHECK(map.GetValueForKey(nullptr), "key"); map.RemoveKey("hi"); - EXPECT_EQ(0u, map.GetCount()); + EXPECT_EQ(map.GetCount(), 0u); } #endif diff --git a/client/simulate_crash_mac_test.cc b/client/simulate_crash_mac_test.cc index 87c5f845..de91ebb2 100644 --- a/client/simulate_crash_mac_test.cc +++ b/client/simulate_crash_mac_test.cc @@ -101,41 +101,41 @@ class TestSimulateCrashMac final : public MachMultiprocess, // Check the entire exception message, because most or all of it was // generated by SimulateCrash() instead of the kernel. - EXPECT_EQ(behavior_, behavior); - EXPECT_EQ(LocalPort(), exception_port); + EXPECT_EQ(behavior, behavior_); + EXPECT_EQ(exception_port, LocalPort()); if (ExceptionBehaviorHasIdentity(behavior)) { - EXPECT_NE(THREAD_NULL, thread); - EXPECT_EQ(ChildTask(), task); + EXPECT_NE(thread, THREAD_NULL); + EXPECT_EQ(task, ChildTask()); } else { - EXPECT_EQ(THREAD_NULL, thread); - EXPECT_EQ(TASK_NULL, task); + EXPECT_EQ(thread, THREAD_NULL); + EXPECT_EQ(task, TASK_NULL); } - EXPECT_EQ(kMachExceptionSimulated, exception); - EXPECT_EQ(2u, code_count); + EXPECT_EQ(exception, kMachExceptionSimulated); + EXPECT_EQ(code_count, 2u); if (code_count >= 1) { - EXPECT_EQ(0, code[0]); + EXPECT_EQ(code[0], 0); } if (code_count >= 2) { - EXPECT_EQ(0, code[1]); + EXPECT_EQ(code[1], 0); } if (!ExceptionBehaviorHasState(behavior)) { - EXPECT_EQ(THREAD_STATE_NONE, *flavor); + EXPECT_EQ(*flavor, THREAD_STATE_NONE); } else { - EXPECT_EQ(flavor_, *flavor); + EXPECT_EQ(*flavor, flavor_); switch (*flavor) { #if defined(ARCH_CPU_X86_FAMILY) case x86_THREAD_STATE: { - EXPECT_EQ(x86_THREAD_STATE_COUNT, old_state_count); + EXPECT_EQ(old_state_count, x86_THREAD_STATE_COUNT); const x86_thread_state* state = reinterpret_cast(old_state); switch (state->tsh.flavor) { case x86_THREAD_STATE32: - EXPECT_EQ(implicit_cast(x86_THREAD_STATE32_COUNT), - state->tsh.count); + EXPECT_EQ(state->tsh.count, + implicit_cast(x86_THREAD_STATE32_COUNT)); break; case x86_THREAD_STATE64: - EXPECT_EQ(implicit_cast(x86_THREAD_STATE64_COUNT), - state->tsh.count); + EXPECT_EQ(state->tsh.count, + implicit_cast(x86_THREAD_STATE64_COUNT)); break; default: ADD_FAILURE() << "unexpected tsh.flavor " << state->tsh.flavor; @@ -144,17 +144,17 @@ class TestSimulateCrashMac final : public MachMultiprocess, break; } case x86_FLOAT_STATE: { - EXPECT_EQ(x86_FLOAT_STATE_COUNT, old_state_count); + EXPECT_EQ(old_state_count, x86_FLOAT_STATE_COUNT); const x86_float_state* state = reinterpret_cast(old_state); switch (state->fsh.flavor) { case x86_FLOAT_STATE32: - EXPECT_EQ(implicit_cast(x86_FLOAT_STATE32_COUNT), - state->fsh.count); + EXPECT_EQ(state->fsh.count, + implicit_cast(x86_FLOAT_STATE32_COUNT)); break; case x86_FLOAT_STATE64: - EXPECT_EQ(implicit_cast(x86_FLOAT_STATE64_COUNT), - state->fsh.count); + EXPECT_EQ(state->fsh.count, + implicit_cast(x86_FLOAT_STATE64_COUNT)); break; default: ADD_FAILURE() << "unexpected fsh.flavor " << state->fsh.flavor; @@ -163,17 +163,17 @@ class TestSimulateCrashMac final : public MachMultiprocess, break; } case x86_DEBUG_STATE: { - EXPECT_EQ(x86_DEBUG_STATE_COUNT, old_state_count); + EXPECT_EQ(old_state_count, x86_DEBUG_STATE_COUNT); const x86_debug_state* state = reinterpret_cast(old_state); switch (state->dsh.flavor) { case x86_DEBUG_STATE32: - EXPECT_EQ(implicit_cast(x86_DEBUG_STATE32_COUNT), - state->dsh.count); + EXPECT_EQ(state->dsh.count, + implicit_cast(x86_DEBUG_STATE32_COUNT)); break; case x86_DEBUG_STATE64: - EXPECT_EQ(implicit_cast(x86_DEBUG_STATE64_COUNT), - state->dsh.count); + EXPECT_EQ(state->dsh.count, + implicit_cast(x86_DEBUG_STATE64_COUNT)); break; default: ADD_FAILURE() << "unexpected dsh.flavor " << state->dsh.flavor; @@ -182,22 +182,22 @@ class TestSimulateCrashMac final : public MachMultiprocess, break; } case x86_THREAD_STATE32: - EXPECT_EQ(x86_THREAD_STATE32_COUNT, old_state_count); + EXPECT_EQ(old_state_count, x86_THREAD_STATE32_COUNT); break; case x86_FLOAT_STATE32: - EXPECT_EQ(x86_FLOAT_STATE32_COUNT, old_state_count); + EXPECT_EQ(old_state_count, x86_FLOAT_STATE32_COUNT); break; case x86_DEBUG_STATE32: - EXPECT_EQ(x86_DEBUG_STATE32_COUNT, old_state_count); + EXPECT_EQ(old_state_count, x86_DEBUG_STATE32_COUNT); break; case x86_THREAD_STATE64: - EXPECT_EQ(x86_THREAD_STATE64_COUNT, old_state_count); + EXPECT_EQ(old_state_count, x86_THREAD_STATE64_COUNT); break; case x86_FLOAT_STATE64: - EXPECT_EQ(x86_FLOAT_STATE64_COUNT, old_state_count); + EXPECT_EQ(old_state_count, x86_FLOAT_STATE64_COUNT); break; case x86_DEBUG_STATE64: - EXPECT_EQ(x86_DEBUG_STATE64_COUNT, old_state_count); + EXPECT_EQ(old_state_count, x86_DEBUG_STATE64_COUNT); break; #else #error Port to your CPU architecture @@ -223,7 +223,7 @@ class TestSimulateCrashMac final : public MachMultiprocess, // thread-level EXC_CRASH handler. To test that it will fall back to // trying the task-level EXC_CRASH handler, return a failure code, which // should cause SimulateCrash() to try the next target. - EXPECT_EQ(kExceptionPortsTargetBoth, target_); + EXPECT_EQ(target_, kExceptionPortsTargetBoth); return KERN_ABORTED; } @@ -259,7 +259,7 @@ class TestSimulateCrashMac final : public MachMultiprocess, MachMessageServer::kOneShot, MachMessageServer::kReceiveLargeError, kMachMessageTimeoutWaitIndefinitely); - EXPECT_EQ(MACH_MSG_SUCCESS, mr) + EXPECT_EQ(mr, MACH_MSG_SUCCESS) << MachErrorMessage(mr, "MachMessageServer::Run"); } @@ -270,7 +270,7 @@ class TestSimulateCrashMac final : public MachMultiprocess, MachMessageServer::kOneShot, MachMessageServer::kReceiveLargeError, kMachMessageTimeoutWaitIndefinitely); - EXPECT_EQ(MACH_MSG_SUCCESS, mr) + EXPECT_EQ(mr, MACH_MSG_SUCCESS) << MachErrorMessage(mr, "MachMessageServer::Run"); } diff --git a/codereview.settings b/codereview.settings index 616a3be0..bf4a3a0a 100644 --- a/codereview.settings +++ b/codereview.settings @@ -17,5 +17,4 @@ GERRIT_SQUASH_UPLOADS: True CODE_REVIEW_SERVER: https://canary-chromium-review.googlesource.com/ VIEW_VC: https://chromium.googlesource.com/crashpad/crashpad/+/ PROJECT: crashpad -BUG_LINE_FORMAT: Bug: %s BUG_PREFIX: crashpad: diff --git a/compat/android/linux/prctl.h b/compat/android/linux/prctl.h new file mode 100644 index 00000000..046f900f --- /dev/null +++ b/compat/android/linux/prctl.h @@ -0,0 +1,25 @@ +// Copyright 2017 The Crashpad Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef CRASHPAD_COMPAT_ANDROID_LINUX_PRCTL_H_ +#define CRASHPAD_COMPAT_ANDROID_LINUX_PRCTL_H_ + +#include_next + +// Android 5.0.0 (API 21) NDK +#if !defined(PR_SET_PTRACER) +#define PR_SET_PTRACER 0x59616d61 +#endif + +#endif // CRASHPAD_COMPAT_ANDROID_LINUX_PRCTL_H_ diff --git a/crashpad.gyp b/crashpad.gyp index 42fe0a26..f30a9df9 100644 --- a/crashpad.gyp +++ b/crashpad.gyp @@ -22,6 +22,7 @@ 'client/client_test.gyp:*', 'compat/compat.gyp:*', 'handler/handler.gyp:*', + 'handler/handler_test.gyp:*', 'minidump/minidump.gyp:*', 'minidump/minidump_test.gyp:*', 'snapshot/snapshot.gyp:*', diff --git a/doc/developing.md b/doc/developing.md index 65d62356..429fff7f 100644 --- a/doc/developing.md +++ b/doc/developing.md @@ -214,9 +214,9 @@ $ adb push \ /data/local/tmp/ [100%] /data/local/tmp/crashpad_test_test_multiprocess_exec_test_child $ adb shell mkdir -p /data/local/tmp/crashpad_test_data_root/test -$ adb push test/paths_test_data_root.txt \ +$ adb push test/test_paths_test_data_root.txt \ /data/local/tmp/crashpad_test_data_root/test/ -[100%] /data/local/tmp/crashpad_test_data_root/test/paths_test_data_root.txt +[100%] /data/local/tmp/crashpad_test_data_root/test/test_paths_test_data_root.txt $ adb shell device:/ $ cd /data/local/tmp device:/data/local/tmp $ CRASHPAD_TEST_DATA_ROOT=crashpad_test_data_root \ diff --git a/doc/overview_design.md b/doc/overview_design.md index ad871c18..07a7d651 100644 --- a/doc/overview_design.md +++ b/doc/overview_design.md @@ -452,6 +452,8 @@ suspend and resume and such. ### Extensibility +#### Client Extensibility + Clients are able to extend the generated crash reports in two ways, by manipulating their CrashpadInfo structure. The two extensibility points are: @@ -461,6 +463,18 @@ The two extensibility points are: In both cases the CrashpadInfo structure has to be updated before a crash occurs. +##### Embedder Extensibility + +Additionally, embedders of the handler can provide "user stream data source" +instances to the handler's main function. Any time a minidump is written, these +instances get called. + +Each data source may contribute a custom stream to the minidump, which can be +computed from e.g. system or application state relevant to the crash. + +As a case in point, it can be handy to know whether the system was under memory +or other resource duress at the time of crash. + ### Dependencies Aside from system headers and APIs, when used outside of Chromium, Crashpad has diff --git a/doc/support/generate.sh b/doc/support/generate.sh index 1e5bc92f..c3065c1d 100755 --- a/doc/support/generate.sh +++ b/doc/support/generate.sh @@ -28,7 +28,7 @@ cd "$(dirname "${0}")/../.." source doc/support/compat.sh -doc/support/generate_doxygen.sh +python doc/support/generate_doxygen.py output_dir=doc/generated maybe_mkdir "${output_dir}" diff --git a/doc/support/generate_doxygen.py b/doc/support/generate_doxygen.py new file mode 100755 index 00000000..11dd0ad0 --- /dev/null +++ b/doc/support/generate_doxygen.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python +# coding: utf-8 + +# Copyright 2017 The Crashpad Authors. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generating Doxygen documentation requires Doxygen, http://www.doxygen.org/. + +import os +import shutil +import subprocess +import sys + + +def main(args): + script_dir = os.path.dirname(__file__) + crashpad_dir = os.path.join(script_dir, os.pardir, os.pardir) + + # Run from the Crashpad project root directory. + os.chdir(crashpad_dir) + + output_dir = os.path.join('out', 'doc', 'doxygen') + + if os.path.isdir(output_dir) and not os.path.islink(output_dir): + shutil.rmtree(output_dir) + elif os.path.exists(output_dir): + os.unlink(output_dir) + + os.makedirs(output_dir, 0755) + + doxy_file = os.path.join('doc', 'support', 'crashpad.doxy') + subprocess.check_call(['doxygen', doxy_file]) + + return 0 + + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) diff --git a/doc/support/generate_doxygen.sh b/doc/support/generate_doxygen.sh deleted file mode 100755 index ba565e7b..00000000 --- a/doc/support/generate_doxygen.sh +++ /dev/null @@ -1,29 +0,0 @@ -#!/bin/sh - -# Copyright 2015 The Crashpad Authors. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -set -e - -# Generating Doxygen documentation requires Doxygen, http://www.doxygen.org/. - -# Run from the Crashpad project root directory. -cd "$(dirname "${0}")/../.." - -output_dir=out/doc/doxygen - -rm -rf "${output_dir}" -mkdir -p "${output_dir}" - -doxygen doc/support/crashpad.doxy diff --git a/handler/crash_report_upload_thread.cc b/handler/crash_report_upload_thread.cc index 2c2b69b9..9ba3f1f8 100644 --- a/handler/crash_report_upload_thread.cc +++ b/handler/crash_report_upload_thread.cc @@ -252,9 +252,12 @@ void CrashReportUploadThread::ProcessPendingReport( break; case CrashReportDatabase::kBusyError: + case CrashReportDatabase::kReportNotFound: + // Someone else may have gotten to it first. If they’re working on it now, + // this will be kBusyError. If they’ve already finished with it, it’ll be + // kReportNotFound. return; - case CrashReportDatabase::kReportNotFound: case CrashReportDatabase::kFileSystemError: case CrashReportDatabase::kDatabaseError: // In these cases, SkipReportUpload() might not work either, but it’s best diff --git a/handler/crashpad_handler.md b/handler/crashpad_handler.md index 30dacfe7..e76fed76 100644 --- a/handler/crashpad_handler.md +++ b/handler/crashpad_handler.md @@ -138,6 +138,51 @@ establish the Crashpad client environment before running a program. service declared in a job’s `MachServices` dictionary (see launchd.plist(5)). The service name may also be completely unknown to the system. + * **--metrics-dir**=_DIR_ + + Metrics information will be written to _DIR_. This option only has an effect + when built as part of Chromium. In non-Chromium builds, and in the absence of + this option, metrics information will not be written. + + * **--monitor-self** + + Causes a second instance of the Crashpad handler program to be started, + monitoring the original instance for exceptions. The original instance will + become a client of the second one. The second instance will be started with + the same **--annotation**, **--database**, **--monitor-self-annotation**, + **--no-rate-limit**, **--no-upload-gzip**, and **--url** arguments as the + original one. The second instance will not be started with a + **--metrics-dir** argument even if the original instance was. + + Where supported by the underlying operating system, the second instance will + be restarted should it exit before the first instance. The second instance + will not be eligible to be started asynchronously. + + * **--monitor-self-annotation**=_KEY_=_VALUE_ + + Sets a module-level annotation mapping _KEY_ to _VALUE_ in the Crashpad + handler. This option may appear zero, one, or more times. + + If **--monitor-self** is in use, the second instance of the Crashpad handler + program will find these annotations stored in the original instance and will + include them in any crash reports written for the original instance. + + These annotations will only appear in crash reports written for the Crashpad + handler itself. To apply a process-level annotation to all crash reports + written by an instance of the Crashpad handler, use **--annotation** instead. + + * **--monitor-self-argument**=_ARGUMENT_ + + When directed by **--monitor-self** to start a second instance of the + Crashpad handler program, the second instance will be started with _ARGUMENT_ + as one of its arguments. This option may appear zero, one, or more times. + This option has no effect in the absence of **--monitor-self**. + + This supports embedding the Crashpad handler into a multi-purpose executable + that dispatches to the desired entry point based on a command-line argument. + To prevent excessive accumulation of handler processes, _ARGUMENT_ must not + be `--monitor-self`. + * **--no-rate-limit** Do not rate limit the upload of crash reports. By default uploads are diff --git a/handler/crashpad_handler_test.cc b/handler/crashpad_handler_test.cc new file mode 100644 index 00000000..7237e8c8 --- /dev/null +++ b/handler/crashpad_handler_test.cc @@ -0,0 +1,132 @@ +// Copyright 2017 The Crashpad Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include +#include +#include + +#include +#include +#include + +#include "base/files/file_path.h" +#include "client/crash_report_database.h" +#include "client/crashpad_client.h" +#include "gtest/gtest.h" +#include "minidump/test/minidump_file_writer_test_util.h" +#include "test/test_paths.h" +#include "test/win/win_multiprocess_with_temp_dir.h" +#include "util/file/file_reader.h" + +namespace crashpad { +namespace test { +namespace { + +void StartAndCrashWithExtendedHandler(const base::FilePath& temp_dir) { + base::FilePath handler_path = TestPaths::Executable().DirName().Append( + FILE_PATH_LITERAL("crashpad_handler_test_extended_handler.exe")); + + CrashpadClient client; + ASSERT_TRUE(client.StartHandler(handler_path, + temp_dir, + base::FilePath(), + "", + std::map(), + std::vector(), + false, + false)); + + __debugbreak(); +} + +class CrashWithExtendedHandler final : public WinMultiprocessWithTempDir { + public: + CrashWithExtendedHandler() : WinMultiprocessWithTempDir() {} + ~CrashWithExtendedHandler() {} + + private: + void ValidateGeneratedDump(); + + void WinMultiprocessParent() override { + SetExpectedChildExitCode(EXCEPTION_BREAKPOINT); + } + + void WinMultiprocessChild() override { + StartAndCrashWithExtendedHandler(GetTempDirPath()); + } + + void WinMultiprocessParentAfterChild(HANDLE child) override { + // At this point the child has exited, which means the crash report should + // have been written. + ValidateGeneratedDump(); + + // Delegate the cleanup to the superclass. + WinMultiprocessWithTempDir::WinMultiprocessParentAfterChild(child); + } +}; + +void CrashWithExtendedHandler::ValidateGeneratedDump() { + // Open the database and find the sole dump that should have been created. + std::unique_ptr database( + CrashReportDatabase::Initialize(GetTempDirPath())); + ASSERT_TRUE(database); + + std::vector reports; + ASSERT_EQ(database->GetCompletedReports(&reports), + CrashReportDatabase::kNoError); + ASSERT_EQ(reports.size(), 1u); + + // Open the dump and validate that it has the extension stream with the + // expected contents. + FileReader reader; + ASSERT_TRUE(reader.Open(reports[0].file_path)); + + // Read the header. + MINIDUMP_HEADER header = {}; + ASSERT_TRUE(reader.ReadExactly(&header, sizeof(header))); + + // Read the directory. + std::vector directory(header.NumberOfStreams); + ASSERT_TRUE(reader.SeekSet(header.StreamDirectoryRva)); + ASSERT_TRUE(reader.ReadExactly(directory.data(), + directory.size() * sizeof(directory[0]))); + + // Search for the extension stream. + size_t found_extension_streams = 0; + for (const auto& entry : directory) { + if (entry.StreamType == 0xCAFEBABE) { + ++found_extension_streams; + + ASSERT_TRUE(reader.SeekSet(entry.Location.Rva)); + + std::vector data; + data.resize(entry.Location.DataSize); + + ASSERT_TRUE(reader.ReadExactly(data.data(), data.size())); + + static const char kExpectedData[] = "Injected extension stream!"; + EXPECT_EQ(memcmp(kExpectedData, data.data(), sizeof(kExpectedData)), 0); + } + } + + EXPECT_EQ(found_extension_streams, 1u); +} + +TEST(CrashpadHandler, ExtensibilityCalloutsWork) { + WinMultiprocessWithTempDir::Run(); +} + +} // namespace +} // namespace test +} // namespace crashpad diff --git a/handler/crashpad_handler_test_extended_handler.cc b/handler/crashpad_handler_test_extended_handler.cc new file mode 100644 index 00000000..ede0f6e7 --- /dev/null +++ b/handler/crashpad_handler_test_extended_handler.cc @@ -0,0 +1,70 @@ +// Copyright 2017 The Crashpad Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "base/macros.h" +#include "base/memory/ptr_util.h" +#include "build/build_config.h" +#include "handler/handler_main.h" +#include "minidump/test/minidump_user_extension_stream_util.h" +#include "tools/tool_support.h" + +#if defined(OS_WIN) +#include +#endif + +namespace { + +class TestUserStreamDataSource : public crashpad::UserStreamDataSource { + public: + TestUserStreamDataSource() {} + + std::unique_ptr + ProduceStreamData(crashpad::ProcessSnapshot* process_snapshot) override; + + private: + DISALLOW_COPY_AND_ASSIGN(TestUserStreamDataSource); +}; + +std::unique_ptr +TestUserStreamDataSource::ProduceStreamData( + crashpad::ProcessSnapshot* process_snapshot) { + static const char kTestData[] = "Injected extension stream!"; + + return base::WrapUnique(new crashpad::test::BufferExtensionStreamDataSource( + 0xCAFEBABE, kTestData, sizeof(kTestData))); +} + +int ExtendedHandlerMain(int argc, char* argv[]) { + crashpad::UserStreamDataSources user_stream_data_sources; + user_stream_data_sources.push_back( + base::WrapUnique(new TestUserStreamDataSource())); + + return crashpad::HandlerMain(argc, argv, &user_stream_data_sources); +} + +} // namespace + +#if defined(OS_MACOSX) + +int main(int argc, char* argv[]) { + return ExtendedHandlerMain(argc, argv); +} + +#elif defined(OS_WIN) + +int wmain(int argc, wchar_t* argv[]) { + return crashpad::ToolSupport::Wmain(argc, argv, &ExtendedHandlerMain); +} + +#endif // OS_MACOSX diff --git a/handler/handler.gyp b/handler/handler.gyp index 6a51222c..d6e4c271 100644 --- a/handler/handler.gyp +++ b/handler/handler.gyp @@ -45,6 +45,8 @@ 'mac/exception_handler_server.h', 'prune_crash_reports_thread.cc', 'prune_crash_reports_thread.h', + 'user_stream_data_source.cc', + 'user_stream_data_source.h', 'win/crash_report_exception_handler.cc', 'win/crash_report_exception_handler.h', ], diff --git a/handler/handler_main.cc b/handler/handler_main.cc index 16eb1142..641bf0f6 100644 --- a/handler/handler_main.cc +++ b/handler/handler_main.cc @@ -20,6 +20,7 @@ #include #include +#include #include #include #include @@ -33,16 +34,20 @@ #include "base/logging.h" #include "base/metrics/persistent_histogram_allocator.h" #include "base/scoped_generic.h" +#include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "client/crash_report_database.h" #include "client/crashpad_client.h" +#include "client/crashpad_info.h" #include "client/prune_crash_reports.h" +#include "client/simple_string_dictionary.h" #include "handler/crash_report_upload_thread.h" #include "handler/prune_crash_reports_thread.h" #include "tools/tool_support.h" #include "util/file/file_io.h" #include "util/misc/metrics.h" +#include "util/misc/paths.h" #include "util/numeric/in_range_cast.h" #include "util/stdlib/map_insert.h" #include "util/stdlib/string_number_conversion.h" @@ -83,8 +88,8 @@ void Usage(const base::FilePath& me) { " --database=PATH store the crash report database at PATH\n" #if defined(OS_MACOSX) " --handshake-fd=FD establish communication with the client over FD\n" -" --mach-service=SERVICE register SERVICE with the bootstrap server\n" -#elif defined(OS_WIN) +#endif // OS_MACOSX +#if defined(OS_WIN) " --initial-client-data=HANDLE_request_crash_dump,\n" " HANDLE_request_non_crash_dump,\n" " HANDLE_non_crash_dump_completed,\n" @@ -94,15 +99,24 @@ void Usage(const base::FilePath& me) { " Address_non_crash_exception_information,\n" " Address_debug_critical_section\n" " use precreated data to register initial client\n" +#endif // OS_WIN +#if defined(OS_MACOSX) +" --mach-service=SERVICE register SERVICE with the bootstrap server\n" #endif // OS_MACOSX " --metrics-dir=DIR store metrics files in DIR (only in Chromium)\n" +" --monitor-self run a second handler to catch crashes in the first\n" +" --monitor-self-annotation=KEY=VALUE\n" +" set a module annotation in the handler\n" +" --monitor-self-argument=ARGUMENT\n" +" provide additional arguments to the second handler\n" " --no-rate-limit don't rate limit crash uploads\n" " --no-upload-gzip don't use gzip compression when uploading\n" +#if defined(OS_WIN) +" --pipe-name=PIPE communicate with the client over PIPE\n" +#endif // OS_WIN #if defined(OS_MACOSX) " --reset-own-crash-exception-port-to-system-default\n" " reset the server's exception handler to default\n" -#elif defined(OS_WIN) -" --pipe-name=PIPE communicate with the client over PIPE\n" #endif // OS_MACOSX " --url=URL send crash reports to this Breakpad server URL,\n" " only if uploads are enabled for the database\n" @@ -112,6 +126,49 @@ void Usage(const base::FilePath& me) { ToolSupport::UsageTail(me); } +struct Options { + std::map annotations; + std::map monitor_self_annotations; + std::string url; + base::FilePath database; + base::FilePath metrics_dir; + std::vector monitor_self_arguments; +#if defined(OS_MACOSX) + std::string mach_service; + int handshake_fd; + bool reset_own_crash_exception_port_to_system_default; +#elif defined(OS_WIN) + std::string pipe_name; + InitialClientData initial_client_data; +#endif // OS_MACOSX + bool monitor_self; + bool rate_limit; + bool upload_gzip; +}; + +// Splits |key_value| on '=' and inserts the resulting key and value into |map|. +// If |key_value| has the wrong format, logs an error and returns false. If the +// key is already in the map, logs a warning, replaces the existing value, and +// returns true. If the key and value were inserted into the map, returns true. +// |argument| is used to give context to logged messages. +bool AddKeyValueToMap(std::map* map, + const std::string& key_value, + const char* argument) { + std::string key; + std::string value; + if (!SplitStringFirst(key_value, '=', &key, &value)) { + LOG(ERROR) << argument << " requires KEY=VALUE"; + return false; + } + + std::string old_value; + if (!MapInsertOrReplace(map, key, value, &old_value)) { + LOG(WARNING) << argument << " has duplicate key " << key + << ", discarding value " << old_value; + } + return true; +} + // Calls Metrics::HandlerLifetimeMilestone, but only on the first call. This is // to prevent multiple exit events from inadvertently being recorded, which // might happen if a crash occurs during destruction in what would otherwise be @@ -188,6 +245,13 @@ void HandleTerminateSignal(int sig, siginfo_t* siginfo, void* context) { Signals::RestoreHandlerAndReraiseSignalOnReturn(siginfo, nullptr); } +void ReinstallCrashHandler() { + // This is used to re-enable the metrics-recording crash handler after + // MonitorSelf() sets up a Crashpad exception handler. On macOS, the + // metrics-recording handler uses signals and the Crashpad handler uses Mach + // exceptions, so there’s nothing to re-enable. +} + void InstallCrashHandler() { Signals::InstallCrashHandlers(HandleCrashSignal, 0, nullptr); @@ -254,9 +318,17 @@ class TerminateHandler final : public SessionEndWatcher { DISALLOW_COPY_AND_ASSIGN(TerminateHandler); }; -void InstallCrashHandler() { +void ReinstallCrashHandler() { + // This is used to re-enable the metrics-recording crash handler after + // MonitorSelf() sets up a Crashpad exception handler. The Crashpad handler + // takes over the UnhandledExceptionFilter, so reinstall the metrics-recording + // one. g_original_exception_filter = SetUnhandledExceptionFilter(&UnhandledExceptionHandler); +} + +void InstallCrashHandler() { + ReinstallCrashHandler(); // These are termination handlers, not crash handlers, but that’s close // enough. Note that destroying the TerminateHandler would wait for its thread @@ -268,9 +340,57 @@ void InstallCrashHandler() { #endif // OS_MACOSX +void MonitorSelf(const Options& options) { + base::FilePath executable_path; + if (!Paths::Executable(&executable_path)) { + return; + } + + if (std::find(options.monitor_self_arguments.begin(), + options.monitor_self_arguments.end(), + "--monitor-self") != options.monitor_self_arguments.end()) { + LOG(WARNING) << "--monitor-self-argument=--monitor-self is not supported"; + return; + } + std::vector extra_arguments(options.monitor_self_arguments); + if (!options.rate_limit) { + extra_arguments.push_back("--no-rate-limit"); + } + if (!options.upload_gzip) { + extra_arguments.push_back("--no-upload-gzip"); + } + for (const auto& iterator : options.monitor_self_annotations) { + extra_arguments.push_back( + base::StringPrintf("--monitor-self-annotation=%s=%s", + iterator.first.c_str(), + iterator.second.c_str())); + } + + // Don’t use options.metrics_dir. The current implementation only allows one + // instance of crashpad_handler to be writing metrics at a time, and it should + // be the primary instance. + CrashpadClient crashpad_client; + if (!crashpad_client.StartHandler(executable_path, + options.database, + base::FilePath(), + options.url, + options.annotations, + extra_arguments, + true, + false)) { + return; + } + + // Make sure that appropriate metrics will be recorded on crash before this + // process is terminated. + ReinstallCrashHandler(); +} + } // namespace -int HandlerMain(int argc, char* argv[]) { +int HandlerMain(int argc, + char* argv[], + const UserStreamDataSources* user_stream_sources) { InstallCrashHandler(); CallMetricsRecordNormalExit metrics_record_normal_exit; @@ -293,12 +413,16 @@ int HandlerMain(int argc, char* argv[]) { kOptionMachService, #endif // OS_MACOSX kOptionMetrics, + kOptionMonitorSelf, + kOptionMonitorSelfAnnotation, + kOptionMonitorSelfArgument, kOptionNoRateLimit, kOptionNoUploadGzip, +#if defined(OS_WIN) + kOptionPipeName, +#endif // OS_WIN #if defined(OS_MACOSX) kOptionResetOwnCrashExceptionPortToSystemDefault, -#elif defined(OS_WIN) - kOptionPipeName, #endif // OS_MACOSX kOptionURL, @@ -307,28 +431,6 @@ int HandlerMain(int argc, char* argv[]) { kOptionVersion = -3, }; - struct { - std::map annotations; - std::string url; - const char* database; - const char* metrics; -#if defined(OS_MACOSX) - int handshake_fd; - std::string mach_service; - bool reset_own_crash_exception_port_to_system_default; -#elif defined(OS_WIN) - std::string pipe_name; - InitialClientData initial_client_data; -#endif // OS_MACOSX - bool rate_limit; - bool upload_gzip; - } options = {}; -#if defined(OS_MACOSX) - options.handshake_fd = -1; -#endif - options.rate_limit = true; - options.upload_gzip = true; - const option long_options[] = { {"annotation", required_argument, nullptr, kOptionAnnotation}, {"database", required_argument, nullptr, kOptionDatabase}, @@ -345,15 +447,25 @@ int HandlerMain(int argc, char* argv[]) { {"mach-service", required_argument, nullptr, kOptionMachService}, #endif // OS_MACOSX {"metrics-dir", required_argument, nullptr, kOptionMetrics}, + {"monitor-self", no_argument, nullptr, kOptionMonitorSelf}, + {"monitor-self-annotation", + required_argument, + nullptr, + kOptionMonitorSelfAnnotation}, + {"monitor-self-argument", + required_argument, + nullptr, + kOptionMonitorSelfArgument}, {"no-rate-limit", no_argument, nullptr, kOptionNoRateLimit}, {"no-upload-gzip", no_argument, nullptr, kOptionNoUploadGzip}, +#if defined(OS_WIN) + {"pipe-name", required_argument, nullptr, kOptionPipeName}, +#endif // OS_WIN #if defined(OS_MACOSX) {"reset-own-crash-exception-port-to-system-default", no_argument, nullptr, kOptionResetOwnCrashExceptionPortToSystemDefault}, -#elif defined(OS_WIN) - {"pipe-name", required_argument, nullptr, kOptionPipeName}, #endif // OS_MACOSX {"url", required_argument, nullptr, kOptionURL}, {"help", no_argument, nullptr, kOptionHelp}, @@ -361,25 +473,25 @@ int HandlerMain(int argc, char* argv[]) { {nullptr, 0, nullptr, 0}, }; + Options options = {}; +#if defined(OS_MACOSX) + options.handshake_fd = -1; +#endif + options.rate_limit = true; + options.upload_gzip = true; + int opt; while ((opt = getopt_long(argc, argv, "", long_options, nullptr)) != -1) { switch (opt) { case kOptionAnnotation: { - std::string key; - std::string value; - if (!SplitStringFirst(optarg, '=', &key, &value)) { - ToolSupport::UsageHint(me, "--annotation requires KEY=VALUE"); + if (!AddKeyValueToMap(&options.annotations, optarg, "--annotation")) { return ExitFailure(); } - std::string old_value; - if (!MapInsertOrReplace(&options.annotations, key, value, &old_value)) { - LOG(WARNING) << "duplicate key " << key << ", discarding value " - << old_value; - } break; } case kOptionDatabase: { - options.database = optarg; + options.database = base::FilePath( + ToolSupport::CommandLineArgumentToFilePathStringType(optarg)); break; } #if defined(OS_MACOSX) @@ -396,7 +508,8 @@ int HandlerMain(int argc, char* argv[]) { options.mach_service = optarg; break; } -#elif defined(OS_WIN) +#endif // OS_MACOSX +#if defined(OS_WIN) case kOptionInitialClientData: { if (!options.initial_client_data.InitializeFromString(optarg)) { ToolSupport::UsageHint( @@ -405,9 +518,26 @@ int HandlerMain(int argc, char* argv[]) { } break; } -#endif // OS_MACOSX +#endif // OS_WIN case kOptionMetrics: { - options.metrics = optarg; + options.metrics_dir = base::FilePath( + ToolSupport::CommandLineArgumentToFilePathStringType(optarg)); + break; + } + case kOptionMonitorSelf: { + options.monitor_self = true; + break; + } + case kOptionMonitorSelfAnnotation: { + if (!AddKeyValueToMap(&options.monitor_self_annotations, + optarg, + "--monitor-self-annotation")) { + return ExitFailure(); + } + break; + } + case kOptionMonitorSelfArgument: { + options.monitor_self_arguments.push_back(optarg); break; } case kOptionNoRateLimit: { @@ -418,16 +548,17 @@ int HandlerMain(int argc, char* argv[]) { options.upload_gzip = false; break; } +#if defined(OS_WIN) + case kOptionPipeName: { + options.pipe_name = optarg; + break; + } +#endif // OS_WIN #if defined(OS_MACOSX) case kOptionResetOwnCrashExceptionPortToSystemDefault: { options.reset_own_crash_exception_port_to_system_default = true; break; } -#elif defined(OS_WIN) - case kOptionPipeName: { - options.pipe_name = optarg; - break; - } #endif // OS_MACOSX case kOptionURL: { options.url = optarg; @@ -475,7 +606,7 @@ int HandlerMain(int argc, char* argv[]) { } #endif // OS_MACOSX - if (!options.database) { + if (options.database.empty()) { ToolSupport::UsageHint(me, "--database is required"); return ExitFailure(); } @@ -485,16 +616,42 @@ int HandlerMain(int argc, char* argv[]) { return ExitFailure(); } +#if defined(OS_MACOSX) + if (options.reset_own_crash_exception_port_to_system_default) { + CrashpadClient::UseSystemDefaultHandler(); + } +#endif // OS_MACOSX + + if (options.monitor_self) { + MonitorSelf(options); + } + + if (!options.monitor_self_annotations.empty()) { + // Establish these annotations even if --monitor-self is not present, in + // case something such as generate_dump wants to try to access them later. + // + // If the handler is part of a multi-purpose executable, simple annotations + // may already be present for this module. If they are, use them. + CrashpadInfo* crashpad_info = CrashpadInfo::GetCrashpadInfo(); + SimpleStringDictionary* module_annotations = + crashpad_info->simple_annotations(); + if (!module_annotations) { + module_annotations = new SimpleStringDictionary(); + crashpad_info->set_simple_annotations(module_annotations); + } + + for (const auto& iterator : options.monitor_self_annotations) { + module_annotations->SetKeyValue(iterator.first.c_str(), + iterator.second.c_str()); + } + } + #if defined(OS_MACOSX) if (options.mach_service.empty()) { // Don’t do this when being run by launchd. See launchd.plist(5). CloseStdinAndStdout(); } - if (options.reset_own_crash_exception_port_to_system_default) { - CrashpadClient::UseSystemDefaultHandler(); - } - base::mac::ScopedMachReceiveRight receive_right; if (options.handshake_fd >= 0) { @@ -543,13 +700,11 @@ int HandlerMain(int argc, char* argv[]) { #endif // OS_MACOSX base::GlobalHistogramAllocator* histogram_allocator = nullptr; - if (options.metrics) { - const base::FilePath metrics_dir( - ToolSupport::CommandLineArgumentToFilePathStringType(options.metrics)); + if (!options.metrics_dir.empty()) { static const char kMetricsName[] = "CrashpadMetrics"; const size_t kMetricsFileSize = 1 << 20; if (base::GlobalHistogramAllocator::CreateWithActiveFileInDir( - metrics_dir, kMetricsFileSize, 0, kMetricsName)) { + options.metrics_dir, kMetricsFileSize, 0, kMetricsName)) { histogram_allocator = base::GlobalHistogramAllocator::Get(); histogram_allocator->CreateTrackingHistograms(kMetricsName); } @@ -557,9 +712,8 @@ int HandlerMain(int argc, char* argv[]) { Metrics::HandlerLifetimeMilestone(Metrics::LifetimeMilestone::kStarted); - std::unique_ptr database(CrashReportDatabase::Initialize( - base::FilePath(ToolSupport::CommandLineArgumentToFilePathStringType( - options.database)))); + std::unique_ptr database( + CrashReportDatabase::Initialize(options.database)); if (!database) { return ExitFailure(); } @@ -575,8 +729,10 @@ int HandlerMain(int argc, char* argv[]) { PruneCondition::GetDefault()); prune_thread.Start(); - CrashReportExceptionHandler exception_handler( - database.get(), &upload_thread, &options.annotations); + CrashReportExceptionHandler exception_handler(database.get(), + &upload_thread, + &options.annotations, + user_stream_sources); #if defined(OS_WIN) if (options.initial_client_data.IsValid()) { diff --git a/handler/handler_main.h b/handler/handler_main.h index 5b5568ec..af01dbe7 100644 --- a/handler/handler_main.h +++ b/handler/handler_main.h @@ -15,13 +15,24 @@ #ifndef CRASHPAD_HANDLER_HANDLER_MAIN_H_ #define CRASHPAD_HANDLER_HANDLER_MAIN_H_ +#include "handler/user_stream_data_source.h" + namespace crashpad { //! \brief The `main()` of the `crashpad_handler` binary. //! //! This is exposed so that `crashpad_handler` can be embedded into another //! binary, but called and used as if it were a standalone executable. -int HandlerMain(int argc, char* argv[]); +//! +//! \param[in] argc \a argc as passed to `main()`. +//! \param[in] argv \a argv as passed to `main()`. +//! \param[in] user_stream_sources An optional vector containing the +//! extensibility data sources to call on crash. Each time a minidump is +//! created, the sources are called in turn. Any streams returned are added +//! to the minidump. +int HandlerMain(int argc, + char* argv[], + const UserStreamDataSources* user_stream_sources); } // namespace crashpad diff --git a/handler/handler_test.gyp b/handler/handler_test.gyp new file mode 100644 index 00000000..e5264182 --- /dev/null +++ b/handler/handler_test.gyp @@ -0,0 +1,64 @@ +# Copyright 2017 The Crashpad Authors. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +{ + 'includes': [ + '../build/crashpad.gypi', + ], + 'targets': [ + { + 'target_name': 'crashpad_handler_test_extended_handler', + 'type': 'executable', + 'dependencies': [ + '../compat/compat.gyp:crashpad_compat', + '../minidump/minidump_test.gyp:crashpad_minidump_test_lib', + '../third_party/mini_chromium/mini_chromium.gyp:base', + '../tools/tools.gyp:crashpad_tool_support', + 'handler.gyp:crashpad_handler_lib', + ], + 'include_dirs': [ + '..', + ], + 'sources': [ + 'crashpad_handler_test_extended_handler.cc', + ], + }, + ], + 'conditions': [ + ['OS=="win"', { + 'targets': [{ + # The handler is only tested on Windows for now. + 'target_name': 'crashpad_handler_test', + 'type': 'executable', + 'dependencies': [ + 'crashpad_handler_test_extended_handler', + 'handler.gyp:crashpad_handler_lib', + '../client/client.gyp:crashpad_client', + '../compat/compat.gyp:crashpad_compat', + '../test/test.gyp:crashpad_gtest_main', + '../test/test.gyp:crashpad_test', + '../third_party/gtest/gtest.gyp:gtest', + '../third_party/mini_chromium/mini_chromium.gyp:base', + '../util/util.gyp:crashpad_util', + ], + 'include_dirs': [ + '..', + ], + 'sources': [ + 'crashpad_handler_test.cc', + ], + }], + }], + ], +} diff --git a/handler/mac/crash_report_exception_handler.cc b/handler/mac/crash_report_exception_handler.cc index 7784afef..a96131cd 100644 --- a/handler/mac/crash_report_exception_handler.cc +++ b/handler/mac/crash_report_exception_handler.cc @@ -22,6 +22,7 @@ #include "base/strings/stringprintf.h" #include "client/settings.h" #include "minidump/minidump_file_writer.h" +#include "minidump/minidump_user_extension_stream_data_source.h" #include "snapshot/crashpad_info_client_options.h" #include "snapshot/mac/process_snapshot_mac.h" #include "util/file/file_writer.h" @@ -41,11 +42,12 @@ namespace crashpad { CrashReportExceptionHandler::CrashReportExceptionHandler( CrashReportDatabase* database, CrashReportUploadThread* upload_thread, - const std::map* process_annotations) + const std::map* process_annotations, + const UserStreamDataSources* user_stream_data_sources) : database_(database), upload_thread_(upload_thread), - process_annotations_(process_annotations) { -} + process_annotations_(process_annotations), + user_stream_data_sources_(user_stream_data_sources) {} CrashReportExceptionHandler::~CrashReportExceptionHandler() { } @@ -169,6 +171,9 @@ kern_return_t CrashReportExceptionHandler::CatchMachException( MinidumpFileWriter minidump; minidump.InitializeFromSnapshot(&process_snapshot); + AddUserExtensionStreams( + user_stream_data_sources_, &process_snapshot, &minidump); + if (!minidump.WriteEverything(&file_writer)) { Metrics::ExceptionCaptureResult( Metrics::CaptureResult::kMinidumpWriteFailed); diff --git a/handler/mac/crash_report_exception_handler.h b/handler/mac/crash_report_exception_handler.h index 63d9bef3..cc314f1f 100644 --- a/handler/mac/crash_report_exception_handler.h +++ b/handler/mac/crash_report_exception_handler.h @@ -23,6 +23,7 @@ #include "base/macros.h" #include "client/crash_report_database.h" #include "handler/crash_report_upload_thread.h" +#include "handler/user_stream_data_source.h" #include "util/mach/exc_server_variants.h" namespace crashpad { @@ -46,10 +47,15 @@ class CrashReportExceptionHandler : public UniversalMachExcServer::Interface { //! To interoperate with Breakpad servers, the recommended practice is to //! specify values for the `"prod"` and `"ver"` keys as process //! annotations. + //! \param[in] user_stream_data_sources Data sources to be used to extend + //! crash reports. For each crash report that is written, the data sources + //! are called in turn. These data sources may contribute additional + //! minidump streams. `nullptr` if not required. CrashReportExceptionHandler( CrashReportDatabase* database, CrashReportUploadThread* upload_thread, - const std::map* process_annotations); + const std::map* process_annotations, + const UserStreamDataSources* user_stream_data_sources); ~CrashReportExceptionHandler(); @@ -77,6 +83,7 @@ class CrashReportExceptionHandler : public UniversalMachExcServer::Interface { CrashReportDatabase* database_; // weak CrashReportUploadThread* upload_thread_; // weak const std::map* process_annotations_; // weak + const UserStreamDataSources* user_stream_data_sources_; // weak DISALLOW_COPY_AND_ASSIGN(CrashReportExceptionHandler); }; diff --git a/handler/main.cc b/handler/main.cc index 7a169e2d..bc4ab99b 100644 --- a/handler/main.cc +++ b/handler/main.cc @@ -23,10 +23,18 @@ #if defined(OS_MACOSX) int main(int argc, char* argv[]) { - return crashpad::HandlerMain(argc, argv); + return crashpad::HandlerMain(argc, argv, nullptr); } #elif defined(OS_WIN) +namespace { + +int HandlerMainAdaptor(int argc, char* argv[]) { + return crashpad::HandlerMain(argc, argv, nullptr); +} + +} // namespace + int APIENTRY wWinMain(HINSTANCE, HINSTANCE, wchar_t*, int) { - return crashpad::ToolSupport::Wmain(__argc, __wargv, crashpad::HandlerMain); + return crashpad::ToolSupport::Wmain(__argc, __wargv, HandlerMainAdaptor); } #endif // OS_MACOSX diff --git a/handler/user_stream_data_source.cc b/handler/user_stream_data_source.cc new file mode 100644 index 00000000..7e30fa8c --- /dev/null +++ b/handler/user_stream_data_source.cc @@ -0,0 +1,43 @@ +// Copyright 2017 The Crashpad Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "handler/user_stream_data_source.h" + +#include "base/logging.h" +#include "minidump/minidump_file_writer.h" +#include "minidump/minidump_user_extension_stream_data_source.h" +#include "snapshot/process_snapshot.h" + +namespace crashpad { + +void AddUserExtensionStreams( + const UserStreamDataSources* user_stream_data_sources, + ProcessSnapshot* process_snapshot, + MinidumpFileWriter* minidump_file_writer) { + if (!user_stream_data_sources) + return; + for (const auto& source : *user_stream_data_sources) { + std::unique_ptr data_source( + source->ProduceStreamData(process_snapshot)); + if (data_source && + !minidump_file_writer->AddUserExtensionStream(std::move(data_source))) { + // This should only happen if multiple user stream sources yield the + // same stream type. It's the user's responsibility to make sure + // sources don't collide on the same stream type. + LOG(ERROR) << "AddUserExtensionStream failed"; + } + } +} + +} // namespace crashpad diff --git a/handler/user_stream_data_source.h b/handler/user_stream_data_source.h new file mode 100644 index 00000000..11bb9c3d --- /dev/null +++ b/handler/user_stream_data_source.h @@ -0,0 +1,68 @@ +// Copyright 2017 The Crashpad Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef CRASHPAD_HANDLER_USER_STREAM_DATA_SOURCE_H_ +#define CRASHPAD_HANDLER_USER_STREAM_DATA_SOURCE_H_ + +#include +#include + +namespace crashpad { + +class MinidumpFileWriter; +class MinidumpUserExtensionStreamDataSource; +class ProcessSnapshot; + +//! \brief Extensibility interface for embedders who wish to add custom streams +//! to minidumps. +class UserStreamDataSource { + public: + virtual ~UserStreamDataSource() {} + + //! \brief Produce the contents for an extension stream for a crashed program. + //! + //! Called after \a process_snapshot has been initialized for the crashed + //! process to (optionally) produce the contents of a user extension stream + //! that will be attached to the minidump. + //! + //! \param[in] process_snapshot An initialized snapshot for the crashed + //! process. + //! + //! \return A new data source for the stream to add to the minidump or + //! `nullptr` on failure or to opt out of adding a stream. + virtual std::unique_ptr + ProduceStreamData(ProcessSnapshot* process_snapshot) = 0; +}; + +using UserStreamDataSources = + std::vector>; + +//! \brief Adds user extension streams to a minidump. +//! +//! Dispatches to each source in \a user_stream_data_sources and adds returned +//! extension streams to \a minidump_file_writer. +//! +//! \param[in] user_stream_data_sources A pointer to the data sources, or +//! `nullptr`. +//! \param[in] process_snapshot An initialized snapshot to the crashing process. +//! \param[in] minidump_file_writer Any extension streams will be added to this +//! minidump. +void AddUserExtensionStreams( + const UserStreamDataSources* user_stream_data_sources, + ProcessSnapshot* process_snapshot, + MinidumpFileWriter* minidump_file_writer); + +} // namespace crashpad + +#endif // CRASHPAD_HANDLER_USER_STREAM_DATA_SOURCE_H_ diff --git a/handler/win/crash_other_program.cc b/handler/win/crash_other_program.cc index 012b4ba3..389aee1f 100644 --- a/handler/win/crash_other_program.cc +++ b/handler/win/crash_other_program.cc @@ -18,8 +18,9 @@ #include "base/files/file_path.h" #include "base/logging.h" +#include "base/strings/stringprintf.h" #include "client/crashpad_client.h" -#include "test/paths.h" +#include "test/test_paths.h" #include "test/win/child_launcher.h" #include "util/file/file_io.h" #include "util/win/scoped_handle.h" @@ -29,20 +30,21 @@ namespace crashpad { namespace test { namespace { +constexpr DWORD kCrashAndDumpTargetExitCode = 0xdeadbea7; + bool CrashAndDumpTarget(const CrashpadClient& client, HANDLE process) { DWORD target_pid = GetProcessId(process); - HANDLE thread_snap_raw = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); - if (thread_snap_raw == INVALID_HANDLE_VALUE) { - LOG(ERROR) << "CreateToolhelp32Snapshot"; + ScopedFileHANDLE thread_snap(CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0)); + if (!thread_snap.is_valid()) { + PLOG(ERROR) << "CreateToolhelp32Snapshot"; return false; } - ScopedFileHANDLE thread_snap(thread_snap_raw); THREADENTRY32 te32; te32.dwSize = sizeof(THREADENTRY32); if (!Thread32First(thread_snap.get(), &te32)) { - LOG(ERROR) << "Thread32First"; + PLOG(ERROR) << "Thread32First"; return false; } @@ -55,9 +57,12 @@ bool CrashAndDumpTarget(const CrashpadClient& client, HANDLE process) { if (te32.tpBasePri == 9) { ScopedKernelHANDLE thread( OpenThread(kXPThreadAllAccess, false, te32.th32ThreadID)); + if (!thread.is_valid()) { + PLOG(ERROR) << "OpenThread"; + return false; + } if (!client.DumpAndCrashTargetProcess( - process, thread.get(), 0xdeadbea7)) { - LOG(ERROR) << "DumpAndCrashTargetProcess failed"; + process, thread.get(), kCrashAndDumpTargetExitCode)) { return false; } return true; @@ -65,6 +70,7 @@ bool CrashAndDumpTarget(const CrashpadClient& client, HANDLE process) { } } while (Thread32Next(thread_snap.get(), &te32)); + LOG(ERROR) << "target not found"; return false; } @@ -73,7 +79,7 @@ int CrashOtherProgram(int argc, wchar_t* argv[]) { if (argc == 2 || argc == 3) { if (!client.SetHandlerIPCPipe(argv[1])) { - LOG(ERROR) << "SetHandler"; + LOG(ERROR) << "SetHandlerIPCPipe"; return EXIT_FAILURE; } } else { @@ -82,7 +88,7 @@ int CrashOtherProgram(int argc, wchar_t* argv[]) { } // Launch another process that hangs. - base::FilePath test_executable = Paths::Executable(); + base::FilePath test_executable = TestPaths::Executable(); std::wstring child_test_executable = test_executable.DirName().Append(L"hanging_program.exe").value(); ChildLauncher child(child_test_executable, argv[1]); @@ -96,15 +102,28 @@ int CrashOtherProgram(int argc, wchar_t* argv[]) { return EXIT_FAILURE; } + DWORD expect_exit_code; if (argc == 3 && wcscmp(argv[2], L"noexception") == 0) { - client.DumpAndCrashTargetProcess(child.process_handle(), 0, 0); - return EXIT_SUCCESS; + expect_exit_code = CrashpadClient::kTriggeredExceptionCode; + if (!client.DumpAndCrashTargetProcess(child.process_handle(), 0, 0)) + return EXIT_FAILURE; } else { - if (CrashAndDumpTarget(client, child.process_handle())) - return EXIT_SUCCESS; + expect_exit_code = kCrashAndDumpTargetExitCode; + if (!CrashAndDumpTarget(client, child.process_handle())) { + return EXIT_FAILURE; + } } - return EXIT_FAILURE; + DWORD exit_code = child.WaitForExit(); + if (exit_code != expect_exit_code) { + LOG(ERROR) << base::StringPrintf( + "incorrect exit code, expected 0x%x, observed 0x%x", + expect_exit_code, + exit_code); + return EXIT_FAILURE; + } + + return EXIT_SUCCESS; } } // namespace diff --git a/handler/win/crash_report_exception_handler.cc b/handler/win/crash_report_exception_handler.cc index 180e6cb0..7828aac6 100644 --- a/handler/win/crash_report_exception_handler.cc +++ b/handler/win/crash_report_exception_handler.cc @@ -20,6 +20,7 @@ #include "client/settings.h" #include "handler/crash_report_upload_thread.h" #include "minidump/minidump_file_writer.h" +#include "minidump/minidump_user_extension_stream_data_source.h" #include "snapshot/win/process_snapshot_win.h" #include "util/file/file_writer.h" #include "util/misc/metrics.h" @@ -32,11 +33,12 @@ namespace crashpad { CrashReportExceptionHandler::CrashReportExceptionHandler( CrashReportDatabase* database, CrashReportUploadThread* upload_thread, - const std::map* process_annotations) + const std::map* process_annotations, + const UserStreamDataSources* user_stream_data_sources) : database_(database), upload_thread_(upload_thread), - process_annotations_(process_annotations) { -} + process_annotations_(process_annotations), + user_stream_data_sources_(user_stream_data_sources) {} CrashReportExceptionHandler::~CrashReportExceptionHandler() { } @@ -107,6 +109,9 @@ unsigned int CrashReportExceptionHandler::ExceptionHandlerServerException( MinidumpFileWriter minidump; minidump.InitializeFromSnapshot(&process_snapshot); + AddUserExtensionStreams( + user_stream_data_sources_, &process_snapshot, &minidump); + if (!minidump.WriteEverything(&file_writer)) { LOG(ERROR) << "WriteEverything failed"; Metrics::ExceptionCaptureResult( diff --git a/handler/win/crash_report_exception_handler.h b/handler/win/crash_report_exception_handler.h index 11b440c4..54dfa971 100644 --- a/handler/win/crash_report_exception_handler.h +++ b/handler/win/crash_report_exception_handler.h @@ -21,6 +21,7 @@ #include #include "base/macros.h" +#include "handler/user_stream_data_source.h" #include "util/win/exception_handler_server.h" namespace crashpad { @@ -47,10 +48,15 @@ class CrashReportExceptionHandler : public ExceptionHandlerServer::Delegate { //! To interoperate with Breakpad servers, the recommended practice is to //! specify values for the `"prod"` and `"ver"` keys as process //! annotations. + //! \param[in] user_stream_data_sources Data sources to be used to extend + //! crash reports. For each crash report that is written, the data sources + //! are called in turn. These data sources may contribute additional + //! minidump streams. `nullptr` if not required. CrashReportExceptionHandler( CrashReportDatabase* database, CrashReportUploadThread* upload_thread, - const std::map* process_annotations); + const std::map* process_annotations, + const UserStreamDataSources* user_stream_data_sources); ~CrashReportExceptionHandler() override; @@ -68,6 +74,7 @@ class CrashReportExceptionHandler : public ExceptionHandlerServer::Delegate { CrashReportDatabase* database_; // weak CrashReportUploadThread* upload_thread_; // weak const std::map* process_annotations_; // weak + const UserStreamDataSources* user_stream_data_sources_; // weak DISALLOW_COPY_AND_ASSIGN(CrashReportExceptionHandler); }; diff --git a/handler/win/crashy_test_z7_loader.cc b/handler/win/crashy_test_z7_loader.cc index 79802cd5..4ffcc031 100644 --- a/handler/win/crashy_test_z7_loader.cc +++ b/handler/win/crashy_test_z7_loader.cc @@ -19,7 +19,7 @@ #include "base/logging.h" #include "build/build_config.h" #include "client/crashpad_client.h" -#include "test/paths.h" +#include "test/test_paths.h" #if !defined(ARCH_CPU_X86) #error This test is only supported on x86. @@ -43,7 +43,7 @@ int CrashyLoadZ7Main(int argc, wchar_t* argv[]) { // The DLL has /Z7 symbols embedded in the binary (rather than in a .pdb). // There's only an x86 version of this dll as newer x64 toolchains can't // generate this format any more. - base::FilePath z7_path = test::Paths::TestDataRoot().Append( + base::FilePath z7_path = test::TestPaths::TestDataRoot().Append( FILE_PATH_LITERAL("handler/win/z7_test.dll")); HMODULE z7_test = LoadLibrary(z7_path.value().c_str()); if (!z7_test) { diff --git a/minidump/minidump_context_writer_test.cc b/minidump/minidump_context_writer_test.cc index 048d1df3..a6b5f3a9 100644 --- a/minidump/minidump_context_writer_test.cc +++ b/minidump/minidump_context_writer_test.cc @@ -39,7 +39,7 @@ TEST(MinidumpContextWriter, MinidumpContextX86Writer) { MinidumpContextX86Writer context_writer; EXPECT_TRUE(context_writer.WriteEverything(&string_file)); - ASSERT_EQ(sizeof(MinidumpContextX86), string_file.string().size()); + ASSERT_EQ(string_file.string().size(), sizeof(MinidumpContextX86)); const MinidumpContextX86* observed = MinidumpWritableAtRVA(string_file.string(), 0); @@ -58,7 +58,7 @@ TEST(MinidumpContextWriter, MinidumpContextX86Writer) { InitializeMinidumpContextX86(context_writer.context(), kSeed); EXPECT_TRUE(context_writer.WriteEverything(&string_file)); - ASSERT_EQ(sizeof(MinidumpContextX86), string_file.string().size()); + ASSERT_EQ(string_file.string().size(), sizeof(MinidumpContextX86)); const MinidumpContextX86* observed = MinidumpWritableAtRVA(string_file.string(), 0); @@ -79,7 +79,7 @@ TEST(MinidumpContextWriter, MinidumpContextAMD64Writer) { MinidumpContextAMD64Writer context_writer; EXPECT_TRUE(context_writer.WriteEverything(&string_file)); - ASSERT_EQ(sizeof(MinidumpContextAMD64), string_file.string().size()); + ASSERT_EQ(string_file.string().size(), sizeof(MinidumpContextAMD64)); const MinidumpContextAMD64* observed = MinidumpWritableAtRVA(string_file.string(), 0); @@ -98,7 +98,7 @@ TEST(MinidumpContextWriter, MinidumpContextAMD64Writer) { InitializeMinidumpContextAMD64(context_writer.context(), kSeed); EXPECT_TRUE(context_writer.WriteEverything(&string_file)); - ASSERT_EQ(sizeof(MinidumpContextAMD64), string_file.string().size()); + ASSERT_EQ(string_file.string().size(), sizeof(MinidumpContextAMD64)); const MinidumpContextAMD64* observed = MinidumpWritableAtRVA(string_file.string(), 0); diff --git a/minidump/minidump_crashpad_info_writer_test.cc b/minidump/minidump_crashpad_info_writer_test.cc index 0b620663..e24a606c 100644 --- a/minidump/minidump_crashpad_info_writer_test.cc +++ b/minidump/minidump_crashpad_info_writer_test.cc @@ -49,7 +49,7 @@ void GetCrashpadInfoStream( ASSERT_NO_FATAL_FAILURE(VerifyMinidumpHeader(header, 1, 0)); ASSERT_TRUE(directory); - ASSERT_EQ(kMinidumpStreamTypeCrashpadInfo, directory[0].StreamType); + ASSERT_EQ(directory[0].StreamType, kMinidumpStreamTypeCrashpadInfo); *crashpad_info = MinidumpWritableAtLocationDescriptor( file_contents, directory[0].Location); @@ -82,9 +82,9 @@ TEST(MinidumpCrashpadInfoWriter, Empty) { ASSERT_NO_FATAL_FAILURE(GetCrashpadInfoStream( string_file.string(), &crashpad_info, &simple_annotations, &module_list)); - EXPECT_EQ(MinidumpCrashpadInfo::kVersion, crashpad_info->version); - EXPECT_EQ(UUID(), crashpad_info->report_id); - EXPECT_EQ(UUID(), crashpad_info->client_id); + EXPECT_EQ(crashpad_info->version, MinidumpCrashpadInfo::kVersion); + EXPECT_EQ(crashpad_info->report_id, UUID()); + EXPECT_EQ(crashpad_info->client_id, UUID()); EXPECT_FALSE(simple_annotations); EXPECT_FALSE(module_list); } @@ -118,9 +118,9 @@ TEST(MinidumpCrashpadInfoWriter, ReportAndClientID) { ASSERT_NO_FATAL_FAILURE(GetCrashpadInfoStream( string_file.string(), &crashpad_info, &simple_annotations, &module_list)); - EXPECT_EQ(MinidumpCrashpadInfo::kVersion, crashpad_info->version); - EXPECT_EQ(report_id, crashpad_info->report_id); - EXPECT_EQ(client_id, crashpad_info->client_id); + EXPECT_EQ(crashpad_info->version, MinidumpCrashpadInfo::kVersion); + EXPECT_EQ(crashpad_info->report_id, report_id); + EXPECT_EQ(crashpad_info->client_id, client_id); EXPECT_FALSE(simple_annotations); EXPECT_FALSE(module_list); } @@ -160,17 +160,17 @@ TEST(MinidumpCrashpadInfoWriter, SimpleAnnotations) { ASSERT_NO_FATAL_FAILURE(GetCrashpadInfoStream( string_file.string(), &crashpad_info, &simple_annotations, &module_list)); - EXPECT_EQ(MinidumpCrashpadInfo::kVersion, crashpad_info->version); + EXPECT_EQ(crashpad_info->version, MinidumpCrashpadInfo::kVersion); EXPECT_FALSE(module_list); ASSERT_TRUE(simple_annotations); - ASSERT_EQ(1u, simple_annotations->count); - EXPECT_EQ(kKey, - MinidumpUTF8StringAtRVAAsString( - string_file.string(), simple_annotations->entries[0].key)); - EXPECT_EQ(kValue, - MinidumpUTF8StringAtRVAAsString( - string_file.string(), simple_annotations->entries[0].value)); + ASSERT_EQ(simple_annotations->count, 1u); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString(string_file.string(), + simple_annotations->entries[0].key), + kKey); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString( + string_file.string(), simple_annotations->entries[0].value), + kValue); } TEST(MinidumpCrashpadInfoWriter, CrashpadModuleList) { @@ -201,24 +201,24 @@ TEST(MinidumpCrashpadInfoWriter, CrashpadModuleList) { ASSERT_NO_FATAL_FAILURE(GetCrashpadInfoStream( string_file.string(), &crashpad_info, &simple_annotations, &module_list)); - EXPECT_EQ(MinidumpCrashpadInfo::kVersion, crashpad_info->version); + EXPECT_EQ(crashpad_info->version, MinidumpCrashpadInfo::kVersion); EXPECT_FALSE(simple_annotations); ASSERT_TRUE(module_list); - ASSERT_EQ(1u, module_list->count); + ASSERT_EQ(module_list->count, 1u); - EXPECT_EQ(kMinidumpModuleListIndex, - module_list->modules[0].minidump_module_list_index); + EXPECT_EQ(module_list->modules[0].minidump_module_list_index, + kMinidumpModuleListIndex); const MinidumpModuleCrashpadInfo* module = MinidumpWritableAtLocationDescriptor( string_file.string(), module_list->modules[0].location); ASSERT_TRUE(module); - EXPECT_EQ(MinidumpModuleCrashpadInfo::kVersion, module->version); - EXPECT_EQ(0u, module->list_annotations.DataSize); - EXPECT_EQ(0u, module->list_annotations.Rva); - EXPECT_EQ(0u, module->simple_annotations.DataSize); - EXPECT_EQ(0u, module->simple_annotations.Rva); + EXPECT_EQ(module->version, MinidumpModuleCrashpadInfo::kVersion); + EXPECT_EQ(module->list_annotations.DataSize, 0u); + EXPECT_EQ(module->list_annotations.Rva, 0u); + EXPECT_EQ(module->simple_annotations.DataSize, 0u); + EXPECT_EQ(module->simple_annotations.Rva, 0u); } TEST(MinidumpCrashpadInfoWriter, InitializeFromSnapshot) { @@ -276,40 +276,40 @@ TEST(MinidumpCrashpadInfoWriter, InitializeFromSnapshot) { ASSERT_NO_FATAL_FAILURE(GetCrashpadInfoStream( string_file.string(), &info, &simple_annotations, &module_list)); - EXPECT_EQ(MinidumpCrashpadInfo::kVersion, info->version); + EXPECT_EQ(info->version, MinidumpCrashpadInfo::kVersion); - EXPECT_EQ(report_id, info->report_id); - EXPECT_EQ(client_id, info->client_id); + EXPECT_EQ(info->report_id, report_id); + EXPECT_EQ(info->client_id, client_id); ASSERT_TRUE(simple_annotations); - ASSERT_EQ(1u, simple_annotations->count); - EXPECT_EQ(kKey, - MinidumpUTF8StringAtRVAAsString( - string_file.string(), simple_annotations->entries[0].key)); - EXPECT_EQ(kValue, - MinidumpUTF8StringAtRVAAsString( - string_file.string(), simple_annotations->entries[0].value)); + ASSERT_EQ(simple_annotations->count, 1u); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString(string_file.string(), + simple_annotations->entries[0].key), + kKey); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString( + string_file.string(), simple_annotations->entries[0].value), + kValue); ASSERT_TRUE(module_list); - ASSERT_EQ(1u, module_list->count); + ASSERT_EQ(module_list->count, 1u); - EXPECT_EQ(0u, module_list->modules[0].minidump_module_list_index); + EXPECT_EQ(module_list->modules[0].minidump_module_list_index, 0u); const MinidumpModuleCrashpadInfo* module = MinidumpWritableAtLocationDescriptor( string_file.string(), module_list->modules[0].location); ASSERT_TRUE(module); - EXPECT_EQ(MinidumpModuleCrashpadInfo::kVersion, module->version); + EXPECT_EQ(module->version, MinidumpModuleCrashpadInfo::kVersion); const MinidumpRVAList* list_annotations = MinidumpWritableAtLocationDescriptor( string_file.string(), module->list_annotations); ASSERT_TRUE(list_annotations); - ASSERT_EQ(1u, list_annotations->count); - EXPECT_EQ(kEntry, - MinidumpUTF8StringAtRVAAsString(string_file.string(), - list_annotations->children[0])); + ASSERT_EQ(list_annotations->count, 1u); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString(string_file.string(), + list_annotations->children[0]), + kEntry); const MinidumpSimpleStringDictionary* module_simple_annotations = MinidumpWritableAtLocationDescriptor( diff --git a/minidump/minidump_exception_writer_test.cc b/minidump/minidump_exception_writer_test.cc index 613c5dd1..f2c0816d 100644 --- a/minidump/minidump_exception_writer_test.cc +++ b/minidump/minidump_exception_writer_test.cc @@ -45,15 +45,15 @@ void GetExceptionStream(const std::string& file_contents, const size_t kContextOffset = kExceptionStreamOffset + sizeof(MINIDUMP_EXCEPTION_STREAM); const size_t kFileSize = kContextOffset + sizeof(MinidumpContextX86); - ASSERT_EQ(file_contents.size(), kFileSize); + ASSERT_EQ(kFileSize, file_contents.size()); const MINIDUMP_DIRECTORY* directory; const MINIDUMP_HEADER* header = MinidumpHeaderAtStart(file_contents, &directory); ASSERT_NO_FATAL_FAILURE(VerifyMinidumpHeader(header, 1, 0)); - ASSERT_EQ(kMinidumpStreamTypeException, directory[0].StreamType); - EXPECT_EQ(kExceptionStreamOffset, directory[0].Location.Rva); + ASSERT_EQ(directory[0].StreamType, kMinidumpStreamTypeException); + EXPECT_EQ(directory[0].Location.Rva, kExceptionStreamOffset); *exception_stream = MinidumpWritableAtLocationDescriptor( @@ -68,24 +68,24 @@ void ExpectExceptionStream(const MINIDUMP_EXCEPTION_STREAM* expected, const MINIDUMP_EXCEPTION_STREAM* observed, const std::string& file_contents, const MinidumpContextX86** context) { - EXPECT_EQ(expected->ThreadId, observed->ThreadId); - EXPECT_EQ(0u, observed->__alignment); - EXPECT_EQ(expected->ExceptionRecord.ExceptionCode, - observed->ExceptionRecord.ExceptionCode); - EXPECT_EQ(expected->ExceptionRecord.ExceptionFlags, - observed->ExceptionRecord.ExceptionFlags); - EXPECT_EQ(expected->ExceptionRecord.ExceptionRecord, - observed->ExceptionRecord.ExceptionRecord); - EXPECT_EQ(expected->ExceptionRecord.ExceptionAddress, - observed->ExceptionRecord.ExceptionAddress); - EXPECT_EQ(expected->ExceptionRecord.NumberParameters, - observed->ExceptionRecord.NumberParameters); - EXPECT_EQ(0u, observed->ExceptionRecord.__unusedAlignment); + EXPECT_EQ(observed->ThreadId, expected->ThreadId); + EXPECT_EQ(observed->__alignment, 0u); + EXPECT_EQ(observed->ExceptionRecord.ExceptionCode, + expected->ExceptionRecord.ExceptionCode); + EXPECT_EQ(observed->ExceptionRecord.ExceptionFlags, + expected->ExceptionRecord.ExceptionFlags); + EXPECT_EQ(observed->ExceptionRecord.ExceptionRecord, + expected->ExceptionRecord.ExceptionRecord); + EXPECT_EQ(observed->ExceptionRecord.ExceptionAddress, + expected->ExceptionRecord.ExceptionAddress); + EXPECT_EQ(observed->ExceptionRecord.NumberParameters, + expected->ExceptionRecord.NumberParameters); + EXPECT_EQ(observed->ExceptionRecord.__unusedAlignment, 0u); for (size_t index = 0; index < arraysize(observed->ExceptionRecord.ExceptionInformation); ++index) { - EXPECT_EQ(expected->ExceptionRecord.ExceptionInformation[index], - observed->ExceptionRecord.ExceptionInformation[index]); + EXPECT_EQ(observed->ExceptionRecord.ExceptionInformation[index], + expected->ExceptionRecord.ExceptionInformation[index]); } *context = MinidumpWritableAtLocationDescriptor( file_contents, observed->ThreadContext); diff --git a/minidump/minidump_file_writer.cc b/minidump/minidump_file_writer.cc index 3e99d2a3..5a34f59c 100644 --- a/minidump/minidump_file_writer.cc +++ b/minidump/minidump_file_writer.cc @@ -206,9 +206,8 @@ bool MinidumpFileWriter::AddUserExtensionStream( DCHECK_EQ(state(), kStateMutable); auto user_stream = base::WrapUnique(new MinidumpUserStreamWriter()); - user_stream->InitializeFromBuffer(user_extension_stream_data->stream_type(), - user_extension_stream_data->buffer(), - user_extension_stream_data->buffer_size()); + user_stream->InitializeFromUserExtensionStream( + std::move(user_extension_stream_data)); return AddStream(std::move(user_stream)); } diff --git a/minidump/minidump_file_writer_test.cc b/minidump/minidump_file_writer_test.cc index 0d300603..63f2ade8 100644 --- a/minidump/minidump_file_writer_test.cc +++ b/minidump/minidump_file_writer_test.cc @@ -28,6 +28,7 @@ #include "minidump/minidump_user_extension_stream_data_source.h" #include "minidump/minidump_writable.h" #include "minidump/test/minidump_file_writer_test_util.h" +#include "minidump/test/minidump_user_extension_stream_util.h" #include "minidump/test/minidump_writable_test_util.h" #include "snapshot/test/test_cpu_context.h" #include "snapshot/test/test_exception_snapshot.h" @@ -47,7 +48,7 @@ TEST(MinidumpFileWriter, Empty) { MinidumpFileWriter minidump_file; StringFile string_file; ASSERT_TRUE(minidump_file.WriteEverything(&string_file)); - ASSERT_EQ(sizeof(MINIDUMP_HEADER), string_file.string().size()); + ASSERT_EQ(string_file.string().size(), sizeof(MINIDUMP_HEADER)); const MINIDUMP_DIRECTORY* directory; const MINIDUMP_HEADER* header = @@ -78,7 +79,7 @@ class TestStream final : public internal::MinidumpStreamWriter { } bool WriteObject(FileWriterInterface* file_writer) override { - EXPECT_EQ(state(), kStateWritable); + EXPECT_EQ(kStateWritable, state()); return file_writer->Write(&stream_data_[0], stream_data_.size()); } @@ -108,7 +109,7 @@ TEST(MinidumpFileWriter, OneStream) { const size_t kStreamOffset = kDirectoryOffset + sizeof(MINIDUMP_DIRECTORY); const size_t kFileSize = kStreamOffset + kStreamSize; - ASSERT_EQ(kFileSize, string_file.string().size()); + ASSERT_EQ(string_file.string().size(), kFileSize); const MINIDUMP_DIRECTORY* directory; const MINIDUMP_HEADER* header = @@ -116,16 +117,16 @@ TEST(MinidumpFileWriter, OneStream) { ASSERT_NO_FATAL_FAILURE(VerifyMinidumpHeader(header, 1, kTimestamp)); ASSERT_TRUE(directory); - EXPECT_EQ(kStreamType, directory[0].StreamType); - EXPECT_EQ(kStreamSize, directory[0].Location.DataSize); - EXPECT_EQ(kStreamOffset, directory[0].Location.Rva); + EXPECT_EQ(directory[0].StreamType, kStreamType); + EXPECT_EQ(directory[0].Location.DataSize, kStreamSize); + EXPECT_EQ(directory[0].Location.Rva, kStreamOffset); const uint8_t* stream_data = MinidumpWritableAtLocationDescriptor( string_file.string(), directory[0].Location); ASSERT_TRUE(stream_data); std::string expected_stream(kStreamSize, kStreamValue); - EXPECT_EQ(0, memcmp(stream_data, expected_stream.c_str(), kStreamSize)); + EXPECT_EQ(memcmp(stream_data, expected_stream.c_str(), kStreamSize), 0); } TEST(MinidumpFileWriter, AddUserExtensionStream) { @@ -137,14 +138,14 @@ TEST(MinidumpFileWriter, AddUserExtensionStream) { const size_t kStreamSize = arraysize(kStreamData); const MinidumpStreamType kStreamType = static_cast(0x4d); - auto stream = base::WrapUnique(new MinidumpUserExtensionStreamDataSource( + auto data_source = base::WrapUnique(new test::BufferExtensionStreamDataSource( kStreamType, kStreamData, kStreamSize)); - ASSERT_TRUE(minidump_file.AddUserExtensionStream(std::move(stream))); + ASSERT_TRUE(minidump_file.AddUserExtensionStream(std::move(data_source))); // Adding the same stream type a second time should fail. - stream = base::WrapUnique(new MinidumpUserExtensionStreamDataSource( + data_source = base::WrapUnique(new test::BufferExtensionStreamDataSource( kStreamType, kStreamData, kStreamSize)); - ASSERT_FALSE(minidump_file.AddUserExtensionStream(std::move(stream))); + ASSERT_FALSE(minidump_file.AddUserExtensionStream(std::move(data_source))); StringFile string_file; ASSERT_TRUE(minidump_file.WriteEverything(&string_file)); @@ -153,7 +154,7 @@ TEST(MinidumpFileWriter, AddUserExtensionStream) { const size_t kStreamOffset = kDirectoryOffset + sizeof(MINIDUMP_DIRECTORY); const size_t kFileSize = kStreamOffset + kStreamSize; - ASSERT_EQ(kFileSize, string_file.string().size()); + ASSERT_EQ(string_file.string().size(), kFileSize); const MINIDUMP_DIRECTORY* directory; const MINIDUMP_HEADER* header = @@ -161,15 +162,46 @@ TEST(MinidumpFileWriter, AddUserExtensionStream) { ASSERT_NO_FATAL_FAILURE(VerifyMinidumpHeader(header, 1, kTimestamp)); ASSERT_TRUE(directory); - EXPECT_EQ(kStreamType, directory[0].StreamType); - EXPECT_EQ(kStreamSize, directory[0].Location.DataSize); - EXPECT_EQ(kStreamOffset, directory[0].Location.Rva); + EXPECT_EQ(directory[0].StreamType, kStreamType); + EXPECT_EQ(directory[0].Location.DataSize, kStreamSize); + EXPECT_EQ(directory[0].Location.Rva, kStreamOffset); const uint8_t* stream_data = MinidumpWritableAtLocationDescriptor( string_file.string(), directory[0].Location); ASSERT_TRUE(stream_data); - EXPECT_EQ(0, memcmp(stream_data, kStreamData, kStreamSize)); + EXPECT_EQ(memcmp(stream_data, kStreamData, kStreamSize), 0); +} + +TEST(MinidumpFileWriter, AddEmptyUserExtensionStream) { + MinidumpFileWriter minidump_file; + const time_t kTimestamp = 0x155d2fb8; + minidump_file.SetTimestamp(kTimestamp); + + const MinidumpStreamType kStreamType = static_cast(0x4d); + + auto data_source = base::WrapUnique( + new test::BufferExtensionStreamDataSource(kStreamType, nullptr, 0)); + ASSERT_TRUE(minidump_file.AddUserExtensionStream(std::move(data_source))); + + StringFile string_file; + ASSERT_TRUE(minidump_file.WriteEverything(&string_file)); + + const size_t kDirectoryOffset = sizeof(MINIDUMP_HEADER); + const size_t kStreamOffset = kDirectoryOffset + sizeof(MINIDUMP_DIRECTORY); + const size_t kFileSize = kStreamOffset; + + ASSERT_EQ(string_file.string().size(), kFileSize); + + const MINIDUMP_DIRECTORY* directory; + const MINIDUMP_HEADER* header = + MinidumpHeaderAtStart(string_file.string(), &directory); + ASSERT_NO_FATAL_FAILURE(VerifyMinidumpHeader(header, 1, kTimestamp)); + ASSERT_TRUE(directory); + + EXPECT_EQ(directory[0].StreamType, kStreamType); + EXPECT_EQ(directory[0].Location.DataSize, 0u); + EXPECT_EQ(directory[0].Location.Rva, kStreamOffset); } TEST(MinidumpFileWriter, ThreeStreams) { @@ -213,7 +245,7 @@ TEST(MinidumpFileWriter, ThreeStreams) { const size_t kStream2Offset = kStream1Offset + kStream1Size + kStream2Padding; const size_t kFileSize = kStream2Offset + kStream2Size; - ASSERT_EQ(kFileSize, string_file.string().size()); + ASSERT_EQ(string_file.string().size(), kFileSize); const MINIDUMP_DIRECTORY* directory; const MINIDUMP_HEADER* header = @@ -221,43 +253,43 @@ TEST(MinidumpFileWriter, ThreeStreams) { ASSERT_NO_FATAL_FAILURE(VerifyMinidumpHeader(header, 3, kTimestamp)); ASSERT_TRUE(directory); - EXPECT_EQ(kStream0Type, directory[0].StreamType); - EXPECT_EQ(kStream0Size, directory[0].Location.DataSize); - EXPECT_EQ(kStream0Offset, directory[0].Location.Rva); - EXPECT_EQ(kStream1Type, directory[1].StreamType); - EXPECT_EQ(kStream1Size, directory[1].Location.DataSize); - EXPECT_EQ(kStream1Offset, directory[1].Location.Rva); - EXPECT_EQ(kStream2Type, directory[2].StreamType); - EXPECT_EQ(kStream2Size, directory[2].Location.DataSize); - EXPECT_EQ(kStream2Offset, directory[2].Location.Rva); + EXPECT_EQ(directory[0].StreamType, kStream0Type); + EXPECT_EQ(directory[0].Location.DataSize, kStream0Size); + EXPECT_EQ(directory[0].Location.Rva, kStream0Offset); + EXPECT_EQ(directory[1].StreamType, kStream1Type); + EXPECT_EQ(directory[1].Location.DataSize, kStream1Size); + EXPECT_EQ(directory[1].Location.Rva, kStream1Offset); + EXPECT_EQ(directory[2].StreamType, kStream2Type); + EXPECT_EQ(directory[2].Location.DataSize, kStream2Size); + EXPECT_EQ(directory[2].Location.Rva, kStream2Offset); const uint8_t* stream0_data = MinidumpWritableAtLocationDescriptor( string_file.string(), directory[0].Location); ASSERT_TRUE(stream0_data); std::string expected_stream0(kStream0Size, kStream0Value); - EXPECT_EQ(0, memcmp(stream0_data, expected_stream0.c_str(), kStream0Size)); + EXPECT_EQ(memcmp(stream0_data, expected_stream0.c_str(), kStream0Size), 0); const int kZeroes[16] = {}; ASSERT_GE(sizeof(kZeroes), kStream1Padding); - EXPECT_EQ(0, memcmp(stream0_data + kStream0Size, kZeroes, kStream1Padding)); + EXPECT_EQ(memcmp(stream0_data + kStream0Size, kZeroes, kStream1Padding), 0); const uint8_t* stream1_data = MinidumpWritableAtLocationDescriptor( string_file.string(), directory[1].Location); ASSERT_TRUE(stream1_data); std::string expected_stream1(kStream1Size, kStream1Value); - EXPECT_EQ(0, memcmp(stream1_data, expected_stream1.c_str(), kStream1Size)); + EXPECT_EQ(memcmp(stream1_data, expected_stream1.c_str(), kStream1Size), 0); ASSERT_GE(sizeof(kZeroes), kStream2Padding); - EXPECT_EQ(0, memcmp(stream1_data + kStream1Size, kZeroes, kStream2Padding)); + EXPECT_EQ(memcmp(stream1_data + kStream1Size, kZeroes, kStream2Padding), 0); const uint8_t* stream2_data = MinidumpWritableAtLocationDescriptor( string_file.string(), directory[2].Location); ASSERT_TRUE(stream2_data); std::string expected_stream2(kStream2Size, kStream2Value); - EXPECT_EQ(0, memcmp(stream2_data, expected_stream2.c_str(), kStream2Size)); + EXPECT_EQ(memcmp(stream2_data, expected_stream2.c_str(), kStream2Size), 0); } TEST(MinidumpFileWriter, ZeroLengthStream) { @@ -275,7 +307,7 @@ TEST(MinidumpFileWriter, ZeroLengthStream) { const size_t kStreamOffset = kDirectoryOffset + sizeof(MINIDUMP_DIRECTORY); const size_t kFileSize = kStreamOffset + kStreamSize; - ASSERT_EQ(kFileSize, string_file.string().size()); + ASSERT_EQ(string_file.string().size(), kFileSize); const MINIDUMP_DIRECTORY* directory; const MINIDUMP_HEADER* header = @@ -283,9 +315,9 @@ TEST(MinidumpFileWriter, ZeroLengthStream) { ASSERT_NO_FATAL_FAILURE(VerifyMinidumpHeader(header, 1, 0)); ASSERT_TRUE(directory); - EXPECT_EQ(kStreamType, directory[0].StreamType); - EXPECT_EQ(kStreamSize, directory[0].Location.DataSize); - EXPECT_EQ(kStreamOffset, directory[0].Location.Rva); + EXPECT_EQ(directory[0].StreamType, kStreamType); + EXPECT_EQ(directory[0].Location.DataSize, kStreamSize); + EXPECT_EQ(directory[0].Location.Rva, kStreamOffset); } TEST(MinidumpFileWriter, InitializeFromSnapshot_Basic) { @@ -320,32 +352,32 @@ TEST(MinidumpFileWriter, InitializeFromSnapshot_Basic) { ASSERT_NO_FATAL_FAILURE(VerifyMinidumpHeader(header, 5, kSnapshotTime)); ASSERT_TRUE(directory); - EXPECT_EQ(kMinidumpStreamTypeSystemInfo, directory[0].StreamType); + EXPECT_EQ(directory[0].StreamType, kMinidumpStreamTypeSystemInfo); EXPECT_TRUE(MinidumpWritableAtLocationDescriptor( string_file.string(), directory[0].Location)); - EXPECT_EQ(kMinidumpStreamTypeMiscInfo, directory[1].StreamType); + EXPECT_EQ(directory[1].StreamType, kMinidumpStreamTypeMiscInfo); EXPECT_TRUE(MinidumpWritableAtLocationDescriptor( string_file.string(), directory[1].Location)); - EXPECT_EQ(kMinidumpStreamTypeThreadList, directory[2].StreamType); + EXPECT_EQ(directory[2].StreamType, kMinidumpStreamTypeThreadList); EXPECT_TRUE(MinidumpWritableAtLocationDescriptor( string_file.string(), directory[2].Location)); - EXPECT_EQ(kMinidumpStreamTypeModuleList, directory[3].StreamType); + EXPECT_EQ(directory[3].StreamType, kMinidumpStreamTypeModuleList); EXPECT_TRUE(MinidumpWritableAtLocationDescriptor( string_file.string(), directory[3].Location)); - EXPECT_EQ(kMinidumpStreamTypeMemoryList, directory[4].StreamType); + EXPECT_EQ(directory[4].StreamType, kMinidumpStreamTypeMemoryList); EXPECT_TRUE(MinidumpWritableAtLocationDescriptor( string_file.string(), directory[4].Location)); const MINIDUMP_MEMORY_LIST* memory_list = MinidumpWritableAtLocationDescriptor( string_file.string(), directory[4].Location); - EXPECT_EQ(1u, memory_list->NumberOfMemoryRanges); - EXPECT_EQ(kPebAddress, memory_list->MemoryRanges[0].StartOfMemoryRange); - EXPECT_EQ(kPebSize, memory_list->MemoryRanges[0].Memory.DataSize); + EXPECT_EQ(memory_list->NumberOfMemoryRanges, 1u); + EXPECT_EQ(memory_list->MemoryRanges[0].StartOfMemoryRange, kPebAddress); + EXPECT_EQ(memory_list->MemoryRanges[0].Memory.DataSize, kPebSize); } TEST(MinidumpFileWriter, InitializeFromSnapshot_Exception) { @@ -391,27 +423,27 @@ TEST(MinidumpFileWriter, InitializeFromSnapshot_Exception) { ASSERT_NO_FATAL_FAILURE(VerifyMinidumpHeader(header, 6, kSnapshotTime)); ASSERT_TRUE(directory); - EXPECT_EQ(kMinidumpStreamTypeSystemInfo, directory[0].StreamType); + EXPECT_EQ(directory[0].StreamType, kMinidumpStreamTypeSystemInfo); EXPECT_TRUE(MinidumpWritableAtLocationDescriptor( string_file.string(), directory[0].Location)); - EXPECT_EQ(kMinidumpStreamTypeMiscInfo, directory[1].StreamType); + EXPECT_EQ(directory[1].StreamType, kMinidumpStreamTypeMiscInfo); EXPECT_TRUE(MinidumpWritableAtLocationDescriptor( string_file.string(), directory[1].Location)); - EXPECT_EQ(kMinidumpStreamTypeThreadList, directory[2].StreamType); + EXPECT_EQ(directory[2].StreamType, kMinidumpStreamTypeThreadList); EXPECT_TRUE(MinidumpWritableAtLocationDescriptor( string_file.string(), directory[2].Location)); - EXPECT_EQ(kMinidumpStreamTypeException, directory[3].StreamType); + EXPECT_EQ(directory[3].StreamType, kMinidumpStreamTypeException); EXPECT_TRUE(MinidumpWritableAtLocationDescriptor( string_file.string(), directory[3].Location)); - EXPECT_EQ(kMinidumpStreamTypeModuleList, directory[4].StreamType); + EXPECT_EQ(directory[4].StreamType, kMinidumpStreamTypeModuleList); EXPECT_TRUE(MinidumpWritableAtLocationDescriptor( string_file.string(), directory[4].Location)); - EXPECT_EQ(kMinidumpStreamTypeMemoryList, directory[5].StreamType); + EXPECT_EQ(directory[5].StreamType, kMinidumpStreamTypeMemoryList); EXPECT_TRUE(MinidumpWritableAtLocationDescriptor( string_file.string(), directory[5].Location)); } @@ -455,31 +487,31 @@ TEST(MinidumpFileWriter, InitializeFromSnapshot_CrashpadInfo) { ASSERT_NO_FATAL_FAILURE(VerifyMinidumpHeader(header, 7, kSnapshotTime)); ASSERT_TRUE(directory); - EXPECT_EQ(kMinidumpStreamTypeSystemInfo, directory[0].StreamType); + EXPECT_EQ(directory[0].StreamType, kMinidumpStreamTypeSystemInfo); EXPECT_TRUE(MinidumpWritableAtLocationDescriptor( string_file.string(), directory[0].Location)); - EXPECT_EQ(kMinidumpStreamTypeMiscInfo, directory[1].StreamType); + EXPECT_EQ(directory[1].StreamType, kMinidumpStreamTypeMiscInfo); EXPECT_TRUE(MinidumpWritableAtLocationDescriptor( string_file.string(), directory[1].Location)); - EXPECT_EQ(kMinidumpStreamTypeThreadList, directory[2].StreamType); + EXPECT_EQ(directory[2].StreamType, kMinidumpStreamTypeThreadList); EXPECT_TRUE(MinidumpWritableAtLocationDescriptor( string_file.string(), directory[2].Location)); - EXPECT_EQ(kMinidumpStreamTypeException, directory[3].StreamType); + EXPECT_EQ(directory[3].StreamType, kMinidumpStreamTypeException); EXPECT_TRUE(MinidumpWritableAtLocationDescriptor( string_file.string(), directory[3].Location)); - EXPECT_EQ(kMinidumpStreamTypeModuleList, directory[4].StreamType); + EXPECT_EQ(directory[4].StreamType, kMinidumpStreamTypeModuleList); EXPECT_TRUE(MinidumpWritableAtLocationDescriptor( string_file.string(), directory[4].Location)); - EXPECT_EQ(kMinidumpStreamTypeCrashpadInfo, directory[5].StreamType); + EXPECT_EQ(directory[5].StreamType, kMinidumpStreamTypeCrashpadInfo); EXPECT_TRUE(MinidumpWritableAtLocationDescriptor( string_file.string(), directory[5].Location)); - EXPECT_EQ(kMinidumpStreamTypeMemoryList, directory[6].StreamType); + EXPECT_EQ(directory[6].StreamType, kMinidumpStreamTypeMemoryList); EXPECT_TRUE(MinidumpWritableAtLocationDescriptor( string_file.string(), directory[6].Location)); } @@ -508,7 +540,7 @@ TEST(MinidumpFileWriter, SameStreamType) { const size_t kStream0Offset = kDirectoryOffset + sizeof(MINIDUMP_DIRECTORY); const size_t kFileSize = kStream0Offset + kStream0Size; - ASSERT_EQ(kFileSize, string_file.string().size()); + ASSERT_EQ(string_file.string().size(), kFileSize); const MINIDUMP_DIRECTORY* directory; const MINIDUMP_HEADER* header = @@ -516,16 +548,16 @@ TEST(MinidumpFileWriter, SameStreamType) { ASSERT_NO_FATAL_FAILURE(VerifyMinidumpHeader(header, 1, 0)); ASSERT_TRUE(directory); - EXPECT_EQ(kStreamType, directory[0].StreamType); - EXPECT_EQ(kStream0Size, directory[0].Location.DataSize); - EXPECT_EQ(kStream0Offset, directory[0].Location.Rva); + EXPECT_EQ(directory[0].StreamType, kStreamType); + EXPECT_EQ(directory[0].Location.DataSize, kStream0Size); + EXPECT_EQ(directory[0].Location.Rva, kStream0Offset); const uint8_t* stream_data = MinidumpWritableAtLocationDescriptor( string_file.string(), directory[0].Location); ASSERT_TRUE(stream_data); std::string expected_stream(kStream0Size, kStream0Value); - EXPECT_EQ(0, memcmp(stream_data, expected_stream.c_str(), kStream0Size)); + EXPECT_EQ(memcmp(stream_data, expected_stream.c_str(), kStream0Size), 0); } } // namespace diff --git a/minidump/minidump_handle_writer_test.cc b/minidump/minidump_handle_writer_test.cc index db4cae5b..6f238c8f 100644 --- a/minidump/minidump_handle_writer_test.cc +++ b/minidump/minidump_handle_writer_test.cc @@ -46,9 +46,9 @@ void GetHandleDataStream( const size_t kDirectoryIndex = 0; - ASSERT_EQ(kMinidumpStreamTypeHandleData, - directory[kDirectoryIndex].StreamType); - EXPECT_EQ(kHandleDataStreamOffset, directory[kDirectoryIndex].Location.Rva); + ASSERT_EQ(directory[kDirectoryIndex].StreamType, + kMinidumpStreamTypeHandleData); + EXPECT_EQ(directory[kDirectoryIndex].Location.Rva, kHandleDataStreamOffset); *handle_data_stream = MinidumpWritableAtLocationDescriptor( @@ -64,15 +64,15 @@ TEST(MinidumpHandleDataWriter, Empty) { StringFile string_file; ASSERT_TRUE(minidump_file_writer.WriteEverything(&string_file)); - ASSERT_EQ(sizeof(MINIDUMP_HEADER) + sizeof(MINIDUMP_DIRECTORY) + - sizeof(MINIDUMP_HANDLE_DATA_STREAM), - string_file.string().size()); + ASSERT_EQ(string_file.string().size(), + sizeof(MINIDUMP_HEADER) + sizeof(MINIDUMP_DIRECTORY) + + sizeof(MINIDUMP_HANDLE_DATA_STREAM)); const MINIDUMP_HANDLE_DATA_STREAM* handle_data_stream = nullptr; ASSERT_NO_FATAL_FAILURE( GetHandleDataStream(string_file.string(), &handle_data_stream)); - EXPECT_EQ(0u, handle_data_stream->NumberOfDescriptors); + EXPECT_EQ(handle_data_stream->NumberOfDescriptors, 0u); } TEST(MinidumpHandleDataWriter, OneHandle) { @@ -99,29 +99,29 @@ TEST(MinidumpHandleDataWriter, OneHandle) { const size_t kTypeNameStringDataLength = (handle_snapshot.type_name.size() + 1) * sizeof(base::char16); - ASSERT_EQ(sizeof(MINIDUMP_HEADER) + sizeof(MINIDUMP_DIRECTORY) + + ASSERT_EQ(string_file.string().size(), + sizeof(MINIDUMP_HEADER) + sizeof(MINIDUMP_DIRECTORY) + sizeof(MINIDUMP_HANDLE_DATA_STREAM) + sizeof(MINIDUMP_HANDLE_DESCRIPTOR) + sizeof(MINIDUMP_STRING) + - kTypeNameStringDataLength, - string_file.string().size()); + kTypeNameStringDataLength); const MINIDUMP_HANDLE_DATA_STREAM* handle_data_stream = nullptr; ASSERT_NO_FATAL_FAILURE( GetHandleDataStream(string_file.string(), &handle_data_stream)); - EXPECT_EQ(1u, handle_data_stream->NumberOfDescriptors); + EXPECT_EQ(handle_data_stream->NumberOfDescriptors, 1u); const MINIDUMP_HANDLE_DESCRIPTOR* handle_descriptor = reinterpret_cast( &handle_data_stream[1]); - EXPECT_EQ(handle_snapshot.handle, handle_descriptor->Handle); - EXPECT_EQ(handle_snapshot.type_name, - base::UTF16ToUTF8(MinidumpStringAtRVAAsString( - string_file.string(), handle_descriptor->TypeNameRva))); - EXPECT_EQ(0u, handle_descriptor->ObjectNameRva); - EXPECT_EQ(handle_snapshot.attributes, handle_descriptor->Attributes); - EXPECT_EQ(handle_snapshot.granted_access, handle_descriptor->GrantedAccess); - EXPECT_EQ(handle_snapshot.handle_count, handle_descriptor->HandleCount); - EXPECT_EQ(handle_snapshot.pointer_count, handle_descriptor->PointerCount); + EXPECT_EQ(handle_descriptor->Handle, handle_snapshot.handle); + EXPECT_EQ(base::UTF16ToUTF8(MinidumpStringAtRVAAsString( + string_file.string(), handle_descriptor->TypeNameRva)), + handle_snapshot.type_name); + EXPECT_EQ(handle_descriptor->ObjectNameRva, 0u); + EXPECT_EQ(handle_descriptor->Attributes, handle_snapshot.attributes); + EXPECT_EQ(handle_descriptor->GrantedAccess, handle_snapshot.granted_access); + EXPECT_EQ(handle_descriptor->HandleCount, handle_snapshot.handle_count); + EXPECT_EQ(handle_descriptor->PointerCount, handle_snapshot.pointer_count); } TEST(MinidumpHandleDataWriter, RepeatedTypeName) { @@ -157,45 +157,45 @@ TEST(MinidumpHandleDataWriter, RepeatedTypeName) { const size_t kTypeNameStringDataLength = (handle_snapshot.type_name.size() + 1) * sizeof(base::char16); - ASSERT_EQ(sizeof(MINIDUMP_HEADER) + sizeof(MINIDUMP_DIRECTORY) + + ASSERT_EQ(string_file.string().size(), + sizeof(MINIDUMP_HEADER) + sizeof(MINIDUMP_DIRECTORY) + sizeof(MINIDUMP_HANDLE_DATA_STREAM) + (sizeof(MINIDUMP_HANDLE_DESCRIPTOR) * 2) + - sizeof(MINIDUMP_STRING) + kTypeNameStringDataLength, - string_file.string().size()); + sizeof(MINIDUMP_STRING) + kTypeNameStringDataLength); const MINIDUMP_HANDLE_DATA_STREAM* handle_data_stream = nullptr; ASSERT_NO_FATAL_FAILURE( GetHandleDataStream(string_file.string(), &handle_data_stream)); - EXPECT_EQ(2u, handle_data_stream->NumberOfDescriptors); + EXPECT_EQ(handle_data_stream->NumberOfDescriptors, 2u); const MINIDUMP_HANDLE_DESCRIPTOR* handle_descriptor = reinterpret_cast( &handle_data_stream[1]); - EXPECT_EQ(handle_snapshot.handle, handle_descriptor->Handle); - EXPECT_EQ(handle_snapshot.type_name, - base::UTF16ToUTF8(MinidumpStringAtRVAAsString( - string_file.string(), handle_descriptor->TypeNameRva))); - EXPECT_EQ(0u, handle_descriptor->ObjectNameRva); - EXPECT_EQ(handle_snapshot.attributes, handle_descriptor->Attributes); - EXPECT_EQ(handle_snapshot.granted_access, handle_descriptor->GrantedAccess); - EXPECT_EQ(handle_snapshot.handle_count, handle_descriptor->HandleCount); - EXPECT_EQ(handle_snapshot.pointer_count, handle_descriptor->PointerCount); + EXPECT_EQ(handle_descriptor->Handle, handle_snapshot.handle); + EXPECT_EQ(base::UTF16ToUTF8(MinidumpStringAtRVAAsString( + string_file.string(), handle_descriptor->TypeNameRva)), + handle_snapshot.type_name); + EXPECT_EQ(handle_descriptor->ObjectNameRva, 0u); + EXPECT_EQ(handle_descriptor->Attributes, handle_snapshot.attributes); + EXPECT_EQ(handle_descriptor->GrantedAccess, handle_snapshot.granted_access); + EXPECT_EQ(handle_descriptor->HandleCount, handle_snapshot.handle_count); + EXPECT_EQ(handle_descriptor->PointerCount, handle_snapshot.pointer_count); const MINIDUMP_HANDLE_DESCRIPTOR* handle_descriptor2 = reinterpret_cast( reinterpret_cast(&handle_data_stream[1]) + sizeof(MINIDUMP_HANDLE_DESCRIPTOR)); - EXPECT_EQ(handle_snapshot2.handle, handle_descriptor2->Handle); - EXPECT_EQ(handle_snapshot2.type_name, - base::UTF16ToUTF8(MinidumpStringAtRVAAsString( - string_file.string(), handle_descriptor2->TypeNameRva))); - EXPECT_EQ(0u, handle_descriptor2->ObjectNameRva); - EXPECT_EQ(handle_snapshot2.attributes, handle_descriptor2->Attributes); - EXPECT_EQ(handle_snapshot2.granted_access, handle_descriptor2->GrantedAccess); - EXPECT_EQ(handle_snapshot2.handle_count, handle_descriptor2->HandleCount); - EXPECT_EQ(handle_snapshot2.pointer_count, handle_descriptor2->PointerCount); + EXPECT_EQ(handle_descriptor2->Handle, handle_snapshot2.handle); + EXPECT_EQ(base::UTF16ToUTF8(MinidumpStringAtRVAAsString( + string_file.string(), handle_descriptor2->TypeNameRva)), + handle_snapshot2.type_name); + EXPECT_EQ(handle_descriptor2->ObjectNameRva, 0u); + EXPECT_EQ(handle_descriptor2->Attributes, handle_snapshot2.attributes); + EXPECT_EQ(handle_descriptor2->GrantedAccess, handle_snapshot2.granted_access); + EXPECT_EQ(handle_descriptor2->HandleCount, handle_snapshot2.handle_count); + EXPECT_EQ(handle_descriptor2->PointerCount, handle_snapshot2.pointer_count); - EXPECT_EQ(handle_descriptor->TypeNameRva, handle_descriptor2->TypeNameRva); + EXPECT_EQ(handle_descriptor2->TypeNameRva, handle_descriptor->TypeNameRva); } } // namespace diff --git a/minidump/minidump_memory_info_writer_test.cc b/minidump/minidump_memory_info_writer_test.cc index 8debff56..1458279f 100644 --- a/minidump/minidump_memory_info_writer_test.cc +++ b/minidump/minidump_memory_info_writer_test.cc @@ -45,10 +45,10 @@ void GetMemoryInfoListStream( const size_t kDirectoryIndex = 0; - ASSERT_EQ(kMinidumpStreamTypeMemoryInfoList, - directory[kDirectoryIndex].StreamType); - EXPECT_EQ(kMemoryInfoListStreamOffset, - directory[kDirectoryIndex].Location.Rva); + ASSERT_EQ(directory[kDirectoryIndex].StreamType, + kMinidumpStreamTypeMemoryInfoList); + EXPECT_EQ(directory[kDirectoryIndex].Location.Rva, + kMemoryInfoListStreamOffset); *memory_info_list = MinidumpWritableAtLocationDescriptor( @@ -66,15 +66,15 @@ TEST(MinidumpMemoryInfoWriter, Empty) { StringFile string_file; ASSERT_TRUE(minidump_file_writer.WriteEverything(&string_file)); - ASSERT_EQ(sizeof(MINIDUMP_HEADER) + sizeof(MINIDUMP_DIRECTORY) + - sizeof(MINIDUMP_MEMORY_INFO_LIST), - string_file.string().size()); + ASSERT_EQ(string_file.string().size(), + sizeof(MINIDUMP_HEADER) + sizeof(MINIDUMP_DIRECTORY) + + sizeof(MINIDUMP_MEMORY_INFO_LIST)); const MINIDUMP_MEMORY_INFO_LIST* memory_info_list = nullptr; ASSERT_NO_FATAL_FAILURE( GetMemoryInfoListStream(string_file.string(), &memory_info_list)); - EXPECT_EQ(0u, memory_info_list->NumberOfEntries); + EXPECT_EQ(memory_info_list->NumberOfEntries, 0u); } TEST(MinidumpMemoryInfoWriter, OneRegion) { @@ -104,25 +104,25 @@ TEST(MinidumpMemoryInfoWriter, OneRegion) { StringFile string_file; ASSERT_TRUE(minidump_file_writer.WriteEverything(&string_file)); - ASSERT_EQ(sizeof(MINIDUMP_HEADER) + sizeof(MINIDUMP_DIRECTORY) + + ASSERT_EQ(string_file.string().size(), + sizeof(MINIDUMP_HEADER) + sizeof(MINIDUMP_DIRECTORY) + sizeof(MINIDUMP_MEMORY_INFO_LIST) + - sizeof(MINIDUMP_MEMORY_INFO), - string_file.string().size()); + sizeof(MINIDUMP_MEMORY_INFO)); const MINIDUMP_MEMORY_INFO_LIST* memory_info_list = nullptr; ASSERT_NO_FATAL_FAILURE( GetMemoryInfoListStream(string_file.string(), &memory_info_list)); - EXPECT_EQ(1u, memory_info_list->NumberOfEntries); + EXPECT_EQ(memory_info_list->NumberOfEntries, 1u); const MINIDUMP_MEMORY_INFO* memory_info = reinterpret_cast(&memory_info_list[1]); - EXPECT_EQ(mmi.BaseAddress, memory_info->BaseAddress); - EXPECT_EQ(mmi.AllocationBase, memory_info->AllocationBase); - EXPECT_EQ(mmi.AllocationProtect, memory_info->AllocationProtect); - EXPECT_EQ(mmi.RegionSize, memory_info->RegionSize); - EXPECT_EQ(mmi.State, memory_info->State); - EXPECT_EQ(mmi.Protect, memory_info->Protect); - EXPECT_EQ(mmi.Type, memory_info->Type); + EXPECT_EQ(memory_info->BaseAddress, mmi.BaseAddress); + EXPECT_EQ(memory_info->AllocationBase, mmi.AllocationBase); + EXPECT_EQ(memory_info->AllocationProtect, mmi.AllocationProtect); + EXPECT_EQ(memory_info->RegionSize, mmi.RegionSize); + EXPECT_EQ(memory_info->State, mmi.State); + EXPECT_EQ(memory_info->Protect, mmi.Protect); + EXPECT_EQ(memory_info->Type, mmi.Type); } } // namespace diff --git a/minidump/minidump_memory_writer_test.cc b/minidump/minidump_memory_writer_test.cc index 65fcca28..45fdf491 100644 --- a/minidump/minidump_memory_writer_test.cc +++ b/minidump/minidump_memory_writer_test.cc @@ -60,15 +60,15 @@ void GetMemoryListStream(const std::string& file_contents, size_t directory_index = 0; if (expected_streams > 1) { - ASSERT_EQ(kBogusStreamType, directory[directory_index].StreamType); - ASSERT_EQ(0u, directory[directory_index].Location.DataSize); - ASSERT_EQ(kMemoryListStreamOffset, directory[directory_index].Location.Rva); + ASSERT_EQ(directory[directory_index].StreamType, kBogusStreamType); + ASSERT_EQ(directory[directory_index].Location.DataSize, 0u); + ASSERT_EQ(directory[directory_index].Location.Rva, kMemoryListStreamOffset); ++directory_index; } - ASSERT_EQ(kMinidumpStreamTypeMemoryList, - directory[directory_index].StreamType); - EXPECT_EQ(kMemoryListStreamOffset, directory[directory_index].Location.Rva); + ASSERT_EQ(directory[directory_index].StreamType, + kMinidumpStreamTypeMemoryList); + EXPECT_EQ(directory[directory_index].Location.Rva, kMemoryListStreamOffset); *memory_list = MinidumpWritableAtLocationDescriptor( file_contents, directory[directory_index].Location); @@ -84,15 +84,15 @@ TEST(MinidumpMemoryWriter, EmptyMemoryList) { StringFile string_file; ASSERT_TRUE(minidump_file_writer.WriteEverything(&string_file)); - ASSERT_EQ(sizeof(MINIDUMP_HEADER) + sizeof(MINIDUMP_DIRECTORY) + - sizeof(MINIDUMP_MEMORY_LIST), - string_file.string().size()); + ASSERT_EQ(string_file.string().size(), + sizeof(MINIDUMP_HEADER) + sizeof(MINIDUMP_DIRECTORY) + + sizeof(MINIDUMP_MEMORY_LIST)); const MINIDUMP_MEMORY_LIST* memory_list = nullptr; ASSERT_NO_FATAL_FAILURE( GetMemoryListStream(string_file.string(), &memory_list, 1)); - EXPECT_EQ(0u, memory_list->NumberOfMemoryRanges); + EXPECT_EQ(memory_list->NumberOfMemoryRanges, 0u); } TEST(MinidumpMemoryWriter, OneMemoryRegion) { @@ -157,7 +157,7 @@ TEST(MinidumpMemoryWriter, TwoMemoryRegions) { ASSERT_NO_FATAL_FAILURE( GetMemoryListStream(string_file.string(), &memory_list, 1)); - EXPECT_EQ(2u, memory_list->NumberOfMemoryRanges); + EXPECT_EQ(memory_list->NumberOfMemoryRanges, 2u); MINIDUMP_MEMORY_DESCRIPTOR expected; @@ -222,7 +222,7 @@ class TestMemoryStream final : public internal::MinidumpStreamWriter { } bool WriteObject(FileWriterInterface* file_writer) override { - EXPECT_EQ(kStateWritable, state()); + EXPECT_EQ(state(), kStateWritable); return true; } @@ -266,7 +266,7 @@ TEST(MinidumpMemoryWriter, ExtraMemory) { ASSERT_NO_FATAL_FAILURE( GetMemoryListStream(string_file.string(), &memory_list, 2)); - EXPECT_EQ(2u, memory_list->NumberOfMemoryRanges); + EXPECT_EQ(memory_list->NumberOfMemoryRanges, 2u); MINIDUMP_MEMORY_DESCRIPTOR expected; @@ -344,7 +344,7 @@ TEST(MinidumpMemoryWriter, AddFromSnapshot) { ASSERT_NO_FATAL_FAILURE( GetMemoryListStream(string_file.string(), &memory_list, 1)); - ASSERT_EQ(3u, memory_list->NumberOfMemoryRanges); + ASSERT_EQ(memory_list->NumberOfMemoryRanges, 3u); for (size_t index = 0; index < memory_list->NumberOfMemoryRanges; ++index) { SCOPED_TRACE(base::StringPrintf("index %" PRIuS, index)); diff --git a/minidump/minidump_misc_info_writer_test.cc b/minidump/minidump_misc_info_writer_test.cc index 71fdbfbd..74a41701 100644 --- a/minidump/minidump_misc_info_writer_test.cc +++ b/minidump/minidump_misc_info_writer_test.cc @@ -49,7 +49,7 @@ void GetMiscInfoStream(const std::string& file_contents, const T** misc_info) { const size_t kMiscInfoStreamSize = sizeof(T); const size_t kFileSize = kMiscInfoStreamOffset + kMiscInfoStreamSize; - ASSERT_EQ(kFileSize, file_contents.size()); + ASSERT_EQ(file_contents.size(), kFileSize); const MINIDUMP_DIRECTORY* directory; const MINIDUMP_HEADER* header = @@ -57,8 +57,8 @@ void GetMiscInfoStream(const std::string& file_contents, const T** misc_info) { ASSERT_NO_FATAL_FAILURE(VerifyMinidumpHeader(header, 1, 0)); ASSERT_TRUE(directory); - ASSERT_EQ(kMinidumpStreamTypeMiscInfo, directory[0].StreamType); - EXPECT_EQ(kMiscInfoStreamOffset, directory[0].Location.Rva); + ASSERT_EQ(directory[0].StreamType, kMinidumpStreamTypeMiscInfo); + EXPECT_EQ(directory[0].Location.Rva, kMiscInfoStreamOffset); *misc_info = MinidumpWritableAtLocationDescriptor(file_contents, directory[0].Location); @@ -70,19 +70,19 @@ void ExpectNULPaddedString16Equal(const base::char16* expected, size_t size) { base::string16 expected_string(expected, size); base::string16 observed_string(observed, size); - EXPECT_EQ(expected_string, observed_string); + EXPECT_EQ(observed_string, expected_string); } void ExpectSystemTimeEqual(const SYSTEMTIME* expected, const SYSTEMTIME* observed) { - EXPECT_EQ(expected->wYear, observed->wYear); - EXPECT_EQ(expected->wMonth, observed->wMonth); - EXPECT_EQ(expected->wDayOfWeek, observed->wDayOfWeek); - EXPECT_EQ(expected->wDay, observed->wDay); - EXPECT_EQ(expected->wHour, observed->wHour); - EXPECT_EQ(expected->wMinute, observed->wMinute); - EXPECT_EQ(expected->wSecond, observed->wSecond); - EXPECT_EQ(expected->wMilliseconds, observed->wMilliseconds); + EXPECT_EQ(observed->wYear, expected->wYear); + EXPECT_EQ(observed->wMonth, expected->wMonth); + EXPECT_EQ(observed->wDayOfWeek, expected->wDayOfWeek); + EXPECT_EQ(observed->wDay, expected->wDay); + EXPECT_EQ(observed->wHour, expected->wHour); + EXPECT_EQ(observed->wMinute, expected->wMinute); + EXPECT_EQ(observed->wSecond, expected->wSecond); + EXPECT_EQ(observed->wMilliseconds, expected->wMilliseconds); } template @@ -92,11 +92,11 @@ template <> void ExpectMiscInfoEqual( const MINIDUMP_MISC_INFO* expected, const MINIDUMP_MISC_INFO* observed) { - EXPECT_EQ(expected->Flags1, observed->Flags1); - EXPECT_EQ(expected->ProcessId, observed->ProcessId); - EXPECT_EQ(expected->ProcessCreateTime, observed->ProcessCreateTime); - EXPECT_EQ(expected->ProcessUserTime, observed->ProcessUserTime); - EXPECT_EQ(expected->ProcessKernelTime, observed->ProcessKernelTime); + EXPECT_EQ(observed->Flags1, expected->Flags1); + EXPECT_EQ(observed->ProcessId, expected->ProcessId); + EXPECT_EQ(observed->ProcessCreateTime, expected->ProcessCreateTime); + EXPECT_EQ(observed->ProcessUserTime, expected->ProcessUserTime); + EXPECT_EQ(observed->ProcessKernelTime, expected->ProcessKernelTime); } template <> @@ -106,12 +106,12 @@ void ExpectMiscInfoEqual( ExpectMiscInfoEqual( reinterpret_cast(expected), reinterpret_cast(observed)); - EXPECT_EQ(expected->ProcessorMaxMhz, observed->ProcessorMaxMhz); - EXPECT_EQ(expected->ProcessorCurrentMhz, observed->ProcessorCurrentMhz); - EXPECT_EQ(expected->ProcessorMhzLimit, observed->ProcessorMhzLimit); - EXPECT_EQ(expected->ProcessorMaxIdleState, observed->ProcessorMaxIdleState); - EXPECT_EQ(expected->ProcessorCurrentIdleState, - observed->ProcessorCurrentIdleState); + EXPECT_EQ(observed->ProcessorMaxMhz, expected->ProcessorMaxMhz); + EXPECT_EQ(observed->ProcessorCurrentMhz, expected->ProcessorCurrentMhz); + EXPECT_EQ(observed->ProcessorMhzLimit, expected->ProcessorMhzLimit); + EXPECT_EQ(observed->ProcessorMaxIdleState, expected->ProcessorMaxIdleState); + EXPECT_EQ(observed->ProcessorCurrentIdleState, + expected->ProcessorCurrentIdleState); } template <> @@ -121,11 +121,11 @@ void ExpectMiscInfoEqual( ExpectMiscInfoEqual( reinterpret_cast(expected), reinterpret_cast(observed)); - EXPECT_EQ(expected->ProcessIntegrityLevel, observed->ProcessIntegrityLevel); - EXPECT_EQ(expected->ProcessExecuteFlags, observed->ProcessExecuteFlags); - EXPECT_EQ(expected->ProtectedProcess, observed->ProtectedProcess); - EXPECT_EQ(expected->TimeZoneId, observed->TimeZoneId); - EXPECT_EQ(expected->TimeZone.Bias, observed->TimeZone.Bias); + EXPECT_EQ(observed->ProcessIntegrityLevel, expected->ProcessIntegrityLevel); + EXPECT_EQ(observed->ProcessExecuteFlags, expected->ProcessExecuteFlags); + EXPECT_EQ(observed->ProtectedProcess, expected->ProtectedProcess); + EXPECT_EQ(observed->TimeZoneId, expected->TimeZoneId); + EXPECT_EQ(observed->TimeZone.Bias, expected->TimeZone.Bias); { SCOPED_TRACE("Standard"); ExpectNULPaddedString16Equal(expected->TimeZone.StandardName, @@ -133,7 +133,7 @@ void ExpectMiscInfoEqual( arraysize(expected->TimeZone.StandardName)); ExpectSystemTimeEqual(&expected->TimeZone.StandardDate, &observed->TimeZone.StandardDate); - EXPECT_EQ(expected->TimeZone.StandardBias, observed->TimeZone.StandardBias); + EXPECT_EQ(observed->TimeZone.StandardBias, expected->TimeZone.StandardBias); } { SCOPED_TRACE("Daylight"); @@ -142,7 +142,7 @@ void ExpectMiscInfoEqual( arraysize(expected->TimeZone.DaylightName)); ExpectSystemTimeEqual(&expected->TimeZone.DaylightDate, &observed->TimeZone.DaylightDate); - EXPECT_EQ(expected->TimeZone.DaylightBias, observed->TimeZone.DaylightBias); + EXPECT_EQ(observed->TimeZone.DaylightBias, expected->TimeZone.DaylightBias); } } @@ -174,20 +174,20 @@ void ExpectMiscInfoEqual( ExpectMiscInfoEqual( reinterpret_cast(expected), reinterpret_cast(observed)); - EXPECT_EQ(expected->XStateData.SizeOfInfo, observed->XStateData.SizeOfInfo); - EXPECT_EQ(expected->XStateData.ContextSize, observed->XStateData.ContextSize); - EXPECT_EQ(expected->XStateData.EnabledFeatures, - observed->XStateData.EnabledFeatures); + EXPECT_EQ(observed->XStateData.SizeOfInfo, expected->XStateData.SizeOfInfo); + EXPECT_EQ(observed->XStateData.ContextSize, expected->XStateData.ContextSize); + EXPECT_EQ(observed->XStateData.EnabledFeatures, + expected->XStateData.EnabledFeatures); for (size_t feature_index = 0; feature_index < arraysize(observed->XStateData.Features); ++feature_index) { SCOPED_TRACE(base::StringPrintf("feature_index %" PRIuS, feature_index)); - EXPECT_EQ(expected->XStateData.Features[feature_index].Offset, - observed->XStateData.Features[feature_index].Offset); - EXPECT_EQ(expected->XStateData.Features[feature_index].Size, - observed->XStateData.Features[feature_index].Size); + EXPECT_EQ(observed->XStateData.Features[feature_index].Offset, + expected->XStateData.Features[feature_index].Offset); + EXPECT_EQ(observed->XStateData.Features[feature_index].Size, + expected->XStateData.Features[feature_index].Size); } - EXPECT_EQ(expected->ProcessCookie, observed->ProcessCookie); + EXPECT_EQ(observed->ProcessCookie, expected->ProcessCookie); } TEST(MinidumpMiscInfoWriter, Empty) { diff --git a/minidump/minidump_module_crashpad_info_writer_test.cc b/minidump/minidump_module_crashpad_info_writer_test.cc index 34761a7c..74451843 100644 --- a/minidump/minidump_module_crashpad_info_writer_test.cc +++ b/minidump/minidump_module_crashpad_info_writer_test.cc @@ -50,7 +50,7 @@ const MinidumpModuleCrashpadInfoList* MinidumpModuleCrashpadInfoListAtStart( } if (list->count != count) { - EXPECT_EQ(count, list->count); + EXPECT_EQ(list->count, count); return nullptr; } @@ -65,8 +65,8 @@ TEST(MinidumpModuleCrashpadInfoWriter, EmptyList) { EXPECT_FALSE(module_list_writer->IsUseful()); EXPECT_TRUE(module_list_writer->WriteEverything(&string_file)); - ASSERT_EQ(sizeof(MinidumpModuleCrashpadInfoList), - string_file.string().size()); + ASSERT_EQ(string_file.string().size(), + sizeof(MinidumpModuleCrashpadInfoList)); const MinidumpModuleCrashpadInfoList* module_list = MinidumpModuleCrashpadInfoListAtStart(string_file.string(), 0); @@ -85,26 +85,26 @@ TEST(MinidumpModuleCrashpadInfoWriter, EmptyModule) { EXPECT_TRUE(module_list_writer->IsUseful()); EXPECT_TRUE(module_list_writer->WriteEverything(&string_file)); - ASSERT_EQ(sizeof(MinidumpModuleCrashpadInfoList) + + ASSERT_EQ(string_file.string().size(), + sizeof(MinidumpModuleCrashpadInfoList) + sizeof(MinidumpModuleCrashpadInfoLink) + - sizeof(MinidumpModuleCrashpadInfo), - string_file.string().size()); + sizeof(MinidumpModuleCrashpadInfo)); const MinidumpModuleCrashpadInfoList* module_list = MinidumpModuleCrashpadInfoListAtStart(string_file.string(), 1); ASSERT_TRUE(module_list); - EXPECT_EQ(0u, module_list->modules[0].minidump_module_list_index); + EXPECT_EQ(module_list->modules[0].minidump_module_list_index, 0u); const MinidumpModuleCrashpadInfo* module = MinidumpWritableAtLocationDescriptor( string_file.string(), module_list->modules[0].location); ASSERT_TRUE(module); - EXPECT_EQ(MinidumpModuleCrashpadInfo::kVersion, module->version); - EXPECT_EQ(0u, module->list_annotations.DataSize); - EXPECT_EQ(0u, module->list_annotations.Rva); - EXPECT_EQ(0u, module->simple_annotations.DataSize); - EXPECT_EQ(0u, module->simple_annotations.Rva); + EXPECT_EQ(module->version, MinidumpModuleCrashpadInfo::kVersion); + EXPECT_EQ(module->list_annotations.DataSize, 0u); + EXPECT_EQ(module->list_annotations.Rva, 0u); + EXPECT_EQ(module->simple_annotations.DataSize, 0u); + EXPECT_EQ(module->simple_annotations.Rva, 0u); } TEST(MinidumpModuleCrashpadInfoWriter, FullModule) { @@ -140,7 +140,8 @@ TEST(MinidumpModuleCrashpadInfoWriter, FullModule) { EXPECT_TRUE(module_list_writer->IsUseful()); EXPECT_TRUE(module_list_writer->WriteEverything(&string_file)); - ASSERT_EQ(sizeof(MinidumpModuleCrashpadInfoList) + + ASSERT_EQ(string_file.string().size(), + sizeof(MinidumpModuleCrashpadInfoList) + sizeof(MinidumpModuleCrashpadInfoLink) + sizeof(MinidumpModuleCrashpadInfo) + sizeof(MinidumpRVAList) + @@ -149,48 +150,47 @@ TEST(MinidumpModuleCrashpadInfoWriter, FullModule) { sizeof(MinidumpSimpleStringDictionaryEntry) + sizeof(MinidumpUTF8String) + arraysize(kEntry) + 2 + // padding sizeof(MinidumpUTF8String) + arraysize(kKey) + - sizeof(MinidumpUTF8String) + arraysize(kValue), - string_file.string().size()); + sizeof(MinidumpUTF8String) + arraysize(kValue)); const MinidumpModuleCrashpadInfoList* module_list = MinidumpModuleCrashpadInfoListAtStart(string_file.string(), 1); ASSERT_TRUE(module_list); - EXPECT_EQ(kMinidumpModuleListIndex, - module_list->modules[0].minidump_module_list_index); + EXPECT_EQ(module_list->modules[0].minidump_module_list_index, + kMinidumpModuleListIndex); const MinidumpModuleCrashpadInfo* module = MinidumpWritableAtLocationDescriptor( string_file.string(), module_list->modules[0].location); ASSERT_TRUE(module); - EXPECT_EQ(MinidumpModuleCrashpadInfo::kVersion, module->version); - EXPECT_NE(0u, module->list_annotations.DataSize); - EXPECT_NE(0u, module->list_annotations.Rva); - EXPECT_NE(0u, module->simple_annotations.DataSize); - EXPECT_NE(0u, module->simple_annotations.Rva); + EXPECT_EQ(module->version, MinidumpModuleCrashpadInfo::kVersion); + EXPECT_NE(module->list_annotations.DataSize, 0u); + EXPECT_NE(module->list_annotations.Rva, 0u); + EXPECT_NE(module->simple_annotations.DataSize, 0u); + EXPECT_NE(module->simple_annotations.Rva, 0u); const MinidumpRVAList* list_annotations = MinidumpWritableAtLocationDescriptor( string_file.string(), module->list_annotations); ASSERT_TRUE(list_annotations); - ASSERT_EQ(1u, list_annotations->count); - EXPECT_EQ(kEntry, - MinidumpUTF8StringAtRVAAsString(string_file.string(), - list_annotations->children[0])); + ASSERT_EQ(list_annotations->count, 1u); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString(string_file.string(), + list_annotations->children[0]), + kEntry); const MinidumpSimpleStringDictionary* simple_annotations = MinidumpWritableAtLocationDescriptor( string_file.string(), module->simple_annotations); ASSERT_TRUE(simple_annotations); - ASSERT_EQ(1u, simple_annotations->count); - EXPECT_EQ(kKey, - MinidumpUTF8StringAtRVAAsString( - string_file.string(), simple_annotations->entries[0].key)); - EXPECT_EQ(kValue, - MinidumpUTF8StringAtRVAAsString( - string_file.string(), simple_annotations->entries[0].value)); + ASSERT_EQ(simple_annotations->count, 1u); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString(string_file.string(), + simple_annotations->entries[0].key), + kKey); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString( + string_file.string(), simple_annotations->entries[0].value), + kValue); } TEST(MinidumpModuleCrashpadInfoWriter, ThreeModules) { @@ -258,14 +258,14 @@ TEST(MinidumpModuleCrashpadInfoWriter, ThreeModules) { MinidumpModuleCrashpadInfoListAtStart(string_file.string(), 3); ASSERT_TRUE(module_list); - EXPECT_EQ(kMinidumpModuleListIndex0, - module_list->modules[0].minidump_module_list_index); + EXPECT_EQ(module_list->modules[0].minidump_module_list_index, + kMinidumpModuleListIndex0); const MinidumpModuleCrashpadInfo* module_0 = MinidumpWritableAtLocationDescriptor( string_file.string(), module_list->modules[0].location); ASSERT_TRUE(module_0); - EXPECT_EQ(MinidumpModuleCrashpadInfo::kVersion, module_0->version); + EXPECT_EQ(module_0->version, MinidumpModuleCrashpadInfo::kVersion); const MinidumpRVAList* list_annotations_0 = MinidumpWritableAtLocationDescriptor( @@ -277,22 +277,22 @@ TEST(MinidumpModuleCrashpadInfoWriter, ThreeModules) { string_file.string(), module_0->simple_annotations); ASSERT_TRUE(simple_annotations_0); - ASSERT_EQ(1u, simple_annotations_0->count); - EXPECT_EQ(kKey0, - MinidumpUTF8StringAtRVAAsString( - string_file.string(), simple_annotations_0->entries[0].key)); - EXPECT_EQ(kValue0, - MinidumpUTF8StringAtRVAAsString( - string_file.string(), simple_annotations_0->entries[0].value)); + ASSERT_EQ(simple_annotations_0->count, 1u); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString( + string_file.string(), simple_annotations_0->entries[0].key), + kKey0); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString( + string_file.string(), simple_annotations_0->entries[0].value), + kValue0); - EXPECT_EQ(kMinidumpModuleListIndex1, - module_list->modules[1].minidump_module_list_index); + EXPECT_EQ(module_list->modules[1].minidump_module_list_index, + kMinidumpModuleListIndex1); const MinidumpModuleCrashpadInfo* module_1 = MinidumpWritableAtLocationDescriptor( string_file.string(), module_list->modules[1].location); ASSERT_TRUE(module_1); - EXPECT_EQ(MinidumpModuleCrashpadInfo::kVersion, module_1->version); + EXPECT_EQ(module_1->version, MinidumpModuleCrashpadInfo::kVersion); const MinidumpRVAList* list_annotations_1 = MinidumpWritableAtLocationDescriptor( @@ -304,14 +304,14 @@ TEST(MinidumpModuleCrashpadInfoWriter, ThreeModules) { string_file.string(), module_1->simple_annotations); EXPECT_FALSE(simple_annotations_1); - EXPECT_EQ(kMinidumpModuleListIndex2, - module_list->modules[2].minidump_module_list_index); + EXPECT_EQ(module_list->modules[2].minidump_module_list_index, + kMinidumpModuleListIndex2); const MinidumpModuleCrashpadInfo* module_2 = MinidumpWritableAtLocationDescriptor( string_file.string(), module_list->modules[2].location); ASSERT_TRUE(module_2); - EXPECT_EQ(MinidumpModuleCrashpadInfo::kVersion, module_2->version); + EXPECT_EQ(module_2->version, MinidumpModuleCrashpadInfo::kVersion); const MinidumpRVAList* list_annotations_2 = MinidumpWritableAtLocationDescriptor( @@ -323,19 +323,19 @@ TEST(MinidumpModuleCrashpadInfoWriter, ThreeModules) { string_file.string(), module_2->simple_annotations); ASSERT_TRUE(simple_annotations_2); - ASSERT_EQ(2u, simple_annotations_2->count); - EXPECT_EQ(kKey2A, - MinidumpUTF8StringAtRVAAsString( - string_file.string(), simple_annotations_2->entries[0].key)); - EXPECT_EQ(kValue2A, - MinidumpUTF8StringAtRVAAsString( - string_file.string(), simple_annotations_2->entries[0].value)); - EXPECT_EQ(kKey2B, - MinidumpUTF8StringAtRVAAsString( - string_file.string(), simple_annotations_2->entries[1].key)); - EXPECT_EQ(kValue2B, - MinidumpUTF8StringAtRVAAsString( - string_file.string(), simple_annotations_2->entries[1].value)); + ASSERT_EQ(simple_annotations_2->count, 2u); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString( + string_file.string(), simple_annotations_2->entries[0].key), + kKey2A); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString( + string_file.string(), simple_annotations_2->entries[0].value), + kValue2A); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString( + string_file.string(), simple_annotations_2->entries[1].key), + kKey2B); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString( + string_file.string(), simple_annotations_2->entries[1].value), + kValue2B); } TEST(MinidumpModuleCrashpadInfoWriter, InitializeFromSnapshot) { @@ -387,13 +387,13 @@ TEST(MinidumpModuleCrashpadInfoWriter, InitializeFromSnapshot) { MinidumpModuleCrashpadInfoListAtStart(string_file.string(), 3); ASSERT_TRUE(module_list); - EXPECT_EQ(0u, module_list->modules[0].minidump_module_list_index); + EXPECT_EQ(module_list->modules[0].minidump_module_list_index, 0u); const MinidumpModuleCrashpadInfo* module_0 = MinidumpWritableAtLocationDescriptor( string_file.string(), module_list->modules[0].location); ASSERT_TRUE(module_0); - EXPECT_EQ(MinidumpModuleCrashpadInfo::kVersion, module_0->version); + EXPECT_EQ(module_0->version, MinidumpModuleCrashpadInfo::kVersion); const MinidumpRVAList* list_annotations_0 = MinidumpWritableAtLocationDescriptor( @@ -405,27 +405,27 @@ TEST(MinidumpModuleCrashpadInfoWriter, InitializeFromSnapshot) { string_file.string(), module_0->simple_annotations); ASSERT_TRUE(simple_annotations_0); - ASSERT_EQ(annotations_simple_map_0.size(), simple_annotations_0->count); - EXPECT_EQ(kKey0B, - MinidumpUTF8StringAtRVAAsString( - string_file.string(), simple_annotations_0->entries[0].key)); - EXPECT_EQ(kValue0B, - MinidumpUTF8StringAtRVAAsString( - string_file.string(), simple_annotations_0->entries[0].value)); - EXPECT_EQ(kKey0A, - MinidumpUTF8StringAtRVAAsString( - string_file.string(), simple_annotations_0->entries[1].key)); - EXPECT_EQ(kValue0A, - MinidumpUTF8StringAtRVAAsString( - string_file.string(), simple_annotations_0->entries[1].value)); + ASSERT_EQ(simple_annotations_0->count, annotations_simple_map_0.size()); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString( + string_file.string(), simple_annotations_0->entries[0].key), + kKey0B); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString( + string_file.string(), simple_annotations_0->entries[0].value), + kValue0B); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString( + string_file.string(), simple_annotations_0->entries[1].key), + kKey0A); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString( + string_file.string(), simple_annotations_0->entries[1].value), + kValue0A); - EXPECT_EQ(2u, module_list->modules[1].minidump_module_list_index); + EXPECT_EQ(module_list->modules[1].minidump_module_list_index, 2u); const MinidumpModuleCrashpadInfo* module_2 = MinidumpWritableAtLocationDescriptor( string_file.string(), module_list->modules[1].location); ASSERT_TRUE(module_2); - EXPECT_EQ(MinidumpModuleCrashpadInfo::kVersion, module_2->version); + EXPECT_EQ(module_2->version, MinidumpModuleCrashpadInfo::kVersion); const MinidumpRVAList* list_annotations_2 = MinidumpWritableAtLocationDescriptor( @@ -437,34 +437,34 @@ TEST(MinidumpModuleCrashpadInfoWriter, InitializeFromSnapshot) { string_file.string(), module_2->simple_annotations); ASSERT_TRUE(simple_annotations_2); - ASSERT_EQ(annotations_simple_map_2.size(), simple_annotations_2->count); - EXPECT_EQ(kKey2, - MinidumpUTF8StringAtRVAAsString( - string_file.string(), simple_annotations_2->entries[0].key)); - EXPECT_EQ(kValue2, - MinidumpUTF8StringAtRVAAsString( - string_file.string(), simple_annotations_2->entries[0].value)); + ASSERT_EQ(simple_annotations_2->count, annotations_simple_map_2.size()); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString( + string_file.string(), simple_annotations_2->entries[0].key), + kKey2); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString( + string_file.string(), simple_annotations_2->entries[0].value), + kValue2); - EXPECT_EQ(3u, module_list->modules[2].minidump_module_list_index); + EXPECT_EQ(module_list->modules[2].minidump_module_list_index, 3u); const MinidumpModuleCrashpadInfo* module_3 = MinidumpWritableAtLocationDescriptor( string_file.string(), module_list->modules[2].location); ASSERT_TRUE(module_3); - EXPECT_EQ(MinidumpModuleCrashpadInfo::kVersion, module_3->version); + EXPECT_EQ(module_3->version, MinidumpModuleCrashpadInfo::kVersion); const MinidumpRVAList* list_annotations_3 = MinidumpWritableAtLocationDescriptor( string_file.string(), module_3->list_annotations); ASSERT_TRUE(list_annotations_3); - ASSERT_EQ(annotations_vector_3.size(), list_annotations_3->count); - EXPECT_EQ(kEntry3A, - MinidumpUTF8StringAtRVAAsString(string_file.string(), - list_annotations_3->children[0])); - EXPECT_EQ(kEntry3B, - MinidumpUTF8StringAtRVAAsString(string_file.string(), - list_annotations_3->children[1])); + ASSERT_EQ(list_annotations_3->count, annotations_vector_3.size()); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString(string_file.string(), + list_annotations_3->children[0]), + kEntry3A); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString(string_file.string(), + list_annotations_3->children[1]), + kEntry3B); const MinidumpSimpleStringDictionary* simple_annotations_3 = MinidumpWritableAtLocationDescriptor( diff --git a/minidump/minidump_module_writer_test.cc b/minidump/minidump_module_writer_test.cc index 6a0464cf..b2478d5a 100644 --- a/minidump/minidump_module_writer_test.cc +++ b/minidump/minidump_module_writer_test.cc @@ -56,8 +56,8 @@ void GetModuleListStream(const std::string& file_contents, ASSERT_NO_FATAL_FAILURE(VerifyMinidumpHeader(header, 1, 0)); ASSERT_TRUE(directory); - ASSERT_EQ(kMinidumpStreamTypeModuleList, directory[0].StreamType); - EXPECT_EQ(kModuleListStreamOffset, directory[0].Location.Rva); + ASSERT_EQ(directory[0].StreamType, kMinidumpStreamTypeModuleList); + EXPECT_EQ(directory[0].Location.Rva, kModuleListStreamOffset); *module_list = MinidumpWritableAtLocationDescriptor( file_contents, directory[0].Location); @@ -73,15 +73,15 @@ TEST(MinidumpModuleWriter, EmptyModuleList) { StringFile string_file; ASSERT_TRUE(minidump_file_writer.WriteEverything(&string_file)); - ASSERT_EQ(sizeof(MINIDUMP_HEADER) + sizeof(MINIDUMP_DIRECTORY) + - sizeof(MINIDUMP_MODULE_LIST), - string_file.string().size()); + ASSERT_EQ(string_file.string().size(), + sizeof(MINIDUMP_HEADER) + sizeof(MINIDUMP_DIRECTORY) + + sizeof(MINIDUMP_MODULE_LIST)); const MINIDUMP_MODULE_LIST* module_list = nullptr; ASSERT_NO_FATAL_FAILURE( GetModuleListStream(string_file.string(), &module_list)); - EXPECT_EQ(0u, module_list->NumberOfModules); + EXPECT_EQ(module_list->NumberOfModules, 0u); } // If |expected_pdb_name| is not nullptr, |codeview_record| is used to locate a @@ -96,7 +96,7 @@ void ExpectCodeViewRecord(const MINIDUMP_LOCATION_DESCRIPTOR* codeview_record, time_t expected_pdb_timestamp, uint32_t expected_pdb_age) { if (expected_pdb_name) { - EXPECT_NE(0u, codeview_record->Rva); + EXPECT_NE(codeview_record->Rva, 0u); std::string observed_pdb_name; if (expected_pdb_uuid) { @@ -105,11 +105,11 @@ void ExpectCodeViewRecord(const MINIDUMP_LOCATION_DESCRIPTOR* codeview_record, MinidumpWritableAtLocationDescriptor( file_contents, *codeview_record); ASSERT_TRUE(codeview_pdb70_record); - EXPECT_EQ(0, - memcmp(expected_pdb_uuid, + EXPECT_EQ(memcmp(expected_pdb_uuid, &codeview_pdb70_record->uuid, - sizeof(codeview_pdb70_record->uuid))); - EXPECT_EQ(expected_pdb_age, codeview_pdb70_record->age); + sizeof(codeview_pdb70_record->uuid)), + 0); + EXPECT_EQ(codeview_pdb70_record->age, expected_pdb_age); observed_pdb_name.assign( reinterpret_cast(&codeview_pdb70_record->pdb_name[0]), @@ -120,9 +120,9 @@ void ExpectCodeViewRecord(const MINIDUMP_LOCATION_DESCRIPTOR* codeview_record, MinidumpWritableAtLocationDescriptor( file_contents, *codeview_record); ASSERT_TRUE(codeview_pdb20_record); - EXPECT_EQ(static_cast(expected_pdb_timestamp), - codeview_pdb20_record->timestamp); - EXPECT_EQ(expected_pdb_age, codeview_pdb20_record->age); + EXPECT_EQ(codeview_pdb20_record->timestamp, + static_cast(expected_pdb_timestamp)); + EXPECT_EQ(codeview_pdb20_record->age, expected_pdb_age); observed_pdb_name.assign( reinterpret_cast(&codeview_pdb20_record->pdb_name[0]), @@ -130,14 +130,14 @@ void ExpectCodeViewRecord(const MINIDUMP_LOCATION_DESCRIPTOR* codeview_record, } // Check for, and then remove, the NUL terminator. - EXPECT_EQ('\0', observed_pdb_name[observed_pdb_name.size() - 1]); + EXPECT_EQ(observed_pdb_name[observed_pdb_name.size() - 1], '\0'); observed_pdb_name.resize(observed_pdb_name.size() - 1); - EXPECT_EQ(expected_pdb_name, observed_pdb_name); + EXPECT_EQ(observed_pdb_name, expected_pdb_name); } else { // There should be no CodeView record. - EXPECT_EQ(0u, codeview_record->DataSize); - EXPECT_EQ(0u, codeview_record->Rva); + EXPECT_EQ(codeview_record->DataSize, 0u); + EXPECT_EQ(codeview_record->Rva, 0u); } } @@ -152,21 +152,21 @@ void ExpectMiscellaneousDebugRecord( uint32_t expected_debug_type, bool expected_debug_utf16) { if (expected_debug_name) { - EXPECT_NE(0u, misc_record->Rva); + EXPECT_NE(misc_record->Rva, 0u); const IMAGE_DEBUG_MISC* misc_debug_record = MinidumpWritableAtLocationDescriptor(file_contents, *misc_record); ASSERT_TRUE(misc_debug_record); - EXPECT_EQ(expected_debug_type, misc_debug_record->DataType); - EXPECT_EQ(expected_debug_utf16, misc_debug_record->Unicode != 0); - EXPECT_EQ(0u, misc_debug_record->Reserved[0]); - EXPECT_EQ(0u, misc_debug_record->Reserved[1]); - EXPECT_EQ(0u, misc_debug_record->Reserved[2]); + EXPECT_EQ(misc_debug_record->DataType, expected_debug_type); + EXPECT_EQ(misc_debug_record->Unicode != 0, expected_debug_utf16); + EXPECT_EQ(misc_debug_record->Reserved[0], 0u); + EXPECT_EQ(misc_debug_record->Reserved[1], 0u); + EXPECT_EQ(misc_debug_record->Reserved[2], 0u); // Check for the NUL terminator. size_t bytes_available = misc_debug_record->Length - offsetof(IMAGE_DEBUG_MISC, Data); - EXPECT_EQ('\0', misc_debug_record->Data[bytes_available - 1]); + EXPECT_EQ(misc_debug_record->Data[bytes_available - 1], '\0'); std::string observed_data( reinterpret_cast(misc_debug_record->Data)); @@ -184,14 +184,14 @@ void ExpectMiscellaneousDebugRecord( // Make sure that any padding bytes after the first NUL are also NUL. for (size_t index = bytes_used; index < bytes_available; ++index) { - EXPECT_EQ('\0', misc_debug_record->Data[index]); + EXPECT_EQ(misc_debug_record->Data[index], '\0'); } - EXPECT_EQ(expected_debug_name, observed_data); + EXPECT_EQ(observed_data, expected_debug_name); } else { // There should be no miscellaneous debugging record. - EXPECT_EQ(0u, misc_record->DataSize); - EXPECT_EQ(0u, misc_record->Rva); + EXPECT_EQ(misc_record->DataSize, 0u); + EXPECT_EQ(misc_record->Rva, 0u); } } @@ -215,43 +215,43 @@ void ExpectModule(const MINIDUMP_MODULE* expected, const char* expected_debug_name, uint32_t expected_debug_type, bool expected_debug_utf16) { - EXPECT_EQ(expected->BaseOfImage, observed->BaseOfImage); - EXPECT_EQ(expected->SizeOfImage, observed->SizeOfImage); - EXPECT_EQ(expected->CheckSum, observed->CheckSum); - EXPECT_EQ(expected->TimeDateStamp, observed->TimeDateStamp); - EXPECT_EQ(implicit_cast(VS_FFI_SIGNATURE), - observed->VersionInfo.dwSignature); - EXPECT_EQ(implicit_cast(VS_FFI_STRUCVERSION), - observed->VersionInfo.dwStrucVersion); - EXPECT_EQ(expected->VersionInfo.dwFileVersionMS, - observed->VersionInfo.dwFileVersionMS); - EXPECT_EQ(expected->VersionInfo.dwFileVersionLS, - observed->VersionInfo.dwFileVersionLS); - EXPECT_EQ(expected->VersionInfo.dwProductVersionMS, - observed->VersionInfo.dwProductVersionMS); - EXPECT_EQ(expected->VersionInfo.dwProductVersionLS, - observed->VersionInfo.dwProductVersionLS); - EXPECT_EQ(expected->VersionInfo.dwFileFlagsMask, - observed->VersionInfo.dwFileFlagsMask); - EXPECT_EQ(expected->VersionInfo.dwFileFlags, - observed->VersionInfo.dwFileFlags); - EXPECT_EQ(expected->VersionInfo.dwFileOS, observed->VersionInfo.dwFileOS); - EXPECT_EQ(expected->VersionInfo.dwFileType, observed->VersionInfo.dwFileType); - EXPECT_EQ(expected->VersionInfo.dwFileSubtype, - observed->VersionInfo.dwFileSubtype); - EXPECT_EQ(expected->VersionInfo.dwFileDateMS, - observed->VersionInfo.dwFileDateMS); - EXPECT_EQ(expected->VersionInfo.dwFileDateLS, - observed->VersionInfo.dwFileDateLS); - EXPECT_EQ(0u, observed->Reserved0); - EXPECT_EQ(0u, observed->Reserved1); + EXPECT_EQ(observed->BaseOfImage, expected->BaseOfImage); + EXPECT_EQ(observed->SizeOfImage, expected->SizeOfImage); + EXPECT_EQ(observed->CheckSum, expected->CheckSum); + EXPECT_EQ(observed->TimeDateStamp, expected->TimeDateStamp); + EXPECT_EQ(observed->VersionInfo.dwSignature, + implicit_cast(VS_FFI_SIGNATURE)); + EXPECT_EQ(observed->VersionInfo.dwStrucVersion, + implicit_cast(VS_FFI_STRUCVERSION)); + EXPECT_EQ(observed->VersionInfo.dwFileVersionMS, + expected->VersionInfo.dwFileVersionMS); + EXPECT_EQ(observed->VersionInfo.dwFileVersionLS, + expected->VersionInfo.dwFileVersionLS); + EXPECT_EQ(observed->VersionInfo.dwProductVersionMS, + expected->VersionInfo.dwProductVersionMS); + EXPECT_EQ(observed->VersionInfo.dwProductVersionLS, + expected->VersionInfo.dwProductVersionLS); + EXPECT_EQ(observed->VersionInfo.dwFileFlagsMask, + expected->VersionInfo.dwFileFlagsMask); + EXPECT_EQ(observed->VersionInfo.dwFileFlags, + expected->VersionInfo.dwFileFlags); + EXPECT_EQ(observed->VersionInfo.dwFileOS, expected->VersionInfo.dwFileOS); + EXPECT_EQ(observed->VersionInfo.dwFileType, expected->VersionInfo.dwFileType); + EXPECT_EQ(observed->VersionInfo.dwFileSubtype, + expected->VersionInfo.dwFileSubtype); + EXPECT_EQ(observed->VersionInfo.dwFileDateMS, + expected->VersionInfo.dwFileDateMS); + EXPECT_EQ(observed->VersionInfo.dwFileDateLS, + expected->VersionInfo.dwFileDateLS); + EXPECT_EQ(observed->Reserved0, 0u); + EXPECT_EQ(observed->Reserved1, 0u); - EXPECT_NE(0u, observed->ModuleNameRva); + EXPECT_NE(observed->ModuleNameRva, 0u); base::string16 observed_module_name_utf16 = MinidumpStringAtRVAAsString(file_contents, observed->ModuleNameRva); base::string16 expected_module_name_utf16 = base::UTF8ToUTF16(expected_module_name); - EXPECT_EQ(expected_module_name_utf16, observed_module_name_utf16); + EXPECT_EQ(observed_module_name_utf16, expected_module_name_utf16); ASSERT_NO_FATAL_FAILURE(ExpectCodeViewRecord(&observed->CvRecord, file_contents, @@ -290,7 +290,7 @@ TEST(MinidumpModuleWriter, EmptyModule) { ASSERT_NO_FATAL_FAILURE( GetModuleListStream(string_file.string(), &module_list)); - EXPECT_EQ(1u, module_list->NumberOfModules); + EXPECT_EQ(module_list->NumberOfModules, 1u); MINIDUMP_MODULE expected = {}; ASSERT_NO_FATAL_FAILURE(ExpectModule(&expected, @@ -381,7 +381,7 @@ TEST(MinidumpModuleWriter, OneModule) { ASSERT_NO_FATAL_FAILURE( GetModuleListStream(string_file.string(), &module_list)); - EXPECT_EQ(1u, module_list->NumberOfModules); + EXPECT_EQ(module_list->NumberOfModules, 1u); MINIDUMP_MODULE expected = {}; expected.BaseOfImage = kModuleBase; @@ -456,7 +456,7 @@ TEST(MinidumpModuleWriter, OneModule_CodeViewUsesPDB20_MiscUsesUTF16) { ASSERT_NO_FATAL_FAILURE( GetModuleListStream(string_file.string(), &module_list)); - EXPECT_EQ(1u, module_list->NumberOfModules); + EXPECT_EQ(module_list->NumberOfModules, 1u); MINIDUMP_MODULE expected = {}; @@ -548,7 +548,7 @@ TEST(MinidumpModuleWriter, ThreeModules) { ASSERT_NO_FATAL_FAILURE( GetModuleListStream(string_file.string(), &module_list)); - EXPECT_EQ(3u, module_list->NumberOfModules); + EXPECT_EQ(module_list->NumberOfModules, 3u); MINIDUMP_MODULE expected = {}; @@ -733,7 +733,7 @@ TEST(MinidumpModuleWriter, InitializeFromSnapshot) { ASSERT_NO_FATAL_FAILURE( GetModuleListStream(string_file.string(), &module_list)); - ASSERT_EQ(3u, module_list->NumberOfModules); + ASSERT_EQ(module_list->NumberOfModules, 3u); for (size_t index = 0; index < module_list->NumberOfModules; ++index) { SCOPED_TRACE(base::StringPrintf("index %" PRIuS, index)); diff --git a/minidump/minidump_rva_list_writer_test.cc b/minidump/minidump_rva_list_writer_test.cc index 4d0d051d..1d26b27b 100644 --- a/minidump/minidump_rva_list_writer_test.cc +++ b/minidump/minidump_rva_list_writer_test.cc @@ -48,7 +48,7 @@ TEST(MinidumpRVAListWriter, Empty) { StringFile string_file; ASSERT_TRUE(list_writer.WriteEverything(&string_file)); - EXPECT_EQ(sizeof(MinidumpRVAList), string_file.string().size()); + EXPECT_EQ(string_file.string().size(), sizeof(MinidumpRVAList)); const MinidumpRVAList* list = MinidumpRVAListAtStart(string_file.string(), 0); ASSERT_TRUE(list); @@ -70,7 +70,7 @@ TEST(MinidumpRVAListWriter, OneChild) { const uint32_t* child = MinidumpWritableAtRVA( string_file.string(), list->children[0]); ASSERT_TRUE(child); - EXPECT_EQ(kValue, *child); + EXPECT_EQ(*child, kValue); } TEST(MinidumpRVAListWriter, ThreeChildren) { @@ -96,7 +96,7 @@ TEST(MinidumpRVAListWriter, ThreeChildren) { const uint32_t* child = MinidumpWritableAtRVA( string_file.string(), list->children[index]); ASSERT_TRUE(child); - EXPECT_EQ(kValues[index], *child); + EXPECT_EQ(*child, kValues[index]); } } diff --git a/minidump/minidump_simple_string_dictionary_writer_test.cc b/minidump/minidump_simple_string_dictionary_writer_test.cc index b4c81443..ebf5601d 100644 --- a/minidump/minidump_simple_string_dictionary_writer_test.cc +++ b/minidump/minidump_simple_string_dictionary_writer_test.cc @@ -51,13 +51,13 @@ TEST(MinidumpSimpleStringDictionaryWriter, EmptySimpleStringDictionary) { EXPECT_FALSE(dictionary_writer.IsUseful()); EXPECT_TRUE(dictionary_writer.WriteEverything(&string_file)); - ASSERT_EQ(sizeof(MinidumpSimpleStringDictionary), - string_file.string().size()); + ASSERT_EQ(string_file.string().size(), + sizeof(MinidumpSimpleStringDictionary)); const MinidumpSimpleStringDictionary* dictionary = MinidumpSimpleStringDictionaryAtStart(string_file.string(), 0); ASSERT_TRUE(dictionary); - EXPECT_EQ(0u, dictionary->count); + EXPECT_EQ(dictionary->count, 0u); } TEST(MinidumpSimpleStringDictionaryWriter, EmptyKeyValue) { @@ -71,23 +71,23 @@ TEST(MinidumpSimpleStringDictionaryWriter, EmptyKeyValue) { EXPECT_TRUE(dictionary_writer.IsUseful()); EXPECT_TRUE(dictionary_writer.WriteEverything(&string_file)); - ASSERT_EQ(sizeof(MinidumpSimpleStringDictionary) + + ASSERT_EQ(string_file.string().size(), + sizeof(MinidumpSimpleStringDictionary) + sizeof(MinidumpSimpleStringDictionaryEntry) + - 2 * sizeof(MinidumpUTF8String) + 1 + 3 + 1, // 3 for padding - string_file.string().size()); + 2 * sizeof(MinidumpUTF8String) + 1 + 3 + 1); // 3 for padding const MinidumpSimpleStringDictionary* dictionary = MinidumpSimpleStringDictionaryAtStart(string_file.string(), 1); ASSERT_TRUE(dictionary); - EXPECT_EQ(1u, dictionary->count); - EXPECT_EQ(12u, dictionary->entries[0].key); - EXPECT_EQ(20u, dictionary->entries[0].value); - EXPECT_EQ("", - MinidumpUTF8StringAtRVAAsString(string_file.string(), - dictionary->entries[0].key)); - EXPECT_EQ("", - MinidumpUTF8StringAtRVAAsString(string_file.string(), - dictionary->entries[0].value)); + EXPECT_EQ(dictionary->count, 1u); + EXPECT_EQ(dictionary->entries[0].key, 12u); + EXPECT_EQ(dictionary->entries[0].value, 20u); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString(string_file.string(), + dictionary->entries[0].key), + ""); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString(string_file.string(), + dictionary->entries[0].value), + ""); } TEST(MinidumpSimpleStringDictionaryWriter, OneKeyValue) { @@ -105,23 +105,23 @@ TEST(MinidumpSimpleStringDictionaryWriter, OneKeyValue) { EXPECT_TRUE(dictionary_writer.IsUseful()); EXPECT_TRUE(dictionary_writer.WriteEverything(&string_file)); - ASSERT_EQ(sizeof(MinidumpSimpleStringDictionary) + + ASSERT_EQ(string_file.string().size(), + sizeof(MinidumpSimpleStringDictionary) + sizeof(MinidumpSimpleStringDictionaryEntry) + - 2 * sizeof(MinidumpUTF8String) + sizeof(kKey) + sizeof(kValue), - string_file.string().size()); + 2 * sizeof(MinidumpUTF8String) + sizeof(kKey) + sizeof(kValue)); const MinidumpSimpleStringDictionary* dictionary = MinidumpSimpleStringDictionaryAtStart(string_file.string(), 1); ASSERT_TRUE(dictionary); - EXPECT_EQ(1u, dictionary->count); - EXPECT_EQ(12u, dictionary->entries[0].key); - EXPECT_EQ(20u, dictionary->entries[0].value); - EXPECT_EQ(kKey, - MinidumpUTF8StringAtRVAAsString(string_file.string(), - dictionary->entries[0].key)); - EXPECT_EQ(kValue, - MinidumpUTF8StringAtRVAAsString(string_file.string(), - dictionary->entries[0].value)); + EXPECT_EQ(dictionary->count, 1u); + EXPECT_EQ(dictionary->entries[0].key, 12u); + EXPECT_EQ(dictionary->entries[0].value, 20u); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString(string_file.string(), + dictionary->entries[0].key), + kKey); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString(string_file.string(), + dictionary->entries[0].value), + kValue); } TEST(MinidumpSimpleStringDictionaryWriter, ThreeKeysValues) { @@ -151,23 +151,23 @@ TEST(MinidumpSimpleStringDictionaryWriter, ThreeKeysValues) { EXPECT_TRUE(dictionary_writer.IsUseful()); EXPECT_TRUE(dictionary_writer.WriteEverything(&string_file)); - ASSERT_EQ(sizeof(MinidumpSimpleStringDictionary) + + ASSERT_EQ(string_file.string().size(), + sizeof(MinidumpSimpleStringDictionary) + 3 * sizeof(MinidumpSimpleStringDictionaryEntry) + 6 * sizeof(MinidumpUTF8String) + sizeof(kKey2) + sizeof(kValue2) + 3 + sizeof(kKey0) + 1 + sizeof(kValue0) + 1 + - sizeof(kKey1) + 3 + sizeof(kValue1), - string_file.string().size()); + sizeof(kKey1) + 3 + sizeof(kValue1)); const MinidumpSimpleStringDictionary* dictionary = MinidumpSimpleStringDictionaryAtStart(string_file.string(), 3); ASSERT_TRUE(dictionary); - EXPECT_EQ(3u, dictionary->count); - EXPECT_EQ(28u, dictionary->entries[0].key); - EXPECT_EQ(36u, dictionary->entries[0].value); - EXPECT_EQ(48u, dictionary->entries[1].key); - EXPECT_EQ(56u, dictionary->entries[1].value); - EXPECT_EQ(68u, dictionary->entries[2].key); - EXPECT_EQ(80u, dictionary->entries[2].value); + EXPECT_EQ(dictionary->count, 3u); + EXPECT_EQ(dictionary->entries[0].key, 28u); + EXPECT_EQ(dictionary->entries[0].value, 36u); + EXPECT_EQ(dictionary->entries[1].key, 48u); + EXPECT_EQ(dictionary->entries[1].value, 56u); + EXPECT_EQ(dictionary->entries[2].key, 68u); + EXPECT_EQ(dictionary->entries[2].value, 80u); // The entries don’t appear in the order they were added. The current // implementation uses a std::map and sorts keys, so the entires appear in @@ -175,24 +175,24 @@ TEST(MinidumpSimpleStringDictionaryWriter, ThreeKeysValues) { // if the writer stops sorting in this order. Testing for a specific order is // just the easiest way to write this test while the writer will output things // in a known order. - EXPECT_EQ(kKey2, - MinidumpUTF8StringAtRVAAsString(string_file.string(), - dictionary->entries[0].key)); - EXPECT_EQ(kValue2, - MinidumpUTF8StringAtRVAAsString(string_file.string(), - dictionary->entries[0].value)); - EXPECT_EQ(kKey0, - MinidumpUTF8StringAtRVAAsString(string_file.string(), - dictionary->entries[1].key)); - EXPECT_EQ(kValue0, - MinidumpUTF8StringAtRVAAsString(string_file.string(), - dictionary->entries[1].value)); - EXPECT_EQ(kKey1, - MinidumpUTF8StringAtRVAAsString(string_file.string(), - dictionary->entries[2].key)); - EXPECT_EQ(kValue1, - MinidumpUTF8StringAtRVAAsString(string_file.string(), - dictionary->entries[2].value)); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString(string_file.string(), + dictionary->entries[0].key), + kKey2); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString(string_file.string(), + dictionary->entries[0].value), + kValue2); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString(string_file.string(), + dictionary->entries[1].key), + kKey0); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString(string_file.string(), + dictionary->entries[1].value), + kValue0); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString(string_file.string(), + dictionary->entries[2].key), + kKey1); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString(string_file.string(), + dictionary->entries[2].value), + kValue1); } TEST(MinidumpSimpleStringDictionaryWriter, DuplicateKeyValue) { @@ -215,23 +215,24 @@ TEST(MinidumpSimpleStringDictionaryWriter, DuplicateKeyValue) { EXPECT_TRUE(dictionary_writer.IsUseful()); EXPECT_TRUE(dictionary_writer.WriteEverything(&string_file)); - ASSERT_EQ(sizeof(MinidumpSimpleStringDictionary) + + ASSERT_EQ(string_file.string().size(), + sizeof(MinidumpSimpleStringDictionary) + sizeof(MinidumpSimpleStringDictionaryEntry) + - 2 * sizeof(MinidumpUTF8String) + sizeof(kKey) + sizeof(kValue1), - string_file.string().size()); + 2 * sizeof(MinidumpUTF8String) + sizeof(kKey) + + sizeof(kValue1)); const MinidumpSimpleStringDictionary* dictionary = MinidumpSimpleStringDictionaryAtStart(string_file.string(), 1); ASSERT_TRUE(dictionary); - EXPECT_EQ(1u, dictionary->count); - EXPECT_EQ(12u, dictionary->entries[0].key); - EXPECT_EQ(20u, dictionary->entries[0].value); - EXPECT_EQ(kKey, - MinidumpUTF8StringAtRVAAsString(string_file.string(), - dictionary->entries[0].key)); - EXPECT_EQ(kValue1, - MinidumpUTF8StringAtRVAAsString(string_file.string(), - dictionary->entries[0].value)); + EXPECT_EQ(dictionary->count, 1u); + EXPECT_EQ(dictionary->entries[0].key, 12u); + EXPECT_EQ(dictionary->entries[0].value, 20u); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString(string_file.string(), + dictionary->entries[0].key), + kKey); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString(string_file.string(), + dictionary->entries[0].value), + kValue1); } TEST(MinidumpSimpleStringDictionaryWriter, InitializeFromMap) { @@ -258,7 +259,7 @@ TEST(MinidumpSimpleStringDictionaryWriter, InitializeFromMap) { const MinidumpSimpleStringDictionary* dictionary = MinidumpSimpleStringDictionaryAtStart(string_file.string(), map.size()); ASSERT_TRUE(dictionary); - ASSERT_EQ(3u, dictionary->count); + ASSERT_EQ(dictionary->count, 3u); // The entries don’t appear in the order they were added. The current // implementation uses a std::map and sorts keys, so the entires appear in @@ -266,24 +267,24 @@ TEST(MinidumpSimpleStringDictionaryWriter, InitializeFromMap) { // if the writer stops sorting in this order. Testing for a specific order is // just the easiest way to write this test while the writer will output things // in a known order. - EXPECT_EQ(kKey1, - MinidumpUTF8StringAtRVAAsString(string_file.string(), - dictionary->entries[0].key)); - EXPECT_EQ(kValue1, - MinidumpUTF8StringAtRVAAsString(string_file.string(), - dictionary->entries[0].value)); - EXPECT_EQ(kKey0, - MinidumpUTF8StringAtRVAAsString(string_file.string(), - dictionary->entries[1].key)); - EXPECT_EQ(kValue0, - MinidumpUTF8StringAtRVAAsString(string_file.string(), - dictionary->entries[1].value)); - EXPECT_EQ(kKey2, - MinidumpUTF8StringAtRVAAsString(string_file.string(), - dictionary->entries[2].key)); - EXPECT_EQ(kValue2, - MinidumpUTF8StringAtRVAAsString(string_file.string(), - dictionary->entries[2].value)); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString(string_file.string(), + dictionary->entries[0].key), + kKey1); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString(string_file.string(), + dictionary->entries[0].value), + kValue1); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString(string_file.string(), + dictionary->entries[1].key), + kKey0); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString(string_file.string(), + dictionary->entries[1].value), + kValue0); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString(string_file.string(), + dictionary->entries[2].key), + kKey2); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString(string_file.string(), + dictionary->entries[2].value), + kValue2); } } // namespace diff --git a/minidump/minidump_string_writer_test.cc b/minidump/minidump_string_writer_test.cc index 09973213..6a1e5c64 100644 --- a/minidump/minidump_string_writer_test.cc +++ b/minidump/minidump_string_writer_test.cc @@ -40,13 +40,13 @@ TEST(MinidumpStringWriter, MinidumpUTF16StringWriter) { string_file.Reset(); crashpad::internal::MinidumpUTF16StringWriter string_writer; EXPECT_TRUE(string_writer.WriteEverything(&string_file)); - ASSERT_EQ(6u, string_file.string().size()); + ASSERT_EQ(string_file.string().size(), 6u); const MINIDUMP_STRING* minidump_string = MinidumpStringAtRVA(string_file.string(), 0); EXPECT_TRUE(minidump_string); - EXPECT_EQ(base::string16(), - MinidumpStringAtRVAAsString(string_file.string(), 0)); + EXPECT_EQ(MinidumpStringAtRVAAsString(string_file.string(), 0), + base::string16()); } const struct { @@ -74,10 +74,9 @@ TEST(MinidumpStringWriter, MinidumpUTF16StringWriter) { // Make sure that the expected output string with its NUL terminator fits in // the space provided. - ASSERT_EQ( - 0, - kTestData[index] - .output_string[arraysize(kTestData[index].output_string) - 1]); + ASSERT_EQ(kTestData[index] + .output_string[arraysize(kTestData[index].output_string) - 1], + 0); string_file.Reset(); crashpad::internal::MinidumpUTF16StringWriter string_writer; @@ -91,16 +90,16 @@ TEST(MinidumpStringWriter, MinidumpUTF16StringWriter) { ALLOW_UNUSED_LOCAL(tmp); const size_t expected_utf16_bytes = expected_utf16_units_with_nul * sizeof(tmp.Buffer[0]); - ASSERT_EQ(sizeof(MINIDUMP_STRING) + expected_utf16_bytes, - string_file.string().size()); + ASSERT_EQ(string_file.string().size(), + sizeof(MINIDUMP_STRING) + expected_utf16_bytes); const MINIDUMP_STRING* minidump_string = MinidumpStringAtRVA(string_file.string(), 0); EXPECT_TRUE(minidump_string); base::string16 expect_string = base::string16( kTestData[index].output_string, kTestData[index].output_length); - EXPECT_EQ(expect_string, - MinidumpStringAtRVAAsString(string_file.string(), 0)); + EXPECT_EQ(MinidumpStringAtRVAAsString(string_file.string(), 0), + expect_string); } } @@ -134,13 +133,13 @@ TEST(MinidumpStringWriter, ConvertInvalidUTF8ToUTF16) { EXPECT_TRUE(minidump_string); MINIDUMP_STRING tmp = {0}; ALLOW_UNUSED_LOCAL(tmp); - EXPECT_EQ(string_file.string().size() - sizeof(MINIDUMP_STRING) - - sizeof(tmp.Buffer[0]), - minidump_string->Length); + EXPECT_EQ(minidump_string->Length, + string_file.string().size() - sizeof(MINIDUMP_STRING) - + sizeof(tmp.Buffer[0])); base::string16 output_string = MinidumpStringAtRVAAsString(string_file.string(), 0); EXPECT_FALSE(output_string.empty()); - EXPECT_NE(base::string16::npos, output_string.find(0xfffd)); + EXPECT_NE(output_string.find(0xfffd), base::string16::npos); } } @@ -152,13 +151,13 @@ TEST(MinidumpStringWriter, MinidumpUTF8StringWriter) { string_file.Reset(); crashpad::internal::MinidumpUTF8StringWriter string_writer; EXPECT_TRUE(string_writer.WriteEverything(&string_file)); - ASSERT_EQ(5u, string_file.string().size()); + ASSERT_EQ(string_file.string().size(), 5u); const MinidumpUTF8String* minidump_string = MinidumpUTF8StringAtRVA(string_file.string(), 0); EXPECT_TRUE(minidump_string); - EXPECT_EQ(std::string(), - MinidumpUTF8StringAtRVAAsString(string_file.string(), 0)); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString(string_file.string(), 0), + std::string()); } const struct { @@ -186,18 +185,18 @@ TEST(MinidumpStringWriter, MinidumpUTF8StringWriter) { crashpad::internal::MinidumpUTF8StringWriter string_writer; std::string test_string(kTestData[index].string, kTestData[index].length); string_writer.SetUTF8(test_string); - EXPECT_EQ(test_string, string_writer.UTF8()); + EXPECT_EQ(string_writer.UTF8(), test_string); EXPECT_TRUE(string_writer.WriteEverything(&string_file)); const size_t expected_utf8_bytes_with_nul = kTestData[index].length + 1; - ASSERT_EQ(sizeof(MinidumpUTF8String) + expected_utf8_bytes_with_nul, - string_file.string().size()); + ASSERT_EQ(string_file.string().size(), + sizeof(MinidumpUTF8String) + expected_utf8_bytes_with_nul); const MinidumpUTF8String* minidump_string = MinidumpUTF8StringAtRVA(string_file.string(), 0); EXPECT_TRUE(minidump_string); - EXPECT_EQ(test_string, - MinidumpUTF8StringAtRVAAsString(string_file.string(), 0)); + EXPECT_EQ(MinidumpUTF8StringAtRVAAsString(string_file.string(), 0), + test_string); } } @@ -245,9 +244,9 @@ void MinidumpStringListTest() { ASSERT_TRUE(list); for (size_t index = 0; index < strings.size(); ++index) { - EXPECT_EQ(Traits::ExpectationForUTF8(strings[index]), - Traits::ObservationAtRVA(string_file.string(), - list->children[index])); + EXPECT_EQ( + Traits::ObservationAtRVA(string_file.string(), list->children[index]), + Traits::ExpectationForUTF8(strings[index])); } } diff --git a/minidump/minidump_system_info_writer_test.cc b/minidump/minidump_system_info_writer_test.cc index 4f35d3d1..0dd90559 100644 --- a/minidump/minidump_system_info_writer_test.cc +++ b/minidump/minidump_system_info_writer_test.cc @@ -54,7 +54,7 @@ void GetSystemInfoStream(const std::string& file_contents, const size_t kFileSize = kCSDVersionOffset + sizeof(MINIDUMP_STRING) + kCSDVersionBytesWithNUL; - ASSERT_EQ(kFileSize, file_contents.size()); + ASSERT_EQ(file_contents.size(), kFileSize); const MINIDUMP_DIRECTORY* directory; const MINIDUMP_HEADER* header = @@ -62,18 +62,18 @@ void GetSystemInfoStream(const std::string& file_contents, ASSERT_NO_FATAL_FAILURE(VerifyMinidumpHeader(header, 1, 0)); ASSERT_TRUE(directory); - ASSERT_EQ(kMinidumpStreamTypeSystemInfo, directory[0].StreamType); - EXPECT_EQ(kSystemInfoStreamOffset, directory[0].Location.Rva); + ASSERT_EQ(directory[0].StreamType, kMinidumpStreamTypeSystemInfo); + EXPECT_EQ(directory[0].Location.Rva, kSystemInfoStreamOffset); *system_info = MinidumpWritableAtLocationDescriptor( file_contents, directory[0].Location); ASSERT_TRUE(system_info); - EXPECT_EQ(kCSDVersionOffset, (*system_info)->CSDVersionRva); + EXPECT_EQ((*system_info)->CSDVersionRva, kCSDVersionOffset); *csd_version = MinidumpStringAtRVA(file_contents, (*system_info)->CSDVersionRva); - EXPECT_EQ(kCSDVersionBytes, (*csd_version)->Length); + EXPECT_EQ((*csd_version)->Length, kCSDVersionBytes); } TEST(MinidumpSystemInfoWriter, Empty) { @@ -93,27 +93,27 @@ TEST(MinidumpSystemInfoWriter, Empty) { ASSERT_NO_FATAL_FAILURE( GetSystemInfoStream(string_file.string(), 0, &system_info, &csd_version)); - EXPECT_EQ(kMinidumpCPUArchitectureUnknown, - system_info->ProcessorArchitecture); - EXPECT_EQ(0u, system_info->ProcessorLevel); - EXPECT_EQ(0u, system_info->ProcessorRevision); - EXPECT_EQ(0u, system_info->NumberOfProcessors); - EXPECT_EQ(0u, system_info->ProductType); - EXPECT_EQ(0u, system_info->MajorVersion); - EXPECT_EQ(0u, system_info->MinorVersion); - EXPECT_EQ(0u, system_info->BuildNumber); - EXPECT_EQ(0u, system_info->PlatformId); - EXPECT_EQ(0u, system_info->SuiteMask); - EXPECT_EQ(0u, system_info->Cpu.X86CpuInfo.VendorId[0]); - EXPECT_EQ(0u, system_info->Cpu.X86CpuInfo.VendorId[1]); - EXPECT_EQ(0u, system_info->Cpu.X86CpuInfo.VendorId[2]); - EXPECT_EQ(0u, system_info->Cpu.X86CpuInfo.VersionInformation); - EXPECT_EQ(0u, system_info->Cpu.X86CpuInfo.FeatureInformation); - EXPECT_EQ(0u, system_info->Cpu.X86CpuInfo.AMDExtendedCpuFeatures); - EXPECT_EQ(0u, system_info->Cpu.OtherCpuInfo.ProcessorFeatures[0]); - EXPECT_EQ(0u, system_info->Cpu.OtherCpuInfo.ProcessorFeatures[1]); + EXPECT_EQ(system_info->ProcessorArchitecture, + kMinidumpCPUArchitectureUnknown); + EXPECT_EQ(system_info->ProcessorLevel, 0u); + EXPECT_EQ(system_info->ProcessorRevision, 0u); + EXPECT_EQ(system_info->NumberOfProcessors, 0u); + EXPECT_EQ(system_info->ProductType, 0u); + EXPECT_EQ(system_info->MajorVersion, 0u); + EXPECT_EQ(system_info->MinorVersion, 0u); + EXPECT_EQ(system_info->BuildNumber, 0u); + EXPECT_EQ(system_info->PlatformId, 0u); + EXPECT_EQ(system_info->SuiteMask, 0u); + EXPECT_EQ(system_info->Cpu.X86CpuInfo.VendorId[0], 0u); + EXPECT_EQ(system_info->Cpu.X86CpuInfo.VendorId[1], 0u); + EXPECT_EQ(system_info->Cpu.X86CpuInfo.VendorId[2], 0u); + EXPECT_EQ(system_info->Cpu.X86CpuInfo.VersionInformation, 0u); + EXPECT_EQ(system_info->Cpu.X86CpuInfo.FeatureInformation, 0u); + EXPECT_EQ(system_info->Cpu.X86CpuInfo.AMDExtendedCpuFeatures, 0u); + EXPECT_EQ(system_info->Cpu.OtherCpuInfo.ProcessorFeatures[0], 0u); + EXPECT_EQ(system_info->Cpu.OtherCpuInfo.ProcessorFeatures[1], 0u); - EXPECT_EQ('\0', csd_version->Buffer[0]); + EXPECT_EQ(csd_version->Buffer[0], '\0'); } TEST(MinidumpSystemInfoWriter, X86_Win) { @@ -137,7 +137,7 @@ TEST(MinidumpSystemInfoWriter, X86_Win) { const uint32_t kAMDFeatures = 0xefd3fbff; uint32_t cpu_vendor_registers[3]; - ASSERT_EQ(sizeof(cpu_vendor_registers), strlen(kCPUVendor)); + ASSERT_EQ(strlen(kCPUVendor), sizeof(cpu_vendor_registers)); memcpy(cpu_vendor_registers, kCPUVendor, sizeof(cpu_vendor_registers)); system_info_writer->SetCPUArchitecture(kCPUArchitecture); @@ -164,25 +164,25 @@ TEST(MinidumpSystemInfoWriter, X86_Win) { ASSERT_NO_FATAL_FAILURE(GetSystemInfoStream( string_file.string(), strlen(kCSDVersion), &system_info, &csd_version)); - EXPECT_EQ(kCPUArchitecture, system_info->ProcessorArchitecture); - EXPECT_EQ(kCPULevel, system_info->ProcessorLevel); - EXPECT_EQ(kCPURevision, system_info->ProcessorRevision); - EXPECT_EQ(kCPUCount, system_info->NumberOfProcessors); - EXPECT_EQ(kOSType, system_info->ProductType); - EXPECT_EQ(kOSVersionMajor, system_info->MajorVersion); - EXPECT_EQ(kOSVersionMinor, system_info->MinorVersion); - EXPECT_EQ(kOSVersionBuild, system_info->BuildNumber); - EXPECT_EQ(kOS, system_info->PlatformId); - EXPECT_EQ(kSuiteMask, system_info->SuiteMask); - EXPECT_EQ(cpu_vendor_registers[0], system_info->Cpu.X86CpuInfo.VendorId[0]); - EXPECT_EQ(cpu_vendor_registers[1], system_info->Cpu.X86CpuInfo.VendorId[1]); - EXPECT_EQ(cpu_vendor_registers[2], system_info->Cpu.X86CpuInfo.VendorId[2]); - EXPECT_EQ(kCPUVersion, system_info->Cpu.X86CpuInfo.VersionInformation); - EXPECT_EQ(kCPUFeatures, system_info->Cpu.X86CpuInfo.FeatureInformation); - EXPECT_EQ(kAMDFeatures, system_info->Cpu.X86CpuInfo.AMDExtendedCpuFeatures); + EXPECT_EQ(system_info->ProcessorArchitecture, kCPUArchitecture); + EXPECT_EQ(system_info->ProcessorLevel, kCPULevel); + EXPECT_EQ(system_info->ProcessorRevision, kCPURevision); + EXPECT_EQ(system_info->NumberOfProcessors, kCPUCount); + EXPECT_EQ(system_info->ProductType, kOSType); + EXPECT_EQ(system_info->MajorVersion, kOSVersionMajor); + EXPECT_EQ(system_info->MinorVersion, kOSVersionMinor); + EXPECT_EQ(system_info->BuildNumber, kOSVersionBuild); + EXPECT_EQ(system_info->PlatformId, kOS); + EXPECT_EQ(system_info->SuiteMask, kSuiteMask); + EXPECT_EQ(system_info->Cpu.X86CpuInfo.VendorId[0], cpu_vendor_registers[0]); + EXPECT_EQ(system_info->Cpu.X86CpuInfo.VendorId[1], cpu_vendor_registers[1]); + EXPECT_EQ(system_info->Cpu.X86CpuInfo.VendorId[2], cpu_vendor_registers[2]); + EXPECT_EQ(system_info->Cpu.X86CpuInfo.VersionInformation, kCPUVersion); + EXPECT_EQ(system_info->Cpu.X86CpuInfo.FeatureInformation, kCPUFeatures); + EXPECT_EQ(system_info->Cpu.X86CpuInfo.AMDExtendedCpuFeatures, kAMDFeatures); for (size_t index = 0; index < strlen(kCSDVersion); ++index) { - EXPECT_EQ(kCSDVersion[index], csd_version->Buffer[index]) << index; + EXPECT_EQ(csd_version->Buffer[index], kCSDVersion[index]) << index; } } @@ -224,20 +224,20 @@ TEST(MinidumpSystemInfoWriter, AMD64_Mac) { ASSERT_NO_FATAL_FAILURE(GetSystemInfoStream( string_file.string(), strlen(kCSDVersion), &system_info, &csd_version)); - EXPECT_EQ(kCPUArchitecture, system_info->ProcessorArchitecture); - EXPECT_EQ(kCPULevel, system_info->ProcessorLevel); - EXPECT_EQ(kCPURevision, system_info->ProcessorRevision); - EXPECT_EQ(kCPUCount, system_info->NumberOfProcessors); - EXPECT_EQ(kOSType, system_info->ProductType); - EXPECT_EQ(kOSVersionMajor, system_info->MajorVersion); - EXPECT_EQ(kOSVersionMinor, system_info->MinorVersion); - EXPECT_EQ(kOSVersionBuild, system_info->BuildNumber); - EXPECT_EQ(kOS, system_info->PlatformId); - EXPECT_EQ(0u, system_info->SuiteMask); - EXPECT_EQ(kCPUFeatures[0], - system_info->Cpu.OtherCpuInfo.ProcessorFeatures[0]); - EXPECT_EQ(kCPUFeatures[1], - system_info->Cpu.OtherCpuInfo.ProcessorFeatures[1]); + EXPECT_EQ(system_info->ProcessorArchitecture, kCPUArchitecture); + EXPECT_EQ(system_info->ProcessorLevel, kCPULevel); + EXPECT_EQ(system_info->ProcessorRevision, kCPURevision); + EXPECT_EQ(system_info->NumberOfProcessors, kCPUCount); + EXPECT_EQ(system_info->ProductType, kOSType); + EXPECT_EQ(system_info->MajorVersion, kOSVersionMajor); + EXPECT_EQ(system_info->MinorVersion, kOSVersionMinor); + EXPECT_EQ(system_info->BuildNumber, kOSVersionBuild); + EXPECT_EQ(system_info->PlatformId, kOS); + EXPECT_EQ(system_info->SuiteMask, 0u); + EXPECT_EQ(system_info->Cpu.OtherCpuInfo.ProcessorFeatures[0], + kCPUFeatures[0]); + EXPECT_EQ(system_info->Cpu.OtherCpuInfo.ProcessorFeatures[1], + kCPUFeatures[1]); } TEST(MinidumpSystemInfoWriter, X86_CPUVendorFromRegisters) { @@ -266,12 +266,12 @@ TEST(MinidumpSystemInfoWriter, X86_CPUVendorFromRegisters) { ASSERT_NO_FATAL_FAILURE( GetSystemInfoStream(string_file.string(), 0, &system_info, &csd_version)); - EXPECT_EQ(kCPUArchitecture, system_info->ProcessorArchitecture); - EXPECT_EQ(0u, system_info->ProcessorLevel); - EXPECT_EQ(kCPUVendor[0], system_info->Cpu.X86CpuInfo.VendorId[0]); - EXPECT_EQ(kCPUVendor[1], system_info->Cpu.X86CpuInfo.VendorId[1]); - EXPECT_EQ(kCPUVendor[2], system_info->Cpu.X86CpuInfo.VendorId[2]); - EXPECT_EQ(0u, system_info->Cpu.X86CpuInfo.VersionInformation); + EXPECT_EQ(system_info->ProcessorArchitecture, kCPUArchitecture); + EXPECT_EQ(system_info->ProcessorLevel, 0u); + EXPECT_EQ(system_info->Cpu.X86CpuInfo.VendorId[0], kCPUVendor[0]); + EXPECT_EQ(system_info->Cpu.X86CpuInfo.VendorId[1], kCPUVendor[1]); + EXPECT_EQ(system_info->Cpu.X86CpuInfo.VendorId[2], kCPUVendor[2]); + EXPECT_EQ(system_info->Cpu.X86CpuInfo.VersionInformation, 0u); } TEST(MinidumpSystemInfoWriter, InitializeFromSnapshot_X86) { @@ -347,32 +347,32 @@ TEST(MinidumpSystemInfoWriter, InitializeFromSnapshot_X86) { &system_info, &csd_version)); - EXPECT_EQ(expect_system_info.ProcessorArchitecture, - system_info->ProcessorArchitecture); - EXPECT_EQ(expect_system_info.ProcessorLevel, system_info->ProcessorLevel); - EXPECT_EQ(expect_system_info.ProcessorRevision, - system_info->ProcessorRevision); - EXPECT_EQ(expect_system_info.NumberOfProcessors, - system_info->NumberOfProcessors); - EXPECT_EQ(expect_system_info.ProductType, system_info->ProductType); - EXPECT_EQ(expect_system_info.MajorVersion, system_info->MajorVersion); - EXPECT_EQ(expect_system_info.MinorVersion, system_info->MinorVersion); - EXPECT_EQ(expect_system_info.BuildNumber, system_info->BuildNumber); - EXPECT_EQ(expect_system_info.PlatformId, system_info->PlatformId); - EXPECT_EQ(expect_system_info.SuiteMask, system_info->SuiteMask); - EXPECT_EQ(expect_system_info.Cpu.X86CpuInfo.VendorId[0], - system_info->Cpu.X86CpuInfo.VendorId[0]); - EXPECT_EQ(expect_system_info.Cpu.X86CpuInfo.VendorId[1], - system_info->Cpu.X86CpuInfo.VendorId[1]); - EXPECT_EQ(expect_system_info.Cpu.X86CpuInfo.VendorId[2], - system_info->Cpu.X86CpuInfo.VendorId[2]); - EXPECT_EQ(expect_system_info.Cpu.X86CpuInfo.VersionInformation, - system_info->Cpu.X86CpuInfo.VersionInformation); - EXPECT_EQ(expect_system_info.Cpu.X86CpuInfo.FeatureInformation, - system_info->Cpu.X86CpuInfo.FeatureInformation); + EXPECT_EQ(system_info->ProcessorArchitecture, + expect_system_info.ProcessorArchitecture); + EXPECT_EQ(system_info->ProcessorLevel, expect_system_info.ProcessorLevel); + EXPECT_EQ(system_info->ProcessorRevision, + expect_system_info.ProcessorRevision); + EXPECT_EQ(system_info->NumberOfProcessors, + expect_system_info.NumberOfProcessors); + EXPECT_EQ(system_info->ProductType, expect_system_info.ProductType); + EXPECT_EQ(system_info->MajorVersion, expect_system_info.MajorVersion); + EXPECT_EQ(system_info->MinorVersion, expect_system_info.MinorVersion); + EXPECT_EQ(system_info->BuildNumber, expect_system_info.BuildNumber); + EXPECT_EQ(system_info->PlatformId, expect_system_info.PlatformId); + EXPECT_EQ(system_info->SuiteMask, expect_system_info.SuiteMask); + EXPECT_EQ(system_info->Cpu.X86CpuInfo.VendorId[0], + expect_system_info.Cpu.X86CpuInfo.VendorId[0]); + EXPECT_EQ(system_info->Cpu.X86CpuInfo.VendorId[1], + expect_system_info.Cpu.X86CpuInfo.VendorId[1]); + EXPECT_EQ(system_info->Cpu.X86CpuInfo.VendorId[2], + expect_system_info.Cpu.X86CpuInfo.VendorId[2]); + EXPECT_EQ(system_info->Cpu.X86CpuInfo.VersionInformation, + expect_system_info.Cpu.X86CpuInfo.VersionInformation); + EXPECT_EQ(system_info->Cpu.X86CpuInfo.FeatureInformation, + expect_system_info.Cpu.X86CpuInfo.FeatureInformation); for (size_t index = 0; index < strlen(kOSVersionBuild); ++index) { - EXPECT_EQ(kOSVersionBuild[index], csd_version->Buffer[index]) << index; + EXPECT_EQ(csd_version->Buffer[index], kOSVersionBuild[index]) << index; } } @@ -443,26 +443,26 @@ TEST(MinidumpSystemInfoWriter, InitializeFromSnapshot_AMD64) { &system_info, &csd_version)); - EXPECT_EQ(expect_system_info.ProcessorArchitecture, - system_info->ProcessorArchitecture); - EXPECT_EQ(expect_system_info.ProcessorLevel, system_info->ProcessorLevel); - EXPECT_EQ(expect_system_info.ProcessorRevision, - system_info->ProcessorRevision); - EXPECT_EQ(expect_system_info.NumberOfProcessors, - system_info->NumberOfProcessors); - EXPECT_EQ(expect_system_info.ProductType, system_info->ProductType); - EXPECT_EQ(expect_system_info.MajorVersion, system_info->MajorVersion); - EXPECT_EQ(expect_system_info.MinorVersion, system_info->MinorVersion); - EXPECT_EQ(expect_system_info.BuildNumber, system_info->BuildNumber); - EXPECT_EQ(expect_system_info.PlatformId, system_info->PlatformId); - EXPECT_EQ(expect_system_info.SuiteMask, system_info->SuiteMask); - EXPECT_EQ(expect_system_info.Cpu.OtherCpuInfo.ProcessorFeatures[0], - system_info->Cpu.OtherCpuInfo.ProcessorFeatures[0]); - EXPECT_EQ(expect_system_info.Cpu.OtherCpuInfo.ProcessorFeatures[1], - system_info->Cpu.OtherCpuInfo.ProcessorFeatures[1]); + EXPECT_EQ(system_info->ProcessorArchitecture, + expect_system_info.ProcessorArchitecture); + EXPECT_EQ(system_info->ProcessorLevel, expect_system_info.ProcessorLevel); + EXPECT_EQ(system_info->ProcessorRevision, + expect_system_info.ProcessorRevision); + EXPECT_EQ(system_info->NumberOfProcessors, + expect_system_info.NumberOfProcessors); + EXPECT_EQ(system_info->ProductType, expect_system_info.ProductType); + EXPECT_EQ(system_info->MajorVersion, expect_system_info.MajorVersion); + EXPECT_EQ(system_info->MinorVersion, expect_system_info.MinorVersion); + EXPECT_EQ(system_info->BuildNumber, expect_system_info.BuildNumber); + EXPECT_EQ(system_info->PlatformId, expect_system_info.PlatformId); + EXPECT_EQ(system_info->SuiteMask, expect_system_info.SuiteMask); + EXPECT_EQ(system_info->Cpu.OtherCpuInfo.ProcessorFeatures[0], + expect_system_info.Cpu.OtherCpuInfo.ProcessorFeatures[0]); + EXPECT_EQ(system_info->Cpu.OtherCpuInfo.ProcessorFeatures[1], + expect_system_info.Cpu.OtherCpuInfo.ProcessorFeatures[1]); for (size_t index = 0; index < strlen(kOSVersionBuild); ++index) { - EXPECT_EQ(kOSVersionBuild[index], csd_version->Buffer[index]) << index; + EXPECT_EQ(csd_version->Buffer[index], kOSVersionBuild[index]) << index; } } diff --git a/minidump/minidump_test.gyp b/minidump/minidump_test.gyp index acf4d635..80f803db 100644 --- a/minidump/minidump_test.gyp +++ b/minidump/minidump_test.gyp @@ -17,10 +17,39 @@ '../build/crashpad.gypi', ], 'targets': [ + { + 'target_name': 'crashpad_minidump_test_lib', + 'type': 'static_library', + 'dependencies': [ + 'minidump.gyp:crashpad_minidump', + '../third_party/gtest/gtest.gyp:gtest', + '../third_party/mini_chromium/mini_chromium.gyp:base', + ], + 'include_dirs': [ + '..', + ], + 'sources': [ + 'test/minidump_context_test_util.cc', + 'test/minidump_context_test_util.h', + 'test/minidump_file_writer_test_util.cc', + 'test/minidump_file_writer_test_util.h', + 'test/minidump_memory_writer_test_util.cc', + 'test/minidump_memory_writer_test_util.h', + 'test/minidump_rva_list_test_util.cc', + 'test/minidump_rva_list_test_util.h', + 'test/minidump_string_writer_test_util.cc', + 'test/minidump_string_writer_test_util.h', + 'test/minidump_user_extension_stream_util.cc', + 'test/minidump_user_extension_stream_util.h', + 'test/minidump_writable_test_util.cc', + 'test/minidump_writable_test_util.h', + ], + }, { 'target_name': 'crashpad_minidump_test', 'type': 'executable', 'dependencies': [ + 'crashpad_minidump_test_lib', 'minidump.gyp:crashpad_minidump', '../snapshot/snapshot_test.gyp:crashpad_snapshot_test_lib', '../test/test.gyp:crashpad_gtest_main', @@ -36,8 +65,8 @@ 'minidump_context_writer_test.cc', 'minidump_crashpad_info_writer_test.cc', 'minidump_exception_writer_test.cc', - 'minidump_handle_writer_test.cc', 'minidump_file_writer_test.cc', + 'minidump_handle_writer_test.cc', 'minidump_memory_info_writer_test.cc', 'minidump_memory_writer_test.cc', 'minidump_misc_info_writer_test.cc', @@ -52,18 +81,6 @@ 'minidump_unloaded_module_writer_test.cc', 'minidump_user_stream_writer_test.cc', 'minidump_writable_test.cc', - 'test/minidump_context_test_util.cc', - 'test/minidump_context_test_util.h', - 'test/minidump_file_writer_test_util.cc', - 'test/minidump_file_writer_test_util.h', - 'test/minidump_memory_writer_test_util.cc', - 'test/minidump_memory_writer_test_util.h', - 'test/minidump_rva_list_test_util.cc', - 'test/minidump_rva_list_test_util.h', - 'test/minidump_string_writer_test_util.cc', - 'test/minidump_string_writer_test_util.h', - 'test/minidump_writable_test_util.cc', - 'test/minidump_writable_test_util.h', ], }, ], diff --git a/minidump/minidump_thread_id_map_test.cc b/minidump/minidump_thread_id_map_test.cc index 2fee93c0..7c6795a3 100644 --- a/minidump/minidump_thread_id_map_test.cc +++ b/minidump/minidump_thread_id_map_test.cc @@ -48,11 +48,11 @@ class MinidumpThreadIDMapTest : public testing::Test { const MinidumpThreadIDMap* map, uint64_t key, uint32_t expected_value) { auto iterator = map->find(key); if (iterator == map->end()) { - EXPECT_NE(map->end(), iterator); + EXPECT_NE(iterator, map->end()); return false; } if (iterator->second != expected_value) { - EXPECT_EQ(expected_value, iterator->second); + EXPECT_EQ(iterator->second, expected_value); return false; } return true; @@ -95,7 +95,7 @@ TEST_F(MinidumpThreadIDMapTest, SimpleMapping) { MinidumpThreadIDMap thread_id_map; BuildMinidumpThreadIDMap(thread_snapshots(), &thread_id_map); - EXPECT_EQ(5u, thread_id_map.size()); + EXPECT_EQ(thread_id_map.size(), 5u); EXPECT_PRED3(MapHasKeyValue, &thread_id_map, 1, 1); EXPECT_PRED3(MapHasKeyValue, &thread_id_map, 3, 3); EXPECT_PRED3(MapHasKeyValue, &thread_id_map, 5, 5); @@ -113,7 +113,7 @@ TEST_F(MinidumpThreadIDMapTest, Truncation) { MinidumpThreadIDMap thread_id_map; BuildMinidumpThreadIDMap(thread_snapshots(), &thread_id_map); - EXPECT_EQ(5u, thread_id_map.size()); + EXPECT_EQ(thread_id_map.size(), 5u); EXPECT_PRED3(MapHasKeyValue, &thread_id_map, 0x0000000000000000, 0x00000000); EXPECT_PRED3(MapHasKeyValue, &thread_id_map, 0x9999999900000001, 0x00000001); EXPECT_PRED3(MapHasKeyValue, &thread_id_map, 0x9999999980000001, 0x80000001); @@ -131,7 +131,7 @@ TEST_F(MinidumpThreadIDMapTest, DuplicateThreadID) { MinidumpThreadIDMap thread_id_map; BuildMinidumpThreadIDMap(thread_snapshots(), &thread_id_map); - EXPECT_EQ(4u, thread_id_map.size()); + EXPECT_EQ(thread_id_map.size(), 4u); EXPECT_PRED3(MapHasKeyValue, &thread_id_map, 2, 2); EXPECT_PRED3(MapHasKeyValue, &thread_id_map, 4, 4); EXPECT_PRED3(MapHasKeyValue, &thread_id_map, 6, 6); @@ -148,7 +148,7 @@ TEST_F(MinidumpThreadIDMapTest, Collision) { MinidumpThreadIDMap thread_id_map; BuildMinidumpThreadIDMap(thread_snapshots(), &thread_id_map); - EXPECT_EQ(5u, thread_id_map.size()); + EXPECT_EQ(thread_id_map.size(), 5u); EXPECT_PRED3(MapHasKeyValue, &thread_id_map, 0x0000000000000010, 0); EXPECT_PRED3(MapHasKeyValue, &thread_id_map, 0x0000000000000020, 1); EXPECT_PRED3(MapHasKeyValue, &thread_id_map, 0x0000000000000030, 2); @@ -166,7 +166,7 @@ TEST_F(MinidumpThreadIDMapTest, DuplicateAndCollision) { MinidumpThreadIDMap thread_id_map; BuildMinidumpThreadIDMap(thread_snapshots(), &thread_id_map); - EXPECT_EQ(4u, thread_id_map.size()); + EXPECT_EQ(thread_id_map.size(), 4u); EXPECT_PRED3(MapHasKeyValue, &thread_id_map, 0x0000000100000010, 0); EXPECT_PRED3(MapHasKeyValue, &thread_id_map, 0x0000000000000010, 1); EXPECT_PRED3(MapHasKeyValue, &thread_id_map, 0x0000000000000020, 2); @@ -183,7 +183,7 @@ TEST_F(MinidumpThreadIDMapTest, AllDuplicates) { MinidumpThreadIDMap thread_id_map; BuildMinidumpThreadIDMap(thread_snapshots(), &thread_id_map); - EXPECT_EQ(1u, thread_id_map.size()); + EXPECT_EQ(thread_id_map.size(), 1u); EXPECT_PRED3(MapHasKeyValue, &thread_id_map, 6, 6); } diff --git a/minidump/minidump_thread_writer_test.cc b/minidump/minidump_thread_writer_test.cc index 61332363..0fa511ba 100644 --- a/minidump/minidump_thread_writer_test.cc +++ b/minidump/minidump_thread_writer_test.cc @@ -61,15 +61,15 @@ void GetThreadListStream(const std::string& file_contents, ASSERT_NO_FATAL_FAILURE(VerifyMinidumpHeader(header, kExpectedStreams, 0)); ASSERT_TRUE(directory); - ASSERT_EQ(kMinidumpStreamTypeThreadList, directory[0].StreamType); - EXPECT_EQ(kThreadListStreamOffset, directory[0].Location.Rva); + ASSERT_EQ(directory[0].StreamType, kMinidumpStreamTypeThreadList); + EXPECT_EQ(directory[0].Location.Rva, kThreadListStreamOffset); *thread_list = MinidumpWritableAtLocationDescriptor( file_contents, directory[0].Location); ASSERT_TRUE(thread_list); if (memory_list) { - ASSERT_EQ(kMinidumpStreamTypeMemoryList, directory[1].StreamType); + ASSERT_EQ(directory[1].StreamType, kMinidumpStreamTypeMemoryList); *memory_list = MinidumpWritableAtLocationDescriptor( file_contents, directory[1].Location); @@ -86,15 +86,15 @@ TEST(MinidumpThreadWriter, EmptyThreadList) { StringFile string_file; ASSERT_TRUE(minidump_file_writer.WriteEverything(&string_file)); - ASSERT_EQ(sizeof(MINIDUMP_HEADER) + sizeof(MINIDUMP_DIRECTORY) + - sizeof(MINIDUMP_THREAD_LIST), - string_file.string().size()); + ASSERT_EQ(string_file.string().size(), + sizeof(MINIDUMP_HEADER) + sizeof(MINIDUMP_DIRECTORY) + + sizeof(MINIDUMP_THREAD_LIST)); const MINIDUMP_THREAD_LIST* thread_list = nullptr; ASSERT_NO_FATAL_FAILURE( GetThreadListStream(string_file.string(), &thread_list, nullptr)); - EXPECT_EQ(0u, thread_list->NumberOfThreads); + EXPECT_EQ(thread_list->NumberOfThreads, 0u); } // The MINIDUMP_THREADs |expected| and |observed| are compared against each @@ -109,30 +109,30 @@ void ExpectThread(const MINIDUMP_THREAD* expected, const std::string& file_contents, const MINIDUMP_MEMORY_DESCRIPTOR** stack, const void** context_base) { - EXPECT_EQ(expected->ThreadId, observed->ThreadId); - EXPECT_EQ(expected->SuspendCount, observed->SuspendCount); - EXPECT_EQ(expected->PriorityClass, observed->PriorityClass); - EXPECT_EQ(expected->Priority, observed->Priority); - EXPECT_EQ(expected->Teb, observed->Teb); + EXPECT_EQ(observed->ThreadId, expected->ThreadId); + EXPECT_EQ(observed->SuspendCount, expected->SuspendCount); + EXPECT_EQ(observed->PriorityClass, expected->PriorityClass); + EXPECT_EQ(observed->Priority, expected->Priority); + EXPECT_EQ(observed->Teb, expected->Teb); - EXPECT_EQ(expected->Stack.StartOfMemoryRange, - observed->Stack.StartOfMemoryRange); - EXPECT_EQ(expected->Stack.Memory.DataSize, observed->Stack.Memory.DataSize); + EXPECT_EQ(observed->Stack.StartOfMemoryRange, + expected->Stack.StartOfMemoryRange); + EXPECT_EQ(observed->Stack.Memory.DataSize, expected->Stack.Memory.DataSize); if (stack) { - ASSERT_NE(0u, observed->Stack.Memory.DataSize); - ASSERT_NE(0u, observed->Stack.Memory.Rva); + ASSERT_NE(observed->Stack.Memory.DataSize, 0u); + ASSERT_NE(observed->Stack.Memory.Rva, 0u); ASSERT_GE(file_contents.size(), observed->Stack.Memory.Rva + observed->Stack.Memory.DataSize); *stack = &observed->Stack; } else { - EXPECT_EQ(0u, observed->Stack.StartOfMemoryRange); - EXPECT_EQ(0u, observed->Stack.Memory.DataSize); - EXPECT_EQ(0u, observed->Stack.Memory.Rva); + EXPECT_EQ(observed->Stack.StartOfMemoryRange, 0u); + EXPECT_EQ(observed->Stack.Memory.DataSize, 0u); + EXPECT_EQ(observed->Stack.Memory.Rva, 0u); } - EXPECT_EQ(expected->ThreadContext.DataSize, observed->ThreadContext.DataSize); - ASSERT_NE(0u, observed->ThreadContext.DataSize); - ASSERT_NE(0u, observed->ThreadContext.Rva); + EXPECT_EQ(observed->ThreadContext.DataSize, expected->ThreadContext.DataSize); + ASSERT_NE(observed->ThreadContext.DataSize, 0u); + ASSERT_NE(observed->ThreadContext.Rva, 0u); ASSERT_GE(file_contents.size(), observed->ThreadContext.Rva + expected->ThreadContext.DataSize); *context_base = &file_contents[observed->ThreadContext.Rva]; @@ -166,16 +166,16 @@ TEST(MinidumpThreadWriter, OneThread_x86_NoStack) { StringFile string_file; ASSERT_TRUE(minidump_file_writer.WriteEverything(&string_file)); - ASSERT_EQ(sizeof(MINIDUMP_HEADER) + sizeof(MINIDUMP_DIRECTORY) + + ASSERT_EQ(string_file.string().size(), + sizeof(MINIDUMP_HEADER) + sizeof(MINIDUMP_DIRECTORY) + sizeof(MINIDUMP_THREAD_LIST) + 1 * sizeof(MINIDUMP_THREAD) + - 1 * sizeof(MinidumpContextX86), - string_file.string().size()); + 1 * sizeof(MinidumpContextX86)); const MINIDUMP_THREAD_LIST* thread_list = nullptr; ASSERT_NO_FATAL_FAILURE( GetThreadListStream(string_file.string(), &thread_list, nullptr)); - EXPECT_EQ(1u, thread_list->NumberOfThreads); + EXPECT_EQ(thread_list->NumberOfThreads, 1u); MINIDUMP_THREAD expected = {}; expected.ThreadId = kThreadID; @@ -236,16 +236,16 @@ TEST(MinidumpThreadWriter, OneThread_AMD64_Stack) { StringFile string_file; ASSERT_TRUE(minidump_file_writer.WriteEverything(&string_file)); - ASSERT_EQ(sizeof(MINIDUMP_HEADER) + sizeof(MINIDUMP_DIRECTORY) + + ASSERT_EQ(string_file.string().size(), + sizeof(MINIDUMP_HEADER) + sizeof(MINIDUMP_DIRECTORY) + sizeof(MINIDUMP_THREAD_LIST) + 1 * sizeof(MINIDUMP_THREAD) + - 1 * sizeof(MinidumpContextAMD64) + kMemorySize, - string_file.string().size()); + 1 * sizeof(MinidumpContextAMD64) + kMemorySize); const MINIDUMP_THREAD_LIST* thread_list = nullptr; ASSERT_NO_FATAL_FAILURE( GetThreadListStream(string_file.string(), &thread_list, nullptr)); - EXPECT_EQ(1u, thread_list->NumberOfThreads); + EXPECT_EQ(thread_list->NumberOfThreads, 1u); MINIDUMP_THREAD expected = {}; expected.ThreadId = kThreadID; @@ -369,21 +369,22 @@ TEST(MinidumpThreadWriter, ThreeThreads_x86_MemoryList) { StringFile string_file; ASSERT_TRUE(minidump_file_writer.WriteEverything(&string_file)); - ASSERT_EQ(sizeof(MINIDUMP_HEADER) + 2 * sizeof(MINIDUMP_DIRECTORY) + - sizeof(MINIDUMP_THREAD_LIST) + 3 * sizeof(MINIDUMP_THREAD) + - sizeof(MINIDUMP_MEMORY_LIST) + - 3 * sizeof(MINIDUMP_MEMORY_DESCRIPTOR) + - 3 * sizeof(MinidumpContextX86) + kMemorySize0 + kMemorySize1 + - kMemorySize2 + 12, // 12 for alignment - string_file.string().size()); + ASSERT_EQ( + string_file.string().size(), + sizeof(MINIDUMP_HEADER) + 2 * sizeof(MINIDUMP_DIRECTORY) + + sizeof(MINIDUMP_THREAD_LIST) + 3 * sizeof(MINIDUMP_THREAD) + + sizeof(MINIDUMP_MEMORY_LIST) + + 3 * sizeof(MINIDUMP_MEMORY_DESCRIPTOR) + + 3 * sizeof(MinidumpContextX86) + kMemorySize0 + kMemorySize1 + + kMemorySize2 + 12); // 12 for alignment const MINIDUMP_THREAD_LIST* thread_list = nullptr; const MINIDUMP_MEMORY_LIST* memory_list = nullptr; ASSERT_NO_FATAL_FAILURE( GetThreadListStream(string_file.string(), &thread_list, &memory_list)); - EXPECT_EQ(3u, thread_list->NumberOfThreads); - EXPECT_EQ(3u, memory_list->NumberOfMemoryRanges); + EXPECT_EQ(thread_list->NumberOfThreads, 3u); + EXPECT_EQ(memory_list->NumberOfMemoryRanges, 3u); { SCOPED_TRACE("thread 0"); @@ -634,8 +635,8 @@ void RunInitializeFromSnapshotTest(bool thread_id_collision) { ASSERT_NO_FATAL_FAILURE( GetThreadListStream(string_file.string(), &thread_list, &memory_list)); - ASSERT_EQ(3u, thread_list->NumberOfThreads); - ASSERT_EQ(5u, memory_list->NumberOfMemoryRanges); + ASSERT_EQ(thread_list->NumberOfThreads, 3u); + ASSERT_EQ(memory_list->NumberOfMemoryRanges, 5u); size_t memory_index = 0; for (size_t index = 0; index < thread_list->NumberOfThreads; ++index) { @@ -678,7 +679,7 @@ void RunInitializeFromSnapshotTest(bool thread_id_collision) { std::string expected_data(kTebSize, static_cast('t' + index)); std::string observed_data(&string_file.string()[memory->Memory.Rva], memory->Memory.DataSize); - EXPECT_EQ(expected_data, observed_data); + EXPECT_EQ(observed_data, expected_data); ++memory_index; } } diff --git a/minidump/minidump_unloaded_module_writer_test.cc b/minidump/minidump_unloaded_module_writer_test.cc index 002c82bb..a6de044f 100644 --- a/minidump/minidump_unloaded_module_writer_test.cc +++ b/minidump/minidump_unloaded_module_writer_test.cc @@ -31,16 +31,16 @@ void ExpectUnloadedModule(const MINIDUMP_UNLOADED_MODULE* expected, const MINIDUMP_UNLOADED_MODULE* observed, const std::string& file_contents, const std::string& expected_module_name) { - EXPECT_EQ(expected->BaseOfImage, observed->BaseOfImage); - EXPECT_EQ(expected->SizeOfImage, observed->SizeOfImage); - EXPECT_EQ(expected->CheckSum, observed->CheckSum); - EXPECT_EQ(expected->TimeDateStamp, observed->TimeDateStamp); - EXPECT_NE(0u, observed->ModuleNameRva); + EXPECT_EQ(observed->BaseOfImage, expected->BaseOfImage); + EXPECT_EQ(observed->SizeOfImage, expected->SizeOfImage); + EXPECT_EQ(observed->CheckSum, expected->CheckSum); + EXPECT_EQ(observed->TimeDateStamp, expected->TimeDateStamp); + EXPECT_NE(observed->ModuleNameRva, 0u); base::string16 observed_module_name_utf16 = MinidumpStringAtRVAAsString(file_contents, observed->ModuleNameRva); base::string16 expected_module_name_utf16 = base::UTF8ToUTF16(expected_module_name); - EXPECT_EQ(expected_module_name_utf16, observed_module_name_utf16); + EXPECT_EQ(observed_module_name_utf16, expected_module_name_utf16); } void GetUnloadedModuleListStream( @@ -60,8 +60,8 @@ void GetUnloadedModuleListStream( ASSERT_NO_FATAL_FAILURE(VerifyMinidumpHeader(header, 1, 0)); ASSERT_TRUE(directory); - ASSERT_EQ(kMinidumpStreamTypeUnloadedModuleList, directory[0].StreamType); - EXPECT_EQ(kUnloadedModuleListStreamOffset, directory[0].Location.Rva); + ASSERT_EQ(directory[0].StreamType, kMinidumpStreamTypeUnloadedModuleList); + EXPECT_EQ(directory[0].Location.Rva, kUnloadedModuleListStreamOffset); *unloaded_module_list = MinidumpWritableAtLocationDescriptor( @@ -97,7 +97,7 @@ TEST(MinidumpUnloadedModuleWriter, EmptyModule) { ASSERT_NO_FATAL_FAILURE( GetUnloadedModuleListStream(string_file.string(), &unloaded_module_list)); - EXPECT_EQ(1u, unloaded_module_list->NumberOfEntries); + EXPECT_EQ(unloaded_module_list->NumberOfEntries, 1u); MINIDUMP_UNLOADED_MODULE expected = {}; ASSERT_NO_FATAL_FAILURE( @@ -144,7 +144,7 @@ TEST(MinidumpUnloadedModuleWriter, OneModule) { ASSERT_NO_FATAL_FAILURE( GetUnloadedModuleListStream(string_file.string(), &unloaded_module_list)); - EXPECT_EQ(1u, unloaded_module_list->NumberOfEntries); + EXPECT_EQ(unloaded_module_list->NumberOfEntries, 1u); MINIDUMP_UNLOADED_MODULE expected = {}; expected.BaseOfImage = kModuleBase; diff --git a/minidump/minidump_user_extension_stream_data_source.cc b/minidump/minidump_user_extension_stream_data_source.cc index 8056011c..884bf859 100644 --- a/minidump/minidump_user_extension_stream_data_source.cc +++ b/minidump/minidump_user_extension_stream_data_source.cc @@ -17,12 +17,8 @@ namespace crashpad { MinidumpUserExtensionStreamDataSource::MinidumpUserExtensionStreamDataSource( - uint32_t stream_type, - const void* buffer, - size_t buffer_size) - : stream_type_(static_cast(stream_type)), - buffer_(buffer), - buffer_size_(buffer_size) {} + uint32_t stream_type) + : stream_type_(static_cast(stream_type)) {} MinidumpUserExtensionStreamDataSource:: ~MinidumpUserExtensionStreamDataSource() {} diff --git a/minidump/minidump_user_extension_stream_data_source.h b/minidump/minidump_user_extension_stream_data_source.h index 1afb1661..3eb0c874 100644 --- a/minidump/minidump_user_extension_stream_data_source.h +++ b/minidump/minidump_user_extension_stream_data_source.h @@ -27,25 +27,54 @@ namespace crashpad { //! \brief Describes a user extension data stream in a minidump. class MinidumpUserExtensionStreamDataSource { public: + //! \brief An interface implemented by readers of + //! MinidumpUserExtensionStreamDataSource. + class Delegate { + public: + //! \brief Called by MinidumpUserExtensionStreamDataSource::Read() to + //! provide data requested by a call to that method. + //! + //! \param[in] data A pointer to the data that was read. The callee does not + //! take ownership of this data. This data is only valid for the + //! duration of the call to this method. This parameter may be `nullptr` + //! if \a size is `0`. + //! \param[in] size The size of the data that was read. + //! + //! \return `true` on success, `false` on failure. + //! MinidumpUserExtensionStreamDataSource::ReadStreamData() will use + //! this as its own return value. + virtual bool ExtensionStreamDataSourceRead(const void* data, + size_t size) = 0; + + protected: + ~Delegate() {} + }; + //! \brief Constructs a MinidumpUserExtensionStreamDataSource. //! //! \param[in] stream_type The type of the user extension stream. - //! \param[in] buffer Points to the data for this stream. \a buffer is not - //! owned, and must outlive the use of this object. - //! \param[in] buffer_size The length of data in \a buffer. - MinidumpUserExtensionStreamDataSource(uint32_t stream_type, - const void* buffer, - size_t buffer_size); - ~MinidumpUserExtensionStreamDataSource(); + explicit MinidumpUserExtensionStreamDataSource(uint32_t stream_type); + virtual ~MinidumpUserExtensionStreamDataSource(); MinidumpStreamType stream_type() const { return stream_type_; } - const void* buffer() const { return buffer_; } - size_t buffer_size() const { return buffer_size_; } + + //! \brief The size of this data stream. + virtual size_t StreamDataSize() = 0; + + //! \brief Calls Delegate::UserStreamDataSourceRead(), providing it with + //! the stream data. + //! + //! Implementations do not necessarily compute the stream data prior to + //! this method being called. The stream data may be computed or loaded + //! lazily and may be discarded after being passed to the delegate. + //! + //! \return `false` on failure, otherwise, the return value of + //! Delegate::ExtensionStreamDataSourceRead(), which should be `true` on + //! success and `false` on failure. + virtual bool ReadStreamData(Delegate* delegate) = 0; private: MinidumpStreamType stream_type_; - const void* buffer_; // weak - size_t buffer_size_; DISALLOW_COPY_AND_ASSIGN(MinidumpUserExtensionStreamDataSource); }; diff --git a/minidump/minidump_user_stream_writer.cc b/minidump/minidump_user_stream_writer.cc index 6520f0f4..2cd50352 100644 --- a/minidump/minidump_user_stream_writer.cc +++ b/minidump/minidump_user_stream_writer.cc @@ -56,22 +56,32 @@ class MinidumpUserStreamWriter::SnapshotContentsWriter final DISALLOW_COPY_AND_ASSIGN(SnapshotContentsWriter); }; -class MinidumpUserStreamWriter::BufferContentsWriter final - : public MinidumpUserStreamWriter::ContentsWriter { +class MinidumpUserStreamWriter::ExtensionStreamContentsWriter final + : public MinidumpUserStreamWriter::ContentsWriter, + public MinidumpUserExtensionStreamDataSource::Delegate { public: - BufferContentsWriter(const void* buffer, size_t buffer_size) - : buffer_(buffer), buffer_size_(buffer_size) {} + explicit ExtensionStreamContentsWriter( + std::unique_ptr data_source) + : data_source_(std::move(data_source)), writer_(nullptr) {} bool WriteContents(FileWriterInterface* writer) override { - return writer->Write(buffer_, buffer_size_); + DCHECK(!writer_); + + writer_ = writer; + return data_source_->ReadStreamData(this); + } + + size_t GetSize() const override { return data_source_->StreamDataSize(); } + + bool ExtensionStreamDataSourceRead(const void* data, size_t size) override { + return writer_->Write(data, size); } - size_t GetSize() const override { return buffer_size_; } private: - const void* buffer_; - size_t buffer_size_; + std::unique_ptr data_source_; + FileWriterInterface* writer_; - DISALLOW_COPY_AND_ASSIGN(BufferContentsWriter); + DISALLOW_COPY_AND_ASSIGN(ExtensionStreamContentsWriter); }; MinidumpUserStreamWriter::MinidumpUserStreamWriter() : stream_type_() {} @@ -89,16 +99,14 @@ void MinidumpUserStreamWriter::InitializeFromSnapshot( base::WrapUnique(new SnapshotContentsWriter(stream->memory())); } -void MinidumpUserStreamWriter::InitializeFromBuffer( - MinidumpStreamType stream_type, - const void* buffer, - size_t buffer_size) { +void MinidumpUserStreamWriter::InitializeFromUserExtensionStream( + std::unique_ptr data_source) { DCHECK_EQ(state(), kStateMutable); DCHECK(!contents_writer_.get()); - stream_type_ = stream_type; - contents_writer_ = - base::WrapUnique(new BufferContentsWriter(buffer, buffer_size)); + stream_type_ = data_source->stream_type(); + contents_writer_ = base::WrapUnique( + new ExtensionStreamContentsWriter(std::move(data_source))); } bool MinidumpUserStreamWriter::Freeze() { diff --git a/minidump/minidump_user_stream_writer.h b/minidump/minidump_user_stream_writer.h index 838ed0de..48698fdc 100644 --- a/minidump/minidump_user_stream_writer.h +++ b/minidump/minidump_user_stream_writer.h @@ -25,6 +25,7 @@ #include "minidump/minidump_extensions.h" #include "minidump/minidump_stream_writer.h" #include "minidump/minidump_writable.h" +#include "minidump/minidump_user_extension_stream_data_source.h" #include "snapshot/module_snapshot.h" namespace crashpad { @@ -42,17 +43,13 @@ class MinidumpUserStreamWriter final : public internal::MinidumpStreamWriter { //! \note Valid in #kStateMutable. void InitializeFromSnapshot(const UserMinidumpStream* stream); - //! \brief Initializes a MINIDUMP_USER_STREAM based on \a stream_type, - //! \a buffer and \a buffer_size. + //! \brief Initializes a MINIDUMP_USER_STREAM based on \a data_source. //! - //! \param[in] stream_type The type of the stream. - //! \param[in] buffer The data for the stream. - //! \param[in] buffer_size The length of \a buffer, and the resulting stream. + //! \param[in] data_source The content and type of the stream. //! //! \note Valid in #kStateMutable. - void InitializeFromBuffer(MinidumpStreamType stream_type, - const void* buffer, - size_t buffer_size); + void InitializeFromUserExtensionStream( + std::unique_ptr data_source); protected: // MinidumpWritable: @@ -67,7 +64,7 @@ class MinidumpUserStreamWriter final : public internal::MinidumpStreamWriter { private: class ContentsWriter; class SnapshotContentsWriter; - class BufferContentsWriter; + class ExtensionStreamContentsWriter; std::unique_ptr contents_writer_; diff --git a/minidump/minidump_user_stream_writer_test.cc b/minidump/minidump_user_stream_writer_test.cc index 3942e0e6..e6627e62 100644 --- a/minidump/minidump_user_stream_writer_test.cc +++ b/minidump/minidump_user_stream_writer_test.cc @@ -21,6 +21,7 @@ #include "gtest/gtest.h" #include "minidump/minidump_file_writer.h" #include "minidump/test/minidump_file_writer_test_util.h" +#include "minidump/test/minidump_user_extension_stream_util.h" #include "minidump/test/minidump_writable_test_util.h" #include "snapshot/test/test_memory_snapshot.h" #include "util/file/string_file.h" @@ -46,9 +47,9 @@ void GetUserStream(const std::string& file_contents, const size_t kDirectoryIndex = 0; - ASSERT_EQ(stream_type, directory[kDirectoryIndex].StreamType); - EXPECT_EQ(kUserStreamOffset, directory[kDirectoryIndex].Location.Rva); - EXPECT_EQ(stream_size, directory[kDirectoryIndex].Location.DataSize); + ASSERT_EQ(directory[kDirectoryIndex].StreamType, stream_type); + EXPECT_EQ(directory[kDirectoryIndex].Location.Rva, kUserStreamOffset); + EXPECT_EQ(directory[kDirectoryIndex].Location.DataSize, stream_size); *user_stream_location = directory[kDirectoryIndex].Location; } @@ -66,25 +67,27 @@ TEST(MinidumpUserStreamWriter, InitializeFromSnapshotNoData) { StringFile string_file; ASSERT_TRUE(minidump_file_writer.WriteEverything(&string_file)); - ASSERT_EQ(sizeof(MINIDUMP_HEADER) + sizeof(MINIDUMP_DIRECTORY), - string_file.string().size()); + ASSERT_EQ(string_file.string().size(), + sizeof(MINIDUMP_HEADER) + sizeof(MINIDUMP_DIRECTORY)); MINIDUMP_LOCATION_DESCRIPTOR user_stream_location; ASSERT_NO_FATAL_FAILURE(GetUserStream( string_file.string(), &user_stream_location, kTestStreamId, 0u)); } -TEST(MinidumpUserStreamWriter, InitializeFromBufferNoData) { +TEST(MinidumpUserStreamWriter, InitializeFromUserExtensionStreamNoData) { MinidumpFileWriter minidump_file_writer; + auto data_source = base::WrapUnique( + new test::BufferExtensionStreamDataSource(kTestStreamId, nullptr, 0)); auto user_stream_writer = base::WrapUnique(new MinidumpUserStreamWriter()); - user_stream_writer->InitializeFromBuffer(kTestStreamId, nullptr, 0); + user_stream_writer->InitializeFromUserExtensionStream(std::move(data_source)); minidump_file_writer.AddStream(std::move(user_stream_writer)); StringFile string_file; ASSERT_TRUE(minidump_file_writer.WriteEverything(&string_file)); - ASSERT_EQ(sizeof(MINIDUMP_HEADER) + sizeof(MINIDUMP_DIRECTORY), - string_file.string().size()); + ASSERT_EQ(string_file.string().size(), + sizeof(MINIDUMP_HEADER) + sizeof(MINIDUMP_DIRECTORY)); MINIDUMP_LOCATION_DESCRIPTOR user_stream_location; ASSERT_NO_FATAL_FAILURE(GetUserStream( @@ -108,39 +111,40 @@ TEST(MinidumpUserStreamWriter, InitializeFromSnapshotOneStream) { StringFile string_file; ASSERT_TRUE(minidump_file_writer.WriteEverything(&string_file)); - ASSERT_EQ(sizeof(MINIDUMP_HEADER) + sizeof(MINIDUMP_DIRECTORY) + kStreamSize, - string_file.string().size()); + ASSERT_EQ(string_file.string().size(), + sizeof(MINIDUMP_HEADER) + sizeof(MINIDUMP_DIRECTORY) + kStreamSize); MINIDUMP_LOCATION_DESCRIPTOR user_stream_location = {}; ASSERT_NO_FATAL_FAILURE(GetUserStream( string_file.string(), &user_stream_location, kTestStreamId, kStreamSize)); const std::string stream_data = string_file.string().substr( user_stream_location.Rva, user_stream_location.DataSize); - EXPECT_EQ(std::string(kStreamSize, 'c'), stream_data); + EXPECT_EQ(stream_data, std::string(kStreamSize, 'c')); } TEST(MinidumpUserStreamWriter, InitializeFromBufferOneStream) { MinidumpFileWriter minidump_file_writer; - auto user_stream_writer = base::WrapUnique(new MinidumpUserStreamWriter()); const size_t kStreamSize = 128; std::vector data(kStreamSize, 'c'); - user_stream_writer->InitializeFromBuffer( - kTestStreamId, &data[0], data.size()); + auto data_source = base::WrapUnique(new test::BufferExtensionStreamDataSource( + kTestStreamId, &data[0], data.size())); + auto user_stream_writer = base::WrapUnique(new MinidumpUserStreamWriter()); + user_stream_writer->InitializeFromUserExtensionStream(std::move(data_source)); minidump_file_writer.AddStream(std::move(user_stream_writer)); StringFile string_file; ASSERT_TRUE(minidump_file_writer.WriteEverything(&string_file)); - ASSERT_EQ(sizeof(MINIDUMP_HEADER) + sizeof(MINIDUMP_DIRECTORY) + kStreamSize, - string_file.string().size()); + ASSERT_EQ(string_file.string().size(), + sizeof(MINIDUMP_HEADER) + sizeof(MINIDUMP_DIRECTORY) + kStreamSize); MINIDUMP_LOCATION_DESCRIPTOR user_stream_location = {}; ASSERT_NO_FATAL_FAILURE(GetUserStream( string_file.string(), &user_stream_location, kTestStreamId, kStreamSize)); const std::string stream_data = string_file.string().substr( user_stream_location.Rva, user_stream_location.DataSize); - EXPECT_EQ(std::string(kStreamSize, 'c'), stream_data); + EXPECT_EQ(stream_data, std::string(kStreamSize, 'c')); } } // namespace diff --git a/minidump/minidump_writable_test.cc b/minidump/minidump_writable_test.cc index be04e604..74b51a83 100644 --- a/minidump/minidump_writable_test.cc +++ b/minidump/minidump_writable_test.cc @@ -53,7 +53,7 @@ class BaseTestMinidumpWritable : public crashpad::internal::MinidumpWritable { void Verify() { verified_ = true; - EXPECT_EQ(kStateWritten, state()); + EXPECT_EQ(state(), kStateWritten); for (BaseTestMinidumpWritable* child : children_) { child->Verify(); } @@ -61,10 +61,10 @@ class BaseTestMinidumpWritable : public crashpad::internal::MinidumpWritable { protected: bool Freeze() override { - EXPECT_EQ(kStateMutable, state()); + EXPECT_EQ(state(), kStateMutable); bool rv = MinidumpWritable::Freeze(); EXPECT_TRUE(rv); - EXPECT_EQ(kStateFrozen, state()); + EXPECT_EQ(state(), kStateFrozen); return rv; } @@ -90,7 +90,7 @@ class BaseTestMinidumpWritable : public crashpad::internal::MinidumpWritable { } bool WillWriteAtOffsetImpl(FileOffset offset) override { - EXPECT_EQ(state(), kStateFrozen); + EXPECT_EQ(kStateFrozen, state()); expected_offset_ = offset; bool rv = MinidumpWritable::WillWriteAtOffsetImpl(offset); EXPECT_TRUE(rv); @@ -98,8 +98,8 @@ class BaseTestMinidumpWritable : public crashpad::internal::MinidumpWritable { } bool WriteObject(FileWriterInterface* file_writer) override { - EXPECT_EQ(state(), kStateWritable); - EXPECT_EQ(expected_offset_, file_writer->Seek(0, SEEK_CUR)); + EXPECT_EQ(kStateWritable, state()); + EXPECT_EQ(file_writer->Seek(0, SEEK_CUR), expected_offset_); // Subclasses must override this. return false; @@ -162,8 +162,8 @@ TEST(MinidumpWritable, MinidumpWritable) { TestStringMinidumpWritable string_writable; string_writable.SetData("a"); EXPECT_TRUE(string_writable.WriteEverything(&string_file)); - EXPECT_EQ(1u, string_file.string().size()); - EXPECT_EQ("a", string_file.string()); + EXPECT_EQ(string_file.string().size(), 1u); + EXPECT_EQ(string_file.string(), "a"); string_writable.Verify(); } @@ -176,8 +176,8 @@ TEST(MinidumpWritable, MinidumpWritable) { child.SetData("c"); parent.AddChild(&child); EXPECT_TRUE(parent.WriteEverything(&string_file)); - EXPECT_EQ(5u, string_file.string().size()); - EXPECT_EQ(std::string("b\0\0\0c", 5), string_file.string()); + EXPECT_EQ(string_file.string().size(), 5u); + EXPECT_EQ(string_file.string(), std::string("b\0\0\0c", 5)); parent.Verify(); } @@ -190,8 +190,8 @@ TEST(MinidumpWritable, MinidumpWritable) { child.SetData("f"); parent.AddChild(&child); EXPECT_TRUE(parent.WriteEverything(&string_file)); - EXPECT_EQ(5u, string_file.string().size()); - EXPECT_EQ(std::string("de\0\0f", 5), string_file.string()); + EXPECT_EQ(string_file.string().size(), 5u); + EXPECT_EQ(string_file.string(), std::string("de\0\0f", 5)); parent.Verify(); } @@ -204,8 +204,8 @@ TEST(MinidumpWritable, MinidumpWritable) { child.SetData("j"); parent.AddChild(&child); EXPECT_TRUE(parent.WriteEverything(&string_file)); - EXPECT_EQ(5u, string_file.string().size()); - EXPECT_EQ(std::string("ghi\0j", 5), string_file.string()); + EXPECT_EQ(string_file.string().size(), 5u); + EXPECT_EQ(string_file.string(), std::string("ghi\0j", 5)); parent.Verify(); } @@ -218,8 +218,8 @@ TEST(MinidumpWritable, MinidumpWritable) { child.SetData("o"); parent.AddChild(&child); EXPECT_TRUE(parent.WriteEverything(&string_file)); - EXPECT_EQ(5u, string_file.string().size()); - EXPECT_EQ("klmno", string_file.string()); + EXPECT_EQ(string_file.string().size(), 5u); + EXPECT_EQ(string_file.string(), "klmno"); parent.Verify(); } @@ -232,8 +232,8 @@ TEST(MinidumpWritable, MinidumpWritable) { child.SetData("u"); parent.AddChild(&child); EXPECT_TRUE(parent.WriteEverything(&string_file)); - EXPECT_EQ(9u, string_file.string().size()); - EXPECT_EQ(std::string("pqrst\0\0\0u", 9), string_file.string()); + EXPECT_EQ(string_file.string().size(), 9u); + EXPECT_EQ(string_file.string(), std::string("pqrst\0\0\0u", 9)); parent.Verify(); } @@ -249,8 +249,9 @@ TEST(MinidumpWritable, MinidumpWritable) { child_1.SetData("child_1"); parent.AddChild(&child_1); EXPECT_TRUE(parent.WriteEverything(&string_file)); - EXPECT_EQ(23u, string_file.string().size()); - EXPECT_EQ(std::string("parent\0\0child_0\0child_1", 23), string_file.string()); + EXPECT_EQ(string_file.string().size(), 23u); + EXPECT_EQ(string_file.string(), + std::string("parent\0\0child_0\0child_1", 23)); parent.Verify(); } @@ -266,9 +267,9 @@ TEST(MinidumpWritable, MinidumpWritable) { grandchild.SetData("grandchild"); child.AddChild(&grandchild); EXPECT_TRUE(parent.WriteEverything(&string_file)); - EXPECT_EQ(26u, string_file.string().size()); - EXPECT_EQ(std::string("parent\0\0child\0\0\0grandchild", 26), - string_file.string()); + EXPECT_EQ(string_file.string().size(), 26u); + EXPECT_EQ(string_file.string(), + std::string("parent\0\0child\0\0\0grandchild", 26)); parent.Verify(); } @@ -283,8 +284,8 @@ TEST(MinidumpWritable, MinidumpWritable) { grandchild.SetData("grandchild"); child.AddChild(&grandchild); EXPECT_TRUE(parent.WriteEverything(&string_file)); - EXPECT_EQ(18u, string_file.string().size()); - EXPECT_EQ(std::string("child\0\0\0grandchild", 18), string_file.string()); + EXPECT_EQ(string_file.string().size(), 18u); + EXPECT_EQ(string_file.string(), std::string("child\0\0\0grandchild", 18)); parent.Verify(); } @@ -299,8 +300,8 @@ TEST(MinidumpWritable, MinidumpWritable) { grandchild.SetData("grandchild"); child.AddChild(&grandchild); EXPECT_TRUE(parent.WriteEverything(&string_file)); - EXPECT_EQ(18u, string_file.string().size()); - EXPECT_EQ(std::string("parent\0\0grandchild", 18), string_file.string()); + EXPECT_EQ(string_file.string().size(), 18u); + EXPECT_EQ(string_file.string(), std::string("parent\0\0grandchild", 18)); parent.Verify(); } @@ -315,8 +316,8 @@ TEST(MinidumpWritable, MinidumpWritable) { TestStringMinidumpWritable grandchild; child.AddChild(&grandchild); EXPECT_TRUE(parent.WriteEverything(&string_file)); - EXPECT_EQ(13u, string_file.string().size()); - EXPECT_EQ(std::string("parent\0\0child", 13), string_file.string()); + EXPECT_EQ(string_file.string().size(), 13u); + EXPECT_EQ(string_file.string(), std::string("parent\0\0child", 13)); parent.Verify(); } @@ -333,9 +334,9 @@ TEST(MinidumpWritable, MinidumpWritable) { grandchild.SetPhaseLate(); child.AddChild(&grandchild); EXPECT_TRUE(parent.WriteEverything(&string_file)); - EXPECT_EQ(26u, string_file.string().size()); - EXPECT_EQ(std::string("parent\0\0child\0\0\0grandchild", 26), - string_file.string()); + EXPECT_EQ(string_file.string().size(), 26u); + EXPECT_EQ(string_file.string(), + std::string("parent\0\0child\0\0\0grandchild", 26)); parent.Verify(); } @@ -352,9 +353,9 @@ TEST(MinidumpWritable, MinidumpWritable) { grandchild.SetData("grandchild"); child.AddChild(&grandchild); EXPECT_TRUE(parent.WriteEverything(&string_file)); - EXPECT_EQ(25u, string_file.string().size()); - EXPECT_EQ(std::string("parent\0\0grandchild\0\0child", 25), - string_file.string()); + EXPECT_EQ(string_file.string().size(), 25u); + EXPECT_EQ(string_file.string(), + std::string("parent\0\0grandchild\0\0child", 25)); parent.Verify(); } @@ -382,9 +383,9 @@ TEST(MinidumpWritable, MinidumpWritable) { grandchild_11.SetData("G11"); child_1.AddChild(&grandchild_11); EXPECT_TRUE(parent.WriteEverything(&string_file)); - EXPECT_EQ(27u, string_file.string().size()); - EXPECT_EQ(std::string("P..\0C0.\0G00\0G01\0C1.\0G10\0G11", 27), - string_file.string()); + EXPECT_EQ(string_file.string().size(), 27u); + EXPECT_EQ(string_file.string(), + std::string("P..\0C0.\0G00\0G01\0C1.\0G10\0G11", 27)); parent.Verify(); } @@ -413,9 +414,9 @@ TEST(MinidumpWritable, MinidumpWritable) { grandchild_11.SetData("G11"); child_1.AddChild(&grandchild_11); EXPECT_TRUE(parent.WriteEverything(&string_file)); - EXPECT_EQ(27u, string_file.string().size()); - EXPECT_EQ(std::string("P..\0G00\0G01\0C1.\0G10\0G11\0C0.", 27), - string_file.string()); + EXPECT_EQ(string_file.string().size(), 27u); + EXPECT_EQ(string_file.string(), + std::string("P..\0G00\0G01\0C1.\0G10\0G11\0C0.", 27)); parent.Verify(); } @@ -445,9 +446,9 @@ TEST(MinidumpWritable, MinidumpWritable) { grandchild_11.SetData("G11"); child_1.AddChild(&grandchild_11); EXPECT_TRUE(parent.WriteEverything(&string_file)); - EXPECT_EQ(27u, string_file.string().size()); - EXPECT_EQ(std::string("P..\0C0.\0C1.\0G10\0G11\0G00\0G01", 27), - string_file.string()); + EXPECT_EQ(string_file.string().size(), 27u); + EXPECT_EQ(string_file.string(), + std::string("P..\0C0.\0C1.\0G10\0G11\0G00\0G01", 27)); parent.Verify(); } @@ -461,8 +462,8 @@ TEST(MinidumpWritable, MinidumpWritable) { child.SetAlignment(1); parent.AddChild(&child); EXPECT_TRUE(parent.WriteEverything(&string_file)); - EXPECT_EQ(2u, string_file.string().size()); - EXPECT_EQ("pc", string_file.string()); + EXPECT_EQ(string_file.string().size(), 2u); + EXPECT_EQ(string_file.string(), "pc"); parent.Verify(); } @@ -476,8 +477,8 @@ TEST(MinidumpWritable, MinidumpWritable) { child.SetAlignment(2); parent.AddChild(&child); EXPECT_TRUE(parent.WriteEverything(&string_file)); - EXPECT_EQ(3u, string_file.string().size()); - EXPECT_EQ(std::string("p\0c", 3), string_file.string()); + EXPECT_EQ(string_file.string().size(), 3u); + EXPECT_EQ(string_file.string(), std::string("p\0c", 3)); parent.Verify(); } } @@ -521,8 +522,8 @@ TEST(MinidumpWritable, RVA) { TestRVAMinidumpWritable rva_writable; EXPECT_TRUE(rva_writable.WriteEverything(&string_file)); - ASSERT_EQ(sizeof(RVA), string_file.string().size()); - EXPECT_EQ(0 * sizeof(RVA), RVAAtIndex(string_file.string(), 0)); + ASSERT_EQ(string_file.string().size(), sizeof(RVA)); + EXPECT_EQ(RVAAtIndex(string_file.string(), 0), 0 * sizeof(RVA)); rva_writable.Verify(); } @@ -533,8 +534,8 @@ TEST(MinidumpWritable, RVA) { rva_writable.SetRVA(&rva_writable); EXPECT_TRUE(rva_writable.WriteEverything(&string_file)); - ASSERT_EQ(sizeof(RVA), string_file.string().size()); - EXPECT_EQ(0 * sizeof(RVA), RVAAtIndex(string_file.string(), 0)); + ASSERT_EQ(string_file.string().size(), sizeof(RVA)); + EXPECT_EQ(RVAAtIndex(string_file.string(), 0), 0 * sizeof(RVA)); rva_writable.Verify(); } @@ -548,9 +549,9 @@ TEST(MinidumpWritable, RVA) { parent.AddChild(&child); EXPECT_TRUE(parent.WriteEverything(&string_file)); - ASSERT_EQ(2 * sizeof(RVA), string_file.string().size()); - EXPECT_EQ(0 * sizeof(RVA), RVAAtIndex(string_file.string(), 0)); - EXPECT_EQ(1 * sizeof(RVA), RVAAtIndex(string_file.string(), 1)); + ASSERT_EQ(string_file.string().size(), 2 * sizeof(RVA)); + EXPECT_EQ(RVAAtIndex(string_file.string(), 0), 0 * sizeof(RVA)); + EXPECT_EQ(RVAAtIndex(string_file.string(), 1), 1 * sizeof(RVA)); parent.Verify(); } @@ -563,9 +564,9 @@ TEST(MinidumpWritable, RVA) { parent.AddChild(&child); EXPECT_TRUE(parent.WriteEverything(&string_file)); - ASSERT_EQ(2 * sizeof(RVA), string_file.string().size()); - EXPECT_EQ(1 * sizeof(RVA), RVAAtIndex(string_file.string(), 0)); - EXPECT_EQ(0 * sizeof(RVA), RVAAtIndex(string_file.string(), 1)); + ASSERT_EQ(string_file.string().size(), 2 * sizeof(RVA)); + EXPECT_EQ(RVAAtIndex(string_file.string(), 0), 1 * sizeof(RVA)); + EXPECT_EQ(RVAAtIndex(string_file.string(), 1), 0 * sizeof(RVA)); parent.Verify(); } @@ -579,9 +580,9 @@ TEST(MinidumpWritable, RVA) { parent.AddChild(&child); EXPECT_TRUE(parent.WriteEverything(&string_file)); - ASSERT_EQ(2 * sizeof(RVA), string_file.string().size()); - EXPECT_EQ(1 * sizeof(RVA), RVAAtIndex(string_file.string(), 0)); - EXPECT_EQ(0 * sizeof(RVA), RVAAtIndex(string_file.string(), 1)); + ASSERT_EQ(string_file.string().size(), 2 * sizeof(RVA)); + EXPECT_EQ(RVAAtIndex(string_file.string(), 0), 1 * sizeof(RVA)); + EXPECT_EQ(RVAAtIndex(string_file.string(), 1), 0 * sizeof(RVA)); parent.Verify(); } @@ -603,12 +604,12 @@ TEST(MinidumpWritable, RVA) { child.AddChild(&grandchild_2); EXPECT_TRUE(parent.WriteEverything(&string_file)); - ASSERT_EQ(5 * sizeof(RVA), string_file.string().size()); - EXPECT_EQ(1 * sizeof(RVA), RVAAtIndex(string_file.string(), 0)); - EXPECT_EQ(0 * sizeof(RVA), RVAAtIndex(string_file.string(), 1)); - EXPECT_EQ(1 * sizeof(RVA), RVAAtIndex(string_file.string(), 2)); - EXPECT_EQ(1 * sizeof(RVA), RVAAtIndex(string_file.string(), 3)); - EXPECT_EQ(1 * sizeof(RVA), RVAAtIndex(string_file.string(), 4)); + ASSERT_EQ(string_file.string().size(), 5 * sizeof(RVA)); + EXPECT_EQ(RVAAtIndex(string_file.string(), 0), 1 * sizeof(RVA)); + EXPECT_EQ(RVAAtIndex(string_file.string(), 1), 0 * sizeof(RVA)); + EXPECT_EQ(RVAAtIndex(string_file.string(), 2), 1 * sizeof(RVA)); + EXPECT_EQ(RVAAtIndex(string_file.string(), 3), 1 * sizeof(RVA)); + EXPECT_EQ(RVAAtIndex(string_file.string(), 4), 1 * sizeof(RVA)); parent.Verify(); } } @@ -674,10 +675,10 @@ TEST(MinidumpWritable, LocationDescriptor) { TestLocationDescriptorMinidumpWritable location_descriptor_writable; EXPECT_TRUE(location_descriptor_writable.WriteEverything(&string_file)); - ASSERT_EQ(9u, string_file.string().size()); + ASSERT_EQ(string_file.string().size(), 9u); const LocationDescriptorAndData* ldd = LDDAtIndex(string_file.string(), 0); - EXPECT_EQ(0u, ldd->location_descriptor.DataSize); - EXPECT_EQ(0u, ldd->location_descriptor.Rva); + EXPECT_EQ(ldd->location_descriptor.DataSize, 0u); + EXPECT_EQ(ldd->location_descriptor.Rva, 0u); location_descriptor_writable.Verify(); } @@ -689,10 +690,10 @@ TEST(MinidumpWritable, LocationDescriptor) { &location_descriptor_writable); EXPECT_TRUE(location_descriptor_writable.WriteEverything(&string_file)); - ASSERT_EQ(9u, string_file.string().size()); + ASSERT_EQ(string_file.string().size(), 9u); const LocationDescriptorAndData* ldd = LDDAtIndex(string_file.string(), 0); - EXPECT_EQ(9u, ldd->location_descriptor.DataSize); - EXPECT_EQ(0u, ldd->location_descriptor.Rva); + EXPECT_EQ(ldd->location_descriptor.DataSize, 9u); + EXPECT_EQ(ldd->location_descriptor.Rva, 0u); location_descriptor_writable.Verify(); } @@ -705,10 +706,10 @@ TEST(MinidumpWritable, LocationDescriptor) { location_descriptor_writable.SetString("zz"); EXPECT_TRUE(location_descriptor_writable.WriteEverything(&string_file)); - ASSERT_EQ(11u, string_file.string().size()); + ASSERT_EQ(string_file.string().size(), 11u); const LocationDescriptorAndData* ldd = LDDAtIndex(string_file.string(), 0); - EXPECT_EQ(11u, ldd->location_descriptor.DataSize); - EXPECT_EQ(0u, ldd->location_descriptor.Rva); + EXPECT_EQ(ldd->location_descriptor.DataSize, 11u); + EXPECT_EQ(ldd->location_descriptor.Rva, 0u); EXPECT_STREQ("zz", ldd->string); location_descriptor_writable.Verify(); } @@ -725,14 +726,14 @@ TEST(MinidumpWritable, LocationDescriptor) { parent.AddChild(&child); EXPECT_TRUE(parent.WriteEverything(&string_file)); - ASSERT_EQ(22u, string_file.string().size()); + ASSERT_EQ(string_file.string().size(), 22u); const LocationDescriptorAndData* ldd = LDDAtIndex(string_file.string(), 0); - EXPECT_EQ(11u, ldd->location_descriptor.DataSize); - EXPECT_EQ(0u, ldd->location_descriptor.Rva); + EXPECT_EQ(ldd->location_descriptor.DataSize, 11u); + EXPECT_EQ(ldd->location_descriptor.Rva, 0u); EXPECT_STREQ("yy", ldd->string); ldd = LDDAtIndex(string_file.string(), 12); - EXPECT_EQ(10u, ldd->location_descriptor.DataSize); - EXPECT_EQ(12u, ldd->location_descriptor.Rva); + EXPECT_EQ(ldd->location_descriptor.DataSize, 10u); + EXPECT_EQ(ldd->location_descriptor.Rva, 12u); EXPECT_STREQ("x", ldd->string); parent.Verify(); } @@ -748,14 +749,14 @@ TEST(MinidumpWritable, LocationDescriptor) { parent.AddChild(&child); EXPECT_TRUE(parent.WriteEverything(&string_file)); - ASSERT_EQ(23u, string_file.string().size()); + ASSERT_EQ(string_file.string().size(), 23u); const LocationDescriptorAndData* ldd = LDDAtIndex(string_file.string(), 0); - EXPECT_EQ(11u, ldd->location_descriptor.DataSize); - EXPECT_EQ(12u, ldd->location_descriptor.Rva); + EXPECT_EQ(ldd->location_descriptor.DataSize, 11u); + EXPECT_EQ(ldd->location_descriptor.Rva, 12u); EXPECT_STREQ("www", ldd->string); ldd = LDDAtIndex(string_file.string(), 12); - EXPECT_EQ(0u, ldd->location_descriptor.DataSize); - EXPECT_EQ(0u, ldd->location_descriptor.Rva); + EXPECT_EQ(ldd->location_descriptor.DataSize, 0u); + EXPECT_EQ(ldd->location_descriptor.Rva, 0u); EXPECT_STREQ("vv", ldd->string); parent.Verify(); } @@ -772,14 +773,14 @@ TEST(MinidumpWritable, LocationDescriptor) { parent.AddChild(&child); EXPECT_TRUE(parent.WriteEverything(&string_file)); - ASSERT_EQ(29u, string_file.string().size()); + ASSERT_EQ(string_file.string().size(), 29u); const LocationDescriptorAndData* ldd = LDDAtIndex(string_file.string(), 0); - EXPECT_EQ(13u, ldd->location_descriptor.DataSize); - EXPECT_EQ(16u, ldd->location_descriptor.Rva); + EXPECT_EQ(ldd->location_descriptor.DataSize, 13u); + EXPECT_EQ(ldd->location_descriptor.Rva, 16u); EXPECT_STREQ("uuuu", ldd->string); ldd = LDDAtIndex(string_file.string(), 16); - EXPECT_EQ(13u, ldd->location_descriptor.DataSize); - EXPECT_EQ(0u, ldd->location_descriptor.Rva); + EXPECT_EQ(ldd->location_descriptor.DataSize, 13u); + EXPECT_EQ(ldd->location_descriptor.Rva, 0u); EXPECT_STREQ("tttt", ldd->string); parent.Verify(); } @@ -807,26 +808,26 @@ TEST(MinidumpWritable, LocationDescriptor) { child.AddChild(&grandchild_2); EXPECT_TRUE(parent.WriteEverything(&string_file)); - ASSERT_EQ(58u, string_file.string().size()); + ASSERT_EQ(string_file.string().size(), 58u); const LocationDescriptorAndData* ldd = LDDAtIndex(string_file.string(), 0); - EXPECT_EQ(10u, ldd->location_descriptor.DataSize); - EXPECT_EQ(12u, ldd->location_descriptor.Rva); + EXPECT_EQ(ldd->location_descriptor.DataSize, 10u); + EXPECT_EQ(ldd->location_descriptor.Rva, 12u); EXPECT_STREQ("s", ldd->string); ldd = LDDAtIndex(string_file.string(), 12); - EXPECT_EQ(0u, ldd->location_descriptor.DataSize); - EXPECT_EQ(0u, ldd->location_descriptor.Rva); + EXPECT_EQ(ldd->location_descriptor.DataSize, 0u); + EXPECT_EQ(ldd->location_descriptor.Rva, 0u); EXPECT_STREQ("r", ldd->string); ldd = LDDAtIndex(string_file.string(), 24); - EXPECT_EQ(10u, ldd->location_descriptor.DataSize); - EXPECT_EQ(12u, ldd->location_descriptor.Rva); + EXPECT_EQ(ldd->location_descriptor.DataSize, 10u); + EXPECT_EQ(ldd->location_descriptor.Rva, 12u); EXPECT_STREQ("q", ldd->string); ldd = LDDAtIndex(string_file.string(), 36); - EXPECT_EQ(10u, ldd->location_descriptor.DataSize); - EXPECT_EQ(12u, ldd->location_descriptor.Rva); + EXPECT_EQ(ldd->location_descriptor.DataSize, 10u); + EXPECT_EQ(ldd->location_descriptor.Rva, 12u); EXPECT_STREQ("p", ldd->string); ldd = LDDAtIndex(string_file.string(), 48); - EXPECT_EQ(10u, ldd->location_descriptor.DataSize); - EXPECT_EQ(12u, ldd->location_descriptor.Rva); + EXPECT_EQ(ldd->location_descriptor.DataSize, 10u); + EXPECT_EQ(ldd->location_descriptor.Rva, 12u); EXPECT_STREQ("o", ldd->string); parent.Verify(); } diff --git a/minidump/test/minidump_context_test_util.cc b/minidump/test/minidump_context_test_util.cc index 8999abe0..cd8e5227 100644 --- a/minidump/test/minidump_context_test_util.cc +++ b/minidump/test/minidump_context_test_util.cc @@ -149,48 +149,48 @@ namespace { template void ExpectMinidumpContextFxsave(const FxsaveType* expected, const FxsaveType* observed) { - EXPECT_EQ(expected->fcw, observed->fcw); - EXPECT_EQ(expected->fsw, observed->fsw); - EXPECT_EQ(expected->ftw, observed->ftw); - EXPECT_EQ(expected->reserved_1, observed->reserved_1); - EXPECT_EQ(expected->fop, observed->fop); - EXPECT_EQ(expected->fpu_ip, observed->fpu_ip); - EXPECT_EQ(expected->fpu_cs, observed->fpu_cs); - EXPECT_EQ(expected->reserved_2, observed->reserved_2); - EXPECT_EQ(expected->fpu_dp, observed->fpu_dp); - EXPECT_EQ(expected->fpu_ds, observed->fpu_ds); - EXPECT_EQ(expected->reserved_3, observed->reserved_3); - EXPECT_EQ(expected->mxcsr, observed->mxcsr); - EXPECT_EQ(expected->mxcsr_mask, observed->mxcsr_mask); + EXPECT_EQ(observed->fcw, expected->fcw); + EXPECT_EQ(observed->fsw, expected->fsw); + EXPECT_EQ(observed->ftw, expected->ftw); + EXPECT_EQ(observed->reserved_1, expected->reserved_1); + EXPECT_EQ(observed->fop, expected->fop); + EXPECT_EQ(observed->fpu_ip, expected->fpu_ip); + EXPECT_EQ(observed->fpu_cs, expected->fpu_cs); + EXPECT_EQ(observed->reserved_2, expected->reserved_2); + EXPECT_EQ(observed->fpu_dp, expected->fpu_dp); + EXPECT_EQ(observed->fpu_ds, expected->fpu_ds); + EXPECT_EQ(observed->reserved_3, expected->reserved_3); + EXPECT_EQ(observed->mxcsr, expected->mxcsr); + EXPECT_EQ(observed->mxcsr_mask, expected->mxcsr_mask); for (size_t st_mm_index = 0; st_mm_index < arraysize(expected->st_mm); ++st_mm_index) { SCOPED_TRACE(base::StringPrintf("st_mm_index %" PRIuS, st_mm_index)); - EXPECT_EQ(BytesToHexString(expected->st_mm[st_mm_index].st, - arraysize(expected->st_mm[st_mm_index].st)), - BytesToHexString(observed->st_mm[st_mm_index].st, - arraysize(observed->st_mm[st_mm_index].st))); + EXPECT_EQ(BytesToHexString(observed->st_mm[st_mm_index].st, + arraysize(observed->st_mm[st_mm_index].st)), + BytesToHexString(expected->st_mm[st_mm_index].st, + arraysize(expected->st_mm[st_mm_index].st))); EXPECT_EQ( - BytesToHexString(expected->st_mm[st_mm_index].st_reserved, - arraysize(expected->st_mm[st_mm_index].st_reserved)), BytesToHexString(observed->st_mm[st_mm_index].st_reserved, - arraysize(observed->st_mm[st_mm_index].st_reserved))); + arraysize(observed->st_mm[st_mm_index].st_reserved)), + BytesToHexString(expected->st_mm[st_mm_index].st_reserved, + arraysize(expected->st_mm[st_mm_index].st_reserved))); } for (size_t xmm_index = 0; xmm_index < arraysize(expected->xmm); ++xmm_index) { - EXPECT_EQ(BytesToHexString(expected->xmm[xmm_index], - arraysize(expected->xmm[xmm_index])), - BytesToHexString(observed->xmm[xmm_index], - arraysize(observed->xmm[xmm_index]))) + EXPECT_EQ(BytesToHexString(observed->xmm[xmm_index], + arraysize(observed->xmm[xmm_index])), + BytesToHexString(expected->xmm[xmm_index], + arraysize(expected->xmm[xmm_index]))) << "xmm_index " << xmm_index; } EXPECT_EQ( - BytesToHexString(expected->reserved_4, arraysize(expected->reserved_4)), - BytesToHexString(observed->reserved_4, arraysize(observed->reserved_4))); + BytesToHexString(observed->reserved_4, arraysize(observed->reserved_4)), + BytesToHexString(expected->reserved_4, arraysize(expected->reserved_4))); EXPECT_EQ( - BytesToHexString(expected->available, arraysize(expected->available)), - BytesToHexString(observed->available, arraysize(observed->available))); + BytesToHexString(observed->available, arraysize(observed->available)), + BytesToHexString(expected->available, arraysize(expected->available))); } } // namespace @@ -200,50 +200,50 @@ void ExpectMinidumpContextX86( MinidumpContextX86 expected; InitializeMinidumpContextX86(&expected, expect_seed); - EXPECT_EQ(expected.context_flags, observed->context_flags); - EXPECT_EQ(expected.dr0, observed->dr0); - EXPECT_EQ(expected.dr1, observed->dr1); - EXPECT_EQ(expected.dr2, observed->dr2); - EXPECT_EQ(expected.dr3, observed->dr3); - EXPECT_EQ(expected.dr6, observed->dr6); - EXPECT_EQ(expected.dr7, observed->dr7); + EXPECT_EQ(observed->context_flags, expected.context_flags); + EXPECT_EQ(observed->dr0, expected.dr0); + EXPECT_EQ(observed->dr1, expected.dr1); + EXPECT_EQ(observed->dr2, expected.dr2); + EXPECT_EQ(observed->dr3, expected.dr3); + EXPECT_EQ(observed->dr6, expected.dr6); + EXPECT_EQ(observed->dr7, expected.dr7); - EXPECT_EQ(expected.fsave.fcw, observed->fsave.fcw); - EXPECT_EQ(expected.fsave.fsw, observed->fsave.fsw); - EXPECT_EQ(expected.fsave.ftw, observed->fsave.ftw); - EXPECT_EQ(expected.fsave.fpu_ip, observed->fsave.fpu_ip); - EXPECT_EQ(expected.fsave.fpu_cs, observed->fsave.fpu_cs); - EXPECT_EQ(expected.fsave.fpu_dp, observed->fsave.fpu_dp); - EXPECT_EQ(expected.fsave.fpu_ds, observed->fsave.fpu_ds); + EXPECT_EQ(observed->fsave.fcw, expected.fsave.fcw); + EXPECT_EQ(observed->fsave.fsw, expected.fsave.fsw); + EXPECT_EQ(observed->fsave.ftw, expected.fsave.ftw); + EXPECT_EQ(observed->fsave.fpu_ip, expected.fsave.fpu_ip); + EXPECT_EQ(observed->fsave.fpu_cs, expected.fsave.fpu_cs); + EXPECT_EQ(observed->fsave.fpu_dp, expected.fsave.fpu_dp); + EXPECT_EQ(observed->fsave.fpu_ds, expected.fsave.fpu_ds); for (size_t index = 0; index < arraysize(expected.fsave.st); ++index) { - EXPECT_EQ(BytesToHexString(expected.fsave.st[index], - arraysize(expected.fsave.st[index])), - BytesToHexString(observed->fsave.st[index], - arraysize(observed->fsave.st[index]))) + EXPECT_EQ(BytesToHexString(observed->fsave.st[index], + arraysize(observed->fsave.st[index])), + BytesToHexString(expected.fsave.st[index], + arraysize(expected.fsave.st[index]))) << "index " << index; } if (snapshot) { - EXPECT_EQ(0u, observed->float_save.spare_0); + EXPECT_EQ(observed->float_save.spare_0, 0u); } else { - EXPECT_EQ(expected.float_save.spare_0, observed->float_save.spare_0); + EXPECT_EQ(observed->float_save.spare_0, expected.float_save.spare_0); } - EXPECT_EQ(expected.gs, observed->gs); - EXPECT_EQ(expected.fs, observed->fs); - EXPECT_EQ(expected.es, observed->es); - EXPECT_EQ(expected.ds, observed->ds); - EXPECT_EQ(expected.edi, observed->edi); - EXPECT_EQ(expected.esi, observed->esi); - EXPECT_EQ(expected.ebx, observed->ebx); - EXPECT_EQ(expected.edx, observed->edx); - EXPECT_EQ(expected.ecx, observed->ecx); - EXPECT_EQ(expected.eax, observed->eax); - EXPECT_EQ(expected.ebp, observed->ebp); - EXPECT_EQ(expected.eip, observed->eip); - EXPECT_EQ(expected.cs, observed->cs); - EXPECT_EQ(expected.eflags, observed->eflags); - EXPECT_EQ(expected.esp, observed->esp); - EXPECT_EQ(expected.ss, observed->ss); + EXPECT_EQ(observed->gs, expected.gs); + EXPECT_EQ(observed->fs, expected.fs); + EXPECT_EQ(observed->es, expected.es); + EXPECT_EQ(observed->ds, expected.ds); + EXPECT_EQ(observed->edi, expected.edi); + EXPECT_EQ(observed->esi, expected.esi); + EXPECT_EQ(observed->ebx, expected.ebx); + EXPECT_EQ(observed->edx, expected.edx); + EXPECT_EQ(observed->ecx, expected.ecx); + EXPECT_EQ(observed->eax, expected.eax); + EXPECT_EQ(observed->ebp, expected.ebp); + EXPECT_EQ(observed->eip, expected.eip); + EXPECT_EQ(observed->cs, expected.cs); + EXPECT_EQ(observed->eflags, expected.eflags); + EXPECT_EQ(observed->esp, expected.esp); + EXPECT_EQ(observed->ss, expected.ss); ExpectMinidumpContextFxsave(&expected.fxsave, &observed->fxsave); } @@ -253,98 +253,100 @@ void ExpectMinidumpContextAMD64( MinidumpContextAMD64 expected; InitializeMinidumpContextAMD64(&expected, expect_seed); - EXPECT_EQ(expected.context_flags, observed->context_flags); + EXPECT_EQ(observed->context_flags, expected.context_flags); if (snapshot) { - EXPECT_EQ(0u, observed->p1_home); - EXPECT_EQ(0u, observed->p2_home); - EXPECT_EQ(0u, observed->p3_home); - EXPECT_EQ(0u, observed->p4_home); - EXPECT_EQ(0u, observed->p5_home); - EXPECT_EQ(0u, observed->p6_home); + EXPECT_EQ(observed->p1_home, 0u); + EXPECT_EQ(observed->p2_home, 0u); + EXPECT_EQ(observed->p3_home, 0u); + EXPECT_EQ(observed->p4_home, 0u); + EXPECT_EQ(observed->p5_home, 0u); + EXPECT_EQ(observed->p6_home, 0u); } else { - EXPECT_EQ(expected.p1_home, observed->p1_home); - EXPECT_EQ(expected.p2_home, observed->p2_home); - EXPECT_EQ(expected.p3_home, observed->p3_home); - EXPECT_EQ(expected.p4_home, observed->p4_home); - EXPECT_EQ(expected.p5_home, observed->p5_home); - EXPECT_EQ(expected.p6_home, observed->p6_home); + EXPECT_EQ(observed->p1_home, expected.p1_home); + EXPECT_EQ(observed->p2_home, expected.p2_home); + EXPECT_EQ(observed->p3_home, expected.p3_home); + EXPECT_EQ(observed->p4_home, expected.p4_home); + EXPECT_EQ(observed->p5_home, expected.p5_home); + EXPECT_EQ(observed->p6_home, expected.p6_home); } - EXPECT_EQ(expected.mx_csr, observed->mx_csr); + EXPECT_EQ(observed->mx_csr, expected.mx_csr); - EXPECT_EQ(expected.cs, observed->cs); + EXPECT_EQ(observed->cs, expected.cs); if (snapshot) { - EXPECT_EQ(0u, observed->ds); - EXPECT_EQ(0u, observed->es); + EXPECT_EQ(observed->ds, 0u); + EXPECT_EQ(observed->es, 0u); } else { - EXPECT_EQ(expected.ds, observed->ds); - EXPECT_EQ(expected.es, observed->es); + EXPECT_EQ(observed->ds, expected.ds); + EXPECT_EQ(observed->es, expected.es); } - EXPECT_EQ(expected.fs, observed->fs); - EXPECT_EQ(expected.gs, observed->gs); + EXPECT_EQ(observed->fs, expected.fs); + EXPECT_EQ(observed->gs, expected.gs); if (snapshot) { - EXPECT_EQ(0u, observed->ss); + EXPECT_EQ(observed->ss, 0u); } else { - EXPECT_EQ(expected.ss, observed->ss); + EXPECT_EQ(observed->ss, expected.ss); } - EXPECT_EQ(expected.eflags, observed->eflags); + EXPECT_EQ(observed->eflags, expected.eflags); - EXPECT_EQ(expected.dr0, observed->dr0); - EXPECT_EQ(expected.dr1, observed->dr1); - EXPECT_EQ(expected.dr2, observed->dr2); - EXPECT_EQ(expected.dr3, observed->dr3); - EXPECT_EQ(expected.dr6, observed->dr6); - EXPECT_EQ(expected.dr7, observed->dr7); + EXPECT_EQ(observed->dr0, expected.dr0); + EXPECT_EQ(observed->dr1, expected.dr1); + EXPECT_EQ(observed->dr2, expected.dr2); + EXPECT_EQ(observed->dr3, expected.dr3); + EXPECT_EQ(observed->dr6, expected.dr6); + EXPECT_EQ(observed->dr7, expected.dr7); - EXPECT_EQ(expected.rax, observed->rax); - EXPECT_EQ(expected.rcx, observed->rcx); - EXPECT_EQ(expected.rdx, observed->rdx); - EXPECT_EQ(expected.rbx, observed->rbx); - EXPECT_EQ(expected.rsp, observed->rsp); - EXPECT_EQ(expected.rbp, observed->rbp); - EXPECT_EQ(expected.rsi, observed->rsi); - EXPECT_EQ(expected.rdi, observed->rdi); - EXPECT_EQ(expected.r8, observed->r8); - EXPECT_EQ(expected.r9, observed->r9); - EXPECT_EQ(expected.r10, observed->r10); - EXPECT_EQ(expected.r11, observed->r11); - EXPECT_EQ(expected.r12, observed->r12); - EXPECT_EQ(expected.r13, observed->r13); - EXPECT_EQ(expected.r14, observed->r14); - EXPECT_EQ(expected.r15, observed->r15); - EXPECT_EQ(expected.rip, observed->rip); + EXPECT_EQ(observed->rax, expected.rax); + EXPECT_EQ(observed->rcx, expected.rcx); + EXPECT_EQ(observed->rdx, expected.rdx); + EXPECT_EQ(observed->rbx, expected.rbx); + EXPECT_EQ(observed->rsp, expected.rsp); + EXPECT_EQ(observed->rbp, expected.rbp); + EXPECT_EQ(observed->rsi, expected.rsi); + EXPECT_EQ(observed->rdi, expected.rdi); + EXPECT_EQ(observed->r8, expected.r8); + EXPECT_EQ(observed->r9, expected.r9); + EXPECT_EQ(observed->r10, expected.r10); + EXPECT_EQ(observed->r11, expected.r11); + EXPECT_EQ(observed->r12, expected.r12); + EXPECT_EQ(observed->r13, expected.r13); + EXPECT_EQ(observed->r14, expected.r14); + EXPECT_EQ(observed->r15, expected.r15); + EXPECT_EQ(observed->rip, expected.rip); ExpectMinidumpContextFxsave(&expected.fxsave, &observed->fxsave); for (size_t index = 0; index < arraysize(expected.vector_register); ++index) { if (snapshot) { - EXPECT_EQ(0u, observed->vector_register[index].lo) << "index " << index; - EXPECT_EQ(0u, observed->vector_register[index].hi) << "index " << index; + EXPECT_EQ(observed->vector_register[index].lo, 0u) << "index " << index; + EXPECT_EQ(observed->vector_register[index].hi, 0u) << "index " << index; } else { - EXPECT_EQ(expected.vector_register[index].lo, - observed->vector_register[index].lo) << "index " << index; - EXPECT_EQ(expected.vector_register[index].hi, - observed->vector_register[index].hi) << "index " << index; + EXPECT_EQ(observed->vector_register[index].lo, + expected.vector_register[index].lo) + << "index " << index; + EXPECT_EQ(observed->vector_register[index].hi, + expected.vector_register[index].hi) + << "index " << index; } } if (snapshot) { - EXPECT_EQ(0u, observed->vector_control); - EXPECT_EQ(0u, observed->debug_control); - EXPECT_EQ(0u, observed->last_branch_to_rip); - EXPECT_EQ(0u, observed->last_branch_from_rip); - EXPECT_EQ(0u, observed->last_exception_to_rip); - EXPECT_EQ(0u, observed->last_exception_from_rip); + EXPECT_EQ(observed->vector_control, 0u); + EXPECT_EQ(observed->debug_control, 0u); + EXPECT_EQ(observed->last_branch_to_rip, 0u); + EXPECT_EQ(observed->last_branch_from_rip, 0u); + EXPECT_EQ(observed->last_exception_to_rip, 0u); + EXPECT_EQ(observed->last_exception_from_rip, 0u); } else { - EXPECT_EQ(expected.vector_control, observed->vector_control); - EXPECT_EQ(expected.debug_control, observed->debug_control); - EXPECT_EQ(expected.last_branch_to_rip, observed->last_branch_to_rip); - EXPECT_EQ(expected.last_branch_from_rip, observed->last_branch_from_rip); - EXPECT_EQ(expected.last_exception_to_rip, observed->last_exception_to_rip); - EXPECT_EQ(expected.last_exception_from_rip, - observed->last_exception_from_rip); + EXPECT_EQ(observed->vector_control, expected.vector_control); + EXPECT_EQ(observed->debug_control, expected.debug_control); + EXPECT_EQ(observed->last_branch_to_rip, expected.last_branch_to_rip); + EXPECT_EQ(observed->last_branch_from_rip, expected.last_branch_from_rip); + EXPECT_EQ(observed->last_exception_to_rip, expected.last_exception_to_rip); + EXPECT_EQ(observed->last_exception_from_rip, + expected.last_exception_from_rip); } } diff --git a/minidump/test/minidump_file_writer_test_util.cc b/minidump/test/minidump_file_writer_test_util.cc index 723e97d0..f372212b 100644 --- a/minidump/test/minidump_file_writer_test_util.cc +++ b/minidump/test/minidump_file_writer_test_util.cc @@ -48,11 +48,11 @@ void VerifyMinidumpHeader(const MINIDUMP_HEADER* header, uint32_t streams, uint32_t timestamp) { ASSERT_TRUE(header); - ASSERT_EQ(streams, header->NumberOfStreams); - ASSERT_EQ(streams ? sizeof(MINIDUMP_HEADER) : 0u, header->StreamDirectoryRva); - EXPECT_EQ(0u, header->CheckSum); - EXPECT_EQ(timestamp, header->TimeDateStamp); - EXPECT_EQ(MiniDumpNormal, header->Flags); + ASSERT_EQ(header->NumberOfStreams, streams); + ASSERT_EQ(header->StreamDirectoryRva, streams ? sizeof(MINIDUMP_HEADER) : 0u); + EXPECT_EQ(header->CheckSum, 0u); + EXPECT_EQ(header->TimeDateStamp, timestamp); + EXPECT_EQ(header->Flags, MiniDumpNormal); } } // namespace test diff --git a/minidump/test/minidump_memory_writer_test_util.cc b/minidump/test/minidump_memory_writer_test_util.cc index 3b94b9c8..a2fa8b63 100644 --- a/minidump/test/minidump_memory_writer_test_util.cc +++ b/minidump/test/minidump_memory_writer_test_util.cc @@ -34,13 +34,13 @@ TestMinidumpMemoryWriter::~TestMinidumpMemoryWriter() { void ExpectMinidumpMemoryDescriptor( const MINIDUMP_MEMORY_DESCRIPTOR* expected, const MINIDUMP_MEMORY_DESCRIPTOR* observed) { - EXPECT_EQ(expected->StartOfMemoryRange, observed->StartOfMemoryRange); - EXPECT_EQ(expected->Memory.DataSize, observed->Memory.DataSize); + EXPECT_EQ(observed->StartOfMemoryRange, expected->StartOfMemoryRange); + EXPECT_EQ(observed->Memory.DataSize, expected->Memory.DataSize); if (expected->Memory.Rva != 0) { const uint32_t kMemoryAlignment = 16; - EXPECT_EQ( - (expected->Memory.Rva + kMemoryAlignment - 1) & ~(kMemoryAlignment - 1), - observed->Memory.Rva); + EXPECT_EQ(observed->Memory.Rva, + (expected->Memory.Rva + kMemoryAlignment - 1) & + ~(kMemoryAlignment - 1)); } } @@ -53,8 +53,8 @@ void ExpectMinidumpMemoryDescriptorAndContents( ExpectMinidumpMemoryDescriptor(expected, observed); if (at_eof) { - EXPECT_EQ(file_contents.size(), - observed->Memory.Rva + observed->Memory.DataSize); + EXPECT_EQ(observed->Memory.Rva + observed->Memory.DataSize, + file_contents.size()); } else { EXPECT_GE(file_contents.size(), observed->Memory.Rva + observed->Memory.DataSize); @@ -63,7 +63,7 @@ void ExpectMinidumpMemoryDescriptorAndContents( std::string expected_data(expected->Memory.DataSize, value); std::string observed_data(&file_contents[observed->Memory.Rva], observed->Memory.DataSize); - EXPECT_EQ(expected_data, observed_data); + EXPECT_EQ(observed_data, expected_data); } } // namespace test diff --git a/minidump/test/minidump_rva_list_test_util.cc b/minidump/test/minidump_rva_list_test_util.cc index 2ba5d024..248161c3 100644 --- a/minidump/test/minidump_rva_list_test_util.cc +++ b/minidump/test/minidump_rva_list_test_util.cc @@ -39,7 +39,7 @@ const MinidumpRVAList* MinidumpRVAListAtStart(const std::string& file_contents, } if (list->count != count) { - EXPECT_EQ(count, list->count); + EXPECT_EQ(list->count, count); return nullptr; } diff --git a/minidump/test/minidump_string_writer_test_util.cc b/minidump/test/minidump_string_writer_test_util.cc index d5c73543..2c07934f 100644 --- a/minidump/test/minidump_string_writer_test_util.cc +++ b/minidump/test/minidump_string_writer_test_util.cc @@ -36,7 +36,7 @@ const T* TMinidumpStringAtRVA(const std::string& file_contents, RVA rva) { // units. const size_t kCodeUnitSize = sizeof(string_base->Buffer[0]); if (string_base->Length % kCodeUnitSize != 0) { - EXPECT_EQ(0u, string_base->Length % kCodeUnitSize); + EXPECT_EQ(string_base->Length % kCodeUnitSize, 0u); return nullptr; } @@ -51,11 +51,11 @@ const T* TMinidumpStringAtRVA(const std::string& file_contents, RVA rva) { return nullptr; } - EXPECT_EQ(string_base, string); + EXPECT_EQ(string, string_base); // Require the NUL terminator to be NUL. if (string->Buffer[string->Length / kCodeUnitSize] != '\0') { - EXPECT_EQ('\0', string->Buffer[string->Length / kCodeUnitSize]); + EXPECT_EQ(string->Buffer[string->Length / kCodeUnitSize], '\0'); return nullptr; } diff --git a/minidump/test/minidump_user_extension_stream_util.cc b/minidump/test/minidump_user_extension_stream_util.cc new file mode 100644 index 00000000..50100822 --- /dev/null +++ b/minidump/test/minidump_user_extension_stream_util.cc @@ -0,0 +1,43 @@ +// Copyright 2017 The Crashpad Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "minidump/test/minidump_user_extension_stream_util.h" + +#include + +namespace crashpad { +namespace test { + +BufferExtensionStreamDataSource::BufferExtensionStreamDataSource( + uint32_t stream_type, + const void* data, + size_t data_size) + : MinidumpUserExtensionStreamDataSource(stream_type) { + data_.resize(data_size); + + if (data_size) + memcpy(data_.data(), data, data_size); +} + +size_t BufferExtensionStreamDataSource::StreamDataSize() { + return data_.size(); +} + +bool BufferExtensionStreamDataSource::ReadStreamData(Delegate* delegate) { + return delegate->ExtensionStreamDataSourceRead( + data_.size() ? data_.data() : nullptr, data_.size()); +} + +} // namespace test +} // namespace crashpad diff --git a/minidump/test/minidump_user_extension_stream_util.h b/minidump/test/minidump_user_extension_stream_util.h new file mode 100644 index 00000000..3a31b948 --- /dev/null +++ b/minidump/test/minidump_user_extension_stream_util.h @@ -0,0 +1,53 @@ +// Copyright 2017 The Crashpad Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef CRASHPAD_MINIDUMP_TEST_MINIDUMP_USER_EXTENSION_STREAM_UTIL_H_ +#define CRASHPAD_MINIDUMP_TEST_MINIDUMP_USER_EXTENSION_STREAM_UTIL_H_ + +#include "minidump/minidump_user_extension_stream_data_source.h" + +#include +#include + +#include + +namespace crashpad { +namespace test { + +//! \brief A user extension data source that wraps a buffer. +class BufferExtensionStreamDataSource final + : public MinidumpUserExtensionStreamDataSource { + public: + //! \brief Creates a data source with \a stream_type. + //! + //! param[in] stream_type The type of the stream. + //! param[in] data The data of the stream. + //! param[in] data_size The length of \a data. + BufferExtensionStreamDataSource(uint32_t stream_type, + const void* data, + size_t data_size); + + size_t StreamDataSize() override; + bool ReadStreamData(Delegate* delegate) override; + + private: + std::vector data_; + + DISALLOW_COPY_AND_ASSIGN(BufferExtensionStreamDataSource); +}; + +} // namespace test +} // namespace crashpad + +#endif // CRASHPAD_MINIDUMP_TEST_MINIDUMP_USER_EXTENSION_STREAM_UTIL_H_ diff --git a/minidump/test/minidump_writable_test_util.cc b/minidump/test/minidump_writable_test_util.cc index 49ff1720..1841243a 100644 --- a/minidump/test/minidump_writable_test_util.cc +++ b/minidump/test/minidump_writable_test_util.cc @@ -58,7 +58,7 @@ const void* MinidumpWritableAtLocationDescriptorInternal( size_t expected_size, bool allow_oversized_data) { if (location.DataSize == 0) { - EXPECT_EQ(0u, location.Rva); + EXPECT_EQ(location.Rva, 0u); return nullptr; } @@ -68,7 +68,7 @@ const void* MinidumpWritableAtLocationDescriptorInternal( return nullptr; } } else if (location.DataSize != expected_size) { - EXPECT_EQ(expected_size, location.DataSize); + EXPECT_EQ(location.DataSize, expected_size); return nullptr; } @@ -95,25 +95,25 @@ const IMAGE_DEBUG_MISC* MinidumpWritableAtLocationDescriptor( } if (misc->DataType != IMAGE_DEBUG_MISC_EXENAME) { - EXPECT_EQ(implicit_cast(IMAGE_DEBUG_MISC_EXENAME), - misc->DataType); + EXPECT_EQ(misc->DataType, + implicit_cast(IMAGE_DEBUG_MISC_EXENAME)); return nullptr; } if (misc->Length != location.DataSize) { - EXPECT_EQ(location.DataSize, misc->Length); + EXPECT_EQ(misc->Length, location.DataSize); return nullptr; } if (misc->Unicode == 0) { size_t string_length = misc->Length - offsetof(IMAGE_DEBUG_MISC, Data) - 1; if (misc->Data[string_length] != '\0') { - EXPECT_EQ('\0', misc->Data[string_length]); + EXPECT_EQ(misc->Data[string_length], '\0'); return nullptr; } } else if (misc->Unicode == 1) { if (misc->Length % sizeof(base::char16) != 0) { - EXPECT_EQ(0u, misc->Length % sizeof(base::char16)); + EXPECT_EQ(misc->Length % sizeof(base::char16), 0u); return nullptr; } @@ -123,7 +123,7 @@ const IMAGE_DEBUG_MISC* MinidumpWritableAtLocationDescriptor( const base::char16* data16 = reinterpret_cast(misc->Data); if (data16[string_length] != '\0') { - EXPECT_EQ('\0', data16[string_length]); + EXPECT_EQ(data16[string_length], '\0'); return nullptr; } } else { @@ -146,11 +146,11 @@ const MINIDUMP_HEADER* MinidumpWritableAtLocationDescriptor( } if (header->Signature != MINIDUMP_SIGNATURE) { - EXPECT_EQ(implicit_cast(MINIDUMP_SIGNATURE), header->Signature); + EXPECT_EQ(header->Signature, implicit_cast(MINIDUMP_SIGNATURE)); return nullptr; } if (header->Version != MINIDUMP_VERSION) { - EXPECT_EQ(implicit_cast(MINIDUMP_VERSION), header->Version); + EXPECT_EQ(header->Version, implicit_cast(MINIDUMP_VERSION)); return nullptr; } @@ -237,7 +237,7 @@ const typename T::ListType* MinidumpListAtLocationDescriptor( size_t expected_size = sizeof(typename T::ListType) + T::ElementCount(list) * T::kElementSize; if (location.DataSize != expected_size) { - EXPECT_EQ(expected_size, location.DataSize); + EXPECT_EQ(location.DataSize, expected_size); return nullptr; } @@ -326,13 +326,13 @@ const T* MinidumpCVPDBAtLocationDescriptor( } if (cv_pdb->signature != T::kSignature) { - EXPECT_EQ(T::kSignature, cv_pdb->signature); + EXPECT_EQ(cv_pdb->signature, T::kSignature); return nullptr; } size_t string_length = location.DataSize - offsetof(T, pdb_name) - 1; if (cv_pdb->pdb_name[string_length] != '\0') { - EXPECT_EQ('\0', cv_pdb->pdb_name[string_length]); + EXPECT_EQ(cv_pdb->pdb_name[string_length], '\0'); return nullptr; } diff --git a/snapshot/api/module_annotations_win_test.cc b/snapshot/api/module_annotations_win_test.cc index ee028683..ecfa4659 100644 --- a/snapshot/api/module_annotations_win_test.cc +++ b/snapshot/api/module_annotations_win_test.cc @@ -42,9 +42,9 @@ class ModuleAnnotationsMultiprocessTest final : public WinMultiprocess { ASSERT_TRUE(ReadModuleAnnotations(process_handle, module, &annotations)); EXPECT_GE(annotations.size(), 3u); - EXPECT_EQ("value", annotations["#APITEST# key"]); - EXPECT_EQ("y", annotations["#APITEST# x"]); - EXPECT_EQ("", annotations["#APITEST# empty_value"]); + EXPECT_EQ(annotations["#APITEST# key"], "value"); + EXPECT_EQ(annotations["#APITEST# x"], "y"); + EXPECT_EQ(annotations["#APITEST# empty_value"], ""); // Signal the child process to terminate. char c = ' '; diff --git a/snapshot/cpu_context_test.cc b/snapshot/cpu_context_test.cc index 6b94871b..706f2fe5 100644 --- a/snapshot/cpu_context_test.cc +++ b/snapshot/cpu_context_test.cc @@ -136,22 +136,22 @@ TEST(CPUContextX86, FxsaveToFsave) { // Everything should have come over from fxsave. Reserved fields should be // zero. - EXPECT_EQ(fxsave.fcw, fsave.fcw); - EXPECT_EQ(0, fsave.reserved_1); - EXPECT_EQ(fxsave.fsw, fsave.fsw); - EXPECT_EQ(0, fsave.reserved_2); - EXPECT_EQ(0xfe90, fsave.ftw); // FxsaveToFsaveTagWord - EXPECT_EQ(0, fsave.reserved_3); - EXPECT_EQ(fxsave.fpu_ip, fsave.fpu_ip); - EXPECT_EQ(fxsave.fpu_cs, fsave.fpu_cs); - EXPECT_EQ(fxsave.fop, fsave.fop); - EXPECT_EQ(fxsave.fpu_dp, fsave.fpu_dp); - EXPECT_EQ(fxsave.fpu_ds, fsave.fpu_ds); - EXPECT_EQ(0, fsave.reserved_4); + EXPECT_EQ(fsave.fcw, fxsave.fcw); + EXPECT_EQ(fsave.reserved_1, 0); + EXPECT_EQ(fsave.fsw, fxsave.fsw); + EXPECT_EQ(fsave.reserved_2, 0); + EXPECT_EQ(fsave.ftw, 0xfe90); // FxsaveToFsaveTagWord + EXPECT_EQ(fsave.reserved_3, 0); + EXPECT_EQ(fsave.fpu_ip, fxsave.fpu_ip); + EXPECT_EQ(fsave.fpu_cs, fxsave.fpu_cs); + EXPECT_EQ(fsave.fop, fxsave.fop); + EXPECT_EQ(fsave.fpu_dp, fxsave.fpu_dp); + EXPECT_EQ(fsave.fpu_ds, fxsave.fpu_ds); + EXPECT_EQ(fsave.reserved_4, 0); for (size_t index = 0; index < arraysize(fsave.st); ++index) { - EXPECT_EQ(BytesToHexString(fxsave.st_mm[index].st, - arraysize(fxsave.st_mm[index].st)), - BytesToHexString(fsave.st[index], arraysize(fsave.st[index]))) + EXPECT_EQ(BytesToHexString(fsave.st[index], arraysize(fsave.st[index])), + BytesToHexString(fxsave.st_mm[index].st, + arraysize(fxsave.st_mm[index].st))) << "index " << index; } } @@ -191,32 +191,32 @@ TEST(CPUContextX86, FsaveToFxsave) { // Everything in fsave should have come over from there. Fields not present in // fsave and reserved fields should be zero. - EXPECT_EQ(fsave.fcw, fxsave.fcw); - EXPECT_EQ(fsave.fsw, fxsave.fsw); - EXPECT_EQ(0xf0, fxsave.ftw); // FsaveToFxsaveTagWord - EXPECT_EQ(0, fxsave.reserved_1); - EXPECT_EQ(fsave.fop, fxsave.fop); - EXPECT_EQ(fsave.fpu_ip, fxsave.fpu_ip); - EXPECT_EQ(fsave.fpu_cs, fxsave.fpu_cs); - EXPECT_EQ(0, fxsave.reserved_2); - EXPECT_EQ(fsave.fpu_dp, fxsave.fpu_dp); - EXPECT_EQ(fsave.fpu_ds, fxsave.fpu_ds); - EXPECT_EQ(0, fxsave.reserved_3); - EXPECT_EQ(0u, fxsave.mxcsr); - EXPECT_EQ(0u, fxsave.mxcsr_mask); + EXPECT_EQ(fxsave.fcw, fsave.fcw); + EXPECT_EQ(fxsave.fsw, fsave.fsw); + EXPECT_EQ(fxsave.ftw, 0xf0); // FsaveToFxsaveTagWord + EXPECT_EQ(fxsave.reserved_1, 0); + EXPECT_EQ(fxsave.fop, fsave.fop); + EXPECT_EQ(fxsave.fpu_ip, fsave.fpu_ip); + EXPECT_EQ(fxsave.fpu_cs, fsave.fpu_cs); + EXPECT_EQ(fxsave.reserved_2, 0); + EXPECT_EQ(fxsave.fpu_dp, fsave.fpu_dp); + EXPECT_EQ(fxsave.fpu_ds, fsave.fpu_ds); + EXPECT_EQ(fxsave.reserved_3, 0); + EXPECT_EQ(fxsave.mxcsr, 0u); + EXPECT_EQ(fxsave.mxcsr_mask, 0u); for (size_t index = 0; index < arraysize(fxsave.st_mm); ++index) { - EXPECT_EQ(BytesToHexString(fsave.st[index], arraysize(fsave.st[index])), - BytesToHexString(fxsave.st_mm[index].st, - arraysize(fxsave.st_mm[index].st))) + EXPECT_EQ(BytesToHexString(fxsave.st_mm[index].st, + arraysize(fxsave.st_mm[index].st)), + BytesToHexString(fsave.st[index], arraysize(fsave.st[index]))) << "index " << index; - EXPECT_EQ(std::string(arraysize(fxsave.st_mm[index].st_reserved) * 2, '0'), - BytesToHexString(fxsave.st_mm[index].st_reserved, - arraysize(fxsave.st_mm[index].st_reserved))) + EXPECT_EQ(BytesToHexString(fxsave.st_mm[index].st_reserved, + arraysize(fxsave.st_mm[index].st_reserved)), + std::string(arraysize(fxsave.st_mm[index].st_reserved) * 2, '0')) << "index " << index; } size_t unused_len = sizeof(fxsave) - offsetof(decltype(fxsave), xmm); - EXPECT_EQ(std::string(unused_len * 2, '0'), - BytesToHexString(fxsave.xmm, unused_len)); + EXPECT_EQ(BytesToHexString(fxsave.xmm, unused_len), + std::string(unused_len * 2, '0')); // Since the fsave format is a subset of the fxsave format, fsave-fxsave-fsave // should round-trip cleanly. @@ -229,7 +229,7 @@ TEST(CPUContextX86, FsaveToFxsave) { fsave.reserved_2 = 0; fsave.reserved_3 = 0; fsave.reserved_4 = 0; - EXPECT_EQ(0, memcmp(&fsave, &fsave_2, sizeof(fsave))); + EXPECT_EQ(memcmp(&fsave, &fsave_2, sizeof(fsave)), 0); } TEST(CPUContextX86, FxsaveToFsaveTagWord) { @@ -258,8 +258,8 @@ TEST(CPUContextX86, FxsaveToFsaveTagWord) { SetX87OrMMXRegister(&st_mm[5], kExponentNormal, true, kFractionNormal); SetX87OrMMXRegister(&st_mm[6], kExponentNormal, false, kFractionAllZero); SetX87OrMMXRegister(&st_mm[7], kExponentNormal, true, kFractionAllZero); - EXPECT_EQ(0xff22, - CPUContextX86::FxsaveToFsaveTagWord(fsw, fxsave_tag, st_mm)); + EXPECT_EQ(CPUContextX86::FxsaveToFsaveTagWord(fsw, fxsave_tag, st_mm), + 0xff22); fsw = 2 << 11; // top = 2: logical 0-7 maps to physical 2-7, 0-1 fxsave_tag = 0xf0; // physical 0-3 (logical 6-7, 0-1) empty @@ -275,8 +275,8 @@ TEST(CPUContextX86, FxsaveToFsaveTagWord) { &st_mm[5], kExponentAllZero, true, kFractionNormal); // spec. SetX87OrMMXRegister(&st_mm[6], kExponentAllZero, false, kFractionAllZero); SetX87OrMMXRegister(&st_mm[7], kExponentAllZero, true, kFractionAllZero); - EXPECT_EQ(0xa9ff, - CPUContextX86::FxsaveToFsaveTagWord(fsw, fxsave_tag, st_mm)); + EXPECT_EQ(CPUContextX86::FxsaveToFsaveTagWord(fsw, fxsave_tag, st_mm), + 0xa9ff); fsw = 5 << 11; // top = 5: logical 0-7 maps to physical 5-7, 0-4 fxsave_tag = 0x5a; // physical 0, 2, 5, and 7 (logical 5, 0, 2, and 3) empty @@ -292,8 +292,8 @@ TEST(CPUContextX86, FxsaveToFsaveTagWord) { &st_mm[6], kExponentAllOne, false, kFractionAllZero); // spec. SetX87OrMMXRegister( &st_mm[7], kExponentAllOne, true, kFractionAllZero); // spec. - EXPECT_EQ(0xeebb, - CPUContextX86::FxsaveToFsaveTagWord(fsw, fxsave_tag, st_mm)); + EXPECT_EQ(CPUContextX86::FxsaveToFsaveTagWord(fsw, fxsave_tag, st_mm), + 0xeebb); // This set set is just a mix of all of the possible tag types in a single // register file. @@ -312,8 +312,8 @@ TEST(CPUContextX86, FxsaveToFsaveTagWord) { SetX87OrMMXRegister(&st_mm[6], kExponentAllZero, false, kFractionAllZero); SetX87OrMMXRegister( &st_mm[7], kExponentNormal, true, kFractionNormal); // valid - EXPECT_EQ(0xfe90, - CPUContextX86::FxsaveToFsaveTagWord(fsw, fxsave_tag, st_mm)); + EXPECT_EQ(CPUContextX86::FxsaveToFsaveTagWord(fsw, fxsave_tag, st_mm), + 0xfe90); // In this set, everything is valid. fsw = 0 << 11; // top = 0: logical 0-7 maps to physical 0-7 @@ -321,25 +321,25 @@ TEST(CPUContextX86, FxsaveToFsaveTagWord) { for (size_t index = 0; index < arraysize(st_mm); ++index) { SetX87OrMMXRegister(&st_mm[index], kExponentNormal, true, kFractionAllZero); } - EXPECT_EQ(0, CPUContextX86::FxsaveToFsaveTagWord(fsw, fxsave_tag, st_mm)); + EXPECT_EQ(CPUContextX86::FxsaveToFsaveTagWord(fsw, fxsave_tag, st_mm), 0); // In this set, everything is empty. The registers shouldn’t be consulted at // all, so they’re left alone from the previous set. fsw = 0 << 11; // top = 0: logical 0-7 maps to physical 0-7 fxsave_tag = 0; // everything empty - EXPECT_EQ(0xffff, - CPUContextX86::FxsaveToFsaveTagWord(fsw, fxsave_tag, st_mm)); + EXPECT_EQ(CPUContextX86::FxsaveToFsaveTagWord(fsw, fxsave_tag, st_mm), + 0xffff); } TEST(CPUContextX86, FsaveToFxsaveTagWord) { // The register sets that these x87 tag words might apply to are given in the // FxsaveToFsaveTagWord test above. - EXPECT_EQ(0x0f, CPUContextX86::FsaveToFxsaveTagWord(0xff22)); - EXPECT_EQ(0xf0, CPUContextX86::FsaveToFxsaveTagWord(0xa9ff)); - EXPECT_EQ(0x5a, CPUContextX86::FsaveToFxsaveTagWord(0xeebb)); - EXPECT_EQ(0x1f, CPUContextX86::FsaveToFxsaveTagWord(0xfe90)); - EXPECT_EQ(0xff, CPUContextX86::FsaveToFxsaveTagWord(0x0000)); - EXPECT_EQ(0x00, CPUContextX86::FsaveToFxsaveTagWord(0xffff)); + EXPECT_EQ(CPUContextX86::FsaveToFxsaveTagWord(0xff22), 0x0f); + EXPECT_EQ(CPUContextX86::FsaveToFxsaveTagWord(0xa9ff), 0xf0); + EXPECT_EQ(CPUContextX86::FsaveToFxsaveTagWord(0xeebb), 0x5a); + EXPECT_EQ(CPUContextX86::FsaveToFxsaveTagWord(0xfe90), 0x1f); + EXPECT_EQ(CPUContextX86::FsaveToFxsaveTagWord(0x0000), 0xff); + EXPECT_EQ(CPUContextX86::FsaveToFxsaveTagWord(0xffff), 0x00); } } // namespace diff --git a/snapshot/crashpad_info_client_options_test.cc b/snapshot/crashpad_info_client_options_test.cc index af607c32..53d4f62e 100644 --- a/snapshot/crashpad_info_client_options_test.cc +++ b/snapshot/crashpad_info_client_options_test.cc @@ -21,7 +21,7 @@ #include "client/crashpad_info.h" #include "gtest/gtest.h" #include "test/errors.h" -#include "test/paths.h" +#include "test/test_paths.h" #if defined(OS_MACOSX) #include @@ -36,20 +36,20 @@ namespace test { namespace { TEST(CrashpadInfoClientOptions, TriStateFromCrashpadInfo) { - EXPECT_EQ(TriState::kUnset, - CrashpadInfoClientOptions::TriStateFromCrashpadInfo(0)); - EXPECT_EQ(TriState::kEnabled, - CrashpadInfoClientOptions::TriStateFromCrashpadInfo(1)); - EXPECT_EQ(TriState::kDisabled, - CrashpadInfoClientOptions::TriStateFromCrashpadInfo(2)); + EXPECT_EQ(CrashpadInfoClientOptions::TriStateFromCrashpadInfo(0), + TriState::kUnset); + EXPECT_EQ(CrashpadInfoClientOptions::TriStateFromCrashpadInfo(1), + TriState::kEnabled); + EXPECT_EQ(CrashpadInfoClientOptions::TriStateFromCrashpadInfo(2), + TriState::kDisabled); // These will produce log messages but should result in kUnset being returned. - EXPECT_EQ(TriState::kUnset, - CrashpadInfoClientOptions::TriStateFromCrashpadInfo(3)); - EXPECT_EQ(TriState::kUnset, - CrashpadInfoClientOptions::TriStateFromCrashpadInfo(4)); - EXPECT_EQ(TriState::kUnset, - CrashpadInfoClientOptions::TriStateFromCrashpadInfo(0xff)); + EXPECT_EQ(CrashpadInfoClientOptions::TriStateFromCrashpadInfo(3), + TriState::kUnset); + EXPECT_EQ(CrashpadInfoClientOptions::TriStateFromCrashpadInfo(4), + TriState::kUnset); + EXPECT_EQ(CrashpadInfoClientOptions::TriStateFromCrashpadInfo(0xff), + TriState::kUnset); } class ScopedUnsetCrashpadInfoOptions { @@ -92,10 +92,10 @@ TEST(CrashpadInfoClientOptions, OneModule) { // Make sure that the initial state has all values unset. auto options = SelfProcessSnapshotAndGetCrashpadOptions(); - EXPECT_EQ(TriState::kUnset, options.crashpad_handler_behavior); - EXPECT_EQ(TriState::kUnset, options.system_crash_reporter_forwarding); - EXPECT_EQ(TriState::kUnset, options.gather_indirectly_referenced_memory); - EXPECT_EQ(0u, options.indirectly_referenced_memory_cap); + EXPECT_EQ(options.crashpad_handler_behavior, TriState::kUnset); + EXPECT_EQ(options.system_crash_reporter_forwarding, TriState::kUnset); + EXPECT_EQ(options.gather_indirectly_referenced_memory, TriState::kUnset); + EXPECT_EQ(options.indirectly_referenced_memory_cap, 0u); CrashpadInfo* crashpad_info = CrashpadInfo::GetCrashpadInfo(); ASSERT_TRUE(crashpad_info); @@ -106,10 +106,10 @@ TEST(CrashpadInfoClientOptions, OneModule) { crashpad_info->set_crashpad_handler_behavior(TriState::kEnabled); options = SelfProcessSnapshotAndGetCrashpadOptions(); - EXPECT_EQ(TriState::kEnabled, options.crashpad_handler_behavior); - EXPECT_EQ(TriState::kUnset, options.system_crash_reporter_forwarding); - EXPECT_EQ(TriState::kUnset, options.gather_indirectly_referenced_memory); - EXPECT_EQ(0u, options.indirectly_referenced_memory_cap); + EXPECT_EQ(options.crashpad_handler_behavior, TriState::kEnabled); + EXPECT_EQ(options.system_crash_reporter_forwarding, TriState::kUnset); + EXPECT_EQ(options.gather_indirectly_referenced_memory, TriState::kUnset); + EXPECT_EQ(options.indirectly_referenced_memory_cap, 0u); } { @@ -118,10 +118,10 @@ TEST(CrashpadInfoClientOptions, OneModule) { crashpad_info->set_system_crash_reporter_forwarding(TriState::kDisabled); options = SelfProcessSnapshotAndGetCrashpadOptions(); - EXPECT_EQ(TriState::kUnset, options.crashpad_handler_behavior); - EXPECT_EQ(TriState::kDisabled, options.system_crash_reporter_forwarding); - EXPECT_EQ(TriState::kUnset, options.gather_indirectly_referenced_memory); - EXPECT_EQ(0u, options.indirectly_referenced_memory_cap); + EXPECT_EQ(options.crashpad_handler_behavior, TriState::kUnset); + EXPECT_EQ(options.system_crash_reporter_forwarding, TriState::kDisabled); + EXPECT_EQ(options.gather_indirectly_referenced_memory, TriState::kUnset); + EXPECT_EQ(options.indirectly_referenced_memory_cap, 0u); } { @@ -131,10 +131,10 @@ TEST(CrashpadInfoClientOptions, OneModule) { 1234); options = SelfProcessSnapshotAndGetCrashpadOptions(); - EXPECT_EQ(TriState::kUnset, options.crashpad_handler_behavior); - EXPECT_EQ(TriState::kUnset, options.system_crash_reporter_forwarding); - EXPECT_EQ(TriState::kEnabled, options.gather_indirectly_referenced_memory); - EXPECT_EQ(1234u, options.indirectly_referenced_memory_cap); + EXPECT_EQ(options.crashpad_handler_behavior, TriState::kUnset); + EXPECT_EQ(options.system_crash_reporter_forwarding, TriState::kUnset); + EXPECT_EQ(options.gather_indirectly_referenced_memory, TriState::kEnabled); + EXPECT_EQ(options.indirectly_referenced_memory_cap, 1234u); } } @@ -187,7 +187,7 @@ TEST(CrashpadInfoClientOptions, TwoModules) { #elif defined(OS_WIN) const base::FilePath::StringType kDlExtension = FILE_PATH_LITERAL(".dll"); #endif - base::FilePath module_path = Paths::Executable().DirName().Append( + base::FilePath module_path = TestPaths::Executable().DirName().Append( FILE_PATH_LITERAL("crashpad_snapshot_test_module") + kDlExtension); #if defined(OS_MACOSX) ScopedDlHandle dl_handle( @@ -213,9 +213,9 @@ TEST(CrashpadInfoClientOptions, TwoModules) { auto options = SelfProcessSnapshotAndGetCrashpadOptions(); // Make sure that the initial state has all values unset. - EXPECT_EQ(TriState::kUnset, options.crashpad_handler_behavior); - EXPECT_EQ(TriState::kUnset, options.system_crash_reporter_forwarding); - EXPECT_EQ(TriState::kUnset, options.gather_indirectly_referenced_memory); + EXPECT_EQ(options.crashpad_handler_behavior, TriState::kUnset); + EXPECT_EQ(options.system_crash_reporter_forwarding, TriState::kUnset); + EXPECT_EQ(options.gather_indirectly_referenced_memory, TriState::kUnset); // Get both CrashpadInfo structures. CrashpadInfo* local_crashpad_info = CrashpadInfo::GetCrashpadInfo(); @@ -232,9 +232,9 @@ TEST(CrashpadInfoClientOptions, TwoModules) { remote_crashpad_info->set_crashpad_handler_behavior(TriState::kEnabled); options = SelfProcessSnapshotAndGetCrashpadOptions(); - EXPECT_EQ(TriState::kEnabled, options.crashpad_handler_behavior); - EXPECT_EQ(TriState::kUnset, options.system_crash_reporter_forwarding); - EXPECT_EQ(TriState::kUnset, options.gather_indirectly_referenced_memory); + EXPECT_EQ(options.crashpad_handler_behavior, TriState::kEnabled); + EXPECT_EQ(options.system_crash_reporter_forwarding, TriState::kUnset); + EXPECT_EQ(options.gather_indirectly_referenced_memory, TriState::kUnset); // When more than one module sets a value, the first one in the module list // applies to the process. The local module should appear before the remote @@ -242,9 +242,9 @@ TEST(CrashpadInfoClientOptions, TwoModules) { local_crashpad_info->set_crashpad_handler_behavior(TriState::kDisabled); options = SelfProcessSnapshotAndGetCrashpadOptions(); - EXPECT_EQ(TriState::kDisabled, options.crashpad_handler_behavior); - EXPECT_EQ(TriState::kUnset, options.system_crash_reporter_forwarding); - EXPECT_EQ(TriState::kUnset, options.gather_indirectly_referenced_memory); + EXPECT_EQ(options.crashpad_handler_behavior, TriState::kDisabled); + EXPECT_EQ(options.system_crash_reporter_forwarding, TriState::kUnset); + EXPECT_EQ(options.gather_indirectly_referenced_memory, TriState::kUnset); } { @@ -256,9 +256,9 @@ TEST(CrashpadInfoClientOptions, TwoModules) { TriState::kDisabled); options = SelfProcessSnapshotAndGetCrashpadOptions(); - EXPECT_EQ(TriState::kUnset, options.crashpad_handler_behavior); - EXPECT_EQ(TriState::kDisabled, options.system_crash_reporter_forwarding); - EXPECT_EQ(TriState::kUnset, options.gather_indirectly_referenced_memory); + EXPECT_EQ(options.crashpad_handler_behavior, TriState::kUnset); + EXPECT_EQ(options.system_crash_reporter_forwarding, TriState::kDisabled); + EXPECT_EQ(options.gather_indirectly_referenced_memory, TriState::kUnset); // When more than one module sets a value, the first one in the module list // applies to the process. The local module should appear before the remote @@ -267,9 +267,9 @@ TEST(CrashpadInfoClientOptions, TwoModules) { TriState::kEnabled); options = SelfProcessSnapshotAndGetCrashpadOptions(); - EXPECT_EQ(TriState::kUnset, options.crashpad_handler_behavior); - EXPECT_EQ(TriState::kEnabled, options.system_crash_reporter_forwarding); - EXPECT_EQ(TriState::kUnset, options.gather_indirectly_referenced_memory); + EXPECT_EQ(options.crashpad_handler_behavior, TriState::kUnset); + EXPECT_EQ(options.system_crash_reporter_forwarding, TriState::kEnabled); + EXPECT_EQ(options.gather_indirectly_referenced_memory, TriState::kUnset); } } diff --git a/snapshot/mac/cpu_context_mac_test.cc b/snapshot/mac/cpu_context_mac_test.cc index 844c9f6e..c7156da1 100644 --- a/snapshot/mac/cpu_context_mac_test.cc +++ b/snapshot/mac/cpu_context_mac_test.cc @@ -43,9 +43,9 @@ TEST(CPUContextMac, InitializeContextX86) { &x86_thread_state32, &x86_float_state32, &x86_debug_state32); - EXPECT_EQ(1u, cpu_context_x86.eax); - EXPECT_EQ(2u, cpu_context_x86.fxsave.ftw); - EXPECT_EQ(3u, cpu_context_x86.dr0); + EXPECT_EQ(cpu_context_x86.eax, 1u); + EXPECT_EQ(cpu_context_x86.fxsave.ftw, 2u); + EXPECT_EQ(cpu_context_x86.dr0, 3u); } // Supply context in a CPU-specific “flavor” parameter expected to be used @@ -69,9 +69,9 @@ TEST(CPUContextMac, InitializeContextX86) { &x86_thread_state32, &x86_float_state32, &x86_debug_state32); - EXPECT_EQ(4u, cpu_context_x86.eax); - EXPECT_EQ(2u, cpu_context_x86.fxsave.ftw); - EXPECT_EQ(3u, cpu_context_x86.dr0); + EXPECT_EQ(cpu_context_x86.eax, 4u); + EXPECT_EQ(cpu_context_x86.fxsave.ftw, 2u); + EXPECT_EQ(cpu_context_x86.dr0, 3u); } { @@ -87,9 +87,9 @@ TEST(CPUContextMac, InitializeContextX86) { &x86_thread_state32, &x86_float_state32, &x86_debug_state32); - EXPECT_EQ(1u, cpu_context_x86.eax); - EXPECT_EQ(5u, cpu_context_x86.fxsave.ftw); - EXPECT_EQ(3u, cpu_context_x86.dr0); + EXPECT_EQ(cpu_context_x86.eax, 1u); + EXPECT_EQ(cpu_context_x86.fxsave.ftw, 5u); + EXPECT_EQ(cpu_context_x86.dr0, 3u); } { @@ -105,9 +105,9 @@ TEST(CPUContextMac, InitializeContextX86) { &x86_thread_state32, &x86_float_state32, &x86_debug_state32); - EXPECT_EQ(1u, cpu_context_x86.eax); - EXPECT_EQ(2u, cpu_context_x86.fxsave.ftw); - EXPECT_EQ(6u, cpu_context_x86.dr0); + EXPECT_EQ(cpu_context_x86.eax, 1u); + EXPECT_EQ(cpu_context_x86.fxsave.ftw, 2u); + EXPECT_EQ(cpu_context_x86.dr0, 6u); } // Supply context in a universal “flavor” parameter expected to be used @@ -132,9 +132,9 @@ TEST(CPUContextMac, InitializeContextX86) { &x86_thread_state32, &x86_float_state32, &x86_debug_state32); - EXPECT_EQ(7u, cpu_context_x86.eax); - EXPECT_EQ(2u, cpu_context_x86.fxsave.ftw); - EXPECT_EQ(3u, cpu_context_x86.dr0); + EXPECT_EQ(cpu_context_x86.eax, 7u); + EXPECT_EQ(cpu_context_x86.fxsave.ftw, 2u); + EXPECT_EQ(cpu_context_x86.dr0, 3u); } { @@ -152,9 +152,9 @@ TEST(CPUContextMac, InitializeContextX86) { &x86_thread_state32, &x86_float_state32, &x86_debug_state32); - EXPECT_EQ(1u, cpu_context_x86.eax); - EXPECT_EQ(8u, cpu_context_x86.fxsave.ftw); - EXPECT_EQ(3u, cpu_context_x86.dr0); + EXPECT_EQ(cpu_context_x86.eax, 1u); + EXPECT_EQ(cpu_context_x86.fxsave.ftw, 8u); + EXPECT_EQ(cpu_context_x86.dr0, 3u); } { @@ -172,9 +172,9 @@ TEST(CPUContextMac, InitializeContextX86) { &x86_thread_state32, &x86_float_state32, &x86_debug_state32); - EXPECT_EQ(1u, cpu_context_x86.eax); - EXPECT_EQ(2u, cpu_context_x86.fxsave.ftw); - EXPECT_EQ(9u, cpu_context_x86.dr0); + EXPECT_EQ(cpu_context_x86.eax, 1u); + EXPECT_EQ(cpu_context_x86.fxsave.ftw, 2u); + EXPECT_EQ(cpu_context_x86.dr0, 9u); } // Supply inappropriate “flavor” contexts to test that @@ -194,9 +194,9 @@ TEST(CPUContextMac, InitializeContextX86) { &x86_thread_state32, &x86_float_state32, &x86_debug_state32); - EXPECT_EQ(1u, cpu_context_x86.eax); - EXPECT_EQ(2u, cpu_context_x86.fxsave.ftw); - EXPECT_EQ(3u, cpu_context_x86.dr0); + EXPECT_EQ(cpu_context_x86.eax, 1u); + EXPECT_EQ(cpu_context_x86.fxsave.ftw, 2u); + EXPECT_EQ(cpu_context_x86.dr0, 3u); } { @@ -213,9 +213,9 @@ TEST(CPUContextMac, InitializeContextX86) { &x86_thread_state32, &x86_float_state32, &x86_debug_state32); - EXPECT_EQ(1u, cpu_context_x86.eax); - EXPECT_EQ(2u, cpu_context_x86.fxsave.ftw); - EXPECT_EQ(3u, cpu_context_x86.dr0); + EXPECT_EQ(cpu_context_x86.eax, 1u); + EXPECT_EQ(cpu_context_x86.fxsave.ftw, 2u); + EXPECT_EQ(cpu_context_x86.dr0, 3u); } } @@ -238,9 +238,9 @@ TEST(CPUContextMac, InitializeContextX86_64) { &x86_thread_state64, &x86_float_state64, &x86_debug_state64); - EXPECT_EQ(10u, cpu_context_x86_64.rax); - EXPECT_EQ(11u, cpu_context_x86_64.fxsave.ftw); - EXPECT_EQ(12u, cpu_context_x86_64.dr0); + EXPECT_EQ(cpu_context_x86_64.rax, 10u); + EXPECT_EQ(cpu_context_x86_64.fxsave.ftw, 11u); + EXPECT_EQ(cpu_context_x86_64.dr0, 12u); } // Supply context in a CPU-specific “flavor” parameter expected to be used @@ -264,9 +264,9 @@ TEST(CPUContextMac, InitializeContextX86_64) { &x86_thread_state64, &x86_float_state64, &x86_debug_state64); - EXPECT_EQ(13u, cpu_context_x86_64.rax); - EXPECT_EQ(11u, cpu_context_x86_64.fxsave.ftw); - EXPECT_EQ(12u, cpu_context_x86_64.dr0); + EXPECT_EQ(cpu_context_x86_64.rax, 13u); + EXPECT_EQ(cpu_context_x86_64.fxsave.ftw, 11u); + EXPECT_EQ(cpu_context_x86_64.dr0, 12u); } { @@ -282,9 +282,9 @@ TEST(CPUContextMac, InitializeContextX86_64) { &x86_thread_state64, &x86_float_state64, &x86_debug_state64); - EXPECT_EQ(10u, cpu_context_x86_64.rax); - EXPECT_EQ(14u, cpu_context_x86_64.fxsave.ftw); - EXPECT_EQ(12u, cpu_context_x86_64.dr0); + EXPECT_EQ(cpu_context_x86_64.rax, 10u); + EXPECT_EQ(cpu_context_x86_64.fxsave.ftw, 14u); + EXPECT_EQ(cpu_context_x86_64.dr0, 12u); } { @@ -300,9 +300,9 @@ TEST(CPUContextMac, InitializeContextX86_64) { &x86_thread_state64, &x86_float_state64, &x86_debug_state64); - EXPECT_EQ(10u, cpu_context_x86_64.rax); - EXPECT_EQ(11u, cpu_context_x86_64.fxsave.ftw); - EXPECT_EQ(15u, cpu_context_x86_64.dr0); + EXPECT_EQ(cpu_context_x86_64.rax, 10u); + EXPECT_EQ(cpu_context_x86_64.fxsave.ftw, 11u); + EXPECT_EQ(cpu_context_x86_64.dr0, 15u); } // Supply context in a universal “flavor” parameter expected to be used @@ -327,9 +327,9 @@ TEST(CPUContextMac, InitializeContextX86_64) { &x86_thread_state64, &x86_float_state64, &x86_debug_state64); - EXPECT_EQ(16u, cpu_context_x86_64.rax); - EXPECT_EQ(11u, cpu_context_x86_64.fxsave.ftw); - EXPECT_EQ(12u, cpu_context_x86_64.dr0); + EXPECT_EQ(cpu_context_x86_64.rax, 16u); + EXPECT_EQ(cpu_context_x86_64.fxsave.ftw, 11u); + EXPECT_EQ(cpu_context_x86_64.dr0, 12u); } { @@ -347,9 +347,9 @@ TEST(CPUContextMac, InitializeContextX86_64) { &x86_thread_state64, &x86_float_state64, &x86_debug_state64); - EXPECT_EQ(10u, cpu_context_x86_64.rax); - EXPECT_EQ(17u, cpu_context_x86_64.fxsave.ftw); - EXPECT_EQ(12u, cpu_context_x86_64.dr0); + EXPECT_EQ(cpu_context_x86_64.rax, 10u); + EXPECT_EQ(cpu_context_x86_64.fxsave.ftw, 17u); + EXPECT_EQ(cpu_context_x86_64.dr0, 12u); } { @@ -367,9 +367,9 @@ TEST(CPUContextMac, InitializeContextX86_64) { &x86_thread_state64, &x86_float_state64, &x86_debug_state64); - EXPECT_EQ(10u, cpu_context_x86_64.rax); - EXPECT_EQ(11u, cpu_context_x86_64.fxsave.ftw); - EXPECT_EQ(18u, cpu_context_x86_64.dr0); + EXPECT_EQ(cpu_context_x86_64.rax, 10u); + EXPECT_EQ(cpu_context_x86_64.fxsave.ftw, 11u); + EXPECT_EQ(cpu_context_x86_64.dr0, 18u); } // Supply inappropriate “flavor” contexts to test that @@ -389,9 +389,9 @@ TEST(CPUContextMac, InitializeContextX86_64) { &x86_thread_state64, &x86_float_state64, &x86_debug_state64); - EXPECT_EQ(10u, cpu_context_x86_64.rax); - EXPECT_EQ(11u, cpu_context_x86_64.fxsave.ftw); - EXPECT_EQ(12u, cpu_context_x86_64.dr0); + EXPECT_EQ(cpu_context_x86_64.rax, 10u); + EXPECT_EQ(cpu_context_x86_64.fxsave.ftw, 11u); + EXPECT_EQ(cpu_context_x86_64.dr0, 12u); } { @@ -408,9 +408,9 @@ TEST(CPUContextMac, InitializeContextX86_64) { &x86_thread_state64, &x86_float_state64, &x86_debug_state64); - EXPECT_EQ(10u, cpu_context_x86_64.rax); - EXPECT_EQ(11u, cpu_context_x86_64.fxsave.ftw); - EXPECT_EQ(12u, cpu_context_x86_64.dr0); + EXPECT_EQ(cpu_context_x86_64.rax, 10u); + EXPECT_EQ(cpu_context_x86_64.fxsave.ftw, 11u); + EXPECT_EQ(cpu_context_x86_64.dr0, 12u); } } diff --git a/snapshot/mac/mach_o_image_annotations_reader_test.cc b/snapshot/mac/mach_o_image_annotations_reader_test.cc index 50e646ae..c73eebbf 100644 --- a/snapshot/mac/mach_o_image_annotations_reader_test.cc +++ b/snapshot/mac/mach_o_image_annotations_reader_test.cc @@ -35,7 +35,7 @@ #include "test/errors.h" #include "test/mac/mach_errors.h" #include "test/mac/mach_multiprocess.h" -#include "test/paths.h" +#include "test/test_paths.h" #include "util/file/file_io.h" #include "util/mac/mac_util.h" #include "util/mach/exc_server_variants.h" @@ -50,12 +50,12 @@ namespace { // \return The path to crashpad_snapshot_test_module_crashy_initializer.so std::string ModuleWithCrashyInitializer() { - return Paths::Executable().value() + "_module_crashy_initializer.so"; + return TestPaths::Executable().value() + "_module_crashy_initializer.so"; } //! \return The path to the crashpad_snapshot_test_no_op executable. base::FilePath NoOpExecutable() { - return base::FilePath(Paths::Executable().value() + "_no_op"); + return base::FilePath(TestPaths::Executable().value() + "_no_op"); } class TestMachOImageAnnotationsReader final @@ -121,14 +121,14 @@ class TestMachOImageAnnotationsReader final // In 10.12.1 and later, the task port will not match ChildTask() in the // kCrashDyld case, because kCrashDyld uses execl(), which results in a // new task port being assigned. - EXPECT_EQ(ChildTask(), task); + EXPECT_EQ(task, ChildTask()); } // The process ID should always compare favorably. pid_t task_pid; kern_return_t kr = pid_for_task(task, &task_pid); - EXPECT_EQ(KERN_SUCCESS, kr) << MachErrorMessage(kr, "pid_for_task"); - EXPECT_EQ(ChildPID(), task_pid); + EXPECT_EQ(kr, KERN_SUCCESS) << MachErrorMessage(kr, "pid_for_task"); + EXPECT_EQ(task_pid, ChildPID()); ProcessReader process_reader; bool rv = process_reader.Initialize(task); @@ -261,11 +261,11 @@ class TestMachOImageAnnotationsReader final } EXPECT_GE(all_annotations_simple_map.size(), 5u); - EXPECT_EQ("crash", all_annotations_simple_map["#TEST# pad"]); - EXPECT_EQ("value", all_annotations_simple_map["#TEST# key"]); - EXPECT_EQ("y", all_annotations_simple_map["#TEST# x"]); - EXPECT_EQ("shorter", all_annotations_simple_map["#TEST# longer"]); - EXPECT_EQ("", all_annotations_simple_map["#TEST# empty_value"]); + EXPECT_EQ(all_annotations_simple_map["#TEST# pad"], "crash"); + EXPECT_EQ(all_annotations_simple_map["#TEST# key"], "value"); + EXPECT_EQ(all_annotations_simple_map["#TEST# x"], "y"); + EXPECT_EQ(all_annotations_simple_map["#TEST# longer"], "shorter"); + EXPECT_EQ(all_annotations_simple_map["#TEST# empty_value"], ""); // Tell the child process that it’s permitted to crash. CheckedWriteFile(WritePipeHandle(), &c, sizeof(c)); @@ -282,7 +282,7 @@ class TestMachOImageAnnotationsReader final MachMessageServer::kOneShot, MachMessageServer::kReceiveLargeError, kMachMessageTimeoutWaitIndefinitely); - EXPECT_EQ(MACH_MSG_SUCCESS, mr) + EXPECT_EQ(mr, MACH_MSG_SUCCESS) << MachErrorMessage(mr, "MachMessageServer::Run"); switch (test_type_) { @@ -360,7 +360,7 @@ class TestMachOImageAnnotationsReader final // This should have crashed in the dlopen(). If dlopen() failed, the // ASSERT_NE() will show the message. If it succeeded without crashing, // the FAIL() will fail the test. - ASSERT_NE(nullptr, dl_handle) << dlerror(); + ASSERT_NE(dl_handle, nullptr) << dlerror(); FAIL(); break; } @@ -369,9 +369,9 @@ class TestMachOImageAnnotationsReader final // Set DYLD_INSERT_LIBRARIES to contain a library that does not exist. // Unable to load it, dyld will abort with a fatal error. ASSERT_EQ( - 0, setenv( - "DYLD_INSERT_LIBRARIES", "/var/empty/NoDirectory/NoLibrary", 1)) + "DYLD_INSERT_LIBRARIES", "/var/empty/NoDirectory/NoLibrary", 1), + 0) << ErrnoMessage("setenv"); // The actual executable doesn’t matter very much, because dyld won’t @@ -381,9 +381,10 @@ class TestMachOImageAnnotationsReader final // with system executables on OS X 10.11 due to System Integrity // Protection. base::FilePath no_op_executable = NoOpExecutable(); - ASSERT_EQ(0, execl(no_op_executable.value().c_str(), - no_op_executable.BaseName().value().c_str(), - nullptr)) + ASSERT_EQ(execl(no_op_executable.value().c_str(), + no_op_executable.BaseName().value().c_str(), + nullptr), + 0) << ErrnoMessage("execl"); break; } diff --git a/snapshot/mac/mach_o_image_reader_test.cc b/snapshot/mac/mach_o_image_reader_test.cc index b2e5fed3..cccf24fa 100644 --- a/snapshot/mac/mach_o_image_reader_test.cc +++ b/snapshot/mac/mach_o_image_reader_test.cc @@ -76,20 +76,20 @@ void ExpectSection(const Section* expect_section, ASSERT_TRUE(actual_section); EXPECT_EQ( - MachOImageSegmentReader::SectionNameString(expect_section->sectname), - MachOImageSegmentReader::SectionNameString(actual_section->sectname)); + MachOImageSegmentReader::SectionNameString(actual_section->sectname), + MachOImageSegmentReader::SectionNameString(expect_section->sectname)); EXPECT_EQ( - MachOImageSegmentReader::SegmentNameString(expect_section->segname), - MachOImageSegmentReader::SegmentNameString(actual_section->segname)); - EXPECT_EQ(expect_section->addr, actual_section->addr); - EXPECT_EQ(expect_section->size, actual_section->size); - EXPECT_EQ(expect_section->offset, actual_section->offset); - EXPECT_EQ(expect_section->align, actual_section->align); - EXPECT_EQ(expect_section->reloff, actual_section->reloff); - EXPECT_EQ(expect_section->nreloc, actual_section->nreloc); - EXPECT_EQ(expect_section->flags, actual_section->flags); - EXPECT_EQ(expect_section->reserved1, actual_section->reserved1); - EXPECT_EQ(expect_section->reserved2, actual_section->reserved2); + MachOImageSegmentReader::SegmentNameString(actual_section->segname), + MachOImageSegmentReader::SegmentNameString(expect_section->segname)); + EXPECT_EQ(actual_section->addr, expect_section->addr); + EXPECT_EQ(actual_section->size, expect_section->size); + EXPECT_EQ(actual_section->offset, expect_section->offset); + EXPECT_EQ(actual_section->align, expect_section->align); + EXPECT_EQ(actual_section->reloff, expect_section->reloff); + EXPECT_EQ(actual_section->nreloc, expect_section->nreloc); + EXPECT_EQ(actual_section->flags, expect_section->flags); + EXPECT_EQ(actual_section->reserved1, expect_section->reserved1); + EXPECT_EQ(actual_section->reserved2, expect_section->reserved2); } // Verifies that |expect_segment| is a valid Mach-O segment load command for the @@ -115,27 +115,28 @@ void ExpectSegmentCommand(const SegmentCommand* expect_segment, ASSERT_TRUE(expect_segment); ASSERT_TRUE(actual_segment); - EXPECT_EQ(kSegmentCommand, expect_segment->cmd); + EXPECT_EQ(expect_segment->cmd, kSegmentCommand); std::string segment_name = actual_segment->Name(); - EXPECT_EQ(MachOImageSegmentReader::SegmentNameString(expect_segment->segname), - segment_name); - EXPECT_EQ(expect_segment->vmaddr, actual_segment->vmaddr()); - EXPECT_EQ(expect_segment->vmsize, actual_segment->vmsize()); - EXPECT_EQ(expect_segment->fileoff, actual_segment->fileoff()); + EXPECT_EQ( + segment_name, + MachOImageSegmentReader::SegmentNameString(expect_segment->segname)); + EXPECT_EQ(actual_segment->vmaddr(), expect_segment->vmaddr); + EXPECT_EQ(actual_segment->vmsize(), expect_segment->vmsize); + EXPECT_EQ(actual_segment->fileoff(), expect_segment->fileoff); if (actual_segment->SegmentSlides()) { - EXPECT_EQ(actual_segment->Address(), - actual_segment->vmaddr() + actual_image->Slide()); + EXPECT_EQ(actual_segment->vmaddr() + actual_image->Slide(), + actual_segment->Address()); unsigned long expect_segment_size; const uint8_t* expect_segment_data = getsegmentdata( expect_image, segment_name.c_str(), &expect_segment_size); mach_vm_address_t expect_segment_address = reinterpret_cast(expect_segment_data); - EXPECT_EQ(expect_segment_address, actual_segment->Address()); - EXPECT_EQ(expect_segment_size, actual_segment->vmsize()); - EXPECT_EQ(actual_segment->vmsize(), actual_segment->Size()); + EXPECT_EQ(actual_segment->Address(), expect_segment_address); + EXPECT_EQ(actual_segment->vmsize(), expect_segment_size); + EXPECT_EQ(actual_segment->Size(), actual_segment->vmsize()); } else { // getsegmentdata() doesn’t return appropriate data for the __PAGEZERO // segment because getsegmentdata() always adjusts for slide, but the @@ -143,18 +144,18 @@ void ExpectSegmentCommand(const SegmentCommand* expect_segment, // check for that segment according to the same rules that the kernel uses // to identify __PAGEZERO. See 10.9.4 xnu-2422.110.17/bsd/kern/mach_loader.c // load_segment(). - EXPECT_EQ(actual_segment->Address(), actual_segment->vmaddr()); - EXPECT_EQ(actual_segment->vmsize() + actual_image->Slide(), - actual_segment->Size()); + EXPECT_EQ(actual_segment->vmaddr(), actual_segment->Address()); + EXPECT_EQ(actual_segment->Size(), + actual_segment->vmsize() + actual_image->Slide()); } - ASSERT_EQ(expect_segment->nsects, actual_segment->nsects()); + ASSERT_EQ(actual_segment->nsects(), expect_segment->nsects); // Make sure that the expected load command is big enough for the number of // sections that it claims to have, and set up a pointer to its first section // structure. - ASSERT_EQ(sizeof(*expect_segment) + expect_segment->nsects * sizeof(Section), - expect_segment->cmdsize); + ASSERT_EQ(expect_segment->cmdsize, + sizeof(*expect_segment) + expect_segment->nsects * sizeof(Section)); const Section* expect_sections = reinterpret_cast(&expect_segment[1]); @@ -170,7 +171,7 @@ void ExpectSegmentCommand(const SegmentCommand* expect_segment, MachOImageSegmentReader::SectionNameString(expect_section->sectname); const process_types::section* actual_section_by_name = actual_segment->GetSectionByName(section_name, nullptr); - EXPECT_EQ(actual_section, actual_section_by_name); + EXPECT_EQ(actual_section_by_name, actual_section); // Make sure that the section is accessible by the parent MachOImageReader’s // GetSectionByName. @@ -178,11 +179,11 @@ void ExpectSegmentCommand(const SegmentCommand* expect_segment, const process_types::section* actual_section_from_image_by_name = actual_image->GetSectionByName( segment_name, section_name, &actual_section_address); - EXPECT_EQ(actual_section, actual_section_from_image_by_name); + EXPECT_EQ(actual_section_from_image_by_name, actual_section); if (actual_segment->SegmentSlides()) { - EXPECT_EQ(actual_section_address, - actual_section->addr + actual_image->Slide()); + EXPECT_EQ(actual_section->addr + actual_image->Slide(), + actual_section_address); unsigned long expect_section_size; const uint8_t* expect_section_data = getsectiondata(expect_image, @@ -191,10 +192,10 @@ void ExpectSegmentCommand(const SegmentCommand* expect_segment, &expect_section_size); mach_vm_address_t expect_section_address = reinterpret_cast(expect_section_data); - EXPECT_EQ(expect_section_address, actual_section_address); - EXPECT_EQ(expect_section_size, actual_section->size); + EXPECT_EQ(actual_section_address, expect_section_address); + EXPECT_EQ(actual_section->size, expect_section_size); } else { - EXPECT_EQ(actual_section_address, actual_section->addr); + EXPECT_EQ(actual_section->addr, actual_section_address); } // Test the parent MachOImageReader’s GetSectionAtIndex as well. @@ -204,13 +205,13 @@ void ExpectSegmentCommand(const SegmentCommand* expect_segment, actual_image->GetSectionAtIndex(++(*section_index), &containing_segment, &actual_section_address_at_index); - EXPECT_EQ(actual_section, actual_section_from_image_at_index); - EXPECT_EQ(actual_segment, containing_segment); - EXPECT_EQ(actual_section_address, actual_section_address_at_index); + EXPECT_EQ(actual_section_from_image_at_index, actual_section); + EXPECT_EQ(containing_segment, actual_segment); + EXPECT_EQ(actual_section_address_at_index, actual_section_address); } - EXPECT_EQ(nullptr, - actual_segment->GetSectionByName("NoSuchSection", nullptr)); + EXPECT_EQ(actual_segment->GetSectionByName("NoSuchSection", nullptr), + nullptr); } // Walks through the load commands of |expect_image|, finding all of the @@ -256,15 +257,15 @@ void ExpectSegmentCommands(const MachHeader* expect_image, } position += command->cmdsize; } - EXPECT_EQ(expect_image->sizeofcmds, position); + EXPECT_EQ(position, expect_image->sizeofcmds); if (test_section_index_bounds) { // GetSectionAtIndex uses a 1-based index. Make sure that the range is // correct. - EXPECT_EQ(nullptr, actual_image->GetSectionAtIndex(0, nullptr, nullptr)); + EXPECT_EQ(actual_image->GetSectionAtIndex(0, nullptr, nullptr), nullptr); EXPECT_EQ( - nullptr, - actual_image->GetSectionAtIndex(section_index + 1, nullptr, nullptr)); + actual_image->GetSectionAtIndex(section_index + 1, nullptr, nullptr), + nullptr); } // Make sure that by-name lookups for names that don’t exist work properly: @@ -306,9 +307,9 @@ void ExpectSegmentCommands(const MachHeader* expect_image, MachOImageSegmentReader::SectionNameString(section->sectname); // It should be possible to look up the first section by name. - EXPECT_EQ(section, - actual_image->GetSectionByName( - section->segname, section->sectname, nullptr)); + EXPECT_EQ(actual_image->GetSectionByName( + section->segname, section->sectname, nullptr), + section); } EXPECT_FALSE( actual_image->GetSectionByName("NoSuchSegment", test_section, nullptr)); @@ -345,29 +346,29 @@ void ExpectMachImage(const MachHeader* expect_image, ASSERT_TRUE(expect_image); ASSERT_TRUE(actual_image); - EXPECT_EQ(kMachMagic, expect_image->magic); - EXPECT_EQ(kCPUType, expect_image->cputype); + EXPECT_EQ(expect_image->magic, kMachMagic); + EXPECT_EQ(expect_image->cputype, kCPUType); - EXPECT_EQ(expect_image->filetype, actual_image->FileType()); - EXPECT_EQ(expect_image_address, actual_image->Address()); + EXPECT_EQ(actual_image->FileType(), expect_image->filetype); + EXPECT_EQ(actual_image->Address(), expect_image_address); if (expect_image_slide != kSlideUnknown) { - EXPECT_EQ(expect_image_slide, actual_image->Slide()); + EXPECT_EQ(actual_image->Slide(), expect_image_slide); } const MachOImageSegmentReader* actual_text_segment = actual_image->GetSegmentByName(SEG_TEXT); ASSERT_TRUE(actual_text_segment); - EXPECT_EQ(expect_image_address, actual_text_segment->Address()); - EXPECT_EQ(actual_image->Size(), actual_text_segment->Size()); - EXPECT_EQ(expect_image_address - actual_text_segment->vmaddr(), - actual_image->Slide()); + EXPECT_EQ(actual_text_segment->Address(), expect_image_address); + EXPECT_EQ(actual_text_segment->Size(), actual_image->Size()); + EXPECT_EQ(actual_image->Slide(), + expect_image_address - actual_text_segment->vmaddr()); uint32_t file_type = actual_image->FileType(); EXPECT_TRUE(file_type == MH_EXECUTE || file_type == MH_DYLIB || file_type == MH_DYLINKER || file_type == MH_BUNDLE); if (file_type == MH_EXECUTE || file_type == MH_DYLINKER) { - EXPECT_EQ("/usr/lib/dyld", actual_image->DylinkerName()); + EXPECT_EQ(actual_image->DylinkerName(), "/usr/lib/dyld"); } // For these, just don’t crash or anything. @@ -418,10 +419,10 @@ void ExpectSymbol(const Nlist* entry, EXPECT_GE(entry->n_sect, 1u); expect_address += actual_image->Slide(); } else { - EXPECT_EQ(NO_SECT, entry->n_sect); + EXPECT_EQ(entry->n_sect, NO_SECT); } - EXPECT_EQ(expect_address, actual_address); + EXPECT_EQ(actual_address, expect_address); } // You’d think that it might be a good idea to verify that if the conditions @@ -452,7 +453,7 @@ void ExpectSymbolTable(const MachHeader* expect_image, ASSERT_LE(position + command->cmdsize, expect_image->sizeofcmds); if (command->cmd == LC_SYMTAB) { ASSERT_FALSE(symtab); - ASSERT_EQ(sizeof(symtab_command), command->cmdsize); + ASSERT_EQ(command->cmdsize, sizeof(symtab_command)); symtab = reinterpret_cast(command); } else if (command->cmd == kSegmentCommand) { ASSERT_GE(command->cmdsize, sizeof(SegmentCommand)); @@ -498,7 +499,7 @@ TEST(MachOImageReader, Self_MainExecutable) { const MachHeader* mh_execute_header = reinterpret_cast(dlsym(RTLD_MAIN_ONLY, MH_EXECUTE_SYM)); - ASSERT_NE(nullptr, mh_execute_header); + ASSERT_NE(mh_execute_header, nullptr); mach_vm_address_t mh_execute_header_address = reinterpret_cast(mh_execute_header); @@ -506,7 +507,7 @@ TEST(MachOImageReader, Self_MainExecutable) { ASSERT_TRUE(image_reader.Initialize( &process_reader, mh_execute_header_address, "executable")); - EXPECT_EQ(implicit_cast(MH_EXECUTE), image_reader.FileType()); + EXPECT_EQ(image_reader.FileType(), implicit_cast(MH_EXECUTE)); // The main executable has image index 0. intptr_t image_slide = _dyld_get_image_vmaddr_slide(0); @@ -522,7 +523,7 @@ TEST(MachOImageReader, Self_MainExecutable) { mach_vm_address_t symbol_address; ASSERT_TRUE(image_reader.LookUpExternalDefinedSymbol(_MH_EXECUTE_SYM, &symbol_address)); - EXPECT_EQ(mh_execute_header_address, symbol_address); + EXPECT_EQ(symbol_address, mh_execute_header_address); ASSERT_NO_FATAL_FAILURE(ExpectSymbolTable(mh_execute_header, &image_reader)); } @@ -554,7 +555,7 @@ TEST(MachOImageReader, Self_DyldImages) { uint32_t file_type = image_reader.FileType(); if (index == 0) { - EXPECT_EQ(implicit_cast(MH_EXECUTE), file_type); + EXPECT_EQ(file_type, implicit_cast(MH_EXECUTE)); } else { EXPECT_TRUE(file_type == MH_DYLIB || file_type == MH_BUNDLE); } @@ -578,7 +579,7 @@ TEST(MachOImageReader, Self_DyldImages) { const struct dyld_all_image_infos* dyld_image_infos = _dyld_get_all_image_infos(); ASSERT_GE(dyld_image_infos->version, 1u); - EXPECT_EQ(count, dyld_image_infos->infoArrayCount); + EXPECT_EQ(dyld_image_infos->infoArrayCount, count); if (dyld_image_infos->version >= 2) { SCOPED_TRACE("dyld"); @@ -593,7 +594,7 @@ TEST(MachOImageReader, Self_DyldImages) { ASSERT_TRUE( image_reader.Initialize(&process_reader, image_address, "dyld")); - EXPECT_EQ(implicit_cast(MH_DYLINKER), image_reader.FileType()); + EXPECT_EQ(image_reader.FileType(), implicit_cast(MH_DYLINKER)); // There’s no good API to get dyld’s slide, so don’t bother checking it. ASSERT_NO_FATAL_FAILURE(ExpectMachImage( @@ -634,7 +635,7 @@ TEST(MachOImageReader, Self_DyldImages) { expected_uuid.InitializeFromBytes(dyld_image->imageUUID); UUID actual_uuid; image_reader.UUID(&actual_uuid); - EXPECT_EQ(expected_uuid, actual_uuid); + EXPECT_EQ(actual_uuid, expected_uuid); } } #endif diff --git a/snapshot/mac/mach_o_image_segment_reader_test.cc b/snapshot/mac/mach_o_image_segment_reader_test.cc index 49eacb04..6e4d415a 100644 --- a/snapshot/mac/mach_o_image_segment_reader_test.cc +++ b/snapshot/mac/mach_o_image_segment_reader_test.cc @@ -36,20 +36,20 @@ namespace { TEST(MachOImageSegmentReader, SegmentNameString) { // The output value should be a string of up to 16 characters, even if the // input value is not NUL-terminated within 16 characters. - EXPECT_EQ("__TEXT", MachOImageSegmentReader::SegmentNameString("__TEXT")); - EXPECT_EQ("__OVER", MachOImageSegmentReader::SegmentNameString("__OVER")); - EXPECT_EQ("", MachOImageSegmentReader::SegmentNameString("")); - EXPECT_EQ("p", MachOImageSegmentReader::SegmentNameString("p")); - EXPECT_EQ("NoUnderChar", - MachOImageSegmentReader::SegmentNameString("NoUnderChar")); - EXPECT_EQ("0123456789abcde", - MachOImageSegmentReader::SegmentNameString("0123456789abcde")); - EXPECT_EQ("0123456789abcdef", - MachOImageSegmentReader::SegmentNameString("0123456789abcdef")); - EXPECT_EQ("gfedcba987654321", - MachOImageSegmentReader::SegmentNameString("gfedcba9876543210")); - EXPECT_EQ("hgfedcba98765432", - MachOImageSegmentReader::SegmentNameString("hgfedcba9876543210")); + EXPECT_EQ(MachOImageSegmentReader::SegmentNameString("__TEXT"), "__TEXT"); + EXPECT_EQ(MachOImageSegmentReader::SegmentNameString("__OVER"), "__OVER"); + EXPECT_EQ(MachOImageSegmentReader::SegmentNameString(""), ""); + EXPECT_EQ(MachOImageSegmentReader::SegmentNameString("p"), "p"); + EXPECT_EQ(MachOImageSegmentReader::SegmentNameString("NoUnderChar"), + "NoUnderChar"); + EXPECT_EQ(MachOImageSegmentReader::SegmentNameString("0123456789abcde"), + "0123456789abcde"); + EXPECT_EQ(MachOImageSegmentReader::SegmentNameString("0123456789abcdef"), + "0123456789abcdef"); + EXPECT_EQ(MachOImageSegmentReader::SegmentNameString("gfedcba9876543210"), + "gfedcba987654321"); + EXPECT_EQ(MachOImageSegmentReader::SegmentNameString("hgfedcba9876543210"), + "hgfedcba98765432"); // Segment names defined in . All of these should come // through SegmentNameString() cleanly and without truncation. @@ -65,8 +65,8 @@ TEST(MachOImageSegmentReader, SegmentNameString) { for (size_t index = 0; index < arraysize(kSegmentTestData); ++index) { EXPECT_EQ( - kSegmentTestData[index], - MachOImageSegmentReader::SegmentNameString(kSegmentTestData[index])) + MachOImageSegmentReader::SegmentNameString(kSegmentTestData[index]), + kSegmentTestData[index]) << base::StringPrintf("index %zu", index); } } @@ -74,20 +74,20 @@ TEST(MachOImageSegmentReader, SegmentNameString) { TEST(MachOImageSegmentReader, SectionNameString) { // The output value should be a string of up to 16 characters, even if the // input value is not NUL-terminated within 16 characters. - EXPECT_EQ("__text", MachOImageSegmentReader::SectionNameString("__text")); - EXPECT_EQ("__over", MachOImageSegmentReader::SectionNameString("__over")); - EXPECT_EQ("", MachOImageSegmentReader::SectionNameString("")); - EXPECT_EQ("p", MachOImageSegmentReader::SectionNameString("p")); - EXPECT_EQ("NoUnderChar", - MachOImageSegmentReader::SectionNameString("NoUnderChar")); - EXPECT_EQ("0123456789abcde", - MachOImageSegmentReader::SectionNameString("0123456789abcde")); - EXPECT_EQ("0123456789abcdef", - MachOImageSegmentReader::SectionNameString("0123456789abcdef")); - EXPECT_EQ("gfedcba987654321", - MachOImageSegmentReader::SectionNameString("gfedcba9876543210")); - EXPECT_EQ("hgfedcba98765432", - MachOImageSegmentReader::SectionNameString("hgfedcba9876543210")); + EXPECT_EQ(MachOImageSegmentReader::SectionNameString("__text"), "__text"); + EXPECT_EQ(MachOImageSegmentReader::SectionNameString("__over"), "__over"); + EXPECT_EQ(MachOImageSegmentReader::SectionNameString(""), ""); + EXPECT_EQ(MachOImageSegmentReader::SectionNameString("p"), "p"); + EXPECT_EQ(MachOImageSegmentReader::SectionNameString("NoUnderChar"), + "NoUnderChar"); + EXPECT_EQ(MachOImageSegmentReader::SectionNameString("0123456789abcde"), + "0123456789abcde"); + EXPECT_EQ(MachOImageSegmentReader::SectionNameString("0123456789abcdef"), + "0123456789abcdef"); + EXPECT_EQ(MachOImageSegmentReader::SectionNameString("gfedcba9876543210"), + "gfedcba987654321"); + EXPECT_EQ(MachOImageSegmentReader::SectionNameString("hgfedcba9876543210"), + "hgfedcba98765432"); // Section names defined in . All of these should come // through SectionNameString() cleanly and without truncation. @@ -108,8 +108,8 @@ TEST(MachOImageSegmentReader, SectionNameString) { for (size_t index = 0; index < arraysize(kSectionTestData); ++index) { EXPECT_EQ( - kSectionTestData[index], - MachOImageSegmentReader::SectionNameString(kSectionTestData[index])) + MachOImageSegmentReader::SectionNameString(kSectionTestData[index]), + kSectionTestData[index]) << base::StringPrintf("index %zu", index); } } @@ -173,9 +173,9 @@ TEST(MachOImageSegmentReader, SegmentAndSectionNameString) { for (size_t index = 0; index < arraysize(kSegmentAndSectionTestData); ++index) { const SegmentAndSectionTestData& test = kSegmentAndSectionTestData[index]; - EXPECT_EQ(test.output, - MachOImageSegmentReader::SegmentAndSectionNameString( - test.segment, test.section)) + EXPECT_EQ(MachOImageSegmentReader::SegmentAndSectionNameString( + test.segment, test.section), + test.output) << base::StringPrintf("index %zu, segment %s, section %s", index, test.segment, diff --git a/snapshot/mac/process_reader_test.cc b/snapshot/mac/process_reader_test.cc index 87fb6394..26cb26d2 100644 --- a/snapshot/mac/process_reader_test.cc +++ b/snapshot/mac/process_reader_test.cc @@ -68,8 +68,8 @@ TEST(ProcessReader, SelfBasic) { EXPECT_TRUE(process_reader.Is64Bit()); #endif - EXPECT_EQ(getpid(), process_reader.ProcessID()); - EXPECT_EQ(getppid(), process_reader.ParentProcessID()); + EXPECT_EQ(process_reader.ProcessID(), getpid()); + EXPECT_EQ(process_reader.ParentProcessID(), getppid()); const char kTestMemory[] = "Some test memory"; char buffer[arraysize(kTestMemory)]; @@ -99,8 +99,8 @@ class ProcessReaderChild final : public MachMultiprocess { EXPECT_TRUE(process_reader.Is64Bit()); #endif - EXPECT_EQ(getpid(), process_reader.ParentProcessID()); - EXPECT_EQ(ChildPID(), process_reader.ProcessID()); + EXPECT_EQ(process_reader.ParentProcessID(), getpid()); + EXPECT_EQ(process_reader.ProcessID(), ChildPID()); FileHandle read_handle = ReadPipeHandle(); @@ -109,7 +109,7 @@ class ProcessReaderChild final : public MachMultiprocess { std::string read_string; ASSERT_TRUE(process_reader.Memory()->ReadCString(address, &read_string)); - EXPECT_EQ(kTestMemory, read_string); + EXPECT_EQ(read_string, kTestMemory); } void MachMultiprocessChild() override { @@ -153,12 +153,12 @@ TEST(ProcessReader, SelfOneThread) { // thread, not exactly one thread. ASSERT_GE(threads.size(), 1u); - EXPECT_EQ(PthreadToThreadID(pthread_self()), threads[0].id); + EXPECT_EQ(threads[0].id, PthreadToThreadID(pthread_self())); thread_t thread_self = MachThreadSelf(); - EXPECT_EQ(thread_self, threads[0].port); + EXPECT_EQ(threads[0].port, thread_self); - EXPECT_EQ(0, threads[0].suspend_count); + EXPECT_EQ(threads[0].suspend_count, 0); } class TestThreadPool { @@ -178,7 +178,7 @@ class TestThreadPool { thread_t thread_port = pthread_mach_thread_np(thread_info->pthread); while (thread_info->suspend_count > 0) { kern_return_t kr = thread_resume(thread_port); - EXPECT_EQ(KERN_SUCCESS, kr) << MachErrorMessage(kr, "thread_resume"); + EXPECT_EQ(kr, KERN_SUCCESS) << MachErrorMessage(kr, "thread_resume"); --thread_info->suspend_count; } } @@ -207,7 +207,7 @@ class TestThreadPool { nullptr, ThreadMain, thread_info); - ASSERT_EQ(0, rv); + ASSERT_EQ(rv, 0); } for (ThreadInfo* thread_info : thread_infos_) { @@ -225,7 +225,7 @@ class TestThreadPool { suspend_count < thread_index; ++suspend_count) { kern_return_t kr = thread_suspend(thread_port); - EXPECT_EQ(KERN_SUCCESS, kr) << MachErrorMessage(kr, "thread_suspend"); + EXPECT_EQ(kr, KERN_SUCCESS) << MachErrorMessage(kr, "thread_suspend"); if (kr == KERN_SUCCESS) { ++thread_infos_[thread_index]->suspend_count; } @@ -317,7 +317,7 @@ void ExpectSeveralThreads(ThreadMap* thread_map, if (tolerate_extra_threads) { ASSERT_GE(threads.size(), thread_map->size()); } else { - ASSERT_EQ(thread_map->size(), threads.size()); + ASSERT_EQ(threads.size(), thread_map->size()); } for (size_t thread_index = 0; thread_index < threads.size(); ++thread_index) { @@ -328,14 +328,14 @@ void ExpectSeveralThreads(ThreadMap* thread_map, const auto& iterator = thread_map->find(thread.id); if (!tolerate_extra_threads) { // Make sure that the thread is in the expectation map. - ASSERT_NE(thread_map->end(), iterator); + ASSERT_NE(iterator, thread_map->end()); } if (iterator != thread_map->end()) { EXPECT_GE(iterator->second.stack_address, thread.stack_region_address); EXPECT_LT(iterator->second.stack_address, thread_stack_region_end); - EXPECT_EQ(iterator->second.suspend_count, thread.suspend_count); + EXPECT_EQ(thread.suspend_count, iterator->second.suspend_count); // Remove the thread from the expectation map since it’s already been // found. This makes it easy to check for duplicate thread IDs, and makes @@ -350,14 +350,14 @@ void ExpectSeveralThreads(ThreadMap* thread_map, for (size_t other_thread_index = 0; other_thread_index < threads.size(); ++other_thread_index) { - if (thread_index == other_thread_index) { + if (other_thread_index == thread_index) { continue; } const ProcessReader::Thread& other_thread = threads[other_thread_index]; - EXPECT_NE(thread.id, other_thread.id); - EXPECT_NE(thread.port, other_thread.port); + EXPECT_NE(other_thread.id, thread.id); + EXPECT_NE(other_thread.port, thread.port); mach_vm_address_t other_thread_stack_region_end = other_thread.stack_region_address + other_thread.stack_region_size; @@ -398,7 +398,7 @@ TEST(ProcessReader, SelfSeveralThreads) { uint64_t thread_id = thread_pool.GetThreadInfo(thread_index, &expectation); // There can’t be any duplicate thread IDs. - EXPECT_EQ(0u, thread_map.count(thread_id)); + EXPECT_EQ(thread_map.count(thread_id), 0u); thread_map[thread_id] = expectation; } @@ -418,7 +418,7 @@ TEST(ProcessReader, SelfSeveralThreads) { if (thread.port == thread_self) { EXPECT_FALSE(found_thread_self); found_thread_self = true; - EXPECT_EQ(self_thread_id, thread.id); + EXPECT_EQ(thread.id, self_thread_id); } } EXPECT_TRUE(found_thread_self); @@ -459,7 +459,7 @@ class ProcessReaderThreadedChild final : public MachMultiprocess { sizeof(expectation.suspend_count)); // There can’t be any duplicate thread IDs. - EXPECT_EQ(0u, thread_map.count(thread_id)); + EXPECT_EQ(thread_map.count(thread_id), 0u); thread_map[thread_id] = expectation; } @@ -556,24 +556,24 @@ class ScopedOpenCLNoOpKernel { ~ScopedOpenCLNoOpKernel() { if (kernel_) { cl_int rv = clReleaseKernel(kernel_); - EXPECT_EQ(CL_SUCCESS, rv) << "clReleaseKernel"; + EXPECT_EQ(rv, CL_SUCCESS) << "clReleaseKernel"; } if (program_) { cl_int rv = clReleaseProgram(program_); - EXPECT_EQ(CL_SUCCESS, rv) << "clReleaseProgram"; + EXPECT_EQ(rv, CL_SUCCESS) << "clReleaseProgram"; } if (context_) { cl_int rv = clReleaseContext(context_); - EXPECT_EQ(CL_SUCCESS, rv) << "clReleaseContext"; + EXPECT_EQ(rv, CL_SUCCESS) << "clReleaseContext"; } } void SetUp() { cl_platform_id platform_id; cl_int rv = clGetPlatformIDs(1, &platform_id, nullptr); - ASSERT_EQ(CL_SUCCESS, rv) << "clGetPlatformIDs"; + ASSERT_EQ(rv, CL_SUCCESS) << "clGetPlatformIDs"; // Use CL_DEVICE_TYPE_CPU to ensure that the kernel would execute on the // CPU. This is the only device type that a cl_kernels image will be created @@ -581,10 +581,10 @@ class ScopedOpenCLNoOpKernel { cl_device_id device_id; rv = clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_CPU, 1, &device_id, nullptr); - ASSERT_EQ(CL_SUCCESS, rv) << "clGetDeviceIDs"; + ASSERT_EQ(rv, CL_SUCCESS) << "clGetDeviceIDs"; context_ = clCreateContext(nullptr, 1, &device_id, nullptr, nullptr, &rv); - ASSERT_EQ(CL_SUCCESS, rv) << "clCreateContext"; + ASSERT_EQ(rv, CL_SUCCESS) << "clCreateContext"; // The goal of the program in |sources| is to produce a cl_kernels image // that doesn’t strictly conform to Mach-O expectations. On OS X 10.10, @@ -610,14 +610,14 @@ class ScopedOpenCLNoOpKernel { program_ = clCreateProgramWithSource( context_, arraysize(sources), sources, source_lengths, &rv); - ASSERT_EQ(CL_SUCCESS, rv) << "clCreateProgramWithSource"; + ASSERT_EQ(rv, CL_SUCCESS) << "clCreateProgramWithSource"; rv = clBuildProgram( program_, 1, &device_id, "-cl-opt-disable", nullptr, nullptr); - ASSERT_EQ(CL_SUCCESS, rv) << "clBuildProgram"; + ASSERT_EQ(rv, CL_SUCCESS) << "clBuildProgram"; kernel_ = clCreateKernel(program_, "NoOp", &rv); - ASSERT_EQ(CL_SUCCESS, rv) << "clCreateKernel"; + ASSERT_EQ(rv, CL_SUCCESS) << "clCreateKernel"; } private: @@ -655,7 +655,7 @@ TEST(ProcessReader, SelfModules) { // dyld_image_count doesn’t include an entry for dyld itself, but |modules| // does. - ASSERT_EQ(dyld_image_count + 1, modules.size()); + ASSERT_EQ(modules.size(), dyld_image_count + 1); bool found_cl_kernels = false; for (uint32_t index = 0; index < dyld_image_count; ++index) { @@ -663,49 +663,48 @@ TEST(ProcessReader, SelfModules) { "index %u, name %s", index, modules[index].name.c_str())); const char* dyld_image_name = _dyld_get_image_name(index); - EXPECT_EQ(dyld_image_name, modules[index].name); + EXPECT_EQ(modules[index].name, dyld_image_name); ASSERT_TRUE(modules[index].reader); EXPECT_EQ( - reinterpret_cast(_dyld_get_image_header(index)), - modules[index].reader->Address()); + modules[index].reader->Address(), + reinterpret_cast(_dyld_get_image_header(index))); if (index == 0) { // dyld didn’t load the main executable, so it couldn’t record its // timestamp, and it is reported as 0. - EXPECT_EQ(0, modules[index].timestamp); + EXPECT_EQ(modules[index].timestamp, 0); } else if (modules[index].reader->FileType() == MH_BUNDLE && modules[index].name == "cl_kernels") { // cl_kernels doesn’t exist as a file. - EXPECT_EQ(0, modules[index].timestamp); + EXPECT_EQ(modules[index].timestamp, 0); found_cl_kernels = true; } else { // Hope that the module didn’t change on disk. struct stat stat_buf; int rv = stat(dyld_image_name, &stat_buf); - EXPECT_EQ(0, rv) << ErrnoMessage("stat"); + EXPECT_EQ(rv, 0) << ErrnoMessage("stat"); if (rv == 0) { - EXPECT_EQ(stat_buf.st_mtime, modules[index].timestamp); + EXPECT_EQ(modules[index].timestamp, stat_buf.st_mtime); } } } - EXPECT_EQ(ExpectCLKernels(), found_cl_kernels); + EXPECT_EQ(found_cl_kernels, ExpectCLKernels()); size_t index = modules.size() - 1; - EXPECT_EQ(kDyldPath, modules[index].name); + EXPECT_EQ(modules[index].name, kDyldPath); // dyld didn’t load itself either, so it couldn’t record its timestamp, and it // is also reported as 0. - EXPECT_EQ(0, modules[index].timestamp); + EXPECT_EQ(modules[index].timestamp, 0); const struct dyld_all_image_infos* dyld_image_infos = _dyld_get_all_image_infos(); if (dyld_image_infos->version >= 2) { ASSERT_TRUE(modules[index].reader); - EXPECT_EQ( - reinterpret_cast( - dyld_image_infos->dyldImageLoadAddress), - modules[index].reader->Address()); + EXPECT_EQ(modules[index].reader->Address(), + reinterpret_cast( + dyld_image_infos->dyldImageLoadAddress)); } } @@ -733,7 +732,7 @@ class ProcessReaderModulesChild final : public MachMultiprocess { CheckedReadFileExactly( read_handle, &expect_modules, sizeof(expect_modules)); - ASSERT_EQ(expect_modules, modules.size()); + ASSERT_EQ(modules.size(), expect_modules); bool found_cl_kernels = false; for (size_t index = 0; index < modules.size(); ++index) { @@ -747,35 +746,35 @@ class ProcessReaderModulesChild final : public MachMultiprocess { // The NUL terminator is not read. std::string expect_name(expect_name_length, '\0'); CheckedReadFileExactly(read_handle, &expect_name[0], expect_name_length); - EXPECT_EQ(expect_name, modules[index].name); + EXPECT_EQ(modules[index].name, expect_name); mach_vm_address_t expect_address; CheckedReadFileExactly( read_handle, &expect_address, sizeof(expect_address)); ASSERT_TRUE(modules[index].reader); - EXPECT_EQ(expect_address, modules[index].reader->Address()); + EXPECT_EQ(modules[index].reader->Address(), expect_address); if (index == 0 || index == modules.size() - 1) { // dyld didn’t load the main executable or itself, so it couldn’t record // these timestamps, and they are reported as 0. - EXPECT_EQ(0, modules[index].timestamp); + EXPECT_EQ(modules[index].timestamp, 0); } else if (modules[index].reader->FileType() == MH_BUNDLE && modules[index].name == "cl_kernels") { // cl_kernels doesn’t exist as a file. - EXPECT_EQ(0, modules[index].timestamp); + EXPECT_EQ(modules[index].timestamp, 0); found_cl_kernels = true; } else { // Hope that the module didn’t change on disk. struct stat stat_buf; int rv = stat(expect_name.c_str(), &stat_buf); - EXPECT_EQ(0, rv) << ErrnoMessage("stat"); + EXPECT_EQ(rv, 0) << ErrnoMessage("stat"); if (rv == 0) { - EXPECT_EQ(stat_buf.st_mtime, modules[index].timestamp); + EXPECT_EQ(modules[index].timestamp, stat_buf.st_mtime); } } } - EXPECT_EQ(ExpectCLKernels(), found_cl_kernels); + EXPECT_EQ(found_cl_kernels, ExpectCLKernels()); } void MachMultiprocessChild() override { diff --git a/snapshot/mac/process_types_test.cc b/snapshot/mac/process_types_test.cc index 8525c14e..f9ff7d19 100644 --- a/snapshot/mac/process_types_test.cc +++ b/snapshot/mac/process_types_test.cc @@ -39,7 +39,7 @@ namespace { std::string proctype_string; \ ASSERT_TRUE(process_reader.Memory()->ReadCString(proctype_view.field, \ &proctype_string)); \ - EXPECT_EQ(self_view->field, proctype_string); \ + EXPECT_EQ(proctype_string, self_view->field); \ } \ } while (false) @@ -66,7 +66,7 @@ TEST(ProcessTypes, DyldImagesSelf) { } #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7 if (self_image_infos->version >= 9) { - EXPECT_EQ(self_image_infos, self_image_infos->dyldAllImageInfosAddress); + EXPECT_EQ(self_image_infos->dyldAllImageInfosAddress, self_image_infos); } #endif @@ -78,10 +78,10 @@ TEST(ProcessTypes, DyldImagesSelf) { TASK_DYLD_INFO, reinterpret_cast(&dyld_info), &count); - ASSERT_EQ(KERN_SUCCESS, kr); + ASSERT_EQ(kr, KERN_SUCCESS); - EXPECT_EQ(reinterpret_cast(self_image_infos), - dyld_info.all_image_info_addr); + EXPECT_EQ(dyld_info.all_image_info_addr, + reinterpret_cast(self_image_infos)); EXPECT_GT(dyld_info.all_image_info_size, 1u); // This field is only present in the OS X 10.7 SDK (at build time) and kernel @@ -89,9 +89,9 @@ TEST(ProcessTypes, DyldImagesSelf) { #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7 if (MacOSXMinorVersion() >= 7) { #if !defined(ARCH_CPU_64_BITS) - EXPECT_EQ(TASK_DYLD_ALL_IMAGE_INFO_32, dyld_info.all_image_info_format); + EXPECT_EQ(dyld_info.all_image_info_format, TASK_DYLD_ALL_IMAGE_INFO_32); #else - EXPECT_EQ(TASK_DYLD_ALL_IMAGE_INFO_64, dyld_info.all_image_info_format); + EXPECT_EQ(dyld_info.all_image_info_format, TASK_DYLD_ALL_IMAGE_INFO_64); #endif } #endif @@ -113,9 +113,9 @@ TEST(ProcessTypes, DyldImagesSelf) { // Make sure that the size of the structure as declared in the SDK matches the // size expected for the version of the structure that the SDK describes. - EXPECT_EQ(sizeof(dyld_all_image_infos), - process_types::dyld_all_image_infos::ExpectedSizeForVersion( - &process_reader, kDyldAllImageInfosVersionInSDK)); + EXPECT_EQ(process_types::dyld_all_image_infos::ExpectedSizeForVersion( + &process_reader, kDyldAllImageInfosVersionInSDK), + sizeof(dyld_all_image_infos)); // Make sure that the computed sizes of various versions of this structure are // correct at different bitnessses. @@ -143,50 +143,50 @@ TEST(ProcessTypes, DyldImagesSelf) { uint32_t version = kVersionsAndSizes[index].version; SCOPED_TRACE(base::StringPrintf("index %zu, version %u", index, version)); - EXPECT_EQ(kVersionsAndSizes[index].size_32, - process_types::internal::dyld_all_image_infos< - process_types::internal::Traits32>:: - ExpectedSizeForVersion(version)); - EXPECT_EQ(kVersionsAndSizes[index].size_64, - process_types::internal::dyld_all_image_infos< - process_types::internal::Traits64>:: - ExpectedSizeForVersion(version)); + EXPECT_EQ( + process_types::internal::dyld_all_image_infos< + process_types::internal::Traits32>::ExpectedSizeForVersion(version), + kVersionsAndSizes[index].size_32); + EXPECT_EQ( + process_types::internal::dyld_all_image_infos< + process_types::internal::Traits64>::ExpectedSizeForVersion(version), + kVersionsAndSizes[index].size_64); } process_types::dyld_all_image_infos proctype_image_infos; ASSERT_TRUE(proctype_image_infos.Read(&process_reader, dyld_info.all_image_info_addr)); - ASSERT_EQ(self_image_infos->version, proctype_image_infos.version); + ASSERT_EQ(proctype_image_infos.version, self_image_infos->version); if (proctype_image_infos.version >= 1) { - EXPECT_EQ(self_image_infos->infoArrayCount, - proctype_image_infos.infoArrayCount); - EXPECT_EQ(reinterpret_cast(self_image_infos->infoArray), - proctype_image_infos.infoArray); - EXPECT_EQ(reinterpret_cast(self_image_infos->notification), - proctype_image_infos.notification); - EXPECT_EQ(self_image_infos->processDetachedFromSharedRegion, - proctype_image_infos.processDetachedFromSharedRegion); + EXPECT_EQ(proctype_image_infos.infoArrayCount, + self_image_infos->infoArrayCount); + EXPECT_EQ(proctype_image_infos.infoArray, + reinterpret_cast(self_image_infos->infoArray)); + EXPECT_EQ(proctype_image_infos.notification, + reinterpret_cast(self_image_infos->notification)); + EXPECT_EQ(proctype_image_infos.processDetachedFromSharedRegion, + self_image_infos->processDetachedFromSharedRegion); } if (proctype_image_infos.version >= 2) { - EXPECT_EQ(self_image_infos->libSystemInitialized, - proctype_image_infos.libSystemInitialized); + EXPECT_EQ(proctype_image_infos.libSystemInitialized, + self_image_infos->libSystemInitialized); EXPECT_EQ( - reinterpret_cast(self_image_infos->dyldImageLoadAddress), - proctype_image_infos.dyldImageLoadAddress); + proctype_image_infos.dyldImageLoadAddress, + reinterpret_cast(self_image_infos->dyldImageLoadAddress)); } if (proctype_image_infos.version >= 3) { - EXPECT_EQ(reinterpret_cast(self_image_infos->jitInfo), - proctype_image_infos.jitInfo); + EXPECT_EQ(proctype_image_infos.jitInfo, + reinterpret_cast(self_image_infos->jitInfo)); } if (proctype_image_infos.version >= 5) { - EXPECT_EQ(reinterpret_cast(self_image_infos->dyldVersion), - proctype_image_infos.dyldVersion); - EXPECT_EQ(reinterpret_cast(self_image_infos->errorMessage), - proctype_image_infos.errorMessage); - EXPECT_EQ(implicit_cast(self_image_infos->terminationFlags), - proctype_image_infos.terminationFlags); + EXPECT_EQ(proctype_image_infos.dyldVersion, + reinterpret_cast(self_image_infos->dyldVersion)); + EXPECT_EQ(proctype_image_infos.errorMessage, + reinterpret_cast(self_image_infos->errorMessage)); + EXPECT_EQ(proctype_image_infos.terminationFlags, + implicit_cast(self_image_infos->terminationFlags)); TEST_STRING( process_reader, self_image_infos, proctype_image_infos, dyldVersion); @@ -195,38 +195,38 @@ TEST(ProcessTypes, DyldImagesSelf) { } if (proctype_image_infos.version >= 6) { EXPECT_EQ( - reinterpret_cast(self_image_infos->coreSymbolicationShmPage), - proctype_image_infos.coreSymbolicationShmPage); + proctype_image_infos.coreSymbolicationShmPage, + reinterpret_cast(self_image_infos->coreSymbolicationShmPage)); } if (proctype_image_infos.version >= 7) { - EXPECT_EQ(implicit_cast(self_image_infos->systemOrderFlag), - proctype_image_infos.systemOrderFlag); + EXPECT_EQ(proctype_image_infos.systemOrderFlag, + implicit_cast(self_image_infos->systemOrderFlag)); } #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7 if (proctype_image_infos.version >= 8) { - EXPECT_EQ(implicit_cast(self_image_infos->uuidArrayCount), - proctype_image_infos.uuidArrayCount); + EXPECT_EQ(proctype_image_infos.uuidArrayCount, + implicit_cast(self_image_infos->uuidArrayCount)); } if (proctype_image_infos.version >= 9) { EXPECT_EQ( - reinterpret_cast(self_image_infos->dyldAllImageInfosAddress), - proctype_image_infos.dyldAllImageInfosAddress); + proctype_image_infos.dyldAllImageInfosAddress, + reinterpret_cast(self_image_infos->dyldAllImageInfosAddress)); } if (proctype_image_infos.version >= 10) { - EXPECT_EQ(implicit_cast(self_image_infos->initialImageCount), - proctype_image_infos.initialImageCount); + EXPECT_EQ(proctype_image_infos.initialImageCount, + implicit_cast(self_image_infos->initialImageCount)); } if (proctype_image_infos.version >= 11) { - EXPECT_EQ(implicit_cast(self_image_infos->errorKind), - proctype_image_infos.errorKind); + EXPECT_EQ(proctype_image_infos.errorKind, + implicit_cast(self_image_infos->errorKind)); EXPECT_EQ( - reinterpret_cast(self_image_infos->errorClientOfDylibPath), - proctype_image_infos.errorClientOfDylibPath); + proctype_image_infos.errorClientOfDylibPath, + reinterpret_cast(self_image_infos->errorClientOfDylibPath)); EXPECT_EQ( - reinterpret_cast(self_image_infos->errorTargetDylibPath), - proctype_image_infos.errorTargetDylibPath); - EXPECT_EQ(reinterpret_cast(self_image_infos->errorSymbol), - proctype_image_infos.errorSymbol); + proctype_image_infos.errorTargetDylibPath, + reinterpret_cast(self_image_infos->errorTargetDylibPath)); + EXPECT_EQ(proctype_image_infos.errorSymbol, + reinterpret_cast(self_image_infos->errorSymbol)); TEST_STRING(process_reader, self_image_infos, @@ -240,31 +240,32 @@ TEST(ProcessTypes, DyldImagesSelf) { process_reader, self_image_infos, proctype_image_infos, errorSymbol); } if (proctype_image_infos.version >= 12) { - EXPECT_EQ(implicit_cast(self_image_infos->sharedCacheSlide), - proctype_image_infos.sharedCacheSlide); + EXPECT_EQ(proctype_image_infos.sharedCacheSlide, + implicit_cast(self_image_infos->sharedCacheSlide)); } #endif #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9 if (proctype_image_infos.version >= 13) { - EXPECT_EQ(0, - memcmp(self_image_infos->sharedCacheUUID, + EXPECT_EQ(memcmp(self_image_infos->sharedCacheUUID, proctype_image_infos.sharedCacheUUID, - sizeof(self_image_infos->sharedCacheUUID))); + sizeof(self_image_infos->sharedCacheUUID)), + 0); } #endif #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_12 if (proctype_image_infos.version >= 15) { - EXPECT_EQ(self_image_infos->infoArrayChangeTimestamp, - proctype_image_infos.infoArrayChangeTimestamp); - EXPECT_EQ(self_image_infos->sharedCacheBaseAddress, - proctype_image_infos.sharedCacheBaseAddress); - EXPECT_EQ(reinterpret_cast(self_image_infos->dyldPath), - proctype_image_infos.dyldPath); + EXPECT_EQ(proctype_image_infos.infoArrayChangeTimestamp, + self_image_infos->infoArrayChangeTimestamp); + EXPECT_EQ(proctype_image_infos.sharedCacheBaseAddress, + self_image_infos->sharedCacheBaseAddress); + EXPECT_EQ(proctype_image_infos.dyldPath, + reinterpret_cast(self_image_infos->dyldPath)); for (size_t index = 0; index < arraysize(self_image_infos->notifyPorts); ++index) { - EXPECT_EQ(self_image_infos->notifyPorts[index], - proctype_image_infos.notifyPorts[index]) << "index " << index; + EXPECT_EQ(proctype_image_infos.notifyPorts[index], + self_image_infos->notifyPorts[index]) + << "index " << index; } TEST_STRING( @@ -283,16 +284,16 @@ TEST(ProcessTypes, DyldImagesSelf) { for (size_t index = 0; index < arraysize(proctype_image_infos.reserved); ++index) { - EXPECT_EQ(implicit_cast(self_image_infos->reserved[index]), - proctype_image_infos.reserved[index]) + EXPECT_EQ(proctype_image_infos.reserved[index], + implicit_cast(self_image_infos->reserved[index])) << "index " << index; } #if defined(ARCH_CPU_64_BITS) - EXPECT_EQ(self_image_infos->reserved[4], proctype_image_infos.reserved_4); - EXPECT_EQ(self_image_infos->reserved[5], proctype_image_infos.reserved_5); - EXPECT_EQ(self_image_infos->reserved[6], proctype_image_infos.reserved_6); - EXPECT_EQ(self_image_infos->reserved[7], proctype_image_infos.reserved_7); - EXPECT_EQ(self_image_infos->reserved[8], proctype_image_infos.reserved_8); + EXPECT_EQ(proctype_image_infos.reserved_4, self_image_infos->reserved[4]); + EXPECT_EQ(proctype_image_infos.reserved_5, self_image_infos->reserved[5]); + EXPECT_EQ(proctype_image_infos.reserved_6, self_image_infos->reserved[6]); + EXPECT_EQ(proctype_image_infos.reserved_7, self_image_infos->reserved[7]); + EXPECT_EQ(proctype_image_infos.reserved_8, self_image_infos->reserved[8]); #endif } #endif @@ -314,14 +315,14 @@ TEST(ProcessTypes, DyldImagesSelf) { const process_types::dyld_image_info& proctype_image_info = proctype_image_info_vector[index]; - EXPECT_EQ(reinterpret_cast(self_image_info->imageLoadAddress), - proctype_image_info.imageLoadAddress) + EXPECT_EQ(proctype_image_info.imageLoadAddress, + reinterpret_cast(self_image_info->imageLoadAddress)) << "index " << index; - EXPECT_EQ(reinterpret_cast(self_image_info->imageFilePath), - proctype_image_info.imageFilePath) + EXPECT_EQ(proctype_image_info.imageFilePath, + reinterpret_cast(self_image_info->imageFilePath)) << "index " << index; - EXPECT_EQ(implicit_cast(self_image_info->imageFileModDate), - proctype_image_info.imageFileModDate) + EXPECT_EQ(proctype_image_info.imageFileModDate, + implicit_cast(self_image_info->imageFileModDate)) << "index " << index; TEST_STRING( @@ -347,13 +348,13 @@ TEST(ProcessTypes, DyldImagesSelf) { const process_types::dyld_uuid_info& proctype_uuid_info = proctype_uuid_info_vector[index]; - EXPECT_EQ(reinterpret_cast(self_uuid_info->imageLoadAddress), - proctype_uuid_info.imageLoadAddress) + EXPECT_EQ(proctype_uuid_info.imageLoadAddress, + reinterpret_cast(self_uuid_info->imageLoadAddress)) << "index " << index; - EXPECT_EQ(0, - memcmp(self_uuid_info->imageUUID, + EXPECT_EQ(memcmp(self_uuid_info->imageUUID, proctype_uuid_info.imageUUID, - sizeof(self_uuid_info->imageUUID))) + sizeof(self_uuid_info->imageUUID)), + 0) << "index " << index; } } diff --git a/snapshot/mac/system_snapshot_mac_test.cc b/snapshot/mac/system_snapshot_mac_test.cc index aff773f3..f21d9a27 100644 --- a/snapshot/mac/system_snapshot_mac_test.cc +++ b/snapshot/mac/system_snapshot_mac_test.cc @@ -52,7 +52,7 @@ class SystemSnapshotMacTest : public testing::Test { // testing::Test: void SetUp() override { ASSERT_TRUE(process_reader_.Initialize(mach_task_self())); - ASSERT_EQ(0, gettimeofday(&snapshot_time_, nullptr)) + ASSERT_EQ(gettimeofday(&snapshot_time_, nullptr), 0) << ErrnoMessage("gettimeofday"); system_snapshot_.Initialize(&process_reader_, &snapshot_time_); } @@ -69,9 +69,9 @@ TEST_F(SystemSnapshotMacTest, GetCPUArchitecture) { CPUArchitecture cpu_architecture = system_snapshot().GetCPUArchitecture(); #if defined(ARCH_CPU_X86) - EXPECT_EQ(kCPUArchitectureX86, cpu_architecture); + EXPECT_EQ(cpu_architecture, kCPUArchitectureX86); #elif defined(ARCH_CPU_X86_64) - EXPECT_EQ(kCPUArchitectureX86_64, cpu_architecture); + EXPECT_EQ(cpu_architecture, kCPUArchitectureX86_64); #else #error port to your architecture #endif @@ -105,8 +105,8 @@ TEST_F(SystemSnapshotMacTest, CPUX86SupportsDAZ) { #endif TEST_F(SystemSnapshotMacTest, GetOperatingSystem) { - EXPECT_EQ(SystemSnapshot::kOperatingSystemMacOSX, - system_snapshot().GetOperatingSystem()); + EXPECT_EQ(system_snapshot().GetOperatingSystem(), + SystemSnapshot::kOperatingSystemMacOSX); } TEST_F(SystemSnapshotMacTest, OSVersion) { @@ -116,8 +116,8 @@ TEST_F(SystemSnapshotMacTest, OSVersion) { std::string build; system_snapshot().OSVersion(&major, &minor, &bugfix, &build); - EXPECT_EQ(10, major); - EXPECT_EQ(MacOSXMinorVersion(), minor); + EXPECT_EQ(major, 10); + EXPECT_EQ(minor, MacOSXMinorVersion()); EXPECT_FALSE(build.empty()); } @@ -138,15 +138,15 @@ class ScopedSetTZ { old_tz_.assign(old_tz); } - EXPECT_EQ(0, setenv(kTZ, tz.c_str(), 1)) << ErrnoMessage("setenv"); + EXPECT_EQ(setenv(kTZ, tz.c_str(), 1), 0) << ErrnoMessage("setenv"); tzset(); } ~ScopedSetTZ() { if (old_tz_set_) { - EXPECT_EQ(0, setenv(kTZ, old_tz_.c_str(), 1)) << ErrnoMessage("setenv"); + EXPECT_EQ(setenv(kTZ, old_tz_.c_str(), 1), 0) << ErrnoMessage("setenv"); } else { - EXPECT_EQ(0, unsetenv(kTZ)) << ErrnoMessage("unsetenv"); + EXPECT_EQ(unsetenv(kTZ), 0) << ErrnoMessage("unsetenv"); } tzset(); } @@ -177,20 +177,20 @@ TEST_F(SystemSnapshotMacTest, TimeZone) { // |standard_offset_seconds| gives seconds east of UTC, and |timezone| gives // seconds west of UTC. - EXPECT_EQ(-timezone, standard_offset_seconds); + EXPECT_EQ(standard_offset_seconds, -timezone); // In contemporary usage, most time zones have an integer hour offset from // UTC, although several are at a half-hour offset, and two are at 15-minute // offsets. Throughout history, other variations existed. See // http://www.timeanddate.com/time/time-zones-interesting.html. - EXPECT_EQ(0, standard_offset_seconds % (15 * 60)) + EXPECT_EQ(standard_offset_seconds % (15 * 60), 0) << "standard_offset_seconds " << standard_offset_seconds; if (dst_status == SystemSnapshot::kDoesNotObserveDaylightSavingTime) { - EXPECT_EQ(standard_offset_seconds, daylight_offset_seconds); - EXPECT_EQ(standard_name, daylight_name); + EXPECT_EQ(daylight_offset_seconds, standard_offset_seconds); + EXPECT_EQ(daylight_name, standard_name); } else { - EXPECT_EQ(0, daylight_offset_seconds % (15 * 60)) + EXPECT_EQ(daylight_offset_seconds % (15 * 60), 0) << "daylight_offset_seconds " << daylight_offset_seconds; // In contemporary usage, dst_delta_seconds will almost always be one hour, @@ -207,6 +207,9 @@ TEST_F(SystemSnapshotMacTest, TimeZone) { // Test a variety of time zones. Some of these observe daylight saving time, // some don’t. Some used to but no longer do. Some have uncommon UTC offsets. + // standard_name and daylight_name can be nullptr where no name exists to + // verify, as may happen when some versions of the timezone database carry + // invented names and others do not. const struct { const char* tz; bool observes_dst; @@ -229,8 +232,8 @@ TEST_F(SystemSnapshotMacTest, TimeZone) { {"Australia/Adelaide", true, 9.5, 10.5, "ACST", "ACDT"}, {"Australia/Brisbane", false, 10, 10, "AEST", "AEST"}, {"Australia/Darwin", false, 9.5, 9.5, "ACST", "ACST"}, - {"Australia/Eucla", false, 8.75, 8.75, "ACWST", "ACWST"}, - {"Australia/Lord_Howe", true, 10.5, 11, "LHST", "LHDT"}, + {"Australia/Eucla", false, 8.75, 8.75, nullptr, nullptr}, + {"Australia/Lord_Howe", true, 10.5, 11, nullptr, nullptr}, {"Australia/Perth", false, 8, 8, "AWST", "AWST"}, {"Australia/Sydney", true, 10, 11, "AEST", "AEDT"}, {"Europe/Bucharest", true, 2, 3, "EET", "EEST"}, @@ -257,14 +260,18 @@ TEST_F(SystemSnapshotMacTest, TimeZone) { &daylight_name); } - EXPECT_EQ(test_time_zone.observes_dst, - dst_status != SystemSnapshot::kDoesNotObserveDaylightSavingTime); - EXPECT_EQ(test_time_zone.standard_offset_hours * 60 * 60, - standard_offset_seconds); - EXPECT_EQ(test_time_zone.daylight_offset_hours * 60 * 60, - daylight_offset_seconds); - EXPECT_EQ(test_time_zone.standard_name, standard_name); - EXPECT_EQ(test_time_zone.daylight_name, daylight_name); + EXPECT_EQ(dst_status != SystemSnapshot::kDoesNotObserveDaylightSavingTime, + test_time_zone.observes_dst); + EXPECT_EQ(standard_offset_seconds, + test_time_zone.standard_offset_hours * 60 * 60); + EXPECT_EQ(daylight_offset_seconds, + test_time_zone.daylight_offset_hours * 60 * 60); + if (test_time_zone.standard_name) { + EXPECT_EQ(standard_name, test_time_zone.standard_name); + } + if (test_time_zone.daylight_name) { + EXPECT_EQ(daylight_name, test_time_zone.daylight_name); + } } } diff --git a/snapshot/minidump/process_snapshot_minidump_test.cc b/snapshot/minidump/process_snapshot_minidump_test.cc index 946c1c49..cb42c396 100644 --- a/snapshot/minidump/process_snapshot_minidump_test.cc +++ b/snapshot/minidump/process_snapshot_minidump_test.cc @@ -60,7 +60,7 @@ TEST(ProcessSnapshotMinidump, Empty) { UUID client_id; process_snapshot.ClientID(&client_id); - EXPECT_EQ(UUID(), client_id); + EXPECT_EQ(client_id, UUID()); EXPECT_TRUE(process_snapshot.AnnotationsSimpleMap().empty()); } @@ -167,7 +167,7 @@ TEST(ProcessSnapshotMinidump, ClientID) { UUID actual_client_id; process_snapshot.ClientID(&actual_client_id); - EXPECT_EQ(client_id, actual_client_id); + EXPECT_EQ(actual_client_id, client_id); EXPECT_TRUE(process_snapshot.AnnotationsSimpleMap().empty()); } @@ -209,10 +209,10 @@ TEST(ProcessSnapshotMinidump, AnnotationsSimpleMap) { UUID client_id; process_snapshot.ClientID(&client_id); - EXPECT_EQ(UUID(), client_id); + EXPECT_EQ(client_id, UUID()); const auto annotations_simple_map = process_snapshot.AnnotationsSimpleMap(); - EXPECT_EQ(dictionary, annotations_simple_map); + EXPECT_EQ(annotations_simple_map, dictionary); } TEST(ProcessSnapshotMinidump, Modules) { @@ -313,10 +313,10 @@ TEST(ProcessSnapshotMinidump, Modules) { EXPECT_TRUE(process_snapshot.Initialize(&string_file)); std::vector modules = process_snapshot.Modules(); - ASSERT_EQ(minidump_module_count, modules.size()); + ASSERT_EQ(modules.size(), minidump_module_count); auto annotations_simple_map = modules[0]->AnnotationsSimpleMap(); - EXPECT_EQ(dictionary_0, annotations_simple_map); + EXPECT_EQ(annotations_simple_map, dictionary_0); auto annotations_vector = modules[0]->AnnotationsVector(); EXPECT_TRUE(annotations_vector.empty()); @@ -328,10 +328,10 @@ TEST(ProcessSnapshotMinidump, Modules) { EXPECT_TRUE(annotations_vector.empty()); annotations_simple_map = modules[2]->AnnotationsSimpleMap(); - EXPECT_EQ(dictionary_2, annotations_simple_map); + EXPECT_EQ(annotations_simple_map, dictionary_2); annotations_vector = modules[2]->AnnotationsVector(); - EXPECT_EQ(list_annotations_2, annotations_vector); + EXPECT_EQ(annotations_vector, list_annotations_2); } } // namespace diff --git a/snapshot/win/cpu_context_win_test.cc b/snapshot/win/cpu_context_win_test.cc index b2e6aae5..41adde3a 100644 --- a/snapshot/win/cpu_context_win_test.cc +++ b/snapshot/win/cpu_context_win_test.cc @@ -41,9 +41,9 @@ void TestInitializeX86Context() { { CPUContextX86 cpu_context_x86 = {}; InitializeX86Context(context, &cpu_context_x86); - EXPECT_EQ(1u, cpu_context_x86.eax); - EXPECT_EQ(2u, cpu_context_x86.fxsave.ftw); - EXPECT_EQ(3u, cpu_context_x86.dr0); + EXPECT_EQ(cpu_context_x86.eax, 1u); + EXPECT_EQ(cpu_context_x86.fxsave.ftw, 2u); + EXPECT_EQ(cpu_context_x86.dr0, 3u); } } @@ -74,29 +74,29 @@ void TestInitializeX86Context_FsaveWithoutFxsave() { CPUContextX86 cpu_context_x86 = {}; InitializeX86Context(context, &cpu_context_x86); - EXPECT_EQ(1u, cpu_context_x86.eax); + EXPECT_EQ(cpu_context_x86.eax, 1u); - EXPECT_EQ(0x027f, cpu_context_x86.fxsave.fcw); - EXPECT_EQ(0x0004, cpu_context_x86.fxsave.fsw); - EXPECT_EQ(0x00f0, cpu_context_x86.fxsave.ftw); - EXPECT_EQ(0x0bad, cpu_context_x86.fxsave.fop); - EXPECT_EQ(0x01234567, cpu_context_x86.fxsave.fpu_ip); - EXPECT_EQ(0x0003, cpu_context_x86.fxsave.fpu_cs); - EXPECT_EQ(0x89abcdef, cpu_context_x86.fxsave.fpu_dp); - EXPECT_EQ(0x0007, cpu_context_x86.fxsave.fpu_ds); + EXPECT_EQ(cpu_context_x86.fxsave.fcw, 0x027f); + EXPECT_EQ(cpu_context_x86.fxsave.fsw, 0x0004); + EXPECT_EQ(cpu_context_x86.fxsave.ftw, 0x00f0); + EXPECT_EQ(cpu_context_x86.fxsave.fop, 0x0bad); + EXPECT_EQ(cpu_context_x86.fxsave.fpu_ip, 0x01234567); + EXPECT_EQ(cpu_context_x86.fxsave.fpu_cs, 0x0003); + EXPECT_EQ(cpu_context_x86.fxsave.fpu_dp, 0x89abcdef); + EXPECT_EQ(cpu_context_x86.fxsave.fpu_ds, 0x0007); for (size_t st_mm = 0; st_mm < 7; ++st_mm) { EXPECT_EQ( - std::string(arraysize(cpu_context_x86.fxsave.st_mm[st_mm].st) * 2, - '0'), BytesToHexString(cpu_context_x86.fxsave.st_mm[st_mm].st, - arraysize(cpu_context_x86.fxsave.st_mm[st_mm].st))) + arraysize(cpu_context_x86.fxsave.st_mm[st_mm].st)), + std::string(arraysize(cpu_context_x86.fxsave.st_mm[st_mm].st) * 2, + '0')) << "st_mm " << st_mm; } - EXPECT_EQ("0000000000000080ff7f", - BytesToHexString(cpu_context_x86.fxsave.st_mm[7].st, - arraysize(cpu_context_x86.fxsave.st_mm[7].st))); + EXPECT_EQ(BytesToHexString(cpu_context_x86.fxsave.st_mm[7].st, + arraysize(cpu_context_x86.fxsave.st_mm[7].st)), + "0000000000000080ff7f"); - EXPECT_EQ(3u, cpu_context_x86.dr0); + EXPECT_EQ(cpu_context_x86.dr0, 3u); } } @@ -117,9 +117,9 @@ TEST(CPUContextWin, InitializeX64Context) { { CPUContextX86_64 cpu_context_x86_64 = {}; InitializeX64Context(context, &cpu_context_x86_64); - EXPECT_EQ(10u, cpu_context_x86_64.rax); - EXPECT_EQ(11u, cpu_context_x86_64.fxsave.ftw); - EXPECT_EQ(12u, cpu_context_x86_64.dr0); + EXPECT_EQ(cpu_context_x86_64.rax, 10u); + EXPECT_EQ(cpu_context_x86_64.fxsave.ftw, 11u); + EXPECT_EQ(cpu_context_x86_64.dr0, 12u); } } diff --git a/snapshot/win/crashpad_snapshot_test_image_reader.cc b/snapshot/win/crashpad_snapshot_test_image_reader.cc index a114d392..6f4203d6 100644 --- a/snapshot/win/crashpad_snapshot_test_image_reader.cc +++ b/snapshot/win/crashpad_snapshot_test_image_reader.cc @@ -17,10 +17,14 @@ #include "base/logging.h" #include "client/crashpad_info.h" #include "util/file/file_io.h" +#include "util/synchronization/semaphore.h" #include "util/win/scoped_handle.h" +namespace { + DWORD WINAPI LotsOfReferencesThreadProc(void* param) { - LONG* count = reinterpret_cast(param); + crashpad::Semaphore* semaphore = + reinterpret_cast(param); // Allocate a bunch of pointers to things on the stack. int* pointers[1000]; @@ -28,28 +32,31 @@ DWORD WINAPI LotsOfReferencesThreadProc(void* param) { pointers[i] = new int[2048]; } - InterlockedIncrement(count); + semaphore->Signal(); Sleep(INFINITE); return 0; } +} // namespace + int wmain(int argc, wchar_t* argv[]) { CHECK_EQ(argc, 2); crashpad::ScopedKernelHANDLE done(CreateEvent(nullptr, true, false, argv[1])); + PCHECK(done.is_valid()) << "CreateEvent"; PCHECK(LoadLibrary(L"crashpad_snapshot_test_image_reader_module.dll")) << "LoadLibrary"; // Create threads with lots of stack pointers to memory. This is used to // verify the cap on pointed-to memory. - LONG thread_ready_count = 0; + crashpad::Semaphore semaphore(0); crashpad::ScopedKernelHANDLE threads[100]; for (int i = 0; i < arraysize(threads); ++i) { threads[i].reset(CreateThread(nullptr, 0, &LotsOfReferencesThreadProc, - reinterpret_cast(&thread_ready_count), + reinterpret_cast(&semaphore), 0, nullptr)); if (!threads[i].is_valid()) { @@ -58,14 +65,8 @@ int wmain(int argc, wchar_t* argv[]) { } } - for (;;) { - if (InterlockedCompareExchange(&thread_ready_count, - arraysize(threads), - arraysize(threads) == arraysize(threads))) { - // All threads have allocated their references. - break; - } - Sleep(10); + for (int i = 0; i < arraysize(threads); ++i) { + semaphore.Wait(); } crashpad::CrashpadInfo* crashpad_info = @@ -80,8 +81,8 @@ int wmain(int argc, wchar_t* argv[]) { crashpad::CheckedWriteFile(out, &c, sizeof(c)); // Parent process says we can exit. - CHECK_EQ(WAIT_OBJECT_0, WaitForSingleObject(done.get(), INFINITE)); + PCHECK(WaitForSingleObject(done.get(), INFINITE) == WAIT_OBJECT_0) + << "WaitForSingleObject"; return 0; } - diff --git a/snapshot/win/end_to_end_test.py b/snapshot/win/end_to_end_test.py index 42999df8..5afdac38 100755 --- a/snapshot/win/end_to_end_test.py +++ b/snapshot/win/end_to_end_test.py @@ -22,6 +22,7 @@ import subprocess import sys import tempfile import time +import win32con g_temp_dirs = [] @@ -80,23 +81,23 @@ def GetCdbPath(): return None -def GetDumpFromProgram(out_dir, pipe_name, executable_name, *args): +def GetDumpFromProgram( + out_dir, pipe_name, executable_name, expect_exit_code, *args): """Initialize a crash database, and run |executable_name| connecting to a crash handler. If pipe_name is set, crashpad_handler will be started first. If pipe_name is empty, the executable is responsible for starting crashpad_handler. *args will be passed after other arguments to - executable_name. Returns the minidump generated by crashpad_handler for - further testing. + executable_name. If the child process does not exit with |expect_exit_code|, + an exception will be raised. Returns the path to the minidump generated by + crashpad_handler for further testing. """ test_database = MakeTempDir() handler = None try: - if subprocess.call( + subprocess.check_call( [os.path.join(out_dir, 'crashpad_database_util.exe'), '--create', - '--database=' + test_database]) != 0: - print 'could not initialize report database' - return None + '--database=' + test_database]) if pipe_name is not None: handler = subprocess.Popen([ @@ -113,12 +114,16 @@ def GetDumpFromProgram(out_dir, pipe_name, executable_name, *args): printed = True time.sleep(0.1) - subprocess.call([os.path.join(out_dir, executable_name), pipe_name] + - list(args)) + exit_code = subprocess.call( + [os.path.join(out_dir, executable_name), pipe_name] + list(args)) else: - subprocess.call([os.path.join(out_dir, executable_name), - os.path.join(out_dir, 'crashpad_handler.com'), - test_database] + list(args)) + exit_code = subprocess.call( + [os.path.join(out_dir, executable_name), + os.path.join(out_dir, 'crashpad_handler.com'), + test_database] + + list(args)) + if exit_code != expect_exit_code: + raise CalledProcessError(exit_code, executable_name) out = subprocess.check_output([ os.path.join(out_dir, 'crashpad_database_util.exe'), @@ -135,24 +140,38 @@ def GetDumpFromProgram(out_dir, pipe_name, executable_name, *args): def GetDumpFromCrashyProgram(out_dir, pipe_name): - return GetDumpFromProgram(out_dir, pipe_name, 'crashy_program.exe') + return GetDumpFromProgram(out_dir, + pipe_name, + 'crashy_program.exe', + win32con.EXCEPTION_ACCESS_VIOLATION) def GetDumpFromOtherProgram(out_dir, pipe_name, *args): - return GetDumpFromProgram(out_dir, pipe_name, 'crash_other_program.exe', - *args) + return GetDumpFromProgram( + out_dir, pipe_name, 'crash_other_program.exe', 0, *args) def GetDumpFromSignal(out_dir, pipe_name, *args): - return GetDumpFromProgram(out_dir, pipe_name, 'crashy_signal.exe', *args) + STATUS_FATAL_APP_EXIT = 0x40000015 # Not known by win32con. + return GetDumpFromProgram(out_dir, + pipe_name, + 'crashy_signal.exe', + STATUS_FATAL_APP_EXIT, + *args) def GetDumpFromSelfDestroyingProgram(out_dir, pipe_name): - return GetDumpFromProgram(out_dir, pipe_name, 'self_destroying_program.exe') + return GetDumpFromProgram(out_dir, + pipe_name, + 'self_destroying_program.exe', + win32con.EXCEPTION_BREAKPOINT) def GetDumpFromZ7Program(out_dir, pipe_name): - return GetDumpFromProgram(out_dir, pipe_name, 'crashy_z7_loader.exe') + return GetDumpFromProgram(out_dir, + pipe_name, + 'crashy_z7_loader.exe', + win32con.EXCEPTION_ACCESS_VIOLATION) class CdbRun(object): diff --git a/snapshot/win/exception_snapshot_win_test.cc b/snapshot/win/exception_snapshot_win_test.cc index 03aa0499..e2776964 100644 --- a/snapshot/win/exception_snapshot_win_test.cc +++ b/snapshot/win/exception_snapshot_win_test.cc @@ -22,7 +22,8 @@ #include "client/crashpad_client.h" #include "gtest/gtest.h" #include "snapshot/win/process_snapshot_win.h" -#include "test/paths.h" +#include "test/errors.h" +#include "test/test_paths.h" #include "test/win/child_launcher.h" #include "util/file/file_io.h" #include "util/thread/thread.h" @@ -96,7 +97,7 @@ class CrashingDelegate : public ExceptionHandlerServer::Delegate { // Confirm the exception record was read correctly. EXPECT_NE(snapshot.Exception()->ThreadID(), 0u); - EXPECT_EQ(snapshot.Exception()->Exception(), EXCEPTION_BREAKPOINT); + EXPECT_EQ(EXCEPTION_BREAKPOINT, snapshot.Exception()->Exception()); // Verify the exception happened at the expected location with a bit of // slop space to allow for reading the current PC before the exception @@ -122,7 +123,9 @@ class CrashingDelegate : public ExceptionHandlerServer::Delegate { void TestCrashingChild(const base::string16& directory_modification) { // Set up the registration server on a background thread. ScopedKernelHANDLE server_ready(CreateEvent(nullptr, false, false, nullptr)); + ASSERT_TRUE(server_ready.is_valid()) << ErrorMessage("CreateEvent"); ScopedKernelHANDLE completed(CreateEvent(nullptr, false, false, nullptr)); + ASSERT_TRUE(completed.is_valid()) << ErrorMessage("CreateEvent"); CrashingDelegate delegate(server_ready.get(), completed.get()); ExceptionHandlerServer exception_handler_server(true); @@ -133,10 +136,11 @@ void TestCrashingChild(const base::string16& directory_modification) { ScopedStopServerAndJoinThread scoped_stop_server_and_join_thread( &exception_handler_server, &server_thread); - WaitForSingleObject(server_ready.get(), INFINITE); + EXPECT_EQ(WaitForSingleObject(server_ready.get(), INFINITE), WAIT_OBJECT_0) + << ErrorMessage("WaitForSingleObject"); // Spawn a child process, passing it the pipe name to connect to. - base::FilePath test_executable = Paths::Executable(); + base::FilePath test_executable = TestPaths::Executable(); std::wstring child_test_executable = test_executable.DirName() .Append(directory_modification) @@ -154,7 +158,10 @@ void TestCrashingChild(const base::string16& directory_modification) { delegate.set_break_near(break_near_address); // Wait for the child to crash and the exception information to be validated. - WaitForSingleObject(completed.get(), INFINITE); + EXPECT_EQ(WaitForSingleObject(completed.get(), INFINITE), WAIT_OBJECT_0) + << ErrorMessage("WaitForSingleObject"); + + EXPECT_EQ(child.WaitForExit(), EXCEPTION_BREAKPOINT); } TEST(ExceptionSnapshotWinTest, ChildCrash) { @@ -194,7 +201,7 @@ class SimulateDelegate : public ExceptionHandlerServer::Delegate { exception_information_address, debug_critical_section_address); EXPECT_TRUE(snapshot.Exception()); - EXPECT_EQ(0x517a7ed, snapshot.Exception()->Exception()); + EXPECT_EQ(snapshot.Exception()->Exception(), 0x517a7ed); // Verify the dump was captured at the expected location with some slop // space. @@ -204,8 +211,8 @@ class SimulateDelegate : public ExceptionHandlerServer::Delegate { EXPECT_LT(snapshot.Exception()->Context()->InstructionPointer(), dump_near_ + kAllowedOffset); - EXPECT_EQ(snapshot.Exception()->Context()->InstructionPointer(), - snapshot.Exception()->ExceptionAddress()); + EXPECT_EQ(snapshot.Exception()->ExceptionAddress(), + snapshot.Exception()->Context()->InstructionPointer()); SetEvent(completed_test_event_); @@ -224,7 +231,9 @@ void TestDumpWithoutCrashingChild( const base::string16& directory_modification) { // Set up the registration server on a background thread. ScopedKernelHANDLE server_ready(CreateEvent(nullptr, false, false, nullptr)); + ASSERT_TRUE(server_ready.is_valid()) << ErrorMessage("CreateEvent"); ScopedKernelHANDLE completed(CreateEvent(nullptr, false, false, nullptr)); + ASSERT_TRUE(completed.is_valid()) << ErrorMessage("CreateEvent"); SimulateDelegate delegate(server_ready.get(), completed.get()); ExceptionHandlerServer exception_handler_server(true); @@ -235,10 +244,11 @@ void TestDumpWithoutCrashingChild( ScopedStopServerAndJoinThread scoped_stop_server_and_join_thread( &exception_handler_server, &server_thread); - WaitForSingleObject(server_ready.get(), INFINITE); + EXPECT_EQ(WaitForSingleObject(server_ready.get(), INFINITE), WAIT_OBJECT_0) + << ErrorMessage("WaitForSingleObject"); // Spawn a child process, passing it the pipe name to connect to. - base::FilePath test_executable = Paths::Executable(); + base::FilePath test_executable = TestPaths::Executable(); std::wstring child_test_executable = test_executable.DirName() .Append(directory_modification) @@ -256,7 +266,10 @@ void TestDumpWithoutCrashingChild( delegate.set_dump_near(dump_near_address); // Wait for the child to crash and the exception information to be validated. - WaitForSingleObject(completed.get(), INFINITE); + EXPECT_EQ(WaitForSingleObject(completed.get(), INFINITE), WAIT_OBJECT_0) + << ErrorMessage("WaitForSingleObject"); + + EXPECT_EQ(child.WaitForExit(), 0); } TEST(SimulateCrash, ChildDumpWithoutCrashing) { diff --git a/snapshot/win/extra_memory_ranges_test.cc b/snapshot/win/extra_memory_ranges_test.cc index 57d41bb5..49d835f0 100644 --- a/snapshot/win/extra_memory_ranges_test.cc +++ b/snapshot/win/extra_memory_ranges_test.cc @@ -25,7 +25,7 @@ #include "client/simple_address_range_bag.h" #include "gtest/gtest.h" #include "snapshot/win/process_snapshot_win.h" -#include "test/paths.h" +#include "test/test_paths.h" #include "test/win/child_launcher.h" #include "util/file/file_io.h" #include "util/win/process_info.h" @@ -45,7 +45,7 @@ enum TestType { void TestExtraMemoryRanges(TestType type, const base::string16& directory_modification) { // Spawn a child process, passing it the pipe name to connect to. - base::FilePath test_executable = Paths::Executable(); + base::FilePath test_executable = TestPaths::Executable(); std::wstring child_test_executable = test_executable.DirName() .Append(directory_modification) @@ -71,15 +71,15 @@ void TestExtraMemoryRanges(TestType type, all_ranges.insert(range); } - EXPECT_EQ(5u, all_ranges.size()); - EXPECT_NE(all_ranges.end(), all_ranges.find(CheckedRange(0, 1))); - EXPECT_NE(all_ranges.end(), all_ranges.find(CheckedRange(1, 0))); - EXPECT_NE(all_ranges.end(), - all_ranges.find(CheckedRange(1234, 5678))); - EXPECT_NE(all_ranges.end(), - all_ranges.find(CheckedRange(0x1000000000ULL, 0x1000))); - EXPECT_NE(all_ranges.end(), - all_ranges.find(CheckedRange(0x2000, 0x2000000000ULL))); + EXPECT_EQ(all_ranges.size(), 5u); + EXPECT_NE(all_ranges.find(CheckedRange(0, 1)), all_ranges.end()); + EXPECT_NE(all_ranges.find(CheckedRange(1, 0)), all_ranges.end()); + EXPECT_NE(all_ranges.find(CheckedRange(1234, 5678)), + all_ranges.end()); + EXPECT_NE(all_ranges.find(CheckedRange(0x1000000000ULL, 0x1000)), + all_ranges.end()); + EXPECT_NE(all_ranges.find(CheckedRange(0x2000, 0x2000000000ULL)), + all_ranges.end()); // Tell the child process to continue. DWORD expected_exit_code; @@ -97,7 +97,7 @@ void TestExtraMemoryRanges(TestType type, } CheckedWriteFile(child.stdin_write_handle(), &c, sizeof(c)); - EXPECT_EQ(expected_exit_code, child.WaitForExit()); + EXPECT_EQ(child.WaitForExit(), expected_exit_code); } TEST(ExtraMemoryRanges, DontCrash) { diff --git a/snapshot/win/pe_image_annotations_reader_test.cc b/snapshot/win/pe_image_annotations_reader_test.cc index f791f80e..02a61232 100644 --- a/snapshot/win/pe_image_annotations_reader_test.cc +++ b/snapshot/win/pe_image_annotations_reader_test.cc @@ -29,7 +29,7 @@ #include "gtest/gtest.h" #include "snapshot/win/pe_image_reader.h" #include "snapshot/win/process_reader_win.h" -#include "test/paths.h" +#include "test/test_paths.h" #include "test/win/child_launcher.h" #include "util/file/file_io.h" #include "util/win/process_info.h" @@ -49,7 +49,7 @@ enum TestType { void TestAnnotationsOnCrash(TestType type, const base::string16& directory_modification) { // Spawn a child process, passing it the pipe name to connect to. - base::FilePath test_executable = Paths::Executable(); + base::FilePath test_executable = TestPaths::Executable(); std::wstring child_test_executable = test_executable.DirName() .Append(directory_modification) @@ -86,11 +86,11 @@ void TestAnnotationsOnCrash(TestType type, } EXPECT_GE(all_annotations_simple_map.size(), 5u); - EXPECT_EQ("crash", all_annotations_simple_map["#TEST# pad"]); - EXPECT_EQ("value", all_annotations_simple_map["#TEST# key"]); - EXPECT_EQ("y", all_annotations_simple_map["#TEST# x"]); - EXPECT_EQ("shorter", all_annotations_simple_map["#TEST# longer"]); - EXPECT_EQ("", all_annotations_simple_map["#TEST# empty_value"]); + EXPECT_EQ(all_annotations_simple_map["#TEST# pad"], "crash"); + EXPECT_EQ(all_annotations_simple_map["#TEST# key"], "value"); + EXPECT_EQ(all_annotations_simple_map["#TEST# x"], "y"); + EXPECT_EQ(all_annotations_simple_map["#TEST# longer"], "shorter"); + EXPECT_EQ(all_annotations_simple_map["#TEST# empty_value"], ""); // Tell the child process to continue. DWORD expected_exit_code; @@ -108,7 +108,7 @@ void TestAnnotationsOnCrash(TestType type, } CheckedWriteFile(child.stdin_write_handle(), &c, sizeof(c)); - EXPECT_EQ(expected_exit_code, child.WaitForExit()); + EXPECT_EQ(child.WaitForExit(), expected_exit_code); } TEST(PEImageAnnotationsReader, DontCrash) { diff --git a/snapshot/win/pe_image_reader_test.cc b/snapshot/win/pe_image_reader_test.cc index 704b6591..2468c140 100644 --- a/snapshot/win/pe_image_reader_test.cc +++ b/snapshot/win/pe_image_reader_test.cc @@ -42,7 +42,7 @@ TEST(PEImageReader, DebugDirectory) { ASSERT_TRUE(CrashpadGetModuleInformation( GetCurrentProcess(), self, &module_info, sizeof(module_info))) << ErrorMessage("GetModuleInformation"); - EXPECT_EQ(self, module_info.lpBaseOfDll); + EXPECT_EQ(module_info.lpBaseOfDll, self); ASSERT_TRUE(pe_image_reader.Initialize(&process_reader, reinterpret_cast(self), module_info.SizeOfImage, @@ -51,11 +51,11 @@ TEST(PEImageReader, DebugDirectory) { DWORD age; std::string pdbname; EXPECT_TRUE(pe_image_reader.DebugDirectoryInformation(&uuid, &age, &pdbname)); - EXPECT_NE(std::string::npos, pdbname.find("crashpad_snapshot_test")); + EXPECT_NE(pdbname.find("crashpad_snapshot_test"), std::string::npos); const std::string suffix(".pdb"); EXPECT_EQ( - 0, - pdbname.compare(pdbname.size() - suffix.size(), suffix.size(), suffix)); + pdbname.compare(pdbname.size() - suffix.size(), suffix.size(), suffix), + 0); } void TestVSFixedFileInfo(ProcessReaderWin* process_reader, @@ -72,12 +72,12 @@ void TestVSFixedFileInfo(ProcessReaderWin* process_reader, ASSERT_TRUE(observed_rv || !known_dll); if (observed_rv) { - EXPECT_EQ(VS_FFI_SIGNATURE, observed.dwSignature); - EXPECT_EQ(VS_FFI_STRUCVERSION, observed.dwStrucVersion); - EXPECT_EQ(0, observed.dwFileFlags & ~observed.dwFileFlagsMask); - EXPECT_EQ(VOS_NT_WINDOWS32, observed.dwFileOS); + EXPECT_EQ(observed.dwSignature, VS_FFI_SIGNATURE); + EXPECT_EQ(observed.dwStrucVersion, VS_FFI_STRUCVERSION); + EXPECT_EQ(observed.dwFileFlags & ~observed.dwFileFlagsMask, 0); + EXPECT_EQ(observed.dwFileOS, VOS_NT_WINDOWS32); if (known_dll) { - EXPECT_EQ(VFT_DLL, observed.dwFileType); + EXPECT_EQ(observed.dwFileType, VFT_DLL); } else { EXPECT_TRUE(observed.dwFileType == VFT_APP || observed.dwFileType == VFT_DLL); @@ -103,22 +103,22 @@ void TestVSFixedFileInfo(ProcessReaderWin* process_reader, const bool expected_rv = GetModuleVersionAndType(module_path, &expected); ASSERT_TRUE(expected_rv || !known_dll); - EXPECT_EQ(expected_rv, observed_rv); + EXPECT_EQ(observed_rv, expected_rv); if (observed_rv && expected_rv) { - EXPECT_EQ(expected.dwSignature, observed.dwSignature); - EXPECT_EQ(expected.dwStrucVersion, observed.dwStrucVersion); - EXPECT_EQ(expected.dwFileVersionMS, observed.dwFileVersionMS); - EXPECT_EQ(expected.dwFileVersionLS, observed.dwFileVersionLS); - EXPECT_EQ(expected.dwProductVersionMS, observed.dwProductVersionMS); - EXPECT_EQ(expected.dwProductVersionLS, observed.dwProductVersionLS); - EXPECT_EQ(expected.dwFileFlagsMask, observed.dwFileFlagsMask); - EXPECT_EQ(expected.dwFileFlags, observed.dwFileFlags); - EXPECT_EQ(expected.dwFileOS, observed.dwFileOS); - EXPECT_EQ(expected.dwFileType, observed.dwFileType); - EXPECT_EQ(expected.dwFileSubtype, observed.dwFileSubtype); - EXPECT_EQ(expected.dwFileDateMS, observed.dwFileDateMS); - EXPECT_EQ(expected.dwFileDateLS, observed.dwFileDateLS); + EXPECT_EQ(observed.dwSignature, expected.dwSignature); + EXPECT_EQ(observed.dwStrucVersion, expected.dwStrucVersion); + EXPECT_EQ(observed.dwFileVersionMS, expected.dwFileVersionMS); + EXPECT_EQ(observed.dwFileVersionLS, expected.dwFileVersionLS); + EXPECT_EQ(observed.dwProductVersionMS, expected.dwProductVersionMS); + EXPECT_EQ(observed.dwProductVersionLS, expected.dwProductVersionLS); + EXPECT_EQ(observed.dwFileFlagsMask, expected.dwFileFlagsMask); + EXPECT_EQ(observed.dwFileFlags, expected.dwFileFlags); + EXPECT_EQ(observed.dwFileOS, expected.dwFileOS); + EXPECT_EQ(observed.dwFileType, expected.dwFileType); + EXPECT_EQ(observed.dwFileSubtype, expected.dwFileSubtype); + EXPECT_EQ(observed.dwFileDateMS, expected.dwFileDateMS); + EXPECT_EQ(observed.dwFileDateLS, expected.dwFileDateLS); } } @@ -135,7 +135,7 @@ TEST(PEImageReader, VSFixedFileInfo_OneModule) { ASSERT_TRUE(CrashpadGetModuleInformation( GetCurrentProcess(), module_handle, &module_info, sizeof(module_info))) << ErrorMessage("GetModuleInformation"); - EXPECT_EQ(module_handle, module_info.lpBaseOfDll); + EXPECT_EQ(module_info.lpBaseOfDll, module_handle); ProcessInfo::Module module; module.name = kModuleName; diff --git a/snapshot/win/process_reader_win.cc b/snapshot/win/process_reader_win.cc index b7bae6ac..f8a2f928 100644 --- a/snapshot/win/process_reader_win.cc +++ b/snapshot/win/process_reader_win.cc @@ -57,6 +57,7 @@ process_types::SYSTEM_PROCESS_INFORMATION* GetProcessInformation( HANDLE process_handle, std::unique_ptr* buffer) { ULONG buffer_size = 16384; + ULONG actual_size; buffer->reset(new uint8_t[buffer_size]); NTSTATUS status; // This must be in retry loop, as we're racing with process creation on the @@ -66,13 +67,19 @@ process_types::SYSTEM_PROCESS_INFORMATION* GetProcessInformation( SystemProcessInformation, reinterpret_cast(buffer->get()), buffer_size, - &buffer_size); + &actual_size); if (status == STATUS_BUFFER_TOO_SMALL || status == STATUS_INFO_LENGTH_MISMATCH) { + DCHECK_GT(actual_size, buffer_size); + // Add a little extra to try to avoid an additional loop iteration. We're // racing with system-wide process creation between here and the next call // to NtQuerySystemInformation(). - buffer_size += 4096; + buffer_size = actual_size + 4096; + + // Free the old buffer before attempting to allocate a new one. + buffer->reset(); + buffer->reset(new uint8_t[buffer_size]); } else { break; @@ -84,6 +91,8 @@ process_types::SYSTEM_PROCESS_INFORMATION* GetProcessInformation( return nullptr; } + DCHECK_LE(actual_size, buffer_size); + process_types::SYSTEM_PROCESS_INFORMATION* process = reinterpret_cast*>( buffer->get()); diff --git a/snapshot/win/process_reader_win_test.cc b/snapshot/win/process_reader_win_test.cc index af57c622..5b4b7d0a 100644 --- a/snapshot/win/process_reader_win_test.cc +++ b/snapshot/win/process_reader_win_test.cc @@ -38,7 +38,7 @@ TEST(ProcessReaderWin, SelfBasic) { EXPECT_TRUE(process_reader.Is64Bit()); #endif - EXPECT_EQ(GetCurrentProcessId(), process_reader.GetProcessInfo().ProcessID()); + EXPECT_EQ(process_reader.GetProcessInfo().ProcessID(), GetCurrentProcessId()); const char kTestMemory[] = "Some test memory"; char buffer[arraysize(kTestMemory)]; @@ -74,7 +74,7 @@ class ProcessReaderChild final : public WinMultiprocess { char buffer[sizeof(kTestMemory)]; ASSERT_TRUE( process_reader.ReadMemory(address, sizeof(kTestMemory), &buffer)); - EXPECT_EQ(0, strcmp(kTestMemory, buffer)); + EXPECT_EQ(strcmp(kTestMemory, buffer), 0); } void WinMultiprocessChild() override { @@ -106,14 +106,14 @@ TEST(ProcessReaderWin, SelfOneThread) { // thread, not exactly one thread. ASSERT_GE(threads.size(), 1u); - EXPECT_EQ(GetCurrentThreadId(), threads[0].id); + EXPECT_EQ(threads[0].id, GetCurrentThreadId()); #if defined(ARCH_CPU_64_BITS) - EXPECT_NE(0, threads[0].context.native.Rip); + EXPECT_NE(threads[0].context.native.Rip, 0); #else - EXPECT_NE(0u, threads[0].context.native.Eip); + EXPECT_NE(threads[0].context.native.Eip, 0u); #endif - EXPECT_EQ(0, threads[0].suspend_count); + EXPECT_EQ(threads[0].suspend_count, 0); } class ProcessReaderChildThreadSuspendCount final : public WinMultiprocess { @@ -143,7 +143,7 @@ class ProcessReaderChildThreadSuspendCount final : public WinMultiprocess { void WinMultiprocessParent() override { char c; CheckedReadFileExactly(ReadPipeHandle(), &c, sizeof(c)); - ASSERT_EQ(' ', c); + ASSERT_EQ(c, ' '); { ProcessReaderWin process_reader; @@ -153,7 +153,7 @@ class ProcessReaderChildThreadSuspendCount final : public WinMultiprocess { const auto& threads = process_reader.Threads(); ASSERT_GE(threads.size(), kCreatedThreads + 1); for (const auto& thread : threads) - EXPECT_EQ(0u, thread.suspend_count); + EXPECT_EQ(thread.suspend_count, 0u); } { @@ -168,7 +168,7 @@ class ProcessReaderChildThreadSuspendCount final : public WinMultiprocess { const auto& threads = process_reader.Threads(); ASSERT_GE(threads.size(), kCreatedThreads + 1); for (const auto& thread : threads) - EXPECT_EQ(0u, thread.suspend_count); + EXPECT_EQ(thread.suspend_count, 0u); } } diff --git a/snapshot/win/process_snapshot_win.cc b/snapshot/win/process_snapshot_win.cc index 7a18dbef..11df2b80 100644 --- a/snapshot/win/process_snapshot_win.cc +++ b/snapshot/win/process_snapshot_win.cc @@ -15,6 +15,7 @@ #include "snapshot/win/process_snapshot_win.h" #include +#include #include @@ -325,8 +326,9 @@ void ProcessSnapshotWin::InitializeUnloadedModules() { uet.SizeOfImage, uet.CheckSum, uet.TimeDateStamp, - base::UTF16ToUTF8( - base::StringPiece16(uet.ImageName, arraysize(uet.ImageName))))); + base::UTF16ToUTF8(base::StringPiece16( + uet.ImageName, + wcsnlen(uet.ImageName, arraysize(uet.ImageName)))))); } } } diff --git a/snapshot/win/process_snapshot_win_test.cc b/snapshot/win/process_snapshot_win_test.cc index 82b29035..75e6e708 100644 --- a/snapshot/win/process_snapshot_win_test.cc +++ b/snapshot/win/process_snapshot_win_test.cc @@ -20,7 +20,8 @@ #include "snapshot/win/module_snapshot_win.h" #include "snapshot/win/pe_image_reader.h" #include "snapshot/win/process_reader_win.h" -#include "test/paths.h" +#include "test/errors.h" +#include "test/test_paths.h" #include "test/win/child_launcher.h" #include "util/file/file_io.h" #include "util/win/scoped_handle.h" @@ -35,9 +36,9 @@ void TestImageReaderChild(const base::string16& directory_modification) { done_uuid.InitializeWithNew(); ScopedKernelHANDLE done( CreateEvent(nullptr, true, false, done_uuid.ToString16().c_str())); - ASSERT_TRUE(done.get()); + ASSERT_TRUE(done.is_valid()) << ErrorMessage("CreateEvent"); - base::FilePath test_executable = Paths::Executable(); + base::FilePath test_executable = TestPaths::Executable(); std::wstring child_test_executable = test_executable.DirName() .Append(directory_modification) @@ -50,61 +51,65 @@ void TestImageReaderChild(const base::string16& directory_modification) { char c; ASSERT_TRUE( LoggingReadFileExactly(child.stdout_read_handle(), &c, sizeof(c))); - ASSERT_EQ(' ', c); + ASSERT_EQ(c, ' '); - ScopedProcessSuspend suspend(child.process_handle()); + { + ScopedProcessSuspend suspend(child.process_handle()); - ProcessSnapshotWin process_snapshot; - ASSERT_TRUE(process_snapshot.Initialize( - child.process_handle(), ProcessSuspensionState::kSuspended, 0, 0)); + ProcessSnapshotWin process_snapshot; + ASSERT_TRUE(process_snapshot.Initialize( + child.process_handle(), ProcessSuspensionState::kSuspended, 0, 0)); - ASSERT_GE(process_snapshot.Modules().size(), 2u); + ASSERT_GE(process_snapshot.Modules().size(), 2u); - UUID uuid; - DWORD age; - std::string pdbname; - const std::string suffix(".pdb"); + UUID uuid; + DWORD age; + std::string pdbname; + const std::string suffix(".pdb"); - // Check the main .exe to see that we can retrieve its sections. - auto module = reinterpret_cast( - process_snapshot.Modules()[0]); - ASSERT_TRUE(module->pe_image_reader().DebugDirectoryInformation( - &uuid, &age, &pdbname)); - EXPECT_NE(std::string::npos, - pdbname.find("crashpad_snapshot_test_image_reader")); - EXPECT_EQ( - 0, - pdbname.compare(pdbname.size() - suffix.size(), suffix.size(), suffix)); + // Check the main .exe to see that we can retrieve its sections. + auto module = reinterpret_cast( + process_snapshot.Modules()[0]); + ASSERT_TRUE(module->pe_image_reader().DebugDirectoryInformation( + &uuid, &age, &pdbname)); + EXPECT_NE(pdbname.find("crashpad_snapshot_test_image_reader"), + std::string::npos); + EXPECT_EQ( + pdbname.compare(pdbname.size() - suffix.size(), suffix.size(), suffix), + 0); - // Check the dll it loads too. - module = reinterpret_cast( - process_snapshot.Modules().back()); - ASSERT_TRUE(module->pe_image_reader().DebugDirectoryInformation( - &uuid, &age, &pdbname)); - EXPECT_NE(std::string::npos, - pdbname.find("crashpad_snapshot_test_image_reader_module")); - EXPECT_EQ( - 0, - pdbname.compare(pdbname.size() - suffix.size(), suffix.size(), suffix)); + // Check the dll it loads too. + module = reinterpret_cast( + process_snapshot.Modules().back()); + ASSERT_TRUE(module->pe_image_reader().DebugDirectoryInformation( + &uuid, &age, &pdbname)); + EXPECT_NE(pdbname.find("crashpad_snapshot_test_image_reader_module"), + std::string::npos); + EXPECT_EQ( + pdbname.compare(pdbname.size() - suffix.size(), suffix.size(), suffix), + 0); - // Sum the size of the extra memory in all the threads and confirm it's near - // the limit that the child process set in its CrashpadInfo. - EXPECT_GE(process_snapshot.Threads().size(), 100u); + // Sum the size of the extra memory in all the threads and confirm it's near + // the limit that the child process set in its CrashpadInfo. + EXPECT_GE(process_snapshot.Threads().size(), 100u); - size_t extra_memory_total = 0; - for (const auto* thread : process_snapshot.Threads()) { - for (const auto* extra_memory : thread->ExtraMemory()) { - extra_memory_total += extra_memory->Size(); + size_t extra_memory_total = 0; + for (const auto* thread : process_snapshot.Threads()) { + for (const auto* extra_memory : thread->ExtraMemory()) { + extra_memory_total += extra_memory->Size(); + } } + + // Confirm that less than 1M of extra data was gathered. The cap is set to + // only 100K, but there are other "extra memory" regions that aren't + // included in the cap. (Completely uncapped it would be > 10M.) + EXPECT_LT(extra_memory_total, 1000000u); } - // We confirm we gathered less than 1M of extra data. The cap is set to only - // 100K, but there are other "extra memory" regions that aren't included in - // the cap. (Completely uncapped it would be > 10M.) - EXPECT_LT(extra_memory_total, 1000000u); - // Tell the child it can terminate. - SetEvent(done.get()); + EXPECT_TRUE(SetEvent(done.get())) << ErrorMessage("SetEvent"); + + EXPECT_EQ(child.WaitForExit(), 0); } TEST(ProcessSnapshotTest, CrashpadInfoChild) { diff --git a/snapshot/win/system_snapshot_win_test.cc b/snapshot/win/system_snapshot_win_test.cc index d0caee7d..64d84c20 100644 --- a/snapshot/win/system_snapshot_win_test.cc +++ b/snapshot/win/system_snapshot_win_test.cc @@ -57,9 +57,9 @@ TEST_F(SystemSnapshotWinTest, GetCPUArchitecture) { CPUArchitecture cpu_architecture = system_snapshot().GetCPUArchitecture(); #if defined(ARCH_CPU_X86) - EXPECT_EQ(kCPUArchitectureX86, cpu_architecture); + EXPECT_EQ(cpu_architecture, kCPUArchitectureX86); #elif defined(ARCH_CPU_X86_64) - EXPECT_EQ(kCPUArchitectureX86_64, cpu_architecture); + EXPECT_EQ(cpu_architecture, kCPUArchitectureX86_64); #endif } @@ -82,8 +82,8 @@ TEST_F(SystemSnapshotWinTest, CPUX86SupportsDAZ) { } TEST_F(SystemSnapshotWinTest, GetOperatingSystem) { - EXPECT_EQ(SystemSnapshot::kOperatingSystemWindows, - system_snapshot().GetOperatingSystem()); + EXPECT_EQ(system_snapshot().GetOperatingSystem(), + SystemSnapshot::kOperatingSystemWindows); } TEST_F(SystemSnapshotWinTest, OSVersion) { @@ -127,20 +127,20 @@ TEST_F(SystemSnapshotWinTest, TimeZone) { long timezone = 0; _get_timezone(&timezone); #endif - EXPECT_EQ(-timezone, standard_offset_seconds); + EXPECT_EQ(standard_offset_seconds, -timezone); // In contemporary usage, most time zones have an integer hour offset from // UTC, although several are at a half-hour offset, and two are at 15-minute // offsets. Throughout history, other variations existed. See // http://www.timeanddate.com/time/time-zones-interesting.html. - EXPECT_EQ(0, standard_offset_seconds % (15 * 60)) + EXPECT_EQ(standard_offset_seconds % (15 * 60), 0) << "standard_offset_seconds " << standard_offset_seconds; if (dst_status == SystemSnapshot::kDoesNotObserveDaylightSavingTime) { - EXPECT_EQ(standard_offset_seconds, daylight_offset_seconds); - EXPECT_EQ(standard_name, daylight_name); + EXPECT_EQ(daylight_offset_seconds, standard_offset_seconds); + EXPECT_EQ(daylight_name, standard_name); } else { - EXPECT_EQ(0, daylight_offset_seconds % (15 * 60)) + EXPECT_EQ(daylight_offset_seconds % (15 * 60), 0) << "daylight_offset_seconds " << daylight_offset_seconds; // In contemporary usage, dst_delta_seconds will almost always be one hour, diff --git a/test/errors.h b/test/errors.h index 17b0bea6..c4f1a532 100644 --- a/test/errors.h +++ b/test/errors.h @@ -30,7 +30,7 @@ namespace test { // Where non-test code could do: // PCHECK(rv == 0) << "close"; // gtest-based test code can do: -// EXPECT_EQ(0, rv) << ErrnoMessage("close"); +// EXPECT_EQ(rv, 0) << ErrnoMessage("close"); //! \brief Formats an error message using an `errno` value. //! diff --git a/test/file.cc b/test/file.cc index cd53b1bb..75af744d 100644 --- a/test/file.cc +++ b/test/file.cc @@ -37,7 +37,7 @@ bool FileExists(const base::FilePath& path) { #error "Not implemented" #endif if (rv < 0) { - EXPECT_EQ(ENOENT, errno) << ErrnoMessage(stat_function) << " " + EXPECT_EQ(errno, ENOENT) << ErrnoMessage(stat_function) << " " << path.value(); return false; } diff --git a/test/hex_string.h b/test/hex_string.h index 08654880..435a692e 100644 --- a/test/hex_string.h +++ b/test/hex_string.h @@ -29,8 +29,8 @@ namespace test { //! uint8_t expected[10]; //! uint8_t observed[10]; //! // … -//! EXPECT_EQ(BytesToHexString(expected, arraysize(expected)), -//! BytesToHexString(observed, arraysize(observed))); +//! EXPECT_EQ(BytesToHexString(observed, arraysize(observed)), +//! BytesToHexString(expected, arraysize(expected))); //! \endcode std::string BytesToHexString(const void* bytes, size_t length); diff --git a/test/hex_string_test.cc b/test/hex_string_test.cc index 62b45c12..1915a856 100644 --- a/test/hex_string_test.cc +++ b/test/hex_string_test.cc @@ -22,11 +22,11 @@ namespace test { namespace { TEST(HexString, HexString) { - EXPECT_EQ("", BytesToHexString(nullptr, 0)); + EXPECT_EQ(BytesToHexString(nullptr, 0), ""); const char kBytes[] = "Abc123xyz \x0a\x7f\xf0\x9f\x92\xa9_"; - EXPECT_EQ("41626331323378797a200a7ff09f92a95f00", - BytesToHexString(kBytes, arraysize(kBytes))); + EXPECT_EQ(BytesToHexString(kBytes, arraysize(kBytes)), + "41626331323378797a200a7ff09f92a95f00"); } } // namespace diff --git a/test/mac/mach_errors.h b/test/mac/mach_errors.h index 2283ae77..0376bd1e 100644 --- a/test/mac/mach_errors.h +++ b/test/mac/mach_errors.h @@ -29,7 +29,7 @@ namespace test { // Where non-test code could do: // MACH_CHECK(kr == KERN_SUCCESS, kr) << "vm_deallocate"; // gtest-based test code can do: -// EXPECT_EQ(KERN_SUCCESS, kr) << MachErrorMessage(kr, "vm_deallocate"); +// EXPECT_EQ(kr, KERN_SUCCESS) << MachErrorMessage(kr, "vm_deallocate"); //! \brief Formats a Mach error message. //! diff --git a/test/mac/mach_multiprocess.cc b/test/mac/mach_multiprocess.cc index b691cd7f..f29a8b0c 100644 --- a/test/mac/mach_multiprocess.cc +++ b/test/mac/mach_multiprocess.cc @@ -74,7 +74,7 @@ MachMultiprocess::MachMultiprocess() : Multiprocess(), info_(nullptr) { } void MachMultiprocess::Run() { - ASSERT_EQ(nullptr, info_); + ASSERT_EQ(info_, nullptr); std::unique_ptr info( new internal::MachMultiprocessInfo); base::AutoReset reset_info(&info_, @@ -124,25 +124,26 @@ void MachMultiprocess::MultiprocessParent() { info_->local_port.get(), MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL); - ASSERT_EQ(MACH_MSG_SUCCESS, kr) << MachErrorMessage(kr, "mach_msg"); + ASSERT_EQ(kr, MACH_MSG_SUCCESS) << MachErrorMessage(kr, "mach_msg"); // Comb through the entire message, checking every field against its expected // value. - EXPECT_EQ(MACH_MSGH_BITS(MACH_MSG_TYPE_MOVE_SEND, MACH_MSG_TYPE_MOVE_SEND) | - MACH_MSGH_BITS_COMPLEX, - message.header.msgh_bits); - ASSERT_EQ(sizeof(SendHelloMessage), message.header.msgh_size); - EXPECT_EQ(info_->local_port, message.header.msgh_local_port); - ASSERT_EQ(1u, message.body.msgh_descriptor_count); - EXPECT_EQ(implicit_cast(MACH_MSG_TYPE_MOVE_SEND), - message.port_descriptor.disposition); - ASSERT_EQ(implicit_cast(MACH_MSG_PORT_DESCRIPTOR), - message.port_descriptor.type); - ASSERT_EQ(implicit_cast(MACH_MSG_TRAILER_FORMAT_0), - message.audit_trailer.msgh_trailer_type); - ASSERT_EQ(sizeof(message.audit_trailer), - message.audit_trailer.msgh_trailer_size); - EXPECT_EQ(0u, message.audit_trailer.msgh_seqno); + EXPECT_EQ(message.header.msgh_bits, + MACH_MSGH_BITS(MACH_MSG_TYPE_MOVE_SEND, MACH_MSG_TYPE_MOVE_SEND) | + MACH_MSGH_BITS_COMPLEX); + ASSERT_EQ(message.header.msgh_size, sizeof(SendHelloMessage)); + EXPECT_EQ(message.header.msgh_local_port, info_->local_port); + ASSERT_EQ(message.body.msgh_descriptor_count, 1u); + EXPECT_EQ(message.port_descriptor.disposition, + implicit_cast(MACH_MSG_TYPE_MOVE_SEND)); + ASSERT_EQ( + message.port_descriptor.type, + implicit_cast(MACH_MSG_PORT_DESCRIPTOR)); + ASSERT_EQ(message.audit_trailer.msgh_trailer_type, + implicit_cast(MACH_MSG_TRAILER_FORMAT_0)); + ASSERT_EQ(message.audit_trailer.msgh_trailer_size, + sizeof(message.audit_trailer)); + EXPECT_EQ(message.audit_trailer.msgh_seqno, 0u); // Check the audit trailer’s values for sanity. This is a little bit of // overkill, but because the service was registered with the bootstrap server @@ -175,19 +176,19 @@ void MachMultiprocess::MultiprocessParent() { pid_t audit_pid = audit_token_to_pid(message.audit_trailer.msgh_audit); au_asid_t audit_asid = audit_token_to_asid(message.audit_trailer.msgh_audit); #endif - EXPECT_EQ(geteuid(), audit_euid); - EXPECT_EQ(getegid(), audit_egid); - EXPECT_EQ(getuid(), audit_ruid); - EXPECT_EQ(getgid(), audit_rgid); - ASSERT_EQ(ChildPID(), audit_pid); + EXPECT_EQ(audit_euid, geteuid()); + EXPECT_EQ(audit_egid, getegid()); + EXPECT_EQ(audit_ruid, getuid()); + EXPECT_EQ(audit_rgid, getgid()); + ASSERT_EQ(audit_pid, ChildPID()); - ASSERT_EQ(ChildPID(), AuditPIDFromMachMessageTrailer(&message.trailer)); + ASSERT_EQ(AuditPIDFromMachMessageTrailer(&message.trailer), ChildPID()); auditinfo_addr_t audit_info; int rv = getaudit_addr(&audit_info, sizeof(audit_info)); - ASSERT_EQ(0, rv) << ErrnoMessage("getaudit_addr"); - EXPECT_EQ(audit_info.ai_auid, audit_auid); - EXPECT_EQ(audit_info.ai_asid, audit_asid); + ASSERT_EQ(rv, 0) << ErrnoMessage("getaudit_addr"); + EXPECT_EQ(audit_auid, audit_info.ai_auid); + EXPECT_EQ(audit_asid, audit_info.ai_asid); // Retrieve the remote port from the message header, and the child’s task port // from the message body. @@ -197,8 +198,8 @@ void MachMultiprocess::MultiprocessParent() { // Verify that the child’s task port is what it purports to be. int mach_pid; kr = pid_for_task(info_->child_task.get(), &mach_pid); - ASSERT_EQ(KERN_SUCCESS, kr) << MachErrorMessage(kr, "pid_for_task"); - ASSERT_EQ(ChildPID(), mach_pid); + ASSERT_EQ(kr, KERN_SUCCESS) << MachErrorMessage(kr, "pid_for_task"); + ASSERT_EQ(mach_pid, ChildPID()); MachMultiprocessParent(); @@ -213,11 +214,11 @@ void MachMultiprocess::MultiprocessChild() { ignore_result(info_->local_port.release()); info_->local_port.reset(NewMachPort(MACH_PORT_RIGHT_RECEIVE)); - ASSERT_NE(kMachPortNull, info_->local_port); + ASSERT_NE(info_->local_port, kMachPortNull); // The remote port can be obtained from the bootstrap server. info_->remote_port = BootstrapLookUp(info_->service_name); - ASSERT_NE(kMachPortNull, info_->remote_port); + ASSERT_NE(info_->remote_port, kMachPortNull); // The “hello” message will provide the parent with its remote port, a send // right to the child task’s local port receive right. It will also carry a @@ -241,7 +242,7 @@ void MachMultiprocess::MultiprocessChild() { MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL); - ASSERT_EQ(MACH_MSG_SUCCESS, kr) << MachErrorMessage(kr, "mach_msg"); + ASSERT_EQ(kr, MACH_MSG_SUCCESS) << MachErrorMessage(kr, "mach_msg"); MachMultiprocessChild(); diff --git a/test/multiprocess_exec_posix.cc b/test/multiprocess_exec_posix.cc index 93363a01..3d7212d1 100644 --- a/test/multiprocess_exec_posix.cc +++ b/test/multiprocess_exec_posix.cc @@ -80,7 +80,7 @@ void MultiprocessExec::MultiprocessChild() { FileHandle read_handle = ReadPipeHandle(); ASSERT_NE(read_handle, STDIN_FILENO); ASSERT_NE(read_handle, STDOUT_FILENO); - ASSERT_EQ(STDIN_FILENO, fileno(stdin)); + ASSERT_EQ(fileno(stdin), STDIN_FILENO); int rv; @@ -88,17 +88,17 @@ void MultiprocessExec::MultiprocessChild() { __fpurge(stdin); #else rv = fpurge(stdin); - ASSERT_EQ(0, rv) << ErrnoMessage("fpurge"); + ASSERT_EQ(rv, 0) << ErrnoMessage("fpurge"); #endif rv = HANDLE_EINTR(dup2(read_handle, STDIN_FILENO)); - ASSERT_EQ(STDIN_FILENO, rv) << ErrnoMessage("dup2"); + ASSERT_EQ(rv, STDIN_FILENO) << ErrnoMessage("dup2"); // Move the write pipe to stdout. FileHandle write_handle = WritePipeHandle(); ASSERT_NE(write_handle, STDIN_FILENO); ASSERT_NE(write_handle, STDOUT_FILENO); - ASSERT_EQ(STDOUT_FILENO, fileno(stdout)); + ASSERT_EQ(fileno(stdout), STDOUT_FILENO); // Make a copy of the original stdout file descriptor so that in case there’s // an execv() failure, the original stdout can be restored so that gtest @@ -113,10 +113,10 @@ void MultiprocessExec::MultiprocessChild() { ASSERT_NE(rv, -1) << ErrnoMessage("fcntl"); rv = HANDLE_EINTR(fflush(stdout)); - ASSERT_EQ(0, rv) << ErrnoMessage("fflush"); + ASSERT_EQ(rv, 0) << ErrnoMessage("fflush"); rv = HANDLE_EINTR(dup2(write_handle, STDOUT_FILENO)); - ASSERT_EQ(STDOUT_FILENO, rv) << ErrnoMessage("dup2"); + ASSERT_EQ(rv, STDOUT_FILENO) << ErrnoMessage("dup2"); CloseMultipleNowOrOnExec(STDERR_FILENO + 1, dup_orig_stdout_fd); diff --git a/test/multiprocess_exec_test.cc b/test/multiprocess_exec_test.cc index 3e958aa8..f35519a0 100644 --- a/test/multiprocess_exec_test.cc +++ b/test/multiprocess_exec_test.cc @@ -18,7 +18,7 @@ #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "gtest/gtest.h" -#include "test/paths.h" +#include "test/test_paths.h" #include "util/file/file_io.h" namespace crashpad { @@ -40,7 +40,7 @@ class TestMultiprocessExec final : public MultiprocessExec { ASSERT_TRUE(LoggingWriteFile(WritePipeHandle(), &c, 1)); ASSERT_TRUE(LoggingReadFileExactly(ReadPipeHandle(), &c, 1)); - EXPECT_EQ('Z', c); + EXPECT_EQ(c, 'Z'); } DISALLOW_COPY_AND_ASSIGN(TestMultiprocessExec); @@ -48,7 +48,7 @@ class TestMultiprocessExec final : public MultiprocessExec { TEST(MultiprocessExec, MultiprocessExec) { TestMultiprocessExec multiprocess_exec; - base::FilePath test_executable = Paths::Executable(); + base::FilePath test_executable = TestPaths::Executable(); #if defined(OS_POSIX) std::string child_test_executable = test_executable.value(); #elif defined(OS_WIN) diff --git a/test/multiprocess_exec_win.cc b/test/multiprocess_exec_win.cc index 3f7d2fac..5eb5d803 100644 --- a/test/multiprocess_exec_win.cc +++ b/test/multiprocess_exec_win.cc @@ -127,7 +127,7 @@ void MultiprocessExec::PreFork() { // Make pipes for child-to-parent and parent-to-child communication. Mark them // as inheritable via the SECURITY_ATTRIBUTES, but use SetHandleInformation to // ensure that the parent sides are not inherited. - ASSERT_EQ(nullptr, info()); + ASSERT_EQ(info(), nullptr); set_info(new internal::MultiprocessInfo()); SECURITY_ATTRIBUTES security_attributes = {0}; diff --git a/test/multiprocess_posix.cc b/test/multiprocess_posix.cc index 4e0e6e6d..d6796dda 100644 --- a/test/multiprocess_posix.cc +++ b/test/multiprocess_posix.cc @@ -60,7 +60,7 @@ Multiprocess::Multiprocess() } void Multiprocess::Run() { - ASSERT_EQ(nullptr, info_); + ASSERT_EQ(info_, nullptr); std::unique_ptr info( new internal::MultiprocessInfo); base::AutoReset reset_info(&info_, info.get()); @@ -90,7 +90,7 @@ void Multiprocess::Run() { int status; pid_t wait_pid = HANDLE_EINTR(waitpid(pid, &status, 0)); - ASSERT_EQ(pid, wait_pid) << ErrnoMessage("waitpid"); + ASSERT_EQ(wait_pid, pid) << ErrnoMessage("waitpid"); TerminationReason reason; int code; @@ -139,21 +139,21 @@ Multiprocess::~Multiprocess() { void Multiprocess::PreFork() { int pipe_fds_c2p[2]; int rv = pipe(pipe_fds_c2p); - ASSERT_EQ(0, rv) << ErrnoMessage("pipe"); + ASSERT_EQ(rv, 0) << ErrnoMessage("pipe"); info_->pipe_c2p_read.reset(pipe_fds_c2p[0]); info_->pipe_c2p_write.reset(pipe_fds_c2p[1]); int pipe_fds_p2c[2]; rv = pipe(pipe_fds_p2c); - ASSERT_EQ(0, rv) << ErrnoMessage("pipe"); + ASSERT_EQ(rv, 0) << ErrnoMessage("pipe"); info_->pipe_p2c_read.reset(pipe_fds_p2c[0]); info_->pipe_p2c_write.reset(pipe_fds_p2c[1]); } pid_t Multiprocess::ChildPID() const { - EXPECT_NE(0, info_->child_pid); + EXPECT_NE(info_->child_pid, 0); return info_->child_pid; } diff --git a/test/multiprocess_posix_test.cc b/test/multiprocess_posix_test.cc index 9f557fab..44894e8c 100644 --- a/test/multiprocess_posix_test.cc +++ b/test/multiprocess_posix_test.cc @@ -40,11 +40,11 @@ class TestMultiprocess final : public Multiprocess { FileHandle read_handle = ReadPipeHandle(); char c; CheckedReadFileExactly(read_handle, &c, 1); - EXPECT_EQ('M', c); + EXPECT_EQ(c, 'M'); pid_t pid; CheckedReadFileExactly(read_handle, &pid, sizeof(pid)); - EXPECT_EQ(pid, ChildPID()); + EXPECT_EQ(ChildPID(), pid); c = 'm'; CheckedWriteFile(WritePipeHandle(), &c, 1); @@ -64,7 +64,7 @@ class TestMultiprocess final : public Multiprocess { CheckedWriteFile(write_handle, &pid, sizeof(pid)); CheckedReadFileExactly(ReadPipeHandle(), &c, 1); - EXPECT_EQ('m', c); + EXPECT_EQ(c, 'm'); } DISALLOW_COPY_AND_ASSIGN(TestMultiprocess); @@ -161,8 +161,8 @@ class TestMultiprocessClosePipe final : public Multiprocess { private: void VerifyInitial() { - ASSERT_NE(-1, ReadPipeHandle()); - ASSERT_NE(-1, WritePipeHandle()); + ASSERT_NE(ReadPipeHandle(), -1); + ASSERT_NE(WritePipeHandle(), -1); } // Verifies that the partner process did what it was supposed to do. This must @@ -198,12 +198,12 @@ class TestMultiprocessClosePipe final : public Multiprocess { switch (what_closes_) { case kReadCloses: CloseReadPipe(); - EXPECT_NE(-1, WritePipeHandle()); + EXPECT_NE(WritePipeHandle(), -1); EXPECT_DEATH_CHECK(ReadPipeHandle(), "fd"); break; case kWriteCloses: CloseWritePipe(); - EXPECT_NE(-1, ReadPipeHandle()); + EXPECT_NE(ReadPipeHandle(), -1); EXPECT_DEATH_CHECK(WritePipeHandle(), "fd"); break; case kReadAndWriteClose: diff --git a/test/scoped_temp_dir_posix.cc b/test/scoped_temp_dir_posix.cc index 03681036..29577529 100644 --- a/test/scoped_temp_dir_posix.cc +++ b/test/scoped_temp_dir_posix.cc @@ -72,15 +72,15 @@ void ScopedTempDir::RecursivelyDeleteTemporaryDirectory( if (entry->d_type == DT_DIR) { RecursivelyDeleteTemporaryDirectory(entry_path); } else { - EXPECT_EQ(0, unlink(entry_path.value().c_str())) + EXPECT_EQ(unlink(entry_path.value().c_str()), 0) << ErrnoMessage("unlink") << " " << entry_path.value(); } } - EXPECT_EQ(0, closedir(dir)) - << ErrnoMessage("closedir") << " " << path.value(); - EXPECT_EQ(0, rmdir(path.value().c_str())) - << ErrnoMessage("rmdir") << " " << path.value(); + EXPECT_EQ(closedir(dir), 0) << ErrnoMessage("closedir") << " " + << path.value(); + EXPECT_EQ(rmdir(path.value().c_str()), 0) << ErrnoMessage("rmdir") << " " + << path.value(); } } // namespace test diff --git a/test/scoped_temp_dir_test.cc b/test/scoped_temp_dir_test.cc index ea8b067b..9ad801f7 100644 --- a/test/scoped_temp_dir_test.cc +++ b/test/scoped_temp_dir_test.cc @@ -38,12 +38,14 @@ void CreateFile(const base::FilePath& path) { #if defined(OS_POSIX) int fd = HANDLE_EINTR(creat(path.value().c_str(), 0644)); ASSERT_GE(fd, 0) << ErrnoMessage("creat") << " " << path.value(); - ASSERT_EQ(0, IGNORE_EINTR(close(fd))) - << ErrnoMessage("close") << " " << path.value(); + + // gcc refuses to compile ASSERT_EQ(IGNORE_EINTR(close(fd)), 0). + int close_rv = IGNORE_EINTR(close(fd)); + ASSERT_EQ(close_rv, 0) << ErrnoMessage("close") << " " << path.value(); #elif defined(OS_WIN) int fd = _wcreat(path.value().c_str(), _S_IREAD | _S_IWRITE); ASSERT_GE(fd, 0) << ErrnoMessage("_wcreat") << " " << path.value(); - ASSERT_EQ(0, _close(fd)) << ErrnoMessage("_close") << " " << path.value(); + ASSERT_EQ(_close(fd), 0) << ErrnoMessage("_close") << " " << path.value(); #else #error "Not implemented" #endif @@ -52,11 +54,11 @@ void CreateFile(const base::FilePath& path) { void CreateDirectory(const base::FilePath& path) { #if defined(OS_POSIX) - ASSERT_EQ(0, mkdir(path.value().c_str(), 0755)) - << ErrnoMessage("mkdir") << " " << path.value(); + ASSERT_EQ(mkdir(path.value().c_str(), 0755), 0) << ErrnoMessage("mkdir") + << " " << path.value(); #elif defined(OS_WIN) - ASSERT_EQ(0, _wmkdir(path.value().c_str())) - << ErrnoMessage("_wmkdir") << " " << path.value(); + ASSERT_EQ(_wmkdir(path.value().c_str()), 0) << ErrnoMessage("_wmkdir") << " " + << path.value(); #else #error "Not implemented" #endif diff --git a/test/scoped_temp_dir_win.cc b/test/scoped_temp_dir_win.cc index cc4820d6..0413ec42 100644 --- a/test/scoped_temp_dir_win.cc +++ b/test/scoped_temp_dir_win.cc @@ -81,7 +81,7 @@ void ScopedTempDir::RecursivelyDeleteTemporaryDirectory( WIN32_FIND_DATA find_data; HANDLE search_handle = FindFirstFile(search_mask.c_str(), &find_data); if (search_handle == INVALID_HANDLE_VALUE) - ASSERT_EQ(ERROR_FILE_NOT_FOUND, GetLastError()); + ASSERT_EQ(GetLastError(), ERROR_FILE_NOT_FOUND); do { if (wcscmp(find_data.cFileName, L".") == 0 || wcscmp(find_data.cFileName, L"..") == 0) { @@ -94,7 +94,7 @@ void ScopedTempDir::RecursivelyDeleteTemporaryDirectory( else EXPECT_TRUE(DeleteFile(entry_path.value().c_str())); } while (FindNextFile(search_handle, &find_data)); - EXPECT_EQ(ERROR_NO_MORE_FILES, GetLastError()); + EXPECT_EQ(GetLastError(), ERROR_NO_MORE_FILES); EXPECT_TRUE(FindClose(search_handle)); EXPECT_TRUE(RemoveDirectory(path.value().c_str())); diff --git a/test/test.gyp b/test/test.gyp index eb0a28b9..94b198c7 100644 --- a/test/test.gyp +++ b/test/test.gyp @@ -49,21 +49,20 @@ 'multiprocess_exec_posix.cc', 'multiprocess_exec_win.cc', 'multiprocess_posix.cc', - 'paths.cc', - 'paths.h', - 'paths_linux.cc', - 'paths_mac.cc', - 'paths_win.cc', 'scoped_temp_dir.cc', 'scoped_temp_dir.h', 'scoped_temp_dir_posix.cc', 'scoped_temp_dir_win.cc', + 'test_paths.cc', + 'test_paths.h', 'win/child_launcher.cc', 'win/child_launcher.h', 'win/win_child_process.cc', 'win/win_child_process.h', 'win/win_multiprocess.cc', 'win/win_multiprocess.h', + 'win/win_multiprocess_with_temp_dir.cc', + 'win/win_multiprocess_with_temp_dir.h', ], 'direct_dependent_settings': { 'include_dirs': [ @@ -86,13 +85,6 @@ }, }], ], - 'target_conditions': [ - ['OS=="android"', { - 'sources/': [ - ['include', '^paths_linux\\.cc$'], - ], - }], - ], }, { 'target_name': 'crashpad_gtest_main', diff --git a/test/paths.cc b/test/test_paths.cc similarity index 66% rename from test/paths.cc rename to test/test_paths.cc index b5eb60b9..4c256030 100644 --- a/test/paths.cc +++ b/test/test_paths.cc @@ -12,13 +12,14 @@ // See the License for the specific language governing permissions and // limitations under the License. -#include "test/paths.h" +#include "test/test_paths.h" #include #include #include "base/logging.h" #include "build/build_config.h" +#include "util/misc/paths.h" namespace crashpad { namespace test { @@ -28,7 +29,7 @@ namespace { bool IsTestDataRoot(const base::FilePath& candidate) { const base::FilePath marker_path = candidate.Append(FILE_PATH_LITERAL("test")) - .Append(FILE_PATH_LITERAL("paths_test_data_root.txt")); + .Append(FILE_PATH_LITERAL("test_paths_test_data_root.txt")); #if !defined(OS_WIN) struct stat stat_buf; @@ -59,23 +60,25 @@ base::FilePath TestDataRootInternal() { // In a standalone build, the test executable is usually at // out/{Debug,Release} relative to the Crashpad root. - const base::FilePath executable = Paths::Executable(); - base::FilePath candidate = - base::FilePath(executable.DirName() - .Append(base::FilePath::kParentDirectory) - .Append(base::FilePath::kParentDirectory)); - if (IsTestDataRoot(candidate)) { - return candidate; - } + base::FilePath executable_path; + if (Paths::Executable(&executable_path)) { + base::FilePath candidate = + base::FilePath(executable_path.DirName() + .Append(base::FilePath::kParentDirectory) + .Append(base::FilePath::kParentDirectory)); + if (IsTestDataRoot(candidate)) { + return candidate; + } - // In an in-Chromium build, the test executable is usually at - // out/{Debug,Release} relative to the Chromium root, and the Crashpad root is - // at third_party/crashpad/crashpad relative to the Chromium root. - candidate = candidate.Append(FILE_PATH_LITERAL("third_party")) - .Append(FILE_PATH_LITERAL("crashpad")) - .Append(FILE_PATH_LITERAL("crashpad")); - if (IsTestDataRoot(candidate)) { - return candidate; + // In an in-Chromium build, the test executable is usually at + // out/{Debug,Release} relative to the Chromium root, and the Crashpad root + // is at third_party/crashpad/crashpad relative to the Chromium root. + candidate = candidate.Append(FILE_PATH_LITERAL("third_party")) + .Append(FILE_PATH_LITERAL("crashpad")) + .Append(FILE_PATH_LITERAL("crashpad")); + if (IsTestDataRoot(candidate)) { + return candidate; + } } // If nothing else worked, use the current directory, issuing a warning if it @@ -90,7 +93,14 @@ base::FilePath TestDataRootInternal() { } // namespace // static -base::FilePath Paths::TestDataRoot() { +base::FilePath TestPaths::Executable() { + base::FilePath executable_path; + CHECK(Paths::Executable(&executable_path)); + return executable_path; +} + +// static +base::FilePath TestPaths::TestDataRoot() { static base::FilePath* test_data_root = new base::FilePath(TestDataRootInternal()); return *test_data_root; diff --git a/test/paths.h b/test/test_paths.h similarity index 88% rename from test/paths.h rename to test/test_paths.h index 7643ddd8..261ab911 100644 --- a/test/paths.h +++ b/test/test_paths.h @@ -12,8 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -#ifndef CRASHPAD_TEST_PATHS_H_ -#define CRASHPAD_TEST_PATHS_H_ +#ifndef CRASHPAD_TEST_TEST_PATHS_H_ +#define CRASHPAD_TEST_TEST_PATHS_H_ #include "base/files/file_path.h" #include "base/macros.h" @@ -22,9 +22,11 @@ namespace crashpad { namespace test { //! \brief Functions to obtain paths from within tests. -class Paths { +class TestPaths { public: //! \brief Returns the pathname of the currently-running test executable. + //! + //! On failure, aborts execution. static base::FilePath Executable(); //! \brief Returns the pathname of the test data root. @@ -40,10 +42,10 @@ class Paths { //! files. static base::FilePath TestDataRoot(); - DISALLOW_IMPLICIT_CONSTRUCTORS(Paths); + DISALLOW_IMPLICIT_CONSTRUCTORS(TestPaths); }; } // namespace test } // namespace crashpad -#endif // CRASHPAD_TEST_PATHS_H_ +#endif // CRASHPAD_TEST_TEST_PATHS_H_ diff --git a/test/paths_test.cc b/test/test_paths_test.cc similarity index 63% rename from test/paths_test.cc rename to test/test_paths_test.cc index 7cbca049..9d43b594 100644 --- a/test/paths_test.cc +++ b/test/test_paths_test.cc @@ -12,10 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -#include "test/paths.h" +#include "test/test_paths.h" #include "base/files/file_path.h" -#include "build/build_config.h" #include "gtest/gtest.h" #include "util/file/file_io.h" @@ -23,22 +22,11 @@ namespace crashpad { namespace test { namespace { -TEST(Paths, Executable) { - base::FilePath executable_path = Paths::Executable(); - base::FilePath executable_name = executable_path.BaseName(); -#if defined(OS_WIN) - EXPECT_EQ(FILE_PATH_LITERAL("crashpad_test_test.exe"), - executable_name.value()); -#else - EXPECT_EQ("crashpad_test_test", executable_name.value()); -#endif // OS_WIN -} - -TEST(Paths, TestDataRoot) { - base::FilePath test_data_root = Paths::TestDataRoot(); +TEST(TestPaths, TestDataRoot) { + base::FilePath test_data_root = TestPaths::TestDataRoot(); ScopedFileHandle file(LoggingOpenFileForRead( test_data_root.Append(FILE_PATH_LITERAL("test")) - .Append(FILE_PATH_LITERAL("paths_test_data_root.txt")))); + .Append(FILE_PATH_LITERAL("test_paths_test_data_root.txt")))); EXPECT_TRUE(file.is_valid()); } diff --git a/test/paths_test_data_root.txt b/test/test_paths_test_data_root.txt similarity index 89% rename from test/paths_test_data_root.txt rename to test/test_paths_test_data_root.txt index 1ddd2642..6ac07806 100644 --- a/test/paths_test_data_root.txt +++ b/test/test_paths_test_data_root.txt @@ -12,5 +12,5 @@ # See the License for the specific language governing permissions and # limitations under the License. -This file is used by Paths::TestDataRoot() to locate the test data root. It +This file is used by TestPaths::TestDataRoot() to locate the test data root. It is present at a known path from the test data root. diff --git a/test/test_test.gyp b/test/test_test.gyp index 053d9c82..a31650da 100644 --- a/test/test_test.gyp +++ b/test/test_test.gyp @@ -39,8 +39,8 @@ 'main_arguments_test.cc', 'multiprocess_exec_test.cc', 'multiprocess_posix_test.cc', - 'paths_test.cc', 'scoped_temp_dir_test.cc', + 'test_paths_test.cc', 'win/win_child_process_test.cc', 'win/win_multiprocess_test.cc', ], diff --git a/test/win/child_launcher.cc b/test/win/child_launcher.cc index e35f1cb8..4ab1c816 100644 --- a/test/win/child_launcher.cc +++ b/test/win/child_launcher.cc @@ -89,8 +89,8 @@ void ChildLauncher::Start() { DWORD ChildLauncher::WaitForExit() { EXPECT_TRUE(process_handle_.is_valid()); - EXPECT_EQ(WAIT_OBJECT_0, - WaitForSingleObject(process_handle_.get(), INFINITE)); + EXPECT_EQ(WaitForSingleObject(process_handle_.get(), INFINITE), + WAIT_OBJECT_0); DWORD exit_code = 0; EXPECT_TRUE(GetExitCodeProcess(process_handle_.get(), &exit_code)); process_handle_.reset(); diff --git a/test/win/win_child_process.cc b/test/win/win_child_process.cc index 06ab21b2..4c821a0c 100644 --- a/test/win/win_child_process.cc +++ b/test/win/win_child_process.cc @@ -24,11 +24,11 @@ #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "gtest/gtest.h" +#include "test/test_paths.h" #include "util/stdlib/string_number_conversion.h" #include "util/string/split_string.h" #include "util/win/handle.h" #include "util/win/scoped_local_alloc.h" -#include "test/paths.h" namespace crashpad { namespace test { @@ -70,7 +70,7 @@ ScopedKernelHANDLE LaunchCommandLine(wchar_t* command_line) { startup_info.hStdError = GetStdHandle(STD_ERROR_HANDLE); startup_info.dwFlags = STARTF_USESTDHANDLES; PROCESS_INFORMATION process_info; - if (!CreateProcess(Paths::Executable().value().c_str(), + if (!CreateProcess(TestPaths::Executable().value().c_str(), &command_line[0], // This cannot be constant, per MSDN. nullptr, nullptr, @@ -186,7 +186,7 @@ std::unique_ptr WinChildProcess::Launch() { const ::testing::TestInfo* const test_info = ::testing::UnitTest::GetInstance()->current_test_info(); std::wstring command_line = - Paths::Executable().value() + L" " + + TestPaths::Executable().value() + L" " + base::UTF8ToUTF16(base::StringPrintf("--gtest_filter=%s.%s %s=0x%x|0x%x", test_info->test_case_name(), test_info->name(), diff --git a/test/win/win_child_process_test.cc b/test/win/win_child_process_test.cc index e464c7c0..eb38ba98 100644 --- a/test/win/win_child_process_test.cc +++ b/test/win/win_child_process_test.cc @@ -28,7 +28,7 @@ int ReadInt(HANDLE handle) { int value = 0; DWORD bytes_read = 0; EXPECT_TRUE(::ReadFile(handle, &value, sizeof(value), &bytes_read, nullptr)); - EXPECT_EQ(sizeof(value), bytes_read); + EXPECT_EQ(bytes_read, sizeof(value)); return value; } @@ -36,7 +36,7 @@ void WriteInt(HANDLE handle, int value) { DWORD bytes_written = 0; EXPECT_TRUE( ::WriteFile(handle, &value, sizeof(value), &bytes_written, nullptr)); - EXPECT_EQ(sizeof(value), bytes_written); + EXPECT_EQ(bytes_written, sizeof(value)); } class TestWinChildProcess final : public WinChildProcess { @@ -61,7 +61,7 @@ TEST(WinChildProcessTest, WinChildProcess) { std::unique_ptr handles = WinChildProcess::Launch(); WriteInt(handles->write.get(), 1); - ASSERT_EQ(1, ReadInt(handles->read.get())); + ASSERT_EQ(ReadInt(handles->read.get()), 1); } TEST(WinChildProcessTest, MultipleChildren) { @@ -77,9 +77,9 @@ TEST(WinChildProcessTest, MultipleChildren) { WriteInt(handles_1->write.get(), 1); WriteInt(handles_2->write.get(), 2); WriteInt(handles_3->write.get(), 3); - ASSERT_EQ(3, ReadInt(handles_3->read.get())); - ASSERT_EQ(2, ReadInt(handles_2->read.get())); - ASSERT_EQ(1, ReadInt(handles_1->read.get())); + ASSERT_EQ(ReadInt(handles_3->read.get()), 3); + ASSERT_EQ(ReadInt(handles_2->read.get()), 2); + ASSERT_EQ(ReadInt(handles_1->read.get()), 1); } } // namespace diff --git a/test/win/win_multiprocess.cc b/test/win/win_multiprocess.cc index 6a451f4d..dce171ce 100644 --- a/test/win/win_multiprocess.cc +++ b/test/win/win_multiprocess.cc @@ -22,7 +22,6 @@ #include "base/strings/utf_string_conversions.h" #include "util/stdlib/string_number_conversion.h" #include "util/string/split_string.h" -#include "test/paths.h" namespace crashpad { namespace test { diff --git a/test/win/win_multiprocess.h b/test/win/win_multiprocess.h index 663c7594..b9e1564c 100644 --- a/test/win/win_multiprocess.h +++ b/test/win/win_multiprocess.h @@ -43,12 +43,16 @@ class WinMultiprocess { ASSERT_NO_FATAL_FAILURE( WinChildProcess::EntryPoint>()); // If WinChildProcess::EntryPoint returns, we are in the parent process. + T parent_process; + WinMultiprocess* parent_multiprocess = &parent_process; + + parent_multiprocess->WinMultiprocessParentBeforeChild(); + std::unique_ptr child_handles = WinChildProcess::Launch(); ASSERT_TRUE(child_handles.get()); - T parent_process; parent_process.child_handles_ = child_handles.get(); - static_cast(&parent_process)->WinMultiprocessParent(); + parent_multiprocess->WinMultiprocessParent(); // Close our side of the handles now that we're done. The child can // use this to know when it's safe to complete. @@ -56,12 +60,15 @@ class WinMultiprocess { child_handles->write.reset(); // Wait for the child to complete. - ASSERT_EQ(WAIT_OBJECT_0, - WaitForSingleObject(child_handles->process.get(), INFINITE)); + ASSERT_EQ(WaitForSingleObject(child_handles->process.get(), INFINITE), + WAIT_OBJECT_0); DWORD exit_code; ASSERT_TRUE(GetExitCodeProcess(child_handles->process.get(), &exit_code)); - ASSERT_EQ(parent_process.exit_code_, exit_code); + ASSERT_EQ(exit_code, parent_process.exit_code_); + + parent_multiprocess->WinMultiprocessParentAfterChild( + child_handles->process.get()); } protected: @@ -162,6 +169,20 @@ class WinMultiprocess { //! Subclasses must implement this method to define how the parent operates. virtual void WinMultiprocessParent() = 0; + //! \brief The optional routine run in parent before the child is spawned. + //! + //! Subclasses may implement this method to prepare the environment for + //! the child process. + virtual void WinMultiprocessParentBeforeChild() {} + + //! \brief The optional routine run in parent after the child exits. + //! + //! Subclasses may implement this method to clean up the environment after + //! the child process has exited. + //! + //! \param[in] child A handle to the exited child process. + virtual void WinMultiprocessParentAfterChild(HANDLE child) {} + //! \brief The subclass-provided child routine. //! //! Test failures should be reported via gtest: `EXPECT_*()`, `ASSERT_*()`, diff --git a/test/win/win_multiprocess_with_temp_dir.cc b/test/win/win_multiprocess_with_temp_dir.cc new file mode 100644 index 00000000..13e38a5b --- /dev/null +++ b/test/win/win_multiprocess_with_temp_dir.cc @@ -0,0 +1,188 @@ +// Copyright 2017 The Crashpad Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "test/win/win_multiprocess_with_temp_dir.h" + +#include + +#include "base/memory/ptr_util.h" +#include "test/errors.h" +#include "util/win/process_info.h" + +namespace crashpad { +namespace test { + +namespace { + +constexpr wchar_t kTempDirEnvName[] = L"CRASHPAD_TEST_TEMP_DIR"; + +// Returns the process IDs of all processes that have |parent_pid| as +// parent process ID. +std::vector GetPotentialChildProcessesOf(pid_t parent_pid) { + ScopedFileHANDLE snapshot(CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)); + if (!snapshot.is_valid()) { + ADD_FAILURE() << ErrorMessage("CreateToolhelp32Snapshot"); + return std::vector(); + } + + PROCESSENTRY32 entry = {sizeof(entry)}; + if (!Process32First(snapshot.get(), &entry)) { + ADD_FAILURE() << ErrorMessage("Process32First"); + return std::vector(); + } + + std::vector child_pids; + do { + if (entry.th32ParentProcessID == parent_pid) + child_pids.push_back(entry.th32ProcessID); + } while (Process32Next(snapshot.get(), &entry)); + + return child_pids; +} + +ULARGE_INTEGER GetProcessCreationTime(HANDLE process) { + ULARGE_INTEGER ret = {}; + FILETIME creation_time; + FILETIME dummy; + if (GetProcessTimes(process, &creation_time, &dummy, &dummy, &dummy)) { + ret.LowPart = creation_time.dwLowDateTime; + ret.HighPart = creation_time.dwHighDateTime; + } else { + ADD_FAILURE() << ErrorMessage("GetProcessTimes"); + } + + return ret; +} + +// Waits for the processes directly created by |parent| - and specifically +// not their offspring. For this to work without race, |parent| has to be +// suspended or have exited. +void WaitForAllChildProcessesOf(HANDLE parent) { + pid_t parent_pid = GetProcessId(parent); + std::vector child_pids = GetPotentialChildProcessesOf(parent_pid); + + ULARGE_INTEGER parent_creationtime = GetProcessCreationTime(parent); + for (pid_t child_pid : child_pids) { + // Try and open the process. This may fail for reasons such as: + // 1. The process isn't |parent|'s child process, but rather a + // higher-privilege sub-process of an earlier process that had + // |parent|'s PID. + // 2. The process no longer exists, e.g. it exited after enumeration. + ScopedKernelHANDLE child_process( + OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION | SYNCHRONIZE, + false, + child_pid)); + if (!child_process.is_valid()) + continue; + + // Check that the child now has the right parent PID, as its PID may have + // been reused after the enumeration above. + ProcessInfo child_info; + if (!child_info.Initialize(child_process.get())) { + // This can happen if child_process has exited after the handle is opened. + LOG(ERROR) << "ProcessInfo::Initialize, pid: " << child_pid; + continue; + } + + if (parent_pid != child_info.ParentProcessID()) { + // The child's process ID was reused after enumeration. + continue; + } + + // We successfully opened |child_process| and it has |parent|'s PID for + // parent process ID. However, this could still be a sub-process of another + // process that earlier had |parent|'s PID. To make sure, check that + // |child_process| was created after |parent_process|. + ULARGE_INTEGER process_creationtime = + GetProcessCreationTime(child_process.get()); + if (process_creationtime.QuadPart < parent_creationtime.QuadPart) + continue; + + DWORD err = WaitForSingleObject(child_process.get(), INFINITE); + if (err == WAIT_FAILED) { + ADD_FAILURE() << ErrorMessage("WaitForSingleObject"); + } else if (err != WAIT_OBJECT_0) { + ADD_FAILURE() << "WaitForSingleObject returned " << err; + } + } +} + +} // namespace + +WinMultiprocessWithTempDir::WinMultiprocessWithTempDir() + : WinMultiprocess(), temp_dir_env_(kTempDirEnvName) {} + +void WinMultiprocessWithTempDir::WinMultiprocessParentBeforeChild() { + temp_dir_ = base::WrapUnique(new ScopedTempDir); + temp_dir_env_.SetValue(temp_dir_->path().value().c_str()); +} + +void WinMultiprocessWithTempDir::WinMultiprocessParentAfterChild(HANDLE child) { + WaitForAllChildProcessesOf(child); + temp_dir_.reset(); +} + +base::FilePath WinMultiprocessWithTempDir::GetTempDirPath() const { + return base::FilePath(temp_dir_env_.GetValue()); +} + +WinMultiprocessWithTempDir::ScopedEnvironmentVariable:: + ScopedEnvironmentVariable(const wchar_t* name) + : name_(name) { + original_value_ = GetValueImpl(&was_defined_); +} + +WinMultiprocessWithTempDir::ScopedEnvironmentVariable:: + ~ScopedEnvironmentVariable() { + if (was_defined_) + SetValue(original_value_.data()); + else + SetValue(nullptr); +} + +std::wstring WinMultiprocessWithTempDir::ScopedEnvironmentVariable::GetValue() + const { + bool dummy; + return GetValueImpl(&dummy); +} + +std::wstring +WinMultiprocessWithTempDir::ScopedEnvironmentVariable::GetValueImpl( + bool* is_defined) const { + // The length returned is inclusive of the terminating zero, except + // if the variable doesn't exist, in which case the return value is zero. + DWORD len = GetEnvironmentVariable(name_, nullptr, 0); + if (len == 0) { + *is_defined = false; + return L""; + } + + *is_defined = true; + + std::wstring ret; + ret.resize(len); + // The length returned on success is exclusive of the terminating zero. + len = GetEnvironmentVariable(name_, &ret[0], len); + ret.resize(len); + + return ret; +} + +void WinMultiprocessWithTempDir::ScopedEnvironmentVariable::SetValue( + const wchar_t* new_value) const { + SetEnvironmentVariable(name_, new_value); +} + +} // namespace test +} // namespace crashpad diff --git a/test/win/win_multiprocess_with_temp_dir.h b/test/win/win_multiprocess_with_temp_dir.h new file mode 100644 index 00000000..c9b48607 --- /dev/null +++ b/test/win/win_multiprocess_with_temp_dir.h @@ -0,0 +1,80 @@ +// Copyright 2017 The Crashpad Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef CRASHPAD_TEST_WIN_WIN_MULTIPROCESS_WITH_TEMPDIR_H_ +#define CRASHPAD_TEST_WIN_WIN_MULTIPROCESS_WITH_TEMPDIR_H_ + +#include +#include + +#include + +#include "base/files/file_path.h" +#include "base/macros.h" +#include "test/scoped_temp_dir.h" +#include "test/win/win_multiprocess.h" + +namespace crashpad { +namespace test { + +//! \brief Manages a multiprocess test on Windows with a parent-created +//! temporary directory. +//! +//! This class creates a temp directory in the parent process for the use of +//! the subprocess and its children. To ensure a raceless rundown, it waits on +//! the child process and any processes directly created by the child before +//! deleting the temporary directory. +class WinMultiprocessWithTempDir : public WinMultiprocess { + public: + WinMultiprocessWithTempDir(); + + protected: + void WinMultiprocessParentBeforeChild() override; + void WinMultiprocessParentAfterChild(HANDLE child) override; + + //! \brief Returns the path of the temp directory. + base::FilePath GetTempDirPath() const; + + private: + class ScopedEnvironmentVariable { + public: + explicit ScopedEnvironmentVariable(const wchar_t* name); + ~ScopedEnvironmentVariable(); + + std::wstring GetValue() const; + + // Sets this environment variable to |new_value|. If |new_value| is nullptr + // this environment variable will be undefined. + void SetValue(const wchar_t* new_value) const; + + private: + std::wstring GetValueImpl(bool* is_defined) const; + + std::wstring original_value_; + const wchar_t* name_; + bool was_defined_; + + DISALLOW_COPY_AND_ASSIGN(ScopedEnvironmentVariable); + }; + + std::unique_ptr temp_dir_; + ScopedEnvironmentVariable temp_dir_env_; + + DISALLOW_COPY_AND_ASSIGN(WinMultiprocessWithTempDir); +}; + +} // namespace test +} // namespace crashpad + +#endif // CRASHPAD_TEST_WIN_WIN_MULTIPROCESS_WITH_TEMPDIR_H_ diff --git a/third_party/getopt/README.crashpad b/third_party/getopt/README.crashpad index a7166e1f..b7ff9543 100644 --- a/third_party/getopt/README.crashpad +++ b/third_party/getopt/README.crashpad @@ -9,9 +9,12 @@ Description: A public domain implementation of getopt. Local Modifications: -- Minor compilation fixes applied for Windows. -- Add copy of copyright (Public domain) to the top of both files for Chromium's - checklicenses step. -- Compiled as .cc, and wrapped in namespace crashpad. -- memcmp() -> strncmp() in getopt.cc to make ASan happier about some string - manipulation. + - Minor compilation fixes applied for Windows. + - NO_ARG, REQUIRED_ARG, and OPTIONAL_ARG were renamed to the more traditional + no_argument, required_argument, and optional_argument for source + compatibility with BSD and glibc getopt_long(). + - Add copy of copyright (Public domain) to the top of both files for Chromium's + checklicenses step. + - Compiled as .cc, and wrapped in namespace crashpad. + - memcmp() -> strncmp() in getopt.cc to make ASan happier about some string + manipulation. diff --git a/third_party/getopt/getopt.cc b/third_party/getopt/getopt.cc index 137218b9..7dfd888c 100644 --- a/third_party/getopt/getopt.cc +++ b/third_party/getopt/getopt.cc @@ -310,16 +310,17 @@ getopt_internal (int argc, char **argv, char *shortopts, } return (optopt = '?'); } - has_arg = ((cp[1] == ':') - ? ((cp[2] == ':') ? OPTIONAL_ARG : required_argument) : no_argument); - possible_arg = argv[optind] + optwhere + 1; - optopt = *cp; + has_arg = ((cp[1] == ':') ? ((cp[2] == ':') ? optional_argument + : required_argument) + : no_argument); + possible_arg = argv[optind] + optwhere + 1; + optopt = *cp; } /* get argument and reset optwhere */ arg_next = 0; switch (has_arg) { - case OPTIONAL_ARG: + case optional_argument: if (*possible_arg == '=') possible_arg++; if (*possible_arg != '\0') diff --git a/third_party/getopt/getopt.h b/third_party/getopt/getopt.h index 282a489e..27ab0dd4 100644 --- a/third_party/getopt/getopt.h +++ b/third_party/getopt/getopt.h @@ -14,7 +14,7 @@ using it. /* macros defined by this include file */ #define no_argument 0 #define required_argument 1 -#define OPTIONAL_ARG 2 +#define optional_argument 2 /* types defined by this include file */ diff --git a/util/file/delimited_file_reader_test.cc b/util/file/delimited_file_reader_test.cc index 63b50836..84ecb846 100644 --- a/util/file/delimited_file_reader_test.cc +++ b/util/file/delimited_file_reader_test.cc @@ -30,12 +30,12 @@ TEST(DelimitedFileReader, EmptyFile) { DelimitedFileReader delimited_file_reader(&string_file); std::string line; - EXPECT_EQ(DelimitedFileReader::Result::kEndOfFile, - delimited_file_reader.GetLine(&line)); + EXPECT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kEndOfFile); // The file is still at EOF. - EXPECT_EQ(DelimitedFileReader::Result::kEndOfFile, - delimited_file_reader.GetLine(&line)); + EXPECT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kEndOfFile); } TEST(DelimitedFileReader, EmptyOneLineFile) { @@ -44,15 +44,15 @@ TEST(DelimitedFileReader, EmptyOneLineFile) { DelimitedFileReader delimited_file_reader(&string_file); std::string line; - ASSERT_EQ(DelimitedFileReader::Result::kSuccess, - delimited_file_reader.GetLine(&line)); - EXPECT_EQ(string_file.string(), line); - EXPECT_EQ(DelimitedFileReader::Result::kEndOfFile, - delimited_file_reader.GetLine(&line)); + ASSERT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kSuccess); + EXPECT_EQ(line, string_file.string()); + EXPECT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kEndOfFile); // The file is still at EOF. - EXPECT_EQ(DelimitedFileReader::Result::kEndOfFile, - delimited_file_reader.GetLine(&line)); + EXPECT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kEndOfFile); } TEST(DelimitedFileReader, SmallOneLineFile) { @@ -61,15 +61,15 @@ TEST(DelimitedFileReader, SmallOneLineFile) { DelimitedFileReader delimited_file_reader(&string_file); std::string line; - ASSERT_EQ(DelimitedFileReader::Result::kSuccess, - delimited_file_reader.GetLine(&line)); - EXPECT_EQ(string_file.string(), line); - EXPECT_EQ(DelimitedFileReader::Result::kEndOfFile, - delimited_file_reader.GetLine(&line)); + ASSERT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kSuccess); + EXPECT_EQ(line, string_file.string()); + EXPECT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kEndOfFile); // The file is still at EOF. - EXPECT_EQ(DelimitedFileReader::Result::kEndOfFile, - delimited_file_reader.GetLine(&line)); + EXPECT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kEndOfFile); } TEST(DelimitedFileReader, SmallOneLineFileWithoutNewline) { @@ -78,15 +78,15 @@ TEST(DelimitedFileReader, SmallOneLineFileWithoutNewline) { DelimitedFileReader delimited_file_reader(&string_file); std::string line; - ASSERT_EQ(DelimitedFileReader::Result::kSuccess, - delimited_file_reader.GetLine(&line)); - EXPECT_EQ(string_file.string(), line); - EXPECT_EQ(DelimitedFileReader::Result::kEndOfFile, - delimited_file_reader.GetLine(&line)); + ASSERT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kSuccess); + EXPECT_EQ(line, string_file.string()); + EXPECT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kEndOfFile); // The file is still at EOF. - EXPECT_EQ(DelimitedFileReader::Result::kEndOfFile, - delimited_file_reader.GetLine(&line)); + EXPECT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kEndOfFile); } TEST(DelimitedFileReader, SmallMultiLineFile) { @@ -95,21 +95,21 @@ TEST(DelimitedFileReader, SmallMultiLineFile) { DelimitedFileReader delimited_file_reader(&string_file); std::string line; - ASSERT_EQ(DelimitedFileReader::Result::kSuccess, - delimited_file_reader.GetLine(&line)); - EXPECT_EQ("first\n", line); - ASSERT_EQ(DelimitedFileReader::Result::kSuccess, - delimited_file_reader.GetLine(&line)); - EXPECT_EQ("second line\n", line); - ASSERT_EQ(DelimitedFileReader::Result::kSuccess, - delimited_file_reader.GetLine(&line)); - EXPECT_EQ("3rd\n", line); - EXPECT_EQ(DelimitedFileReader::Result::kEndOfFile, - delimited_file_reader.GetLine(&line)); + ASSERT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kSuccess); + EXPECT_EQ(line, "first\n"); + ASSERT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kSuccess); + EXPECT_EQ(line, "second line\n"); + ASSERT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kSuccess); + EXPECT_EQ(line, "3rd\n"); + EXPECT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kEndOfFile); // The file is still at EOF. - EXPECT_EQ(DelimitedFileReader::Result::kEndOfFile, - delimited_file_reader.GetLine(&line)); + EXPECT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kEndOfFile); } TEST(DelimitedFileReader, SmallMultiFieldFile) { @@ -118,21 +118,21 @@ TEST(DelimitedFileReader, SmallMultiFieldFile) { DelimitedFileReader delimited_file_reader(&string_file); std::string field; - ASSERT_EQ(DelimitedFileReader::Result::kSuccess, - delimited_file_reader.GetDelim(',', &field)); - EXPECT_EQ("first,", field); - ASSERT_EQ(DelimitedFileReader::Result::kSuccess, - delimited_file_reader.GetDelim(',', &field)); - EXPECT_EQ("second field\ntwo lines,", field); - ASSERT_EQ(DelimitedFileReader::Result::kSuccess, - delimited_file_reader.GetDelim(',', &field)); - EXPECT_EQ("3rd,", field); - EXPECT_EQ(DelimitedFileReader::Result::kEndOfFile, - delimited_file_reader.GetDelim(',', &field)); + ASSERT_EQ(delimited_file_reader.GetDelim(',', &field), + DelimitedFileReader::Result::kSuccess); + EXPECT_EQ(field, "first,"); + ASSERT_EQ(delimited_file_reader.GetDelim(',', &field), + DelimitedFileReader::Result::kSuccess); + EXPECT_EQ(field, "second field\ntwo lines,"); + ASSERT_EQ(delimited_file_reader.GetDelim(',', &field), + DelimitedFileReader::Result::kSuccess); + EXPECT_EQ(field, "3rd,"); + EXPECT_EQ(delimited_file_reader.GetDelim(',', &field), + DelimitedFileReader::Result::kEndOfFile); // The file is still at EOF. - EXPECT_EQ(DelimitedFileReader::Result::kEndOfFile, - delimited_file_reader.GetDelim(',', &field)); + EXPECT_EQ(delimited_file_reader.GetDelim(',', &field), + DelimitedFileReader::Result::kEndOfFile); } TEST(DelimitedFileReader, SmallMultiFieldFile_MixedDelimiters) { @@ -141,27 +141,27 @@ TEST(DelimitedFileReader, SmallMultiFieldFile_MixedDelimiters) { DelimitedFileReader delimited_file_reader(&string_file); std::string field; - ASSERT_EQ(DelimitedFileReader::Result::kSuccess, - delimited_file_reader.GetDelim(',', &field)); - EXPECT_EQ("first,", field); - ASSERT_EQ(DelimitedFileReader::Result::kSuccess, - delimited_file_reader.GetDelim('\t', &field)); - EXPECT_EQ("second, still 2nd\t", field); - ASSERT_EQ(DelimitedFileReader::Result::kSuccess, - delimited_file_reader.GetLine(&field)); - EXPECT_EQ("3rd\n", field); - ASSERT_EQ(DelimitedFileReader::Result::kSuccess, - delimited_file_reader.GetDelim('\n', &field)); - EXPECT_EQ("also\tnewline\n", field); - ASSERT_EQ(DelimitedFileReader::Result::kSuccess, - delimited_file_reader.GetDelim('$', &field)); - EXPECT_EQ("55555$", field); - EXPECT_EQ(DelimitedFileReader::Result::kEndOfFile, - delimited_file_reader.GetDelim('?', &field)); + ASSERT_EQ(delimited_file_reader.GetDelim(',', &field), + DelimitedFileReader::Result::kSuccess); + EXPECT_EQ(field, "first,"); + ASSERT_EQ(delimited_file_reader.GetDelim('\t', &field), + DelimitedFileReader::Result::kSuccess); + EXPECT_EQ(field, "second, still 2nd\t"); + ASSERT_EQ(delimited_file_reader.GetLine(&field), + DelimitedFileReader::Result::kSuccess); + EXPECT_EQ(field, "3rd\n"); + ASSERT_EQ(delimited_file_reader.GetDelim('\n', &field), + DelimitedFileReader::Result::kSuccess); + EXPECT_EQ(field, "also\tnewline\n"); + ASSERT_EQ(delimited_file_reader.GetDelim('$', &field), + DelimitedFileReader::Result::kSuccess); + EXPECT_EQ(field, "55555$"); + EXPECT_EQ(delimited_file_reader.GetDelim('?', &field), + DelimitedFileReader::Result::kEndOfFile); // The file is still at EOF. - EXPECT_EQ(DelimitedFileReader::Result::kEndOfFile, - delimited_file_reader.GetLine(&field)); + EXPECT_EQ(delimited_file_reader.GetLine(&field), + DelimitedFileReader::Result::kEndOfFile); } TEST(DelimitedFileReader, EmptyLineMultiLineFile) { @@ -170,24 +170,24 @@ TEST(DelimitedFileReader, EmptyLineMultiLineFile) { DelimitedFileReader delimited_file_reader(&string_file); std::string line; - ASSERT_EQ(DelimitedFileReader::Result::kSuccess, - delimited_file_reader.GetLine(&line)); - EXPECT_EQ("first\n", line); - ASSERT_EQ(DelimitedFileReader::Result::kSuccess, - delimited_file_reader.GetLine(&line)); - EXPECT_EQ("\n", line); - ASSERT_EQ(DelimitedFileReader::Result::kSuccess, - delimited_file_reader.GetLine(&line)); - EXPECT_EQ("\n", line); - ASSERT_EQ(DelimitedFileReader::Result::kSuccess, - delimited_file_reader.GetLine(&line)); - EXPECT_EQ("4444\n", line); - EXPECT_EQ(DelimitedFileReader::Result::kEndOfFile, - delimited_file_reader.GetLine(&line)); + ASSERT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kSuccess); + EXPECT_EQ(line, "first\n"); + ASSERT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kSuccess); + EXPECT_EQ(line, "\n"); + ASSERT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kSuccess); + EXPECT_EQ(line, "\n"); + ASSERT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kSuccess); + EXPECT_EQ(line, "4444\n"); + EXPECT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kEndOfFile); // The file is still at EOF. - EXPECT_EQ(DelimitedFileReader::Result::kEndOfFile, - delimited_file_reader.GetLine(&line)); + EXPECT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kEndOfFile); } TEST(DelimitedFileReader, LongOneLineFile) { @@ -200,15 +200,15 @@ TEST(DelimitedFileReader, LongOneLineFile) { DelimitedFileReader delimited_file_reader(&string_file); std::string line; - ASSERT_EQ(DelimitedFileReader::Result::kSuccess, - delimited_file_reader.GetLine(&line)); - EXPECT_EQ(contents, line); - EXPECT_EQ(DelimitedFileReader::Result::kEndOfFile, - delimited_file_reader.GetLine(&line)); + ASSERT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kSuccess); + EXPECT_EQ(line, contents); + EXPECT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kEndOfFile); // The file is still at EOF. - EXPECT_EQ(DelimitedFileReader::Result::kEndOfFile, - delimited_file_reader.GetLine(&line)); + EXPECT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kEndOfFile); } void TestLongMultiLineFile(int base_length) { @@ -236,16 +236,16 @@ void TestLongMultiLineFile(int base_length) { std::string line; for (size_t line_index = 0; line_index < lines.size(); ++line_index) { SCOPED_TRACE(base::StringPrintf("line_index %" PRIuS, line_index)); - ASSERT_EQ(DelimitedFileReader::Result::kSuccess, - delimited_file_reader.GetLine(&line)); - EXPECT_EQ(lines[line_index], line); + ASSERT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kSuccess); + EXPECT_EQ(line, lines[line_index]); } - EXPECT_EQ(DelimitedFileReader::Result::kEndOfFile, - delimited_file_reader.GetLine(&line)); + EXPECT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kEndOfFile); // The file is still at EOF. - EXPECT_EQ(DelimitedFileReader::Result::kEndOfFile, - delimited_file_reader.GetLine(&line)); + EXPECT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kEndOfFile); } TEST(DelimitedFileReader, LongMultiLineFile) { @@ -263,15 +263,15 @@ TEST(DelimitedFileReader, EmbeddedNUL) { DelimitedFileReader delimited_file_reader(&string_file); std::string line; - ASSERT_EQ(DelimitedFileReader::Result::kSuccess, - delimited_file_reader.GetLine(&line)); - EXPECT_EQ(string_file.string(), line); - EXPECT_EQ(DelimitedFileReader::Result::kEndOfFile, - delimited_file_reader.GetLine(&line)); + ASSERT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kSuccess); + EXPECT_EQ(line, string_file.string()); + EXPECT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kEndOfFile); // The file is still at EOF. - EXPECT_EQ(DelimitedFileReader::Result::kEndOfFile, - delimited_file_reader.GetLine(&line)); + EXPECT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kEndOfFile); } TEST(DelimitedFileReader, NULDelimiter) { @@ -281,21 +281,21 @@ TEST(DelimitedFileReader, NULDelimiter) { DelimitedFileReader delimited_file_reader(&string_file); std::string field; - ASSERT_EQ(DelimitedFileReader::Result::kSuccess, - delimited_file_reader.GetDelim('\0', &field)); - EXPECT_EQ(std::string("aa\0", 3), field); - ASSERT_EQ(DelimitedFileReader::Result::kSuccess, - delimited_file_reader.GetDelim('\0', &field)); - EXPECT_EQ(std::string("b\0", 2), field); - ASSERT_EQ(DelimitedFileReader::Result::kSuccess, - delimited_file_reader.GetDelim('\0', &field)); - EXPECT_EQ(std::string("ccc\0", 4), field); - EXPECT_EQ(DelimitedFileReader::Result::kEndOfFile, - delimited_file_reader.GetDelim('\0', &field)); + ASSERT_EQ(delimited_file_reader.GetDelim('\0', &field), + DelimitedFileReader::Result::kSuccess); + EXPECT_EQ(field, std::string("aa\0", 3)); + ASSERT_EQ(delimited_file_reader.GetDelim('\0', &field), + DelimitedFileReader::Result::kSuccess); + EXPECT_EQ(field, std::string("b\0", 2)); + ASSERT_EQ(delimited_file_reader.GetDelim('\0', &field), + DelimitedFileReader::Result::kSuccess); + EXPECT_EQ(field, std::string("ccc\0", 4)); + EXPECT_EQ(delimited_file_reader.GetDelim('\0', &field), + DelimitedFileReader::Result::kEndOfFile); // The file is still at EOF. - EXPECT_EQ(DelimitedFileReader::Result::kEndOfFile, - delimited_file_reader.GetDelim('\0', &field)); + EXPECT_EQ(delimited_file_reader.GetDelim('\0', &field), + DelimitedFileReader::Result::kEndOfFile); } TEST(DelimitedFileReader, EdgeCases) { @@ -313,48 +313,48 @@ TEST(DelimitedFileReader, EdgeCases) { DelimitedFileReader delimited_file_reader(&string_file); std::string line; - ASSERT_EQ(DelimitedFileReader::Result::kSuccess, - delimited_file_reader.GetLine(&line)); - EXPECT_EQ(line_0, line); - EXPECT_EQ(DelimitedFileReader::Result::kEndOfFile, - delimited_file_reader.GetLine(&line)); + ASSERT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kSuccess); + EXPECT_EQ(line, line_0); + EXPECT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kEndOfFile); // The file is still at EOF. - EXPECT_EQ(DelimitedFileReader::Result::kEndOfFile, - delimited_file_reader.GetLine(&line)); + EXPECT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kEndOfFile); std::string line_1(size, '@'); line_1.push_back('\n'); string_file.SetString(line_0 + line_1); - ASSERT_EQ(DelimitedFileReader::Result::kSuccess, - delimited_file_reader.GetLine(&line)); - EXPECT_EQ(line_0, line); - ASSERT_EQ(DelimitedFileReader::Result::kSuccess, - delimited_file_reader.GetLine(&line)); - EXPECT_EQ(line_1, line); - EXPECT_EQ(DelimitedFileReader::Result::kEndOfFile, - delimited_file_reader.GetLine(&line)); + ASSERT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kSuccess); + EXPECT_EQ(line, line_0); + ASSERT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kSuccess); + EXPECT_EQ(line, line_1); + EXPECT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kEndOfFile); // The file is still at EOF. - EXPECT_EQ(DelimitedFileReader::Result::kEndOfFile, - delimited_file_reader.GetLine(&line)); + EXPECT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kEndOfFile); line_1[size] = '?'; string_file.SetString(line_0 + line_1); - ASSERT_EQ(DelimitedFileReader::Result::kSuccess, - delimited_file_reader.GetLine(&line)); - EXPECT_EQ(line_0, line); - ASSERT_EQ(DelimitedFileReader::Result::kSuccess, - delimited_file_reader.GetLine(&line)); - EXPECT_EQ(line_1, line); - EXPECT_EQ(DelimitedFileReader::Result::kEndOfFile, - delimited_file_reader.GetLine(&line)); + ASSERT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kSuccess); + EXPECT_EQ(line, line_0); + ASSERT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kSuccess); + EXPECT_EQ(line, line_1); + EXPECT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kEndOfFile); // The file is still at EOF. - EXPECT_EQ(DelimitedFileReader::Result::kEndOfFile, - delimited_file_reader.GetLine(&line)); + EXPECT_EQ(delimited_file_reader.GetLine(&line), + DelimitedFileReader::Result::kEndOfFile); } } diff --git a/util/file/file_io_test.cc b/util/file/file_io_test.cc index c4e60585..a784abd2 100644 --- a/util/file/file_io_test.cc +++ b/util/file/file_io_test.cc @@ -381,57 +381,57 @@ void TestOpenFileForWrite(FileHandle (*opener)(const base::FilePath&, ScopedFileHandle file_handle(opener(file_path_1, FileWriteMode::kReuseOrFail, FilePermissions::kWorldReadable)); - EXPECT_EQ(kInvalidFileHandle, file_handle); + EXPECT_EQ(file_handle, kInvalidFileHandle); EXPECT_FALSE(FileExists(file_path_1)); file_handle.reset(opener(file_path_1, FileWriteMode::kCreateOrFail, FilePermissions::kWorldReadable)); - EXPECT_NE(kInvalidFileHandle, file_handle); + EXPECT_NE(file_handle, kInvalidFileHandle); EXPECT_TRUE(FileExists(file_path_1)); - EXPECT_EQ(0, FileSize(file_path_1)); + EXPECT_EQ(FileSize(file_path_1), 0); file_handle.reset(opener(file_path_1, FileWriteMode::kReuseOrCreate, FilePermissions::kWorldReadable)); - EXPECT_NE(kInvalidFileHandle, file_handle); + EXPECT_NE(file_handle, kInvalidFileHandle); EXPECT_TRUE(FileExists(file_path_1)); - EXPECT_EQ(0, FileSize(file_path_1)); + EXPECT_EQ(FileSize(file_path_1), 0); const char data = '%'; EXPECT_TRUE(LoggingWriteFile(file_handle.get(), &data, sizeof(data))); // Close file_handle to ensure that the write is flushed to disk. file_handle.reset(); - EXPECT_EQ(implicit_cast(sizeof(data)), FileSize(file_path_1)); + EXPECT_EQ(FileSize(file_path_1), implicit_cast(sizeof(data))); file_handle.reset(opener(file_path_1, FileWriteMode::kReuseOrCreate, FilePermissions::kWorldReadable)); - EXPECT_NE(kInvalidFileHandle, file_handle); + EXPECT_NE(file_handle, kInvalidFileHandle); EXPECT_TRUE(FileExists(file_path_1)); - EXPECT_EQ(implicit_cast(sizeof(data)), FileSize(file_path_1)); + EXPECT_EQ(FileSize(file_path_1), implicit_cast(sizeof(data))); file_handle.reset(opener(file_path_1, FileWriteMode::kCreateOrFail, FilePermissions::kWorldReadable)); - EXPECT_EQ(kInvalidFileHandle, file_handle); + EXPECT_EQ(file_handle, kInvalidFileHandle); EXPECT_TRUE(FileExists(file_path_1)); - EXPECT_EQ(implicit_cast(sizeof(data)), FileSize(file_path_1)); + EXPECT_EQ(FileSize(file_path_1), implicit_cast(sizeof(data))); file_handle.reset(opener(file_path_1, FileWriteMode::kReuseOrFail, FilePermissions::kWorldReadable)); - EXPECT_NE(kInvalidFileHandle, file_handle); + EXPECT_NE(file_handle, kInvalidFileHandle); EXPECT_TRUE(FileExists(file_path_1)); - EXPECT_EQ(implicit_cast(sizeof(data)), FileSize(file_path_1)); + EXPECT_EQ(FileSize(file_path_1), implicit_cast(sizeof(data))); file_handle.reset(opener(file_path_1, FileWriteMode::kTruncateOrCreate, FilePermissions::kWorldReadable)); - EXPECT_NE(kInvalidFileHandle, file_handle); + EXPECT_NE(file_handle, kInvalidFileHandle); EXPECT_TRUE(FileExists(file_path_1)); - EXPECT_EQ(0, FileSize(file_path_1)); + EXPECT_EQ(FileSize(file_path_1), 0); base::FilePath file_path_2 = temp_dir.path().Append(FILE_PATH_LITERAL("file_2")); @@ -440,9 +440,9 @@ void TestOpenFileForWrite(FileHandle (*opener)(const base::FilePath&, file_handle.reset(opener(file_path_2, FileWriteMode::kTruncateOrCreate, FilePermissions::kWorldReadable)); - EXPECT_NE(kInvalidFileHandle, file_handle); + EXPECT_NE(file_handle, kInvalidFileHandle); EXPECT_TRUE(FileExists(file_path_2)); - EXPECT_EQ(0, FileSize(file_path_2)); + EXPECT_EQ(FileSize(file_path_2), 0); base::FilePath file_path_3 = temp_dir.path().Append(FILE_PATH_LITERAL("file_3")); @@ -451,9 +451,9 @@ void TestOpenFileForWrite(FileHandle (*opener)(const base::FilePath&, file_handle.reset(opener(file_path_3, FileWriteMode::kReuseOrCreate, FilePermissions::kWorldReadable)); - EXPECT_NE(kInvalidFileHandle, file_handle); + EXPECT_NE(file_handle, kInvalidFileHandle); EXPECT_TRUE(FileExists(file_path_3)); - EXPECT_EQ(0, FileSize(file_path_3)); + EXPECT_EQ(FileSize(file_path_3), 0); } TEST(FileIO, OpenFileForWrite) { @@ -625,7 +625,7 @@ void LockingTest(FileLocking main_lock, FileLocking other_locks) { base::subtle::Atomic32 result = base::subtle::NoBarrier_Load(&actual_iterations); - EXPECT_EQ(0, result); + EXPECT_EQ(result, 0); ASSERT_TRUE(LoggingUnlockFile(initial.get())); @@ -633,7 +633,7 @@ void LockingTest(FileLocking main_lock, FileLocking other_locks) { t.Join(); result = base::subtle::NoBarrier_Load(&actual_iterations); - EXPECT_EQ(expected_iterations, result); + EXPECT_EQ(result, expected_iterations); } TEST(FileIO, ExclusiveVsExclusives) { @@ -649,7 +649,7 @@ TEST(FileIO, SharedVsExclusives) { } TEST(FileIO, FileSizeByHandle) { - EXPECT_EQ(-1, LoggingFileSizeByHandle(kInvalidFileHandle)); + EXPECT_EQ(LoggingFileSizeByHandle(kInvalidFileHandle), -1); ScopedTempDir temp_dir; base::FilePath file_path = @@ -657,13 +657,13 @@ TEST(FileIO, FileSizeByHandle) { ScopedFileHandle file_handle(LoggingOpenFileForWrite( file_path, FileWriteMode::kCreateOrFail, FilePermissions::kOwnerOnly)); - ASSERT_NE(kInvalidFileHandle, file_handle.get()); - EXPECT_EQ(0, LoggingFileSizeByHandle(file_handle.get())); + ASSERT_NE(file_handle.get(), kInvalidFileHandle); + EXPECT_EQ(LoggingFileSizeByHandle(file_handle.get()), 0); const char data[] = "zippyzap"; ASSERT_TRUE(LoggingWriteFile(file_handle.get(), &data, sizeof(data))); - EXPECT_EQ(9, LoggingFileSizeByHandle(file_handle.get())); + EXPECT_EQ(LoggingFileSizeByHandle(file_handle.get()), 9); } FileHandle FileHandleForFILE(FILE* file) { @@ -678,12 +678,12 @@ FileHandle FileHandleForFILE(FILE* file) { } TEST(FileIO, StdioFileHandle) { - EXPECT_EQ(FileHandleForFILE(stdin), - StdioFileHandle(StdioStream::kStandardInput)); - EXPECT_EQ(FileHandleForFILE(stdout), - StdioFileHandle(StdioStream::kStandardOutput)); - EXPECT_EQ(FileHandleForFILE(stderr), - StdioFileHandle(StdioStream::kStandardError)); + EXPECT_EQ(StdioFileHandle(StdioStream::kStandardInput), + FileHandleForFILE(stdin)); + EXPECT_EQ(StdioFileHandle(StdioStream::kStandardOutput), + FileHandleForFILE(stdout)); + EXPECT_EQ(StdioFileHandle(StdioStream::kStandardError), + FileHandleForFILE(stderr)); } } // namespace diff --git a/util/file/string_file_test.cc b/util/file/string_file_test.cc index 1b154bb9..5c8512ba 100644 --- a/util/file/string_file_test.cc +++ b/util/file/string_file_test.cc @@ -30,15 +30,15 @@ namespace { TEST(StringFile, EmptyFile) { StringFile string_file; EXPECT_TRUE(string_file.string().empty()); - EXPECT_EQ(0, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 0); EXPECT_TRUE(string_file.Write("", 0)); EXPECT_TRUE(string_file.string().empty()); - EXPECT_EQ(0, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 0); char c = '6'; - EXPECT_EQ(0, string_file.Read(&c, 1)); - EXPECT_EQ('6', c); - EXPECT_EQ(0, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.Read(&c, 1), 0); + EXPECT_EQ(c, '6'); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 0); EXPECT_TRUE(string_file.string().empty()); } @@ -47,76 +47,76 @@ TEST(StringFile, OneByteFile) { StringFile string_file; EXPECT_TRUE(string_file.Write("a", 1)); - EXPECT_EQ(1u, string_file.string().size()); - EXPECT_EQ("a", string_file.string()); - EXPECT_EQ(1, string_file.Seek(0, SEEK_CUR)); - EXPECT_EQ(0, string_file.Seek(0, SEEK_SET)); + EXPECT_EQ(string_file.string().size(), 1u); + EXPECT_EQ(string_file.string(), "a"); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 1); + EXPECT_EQ(string_file.Seek(0, SEEK_SET), 0); char c = '6'; - EXPECT_EQ(1, string_file.Read(&c, 1)); - EXPECT_EQ('a', c); - EXPECT_EQ(1, string_file.Seek(0, SEEK_CUR)); - EXPECT_EQ(0, string_file.Read(&c, 1)); - EXPECT_EQ('a', c); - EXPECT_EQ(1, string_file.Seek(0, SEEK_CUR)); - EXPECT_EQ("a", string_file.string()); + EXPECT_EQ(string_file.Read(&c, 1), 1); + EXPECT_EQ(c, 'a'); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 1); + EXPECT_EQ(string_file.Read(&c, 1), 0); + EXPECT_EQ(c, 'a'); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 1); + EXPECT_EQ(string_file.string(), "a"); - EXPECT_EQ(0, string_file.Seek(0, SEEK_SET)); + EXPECT_EQ(string_file.Seek(0, SEEK_SET), 0); EXPECT_TRUE(string_file.Write("b", 1)); - EXPECT_EQ(1u, string_file.string().size()); - EXPECT_EQ("b", string_file.string()); - EXPECT_EQ(1, string_file.Seek(0, SEEK_CUR)); - EXPECT_EQ(0, string_file.Seek(0, SEEK_SET)); - EXPECT_EQ(1, string_file.Read(&c, 1)); - EXPECT_EQ('b', c); - EXPECT_EQ(1, string_file.Seek(0, SEEK_CUR)); - EXPECT_EQ(0, string_file.Read(&c, 1)); - EXPECT_EQ('b', c); - EXPECT_EQ(1, string_file.Seek(0, SEEK_CUR)); - EXPECT_EQ("b", string_file.string()); + EXPECT_EQ(string_file.string().size(), 1u); + EXPECT_EQ(string_file.string(), "b"); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 1); + EXPECT_EQ(string_file.Seek(0, SEEK_SET), 0); + EXPECT_EQ(string_file.Read(&c, 1), 1); + EXPECT_EQ(c, 'b'); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 1); + EXPECT_EQ(string_file.Read(&c, 1), 0); + EXPECT_EQ(c, 'b'); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 1); + EXPECT_EQ(string_file.string(), "b"); - EXPECT_EQ(0, string_file.Seek(0, SEEK_SET)); + EXPECT_EQ(string_file.Seek(0, SEEK_SET), 0); EXPECT_TRUE(string_file.Write("\0", 1)); - EXPECT_EQ(1u, string_file.string().size()); - EXPECT_EQ('\0', string_file.string()[0]); - EXPECT_EQ(1, string_file.Seek(0, SEEK_CUR)); - EXPECT_EQ(1u, string_file.string().size()); - EXPECT_EQ('\0', string_file.string()[0]); + EXPECT_EQ(string_file.string().size(), 1u); + EXPECT_EQ(string_file.string()[0], '\0'); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 1); + EXPECT_EQ(string_file.string().size(), 1u); + EXPECT_EQ(string_file.string()[0], '\0'); } TEST(StringFile, SetString) { char kString1[] = "Four score"; StringFile string_file; string_file.SetString(kString1); - EXPECT_EQ(0, string_file.Seek(0, SEEK_SET)); + EXPECT_EQ(string_file.Seek(0, SEEK_SET), 0); char buf[5] = "****"; - EXPECT_EQ(4, string_file.Read(buf, 4)); + EXPECT_EQ(string_file.Read(buf, 4), 4); EXPECT_STREQ("Four", buf); - EXPECT_EQ(4, string_file.Seek(0, SEEK_CUR)); - EXPECT_EQ(static_cast(strlen(kString1)), - string_file.Seek(0, SEEK_END)); - EXPECT_EQ(kString1, string_file.string()); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 4); + EXPECT_EQ(string_file.Seek(0, SEEK_END), + static_cast(strlen(kString1))); + EXPECT_EQ(string_file.string(), kString1); char kString2[] = "and seven years ago"; - EXPECT_EQ(4, string_file.Seek(4, SEEK_SET)); - EXPECT_EQ(4, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(4, SEEK_SET), 4); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 4); string_file.SetString(kString2); - EXPECT_EQ(0, string_file.Seek(0, SEEK_CUR)); - EXPECT_EQ(4, string_file.Read(buf, 4)); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 0); + EXPECT_EQ(string_file.Read(buf, 4), 4); EXPECT_STREQ("and ", buf); - EXPECT_EQ(static_cast(strlen(kString2)), - string_file.Seek(0, SEEK_END)); - EXPECT_EQ(kString2, string_file.string()); + EXPECT_EQ(string_file.Seek(0, SEEK_END), + static_cast(strlen(kString2))); + EXPECT_EQ(string_file.string(), kString2); char kString3[] = "our fathers"; - EXPECT_EQ(4, string_file.Seek(4, SEEK_SET)); - EXPECT_EQ(4, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(4, SEEK_SET), 4); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 4); string_file.SetString(kString3); - EXPECT_EQ(0, string_file.Seek(0, SEEK_CUR)); - EXPECT_EQ(4, string_file.Read(buf, 4)); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 0); + EXPECT_EQ(string_file.Read(buf, 4), 4); EXPECT_STREQ("our ", buf); - EXPECT_EQ(static_cast(strlen(kString3)), - string_file.Seek(0, SEEK_END)); - EXPECT_EQ(kString3, string_file.string()); + EXPECT_EQ(string_file.Seek(0, SEEK_END), + static_cast(strlen(kString3))); + EXPECT_EQ(string_file.string(), kString3); } TEST(StringFile, ReadExactly) { @@ -134,83 +134,83 @@ TEST(StringFile, Reset) { StringFile string_file; EXPECT_TRUE(string_file.Write("abc", 3)); - EXPECT_EQ(3u, string_file.string().size()); - EXPECT_EQ("abc", string_file.string()); - EXPECT_EQ(3, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.string().size(), 3u); + EXPECT_EQ(string_file.string(), "abc"); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 3); char buf[10] = "*********"; - EXPECT_EQ(0, string_file.Seek(0, SEEK_SET)); - EXPECT_EQ(3, string_file.Read(&buf, 10)); + EXPECT_EQ(string_file.Seek(0, SEEK_SET), 0); + EXPECT_EQ(string_file.Read(&buf, 10), 3); EXPECT_STREQ("abc******", buf); - EXPECT_EQ(3, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 3); EXPECT_FALSE(string_file.string().empty()); string_file.Reset(); EXPECT_TRUE(string_file.string().empty()); - EXPECT_EQ(0, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 0); EXPECT_TRUE(string_file.Write("de", 2)); - EXPECT_EQ(2u, string_file.string().size()); - EXPECT_EQ("de", string_file.string()); - EXPECT_EQ(2, string_file.Seek(0, SEEK_CUR)); - EXPECT_EQ(0, string_file.Seek(0, SEEK_SET)); - EXPECT_EQ(2, string_file.Read(&buf, 10)); + EXPECT_EQ(string_file.string().size(), 2u); + EXPECT_EQ(string_file.string(), "de"); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 2); + EXPECT_EQ(string_file.Seek(0, SEEK_SET), 0); + EXPECT_EQ(string_file.Read(&buf, 10), 2); EXPECT_STREQ("dec******", buf); - EXPECT_EQ(2, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 2); EXPECT_FALSE(string_file.string().empty()); string_file.Reset(); EXPECT_TRUE(string_file.string().empty()); - EXPECT_EQ(0, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 0); EXPECT_TRUE(string_file.Write("fghi", 4)); - EXPECT_EQ(4u, string_file.string().size()); - EXPECT_EQ("fghi", string_file.string()); - EXPECT_EQ(4, string_file.Seek(0, SEEK_CUR)); - EXPECT_EQ(0, string_file.Seek(0, SEEK_SET)); - EXPECT_EQ(2, string_file.Read(&buf, 2)); + EXPECT_EQ(string_file.string().size(), 4u); + EXPECT_EQ(string_file.string(), "fghi"); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 4); + EXPECT_EQ(string_file.Seek(0, SEEK_SET), 0); + EXPECT_EQ(string_file.Read(&buf, 2), 2); EXPECT_STREQ("fgc******", buf); - EXPECT_EQ(2, string_file.Seek(0, SEEK_CUR)); - EXPECT_EQ(2, string_file.Read(&buf, 2)); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 2); + EXPECT_EQ(string_file.Read(&buf, 2), 2); EXPECT_STREQ("hic******", buf); - EXPECT_EQ(4, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 4); EXPECT_FALSE(string_file.string().empty()); string_file.Reset(); EXPECT_TRUE(string_file.string().empty()); - EXPECT_EQ(0, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 0); // Test resetting after a sparse write. - EXPECT_EQ(1, string_file.Seek(1, SEEK_SET)); + EXPECT_EQ(string_file.Seek(1, SEEK_SET), 1); EXPECT_TRUE(string_file.Write("j", 1)); - EXPECT_EQ(2u, string_file.string().size()); - EXPECT_EQ(std::string("\0j", 2), string_file.string()); - EXPECT_EQ(2, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.string().size(), 2u); + EXPECT_EQ(string_file.string(), std::string("\0j", 2)); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 2); EXPECT_FALSE(string_file.string().empty()); string_file.Reset(); EXPECT_TRUE(string_file.string().empty()); - EXPECT_EQ(0, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 0); } TEST(StringFile, WriteInvalid) { StringFile string_file; - EXPECT_EQ(0, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 0); EXPECT_FALSE(string_file.Write( "", implicit_cast(std::numeric_limits::max()) + 1)); EXPECT_TRUE(string_file.string().empty()); - EXPECT_EQ(0, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 0); EXPECT_TRUE(string_file.Write("a", 1)); EXPECT_FALSE(string_file.Write( "", implicit_cast(std::numeric_limits::max()))); - EXPECT_EQ(1u, string_file.string().size()); - EXPECT_EQ("a", string_file.string()); - EXPECT_EQ(1, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.string().size(), 1u); + EXPECT_EQ(string_file.string(), "a"); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 1); } TEST(StringFile, WriteIoVec) { @@ -223,23 +223,23 @@ TEST(StringFile, WriteIoVec) { iovecs.push_back(iov); EXPECT_TRUE(string_file.WriteIoVec(&iovecs)); EXPECT_TRUE(string_file.string().empty()); - EXPECT_EQ(0, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 0); iovecs.clear(); iov.iov_base = "a"; iov.iov_len = 1; iovecs.push_back(iov); EXPECT_TRUE(string_file.WriteIoVec(&iovecs)); - EXPECT_EQ(1u, string_file.string().size()); - EXPECT_EQ("a", string_file.string()); - EXPECT_EQ(1, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.string().size(), 1u); + EXPECT_EQ(string_file.string(), "a"); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 1); iovecs.clear(); iovecs.push_back(iov); EXPECT_TRUE(string_file.WriteIoVec(&iovecs)); - EXPECT_EQ(2u, string_file.string().size()); - EXPECT_EQ("aa", string_file.string()); - EXPECT_EQ(2, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.string().size(), 2u); + EXPECT_EQ(string_file.string(), "aa"); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 2); iovecs.clear(); iovecs.push_back(iov); @@ -247,14 +247,14 @@ TEST(StringFile, WriteIoVec) { iov.iov_len = 2; iovecs.push_back(iov); EXPECT_TRUE(string_file.WriteIoVec(&iovecs)); - EXPECT_EQ(5u, string_file.string().size()); - EXPECT_EQ("aaabc", string_file.string()); - EXPECT_EQ(5, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.string().size(), 5u); + EXPECT_EQ(string_file.string(), "aaabc"); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 5); EXPECT_TRUE(string_file.Write("def", 3)); - EXPECT_EQ(8u, string_file.string().size()); - EXPECT_EQ("aaabcdef", string_file.string()); - EXPECT_EQ(8, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.string().size(), 8u); + EXPECT_EQ(string_file.string(), "aaabcdef"); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 8); iovecs.clear(); iov.iov_base = "ghij"; @@ -264,23 +264,23 @@ TEST(StringFile, WriteIoVec) { iov.iov_len = 5; iovecs.push_back(iov); EXPECT_TRUE(string_file.WriteIoVec(&iovecs)); - EXPECT_EQ(17u, string_file.string().size()); - EXPECT_EQ("aaabcdefghijklmno", string_file.string()); - EXPECT_EQ(17, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.string().size(), 17u); + EXPECT_EQ(string_file.string(), "aaabcdefghijklmno"); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 17); string_file.Reset(); EXPECT_TRUE(string_file.string().empty()); - EXPECT_EQ(0, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 0); iovecs.clear(); iov.iov_base = "abcd"; iov.iov_len = 4; iovecs.resize(16, iov); EXPECT_TRUE(string_file.WriteIoVec(&iovecs)); - EXPECT_EQ(64u, string_file.string().size()); - EXPECT_EQ("abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd", - string_file.string()); - EXPECT_EQ(64, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.string().size(), 64u); + EXPECT_EQ(string_file.string(), + "abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd"); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 64); } TEST(StringFile, WriteIoVecInvalid) { @@ -289,16 +289,16 @@ TEST(StringFile, WriteIoVecInvalid) { std::vector iovecs; EXPECT_FALSE(string_file.WriteIoVec(&iovecs)); EXPECT_TRUE(string_file.string().empty()); - EXPECT_EQ(0, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 0); WritableIoVec iov; - EXPECT_EQ(1, string_file.Seek(1, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(1, SEEK_CUR), 1); iov.iov_base = "a"; iov.iov_len = std::numeric_limits::max(); iovecs.push_back(iov); EXPECT_FALSE(string_file.WriteIoVec(&iovecs)); EXPECT_TRUE(string_file.string().empty()); - EXPECT_EQ(1, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 1); iovecs.clear(); iov.iov_base = "a"; @@ -308,158 +308,158 @@ TEST(StringFile, WriteIoVecInvalid) { iovecs.push_back(iov); EXPECT_FALSE(string_file.WriteIoVec(&iovecs)); EXPECT_TRUE(string_file.string().empty()); - EXPECT_EQ(1, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 1); } TEST(StringFile, Seek) { StringFile string_file; EXPECT_TRUE(string_file.Write("abcd", 4)); - EXPECT_EQ(4u, string_file.string().size()); - EXPECT_EQ("abcd", string_file.string()); - EXPECT_EQ(4, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.string().size(), 4u); + EXPECT_EQ(string_file.string(), "abcd"); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 4); - EXPECT_EQ(0, string_file.Seek(0, SEEK_SET)); + EXPECT_EQ(string_file.Seek(0, SEEK_SET), 0); EXPECT_TRUE(string_file.Write("efgh", 4)); - EXPECT_EQ(4u, string_file.string().size()); - EXPECT_EQ("efgh", string_file.string()); - EXPECT_EQ(4, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.string().size(), 4u); + EXPECT_EQ(string_file.string(), "efgh"); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 4); - EXPECT_EQ(0, string_file.Seek(0, SEEK_SET)); + EXPECT_EQ(string_file.Seek(0, SEEK_SET), 0); EXPECT_TRUE(string_file.Write("ijk", 3)); - EXPECT_EQ(4u, string_file.string().size()); - EXPECT_EQ("ijkh", string_file.string()); - EXPECT_EQ(3, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.string().size(), 4u); + EXPECT_EQ(string_file.string(), "ijkh"); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 3); - EXPECT_EQ(0, string_file.Seek(0, SEEK_SET)); + EXPECT_EQ(string_file.Seek(0, SEEK_SET), 0); EXPECT_TRUE(string_file.Write("lmnop", 5)); - EXPECT_EQ(5u, string_file.string().size()); - EXPECT_EQ("lmnop", string_file.string()); - EXPECT_EQ(5, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.string().size(), 5u); + EXPECT_EQ(string_file.string(), "lmnop"); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 5); - EXPECT_EQ(1, string_file.Seek(1, SEEK_SET)); + EXPECT_EQ(string_file.Seek(1, SEEK_SET), 1); EXPECT_TRUE(string_file.Write("q", 1)); - EXPECT_EQ(5u, string_file.string().size()); - EXPECT_EQ("lqnop", string_file.string()); - EXPECT_EQ(2, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.string().size(), 5u); + EXPECT_EQ(string_file.string(), "lqnop"); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 2); - EXPECT_EQ(1, string_file.Seek(-1, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(-1, SEEK_CUR), 1); EXPECT_TRUE(string_file.Write("r", 1)); - EXPECT_EQ(5u, string_file.string().size()); - EXPECT_EQ("lrnop", string_file.string()); - EXPECT_EQ(2, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.string().size(), 5u); + EXPECT_EQ(string_file.string(), "lrnop"); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 2); EXPECT_TRUE(string_file.Write("s", 1)); - EXPECT_EQ(5u, string_file.string().size()); - EXPECT_EQ("lrsop", string_file.string()); - EXPECT_EQ(3, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.string().size(), 5u); + EXPECT_EQ(string_file.string(), "lrsop"); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 3); - EXPECT_EQ(2, string_file.Seek(-1, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(-1, SEEK_CUR), 2); EXPECT_TRUE(string_file.Write("t", 1)); - EXPECT_EQ(5u, string_file.string().size()); - EXPECT_EQ("lrtop", string_file.string()); - EXPECT_EQ(3, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.string().size(), 5u); + EXPECT_EQ(string_file.string(), "lrtop"); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 3); - EXPECT_EQ(4, string_file.Seek(-1, SEEK_END)); + EXPECT_EQ(string_file.Seek(-1, SEEK_END), 4); EXPECT_TRUE(string_file.Write("u", 1)); - EXPECT_EQ(5u, string_file.string().size()); - EXPECT_EQ("lrtou", string_file.string()); - EXPECT_EQ(5, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.string().size(), 5u); + EXPECT_EQ(string_file.string(), "lrtou"); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 5); - EXPECT_EQ(0, string_file.Seek(-5, SEEK_END)); + EXPECT_EQ(string_file.Seek(-5, SEEK_END), 0); EXPECT_TRUE(string_file.Write("v", 1)); - EXPECT_EQ(5u, string_file.string().size()); - EXPECT_EQ("vrtou", string_file.string()); - EXPECT_EQ(1, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.string().size(), 5u); + EXPECT_EQ(string_file.string(), "vrtou"); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 1); - EXPECT_EQ(5, string_file.Seek(0, SEEK_END)); + EXPECT_EQ(string_file.Seek(0, SEEK_END), 5); EXPECT_TRUE(string_file.Write("w", 1)); - EXPECT_EQ(6u, string_file.string().size()); - EXPECT_EQ("vrtouw", string_file.string()); - EXPECT_EQ(6, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.string().size(), 6u); + EXPECT_EQ(string_file.string(), "vrtouw"); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 6); - EXPECT_EQ(8, string_file.Seek(2, SEEK_END)); - EXPECT_EQ(6u, string_file.string().size()); - EXPECT_EQ("vrtouw", string_file.string()); + EXPECT_EQ(string_file.Seek(2, SEEK_END), 8); + EXPECT_EQ(string_file.string().size(), 6u); + EXPECT_EQ(string_file.string(), "vrtouw"); - EXPECT_EQ(6, string_file.Seek(0, SEEK_END)); + EXPECT_EQ(string_file.Seek(0, SEEK_END), 6); EXPECT_TRUE(string_file.Write("x", 1)); - EXPECT_EQ(7u, string_file.string().size()); - EXPECT_EQ("vrtouwx", string_file.string()); - EXPECT_EQ(7, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.string().size(), 7u); + EXPECT_EQ(string_file.string(), "vrtouwx"); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 7); } TEST(StringFile, SeekSparse) { StringFile string_file; - EXPECT_EQ(3, string_file.Seek(3, SEEK_SET)); + EXPECT_EQ(string_file.Seek(3, SEEK_SET), 3); EXPECT_TRUE(string_file.string().empty()); - EXPECT_EQ(3, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 3); EXPECT_TRUE(string_file.Write("abc", 3)); - EXPECT_EQ(6u, string_file.string().size()); - EXPECT_EQ(std::string("\0\0\0abc", 6), string_file.string()); - EXPECT_EQ(6, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.string().size(), 6u); + EXPECT_EQ(string_file.string(), std::string("\0\0\0abc", 6)); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 6); - EXPECT_EQ(9, string_file.Seek(3, SEEK_END)); - EXPECT_EQ(6u, string_file.string().size()); - EXPECT_EQ(9, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(3, SEEK_END), 9); + EXPECT_EQ(string_file.string().size(), 6u); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 9); char c; - EXPECT_EQ(0, string_file.Read(&c, 1)); - EXPECT_EQ(9, string_file.Seek(0, SEEK_CUR)); - EXPECT_EQ(6u, string_file.string().size()); + EXPECT_EQ(string_file.Read(&c, 1), 0); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 9); + EXPECT_EQ(string_file.string().size(), 6u); EXPECT_TRUE(string_file.Write("def", 3)); - EXPECT_EQ(12u, string_file.string().size()); - EXPECT_EQ(std::string("\0\0\0abc\0\0\0def", 12), string_file.string()); - EXPECT_EQ(12, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.string().size(), 12u); + EXPECT_EQ(string_file.string(), std::string("\0\0\0abc\0\0\0def", 12)); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 12); - EXPECT_EQ(7, string_file.Seek(-5, SEEK_END)); - EXPECT_EQ(12u, string_file.string().size()); - EXPECT_EQ(7, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(-5, SEEK_END), 7); + EXPECT_EQ(string_file.string().size(), 12u); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 7); EXPECT_TRUE(string_file.Write("g", 1)); - EXPECT_EQ(12u, string_file.string().size()); - EXPECT_EQ(std::string("\0\0\0abc\0g\0def", 12), string_file.string()); - EXPECT_EQ(8, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.string().size(), 12u); + EXPECT_EQ(string_file.string(), std::string("\0\0\0abc\0g\0def", 12)); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 8); - EXPECT_EQ(15, string_file.Seek(7, SEEK_CUR)); - EXPECT_EQ(12u, string_file.string().size()); - EXPECT_EQ(15, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(7, SEEK_CUR), 15); + EXPECT_EQ(string_file.string().size(), 12u); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 15); EXPECT_TRUE(string_file.Write("hij", 3)); - EXPECT_EQ(18u, string_file.string().size()); - EXPECT_EQ(std::string("\0\0\0abc\0g\0def\0\0\0hij", 18), - string_file.string()); - EXPECT_EQ(18, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.string().size(), 18u); + EXPECT_EQ(string_file.string(), + std::string("\0\0\0abc\0g\0def\0\0\0hij", 18)); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 18); - EXPECT_EQ(1, string_file.Seek(-17, SEEK_CUR)); - EXPECT_EQ(18u, string_file.string().size()); - EXPECT_EQ(1, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(-17, SEEK_CUR), 1); + EXPECT_EQ(string_file.string().size(), 18u); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 1); EXPECT_TRUE(string_file.Write("k", 1)); - EXPECT_EQ(18u, string_file.string().size()); - EXPECT_EQ(std::string("\0k\0abc\0g\0def\0\0\0hij", 18), string_file.string()); - EXPECT_EQ(2, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.string().size(), 18u); + EXPECT_EQ(string_file.string(), std::string("\0k\0abc\0g\0def\0\0\0hij", 18)); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 2); EXPECT_TRUE(string_file.Write("l", 1)); EXPECT_TRUE(string_file.Write("mnop", 4)); - EXPECT_EQ(18u, string_file.string().size()); - EXPECT_EQ(std::string("\0klmnopg\0def\0\0\0hij", 18), string_file.string()); - EXPECT_EQ(7, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.string().size(), 18u); + EXPECT_EQ(string_file.string(), std::string("\0klmnopg\0def\0\0\0hij", 18)); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 7); } TEST(StringFile, SeekInvalid) { StringFile string_file; - EXPECT_EQ(0, string_file.Seek(0, SEEK_CUR)); - EXPECT_EQ(1, string_file.Seek(1, SEEK_SET)); - EXPECT_EQ(1, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 0); + EXPECT_EQ(string_file.Seek(1, SEEK_SET), 1); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 1); EXPECT_LT(string_file.Seek(-1, SEEK_SET), 0); - EXPECT_EQ(1, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 1); EXPECT_LT(string_file.Seek(std::numeric_limits::min(), SEEK_SET), 0); - EXPECT_EQ(1, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 1); EXPECT_LT(string_file.Seek(std::numeric_limits::min(), SEEK_SET), 0); - EXPECT_EQ(1, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 1); EXPECT_TRUE(string_file.string().empty()); static_assert(SEEK_SET != 3 && SEEK_CUR != 3 && SEEK_END != 3, @@ -467,37 +467,37 @@ TEST(StringFile, SeekInvalid) { EXPECT_LT(string_file.Seek(0, 3), 0); string_file.Reset(); - EXPECT_EQ(0, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 0); EXPECT_TRUE(string_file.string().empty()); const FileOffset kMaxOffset = static_cast( std::min(implicit_cast(std::numeric_limits::max()), implicit_cast(std::numeric_limits::max()))); - EXPECT_EQ(kMaxOffset, string_file.Seek(kMaxOffset, SEEK_SET)); - EXPECT_EQ(kMaxOffset, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(kMaxOffset, SEEK_SET), kMaxOffset); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), kMaxOffset); EXPECT_LT(string_file.Seek(1, SEEK_CUR), 0); - EXPECT_EQ(1, string_file.Seek(1, SEEK_SET)); - EXPECT_EQ(1, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(1, SEEK_SET), 1); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 1); EXPECT_LT(string_file.Seek(kMaxOffset, SEEK_CUR), 0); } TEST(StringFile, SeekSet) { StringFile string_file; EXPECT_TRUE(string_file.SeekSet(1)); - EXPECT_EQ(1, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 1); EXPECT_TRUE(string_file.SeekSet(0)); - EXPECT_EQ(0, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 0); EXPECT_TRUE(string_file.SeekSet(10)); - EXPECT_EQ(10, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 10); EXPECT_FALSE(string_file.SeekSet(-1)); - EXPECT_EQ(10, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 10); EXPECT_FALSE( string_file.SeekSet(std::numeric_limits::min())); - EXPECT_EQ(10, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 10); EXPECT_FALSE(string_file.SeekSet(std::numeric_limits::min())); - EXPECT_EQ(10, string_file.Seek(0, SEEK_CUR)); + EXPECT_EQ(string_file.Seek(0, SEEK_CUR), 10); } } // namespace diff --git a/util/linux/address_types.h b/util/linux/address_types.h new file mode 100644 index 00000000..8c8f13d7 --- /dev/null +++ b/util/linux/address_types.h @@ -0,0 +1,32 @@ +// Copyright 2017 The Crashpad Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef CRASHPAD_UTIL_LINUX_ADDRESS_TYPES_H_ +#define CRASHPAD_UTIL_LINUX_ADDRESS_TYPES_H_ + +#include + +namespace crashpad { + +//! \brief Type used to represent an address in a process, potentially across +//! bitness. +using LinuxVMAddress = uint64_t; + +//! \brief Type used to represent the size of a memory range (with a +//! LinuxVMAddress), potentially across bitness. +using LinuxVMSize = uint64_t; + +} // namespace crashpad + +#endif // CRASHPAD_UTIL_LINUX_ADDRESS_TYPES_H_ diff --git a/util/linux/process_memory.cc b/util/linux/process_memory.cc new file mode 100644 index 00000000..8f3290ac --- /dev/null +++ b/util/linux/process_memory.cc @@ -0,0 +1,124 @@ +// Copyright 2017 The Crashpad Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "util/linux/process_memory.h" + +#include +#include +#include +#include + +#include + +#include "base/logging.h" +#include "base/posix/eintr_wrapper.h" + +namespace crashpad { + +ProcessMemory::ProcessMemory() : mem_fd_(), pid_(-1) {} + +ProcessMemory::~ProcessMemory() {} + +bool ProcessMemory::Initialize(pid_t pid) { + pid_ = pid; + char path[32]; + snprintf(path, sizeof(path), "/proc/%d/mem", pid_); + mem_fd_.reset(HANDLE_EINTR(open(path, O_RDONLY | O_NOCTTY | O_CLOEXEC))); + if (!mem_fd_.is_valid()) { + PLOG(ERROR) << "open"; + return false; + } + return true; +} + +bool ProcessMemory::Read(LinuxVMAddress address, + size_t size, + void* buffer) const { + DCHECK(mem_fd_.is_valid()); + + char* buffer_c = static_cast(buffer); + while (size > 0) { + ssize_t bytes_read = + HANDLE_EINTR(pread64(mem_fd_.get(), buffer_c, size, address)); + if (bytes_read < 0) { + PLOG(ERROR) << "pread64"; + return false; + } + if (bytes_read == 0) { + LOG(ERROR) << "unexpected eof"; + return false; + } + DCHECK_LE(static_cast(bytes_read), size); + size -= bytes_read; + address += bytes_read; + buffer_c += bytes_read; + } + return true; +} + +bool ProcessMemory::ReadCString(LinuxVMAddress address, + std::string* string) const { + return ReadCStringInternal(address, false, 0, string); +} + +bool ProcessMemory::ReadCStringSizeLimited(LinuxVMAddress address, + size_t size, + std::string* string) const { + return ReadCStringInternal(address, true, size, string); +} + +bool ProcessMemory::ReadCStringInternal(LinuxVMAddress address, + bool has_size, + size_t size, + std::string* string) const { + DCHECK(mem_fd_.is_valid()); + + string->clear(); + + char buffer[4096]; + do { + size_t read_size; + if (has_size) { + read_size = std::min(sizeof(buffer), size); + } else { + read_size = sizeof(buffer); + } + ssize_t bytes_read; + bytes_read = + HANDLE_EINTR(pread64(mem_fd_.get(), buffer, read_size, address)); + if (bytes_read < 0) { + PLOG(ERROR) << "pread64"; + return false; + } + if (bytes_read == 0) { + break; + } + DCHECK_LE(static_cast(bytes_read), read_size); + + char* nul = static_cast(memchr(buffer, '\0', bytes_read)); + if (nul != nullptr) { + string->append(buffer, nul - buffer); + return true; + } + string->append(buffer, bytes_read); + + address += bytes_read; + size -= bytes_read; + } while (!has_size || size > 0); + + LOG(ERROR) << "unterminated string"; + return false; +} + +} // namespace crashpad diff --git a/util/linux/process_memory.h b/util/linux/process_memory.h new file mode 100644 index 00000000..6a04dea3 --- /dev/null +++ b/util/linux/process_memory.h @@ -0,0 +1,105 @@ +// Copyright 2017 The Crashpad Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef CRASHPAD_UTIL_LINUX_PROCESS_MEMORY_H_ +#define CRASHPAD_UTIL_LINUX_PROCESS_MEMORY_H_ + +#include + +#include + +#include "base/files/scoped_file.h" +#include "base/macros.h" +#include "util/linux/address_types.h" + +namespace crashpad { + +//! \brief Accesses the memory of another process. +class ProcessMemory { + public: + ProcessMemory(); + ~ProcessMemory(); + + //! \brief Initializes this object to read the memory of a process whose ID + //! is \a pid. + //! + //! This method must be called successfully prior to calling any other method + //! in this class. + //! + //! \param[in] pid The process ID of a target process. + //! + //! \return `true` on success, `false` on failure with a message logged. + bool Initialize(pid_t pid); + + //! \brief Copies memory from the target process into a caller-provided buffer + //! in the current process. + //! + //! \param[in] address The address, in the target process' address space, of + //! the memory region to copy. + //! \param[in] size The size, in bytes, of the memory region to copy. + //! \a buffer must be at least this size. + //! \param[out] buffer The buffer into which the contents of the other + //! process' memory will be copied. + //! + //! \return `true` on success, with \a buffer filled appropriately. `false` on + //! failure, with a message logged. + bool Read(LinuxVMAddress address, size_t size, void* buffer) const; + + //! \brief Reads a `NUL`-terminated C string from the target process into a + //! string in the current process. + //! + //! The length of the string need not be known ahead of time. This method will + //! read contiguous memory until a `NUL` terminator is found. + //! + //! \param[in] address The address, in the target process’s address space, of + //! the string to copy. + //! \param[out] string The string read from the other process. + //! + //! \return `true` on success, with \a string set appropriately. `false` on + //! failure, with a message logged. Failures can occur, for example, when + //! encountering unmapped or unreadable pages. + bool ReadCString(LinuxVMAddress address, std::string* string) const; + + //! \brief Reads a `NUL`-terminated C string from the target process into a + //! string in the current process. + //! + //! \param[in] address The address, in the target process’s address space, of + //! the string to copy. + //! \param[in] size The maximum number of bytes to read. The string is + //! required to be `NUL`-terminated within this many bytes. + //! \param[out] string The string read from the other process. + //! + //! \return `true` on success, with \a string set appropriately. `false` on + //! failure, with a message logged. Failures can occur, for example, when + //! a `NUL` terminator is not found within \a size bytes, or when + //! encountering unmapped or unreadable pages. + bool ReadCStringSizeLimited(LinuxVMAddress address, + size_t size, + std::string* string) const; + + private: + bool ReadCStringInternal(LinuxVMAddress address, + bool has_size, + size_t size, + std::string* string) const; + + base::ScopedFD mem_fd_; + pid_t pid_; + + DISALLOW_COPY_AND_ASSIGN(ProcessMemory); +}; + +} // namespace crashpad + +#endif // CRASHPAD_UTIL_LINUX_PROCESS_MEMORY_H_ diff --git a/util/linux/process_memory_test.cc b/util/linux/process_memory_test.cc new file mode 100644 index 00000000..e00134a7 --- /dev/null +++ b/util/linux/process_memory_test.cc @@ -0,0 +1,403 @@ +// Copyright 2017 The Crashpad Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "util/linux/process_memory.h" + +#include +#include +#include + +#include + +#include "gtest/gtest.h" +#include "test/errors.h" +#include "test/multiprocess.h" +#include "util/file/file_io.h" +#include "util/posix/scoped_mmap.h" + +namespace crashpad { +namespace test { +namespace { + +class TargetProcessTest : public Multiprocess { + public: + TargetProcessTest() : Multiprocess() {} + ~TargetProcessTest() {} + + void RunAgainstSelf() { DoTest(getpid()); } + + void RunAgainstForked() { Run(); } + + private: + void MultiprocessParent() override { DoTest(ChildPID()); } + + void MultiprocessChild() override { CheckedReadFileAtEOF(ReadPipeHandle()); } + + virtual void DoTest(pid_t pid) = 0; + + DISALLOW_COPY_AND_ASSIGN(TargetProcessTest); +}; + +class ReadTest : public TargetProcessTest { + public: + ReadTest() + : TargetProcessTest(), + page_size_(getpagesize()), + region_size_(4 * page_size_), + region_(new char[region_size_]) { + for (size_t index = 0; index < region_size_; ++index) { + region_[index] = index % 256; + } + } + + private: + void DoTest(pid_t pid) override { + ProcessMemory memory; + ASSERT_TRUE(memory.Initialize(pid)); + + LinuxVMAddress address = reinterpret_cast(region_.get()); + std::unique_ptr result(new char[region_size_]); + + // Ensure that the entire region can be read. + ASSERT_TRUE(memory.Read(address, region_size_, result.get())); + EXPECT_EQ(memcmp(region_.get(), result.get(), region_size_), 0); + + // Ensure that a read of length 0 succeeds and doesn’t touch the result. + memset(result.get(), '\0', region_size_); + ASSERT_TRUE(memory.Read(address, 0, result.get())); + for (size_t i = 0; i < region_size_; ++i) { + EXPECT_EQ(result[i], 0); + } + + // Ensure that a read starting at an unaligned address works. + ASSERT_TRUE(memory.Read(address + 1, region_size_ - 1, result.get())); + EXPECT_EQ(memcmp(region_.get() + 1, result.get(), region_size_ - 1), 0); + + // Ensure that a read ending at an unaligned address works. + ASSERT_TRUE(memory.Read(address, region_size_ - 1, result.get())); + EXPECT_EQ(memcmp(region_.get(), result.get(), region_size_ - 1), 0); + + // Ensure that a read starting and ending at unaligned addresses works. + ASSERT_TRUE(memory.Read(address + 1, region_size_ - 2, result.get())); + EXPECT_EQ(memcmp(region_.get() + 1, result.get(), region_size_ - 2), 0); + + // Ensure that a read of exactly one page works. + ASSERT_TRUE(memory.Read(address + page_size_, page_size_, result.get())); + EXPECT_EQ(memcmp(region_.get() + page_size_, result.get(), page_size_), 0); + + // Ensure that reading exactly a single byte works. + result[1] = 'J'; + ASSERT_TRUE(memory.Read(address + 2, 1, result.get())); + EXPECT_EQ(result[0], region_[2]); + EXPECT_EQ(result[1], 'J'); + } + + const size_t page_size_; + const size_t region_size_; + std::unique_ptr region_; + + DISALLOW_COPY_AND_ASSIGN(ReadTest); +}; + +TEST(ProcessMemory, ReadSelf) { + ReadTest test; + test.RunAgainstSelf(); +} + +TEST(ProcessMemory, ReadForked) { + ReadTest test; + test.RunAgainstForked(); +} + +bool ReadCString(const ProcessMemory& memory, + const char* pointer, + std::string* result) { + return memory.ReadCString(reinterpret_cast(pointer), result); +} + +bool ReadCStringSizeLimited(const ProcessMemory& memory, + const char* pointer, + size_t size, + std::string* result) { + return memory.ReadCStringSizeLimited( + reinterpret_cast(pointer), size, result); +} + +const char kConstCharEmpty[] = ""; +const char kConstCharShort[] = "A short const char[]"; + +class ReadCStringTest : public TargetProcessTest { + public: + ReadCStringTest(bool limit_size) + : TargetProcessTest(), + member_char_empty_(""), + member_char_short_("A short member char[]"), + limit_size_(limit_size) { + const size_t kStringLongSize = 4 * getpagesize(); + for (size_t index = 0; index < kStringLongSize; ++index) { + string_long_.push_back((index % 255) + 1); + } + EXPECT_EQ(string_long_.size(), kStringLongSize); + } + + private: + void DoTest(pid_t pid) override { + ProcessMemory memory; + ASSERT_TRUE(memory.Initialize(pid)); + + std::string result; + + if (limit_size_) { + ASSERT_TRUE(ReadCStringSizeLimited( + memory, kConstCharEmpty, arraysize(kConstCharEmpty), &result)); + EXPECT_EQ(result, kConstCharEmpty); + + ASSERT_TRUE(ReadCStringSizeLimited( + memory, kConstCharShort, arraysize(kConstCharShort), &result)); + EXPECT_EQ(result, kConstCharShort); + EXPECT_FALSE(ReadCStringSizeLimited( + memory, kConstCharShort, arraysize(kConstCharShort) - 1, &result)); + + ASSERT_TRUE(ReadCStringSizeLimited( + memory, member_char_empty_, strlen(member_char_empty_) + 1, &result)); + EXPECT_EQ(result, member_char_empty_); + + ASSERT_TRUE(ReadCStringSizeLimited( + memory, member_char_short_, strlen(member_char_short_) + 1, &result)); + EXPECT_EQ(result, member_char_short_); + EXPECT_FALSE(ReadCStringSizeLimited( + memory, member_char_short_, strlen(member_char_short_), &result)); + + ASSERT_TRUE(ReadCStringSizeLimited( + memory, string_long_.c_str(), string_long_.size() + 1, &result)); + EXPECT_EQ(result, string_long_); + EXPECT_FALSE(ReadCStringSizeLimited( + memory, string_long_.c_str(), string_long_.size(), &result)); + } else { + ASSERT_TRUE(ReadCString(memory, kConstCharEmpty, &result)); + EXPECT_EQ(result, kConstCharEmpty); + + ASSERT_TRUE(ReadCString(memory, kConstCharShort, &result)); + EXPECT_EQ(result, kConstCharShort); + + ASSERT_TRUE(ReadCString(memory, member_char_empty_, &result)); + EXPECT_EQ(result, member_char_empty_); + + ASSERT_TRUE(ReadCString(memory, member_char_short_, &result)); + EXPECT_EQ(result, member_char_short_); + + ASSERT_TRUE(ReadCString(memory, string_long_.c_str(), &result)); + EXPECT_EQ(result, string_long_); + } + } + + std::string string_long_; + const char* member_char_empty_; + const char* member_char_short_; + const bool limit_size_; + + DISALLOW_COPY_AND_ASSIGN(ReadCStringTest); +}; + +TEST(ProcessMemory, ReadCStringSelf) { + ReadCStringTest test(/* limit_size= */ false); + test.RunAgainstSelf(); +} + +TEST(ProcessMemory, ReadCStringForked) { + ReadCStringTest test(/* limit_size= */ false); + test.RunAgainstForked(); +} + +TEST(ProcessMemory, ReadCStringSizeLimitedSelf) { + ReadCStringTest test(/* limit_size= */ true); + test.RunAgainstSelf(); +} + +TEST(ProcessMemory, ReadCStringSizeLimitedForked) { + ReadCStringTest test(/* limit_size= */ true); + test.RunAgainstForked(); +} + +class ReadUnmappedTest : public TargetProcessTest { + public: + ReadUnmappedTest() + : TargetProcessTest(), + page_size_(getpagesize()), + region_size_(2 * page_size_), + result_(new char[region_size_]) { + if (!pages_.ResetMmap(nullptr, + region_size_, + PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANONYMOUS, + -1, + 0)) { + ADD_FAILURE(); + return; + } + + char* region = pages_.addr_as(); + for (size_t index = 0; index < region_size_; ++index) { + region[index] = index % 256; + } + + EXPECT_TRUE(pages_.ResetAddrLen(region, page_size_)); + } + + private: + void DoTest(pid_t pid) override { + ProcessMemory memory; + ASSERT_TRUE(memory.Initialize(pid)); + + LinuxVMAddress page_addr1 = pages_.addr_as(); + LinuxVMAddress page_addr2 = page_addr1 + page_size_; + + EXPECT_TRUE(memory.Read(page_addr1, page_size_, result_.get())); + EXPECT_TRUE(memory.Read(page_addr2 - 1, 1, result_.get())); + + EXPECT_FALSE(memory.Read(page_addr1, region_size_, result_.get())); + EXPECT_FALSE(memory.Read(page_addr2, page_size_, result_.get())); + EXPECT_FALSE(memory.Read(page_addr2 - 1, 2, result_.get())); + } + + ScopedMmap pages_; + const size_t page_size_; + const size_t region_size_; + std::unique_ptr result_; + + DISALLOW_COPY_AND_ASSIGN(ReadUnmappedTest); +}; + +TEST(ProcessMemory, ReadUnmappedSelf) { + ReadUnmappedTest test; + ASSERT_FALSE(testing::Test::HasFailure()); + test.RunAgainstSelf(); +} + +TEST(ProcessMemory, ReadUnmappedForked) { + ReadUnmappedTest test; + ASSERT_FALSE(testing::Test::HasFailure()); + test.RunAgainstForked(); +} + +class ReadCStringUnmappedTest : public TargetProcessTest { + public: + ReadCStringUnmappedTest(bool limit_size) + : TargetProcessTest(), + page_size_(getpagesize()), + region_size_(2 * page_size_), + limit_size_(limit_size) { + if (!pages_.ResetMmap(nullptr, + region_size_, + PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANONYMOUS, + -1, + 0)) { + ADD_FAILURE(); + return; + } + + char* region = pages_.addr_as(); + for (size_t index = 0; index < region_size_; ++index) { + region[index] = 1 + index % 255; + } + + // A string at the start of the mapped region + string1_ = region; + string1_[expected_length_] = '\0'; + + // A string near the end of the mapped region + string2_ = region + page_size_ - expected_length_ * 2; + string2_[expected_length_] = '\0'; + + // A string that crosses from the mapped into the unmapped region + string3_ = region + page_size_ - expected_length_ + 1; + string3_[expected_length_] = '\0'; + + // A string entirely in the unmapped region + string4_ = region + page_size_ + 10; + string4_[expected_length_] = '\0'; + + result_.reserve(expected_length_ + 1); + + EXPECT_TRUE(pages_.ResetAddrLen(region, page_size_)); + } + + private: + void DoTest(pid_t pid) { + ProcessMemory memory; + ASSERT_TRUE(memory.Initialize(pid)); + + if (limit_size_) { + ASSERT_TRUE(ReadCStringSizeLimited( + memory, string1_, expected_length_ + 1, &result_)); + EXPECT_EQ(result_, string1_); + ASSERT_TRUE(ReadCStringSizeLimited( + memory, string2_, expected_length_ + 1, &result_)); + EXPECT_EQ(result_, string2_); + EXPECT_FALSE(ReadCStringSizeLimited( + memory, string3_, expected_length_ + 1, &result_)); + EXPECT_FALSE(ReadCStringSizeLimited( + memory, string4_, expected_length_ + 1, &result_)); + } else { + ASSERT_TRUE(ReadCString(memory, string1_, &result_)); + EXPECT_EQ(result_, string1_); + ASSERT_TRUE(ReadCString(memory, string2_, &result_)); + EXPECT_EQ(result_, string2_); + EXPECT_FALSE(ReadCString(memory, string3_, &result_)); + EXPECT_FALSE(ReadCString(memory, string4_, &result_)); + } + } + + std::string result_; + ScopedMmap pages_; + const size_t page_size_; + const size_t region_size_; + static const size_t expected_length_ = 10; + char* string1_; + char* string2_; + char* string3_; + char* string4_; + const bool limit_size_; + + DISALLOW_COPY_AND_ASSIGN(ReadCStringUnmappedTest); +}; + +TEST(ProcessMemory, ReadCStringUnmappedSelf) { + ReadCStringUnmappedTest test(/* limit_size= */ false); + ASSERT_FALSE(testing::Test::HasFailure()); + test.RunAgainstSelf(); +} + +TEST(ProcessMemory, ReadCStringUnmappedForked) { + ReadCStringUnmappedTest test(/* limit_size= */ false); + ASSERT_FALSE(testing::Test::HasFailure()); + test.RunAgainstForked(); +} + +TEST(ProcessMemory, ReadCStringSizeLimitedUnmappedSelf) { + ReadCStringUnmappedTest test(/* limit_size= */ true); + ASSERT_FALSE(testing::Test::HasFailure()); + test.RunAgainstSelf(); +} + +TEST(ProcessMemory, ReadCStringSizeLimitedUnmappedForked) { + ReadCStringUnmappedTest test(/* limit_size= */ true); + ASSERT_FALSE(testing::Test::HasFailure()); + test.RunAgainstForked(); +} + +} // namespace +} // namespace test +} // namespace crashpad diff --git a/util/linux/scoped_ptrace_attach.cc b/util/linux/scoped_ptrace_attach.cc new file mode 100644 index 00000000..09e3fba5 --- /dev/null +++ b/util/linux/scoped_ptrace_attach.cc @@ -0,0 +1,62 @@ +// Copyright 2017 The Crashpad Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "util/linux/scoped_ptrace_attach.h" + +#include +#include + +#include "base/logging.h" +#include "base/posix/eintr_wrapper.h" + +namespace crashpad { + +ScopedPtraceAttach::ScopedPtraceAttach() + : pid_(-1) {} + +ScopedPtraceAttach::~ScopedPtraceAttach() { + Reset(); +} + +bool ScopedPtraceAttach::Reset() { + if (pid_ >= 0 && ptrace(PTRACE_DETACH, pid_, nullptr, nullptr) != 0) { + PLOG(ERROR) << "ptrace"; + return false; + } + pid_ = -1; + return true; +} + +bool ScopedPtraceAttach::ResetAttach(pid_t pid) { + Reset(); + + if (ptrace(PTRACE_ATTACH, pid, nullptr, nullptr) != 0) { + PLOG(ERROR) << "ptrace"; + return false; + } + pid_ = pid; + + int status; + if (HANDLE_EINTR(waitpid(pid_, &status, __WALL)) < 0) { + PLOG(ERROR) << "waitpid"; + return false; + } + if (!WIFSTOPPED(status)) { + LOG(ERROR) << "process not stopped"; + return false; + } + return true; +} + +} // namespace crashpad diff --git a/util/linux/scoped_ptrace_attach.h b/util/linux/scoped_ptrace_attach.h new file mode 100644 index 00000000..a3d9d698 --- /dev/null +++ b/util/linux/scoped_ptrace_attach.h @@ -0,0 +1,52 @@ +// Copyright 2017 The Crashpad Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef CRASHPAD_UTIL_LINUX_SCOPED_PTRACE_ATTACH_H_ +#define CRASHPAD_UTIL_LINUX_SCOPED_PTRACE_ATTACH_H_ + +#include + +#include "base/macros.h" + +namespace crashpad { + +//! \brief Maintains a `ptrace()` attachment to a process. +//! +//! On destruction, the process will be detached. +class ScopedPtraceAttach { + public: + ScopedPtraceAttach(); + ~ScopedPtraceAttach(); + + //! \brief Detaches from the process by calling `ptrace()`. + //! + //! \return `true` on success. `false` on failure, with a message logged. + bool Reset(); + + //! \brief Detaches from any previously attached process, attaches to the + //! process with process ID \a pid, and blocks until the target process + //! has stopped by calling `waitpid()`. + //! + //! \return `true` on success. `false` on failure, with a message logged. + bool ResetAttach(pid_t pid); + + private: + pid_t pid_; + + DISALLOW_COPY_AND_ASSIGN(ScopedPtraceAttach); +}; + +} // namespace crashpad + +#endif // CRASHPAD_UTIL_LINUX_SCOPED_PTRACE_ATTACH_H_ diff --git a/util/linux/scoped_ptrace_attach_test.cc b/util/linux/scoped_ptrace_attach_test.cc new file mode 100644 index 00000000..99072e4c --- /dev/null +++ b/util/linux/scoped_ptrace_attach_test.cc @@ -0,0 +1,204 @@ +// Copyright 2017 The Crashpad Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "util/linux/scoped_ptrace_attach.h" + +#include +#include +#include +#include + +#include "gtest/gtest.h" +#include "test/errors.h" +#include "test/multiprocess.h" +#include "util/file/file_io.h" + +namespace crashpad { +namespace test { +namespace { + +class ScopedPrSetPtracer { + public: + explicit ScopedPrSetPtracer(pid_t pid) { + // PR_SET_PTRACER is only supported if the Yama Linux security module (LSM) + // is enabled. Otherwise, this prctl() call fails with EINVAL. See + // linux-4.9.20/security/yama/yama_lsm.c yama_task_prctl() and + // linux-4.9.20/kernel/sys.c [sys_]prctl(). + // + // If Yama is not enabled, the default ptrace restrictions should be + // sufficient for these tests. + // + // If Yama is enabled, then /proc/sys/kernel/yama/ptrace_scope must be 0 + // (YAMA_SCOPE_DISABLED, in which case this prctl() is not necessary) or 1 + // (YAMA_SCOPE_RELATIONAL) for these tests to succeed. If it is 2 + // (YAMA_SCOPE_CAPABILITY) then the test requires CAP_SYS_PTRACE, and if it + // is 3 (YAMA_SCOPE_NO_ATTACH), these tests will fail. + success_ = prctl(PR_SET_PTRACER, pid, 0, 0, 0) == 0; + if (!success_) { + EXPECT_EQ(errno, EINVAL) << ErrnoMessage("prctl"); + } + } + + ~ScopedPrSetPtracer() { + if (success_) { + EXPECT_EQ(prctl(PR_SET_PTRACER, 0, 0, 0, 0), 0) << ErrnoMessage("prctl"); + } + } + + private: + bool success_; + + DISALLOW_COPY_AND_ASSIGN(ScopedPrSetPtracer); +}; + +class AttachTest : public Multiprocess { + public: + AttachTest() : Multiprocess() {} + ~AttachTest() {} + + protected: + const long kWord = 42; + + private: + DISALLOW_COPY_AND_ASSIGN(AttachTest); +}; + +class AttachToChildTest : public AttachTest { + public: + AttachToChildTest() : AttachTest() {} + ~AttachToChildTest() {} + + private: + void MultiprocessParent() override { + // Wait for the child to set the parent as its ptracer. + char c; + CheckedReadFileExactly(ReadPipeHandle(), &c, sizeof(c)); + + pid_t pid = ChildPID(); + + ASSERT_EQ(ptrace(PTRACE_PEEKDATA, pid, &kWord, nullptr), -1); + EXPECT_EQ(errno, ESRCH) << ErrnoMessage("ptrace"); + + ScopedPtraceAttach attachment; + ASSERT_EQ(attachment.ResetAttach(pid), true); + EXPECT_EQ(ptrace(PTRACE_PEEKDATA, pid, &kWord, nullptr), kWord) + << ErrnoMessage("ptrace"); + attachment.Reset(); + + ASSERT_EQ(ptrace(PTRACE_PEEKDATA, pid, &kWord, nullptr), -1); + EXPECT_EQ(errno, ESRCH) << ErrnoMessage("ptrace"); + } + + void MultiprocessChild() override { + ScopedPrSetPtracer set_ptracer(getppid()); + + char c = '\0'; + CheckedWriteFile(WritePipeHandle(), &c, sizeof(c)); + + CheckedReadFileAtEOF(ReadPipeHandle()); + } + + DISALLOW_COPY_AND_ASSIGN(AttachToChildTest); +}; + +TEST(ScopedPtraceAttach, AttachChild) { + AttachToChildTest test; + test.Run(); +} + +class AttachToParentResetTest : public AttachTest { + public: + AttachToParentResetTest() : AttachTest() {} + ~AttachToParentResetTest() {} + + private: + void MultiprocessParent() override { + ScopedPrSetPtracer set_ptracer(ChildPID()); + char c = '\0'; + CheckedWriteFile(WritePipeHandle(), &c, sizeof(c)); + + CheckedReadFileAtEOF(ReadPipeHandle()); + } + + void MultiprocessChild() override { + // Wait for the parent to set the child as its ptracer. + char c; + CheckedReadFileExactly(ReadPipeHandle(), &c, sizeof(c)); + + pid_t pid = getppid(); + + ASSERT_EQ(ptrace(PTRACE_PEEKDATA, pid, &kWord, nullptr), -1); + EXPECT_EQ(errno, ESRCH) << ErrnoMessage("ptrace"); + + ScopedPtraceAttach attachment; + ASSERT_EQ(attachment.ResetAttach(pid), true); + EXPECT_EQ(ptrace(PTRACE_PEEKDATA, pid, &kWord, nullptr), kWord) + << ErrnoMessage("ptrace"); + attachment.Reset(); + + ASSERT_EQ(ptrace(PTRACE_PEEKDATA, pid, &kWord, nullptr), -1); + EXPECT_EQ(errno, ESRCH) << ErrnoMessage("ptrace"); + } + + DISALLOW_COPY_AND_ASSIGN(AttachToParentResetTest); +}; + +TEST(ScopedPtraceAttach, AttachParentReset) { + AttachToParentResetTest test; + test.Run(); +} + +class AttachToParentDestructorTest : public AttachTest { + public: + AttachToParentDestructorTest() : AttachTest() {} + ~AttachToParentDestructorTest() {} + + private: + void MultiprocessParent() override { + ScopedPrSetPtracer set_ptracer(ChildPID()); + char c = '\0'; + CheckedWriteFile(WritePipeHandle(), &c, sizeof(c)); + + CheckedReadFileAtEOF(ReadPipeHandle()); + } + + void MultiprocessChild() override { + // Wait for the parent to set the child as its ptracer. + char c; + CheckedReadFileExactly(ReadPipeHandle(), &c, sizeof(c)); + + pid_t pid = getppid(); + ASSERT_EQ(ptrace(PTRACE_PEEKDATA, pid, &kWord, nullptr), -1); + EXPECT_EQ(errno, ESRCH) << ErrnoMessage("ptrace"); + { + ScopedPtraceAttach attachment; + ASSERT_EQ(attachment.ResetAttach(pid), true); + EXPECT_EQ(ptrace(PTRACE_PEEKDATA, pid, &kWord, nullptr), kWord) + << ErrnoMessage("ptrace"); + } + ASSERT_EQ(ptrace(PTRACE_PEEKDATA, pid, &kWord, nullptr), -1); + EXPECT_EQ(errno, ESRCH) << ErrnoMessage("ptrace"); + } + + DISALLOW_COPY_AND_ASSIGN(AttachToParentDestructorTest); +}; + +TEST(ScopedPtraceAttach, AttachParentDestructor) { + AttachToParentDestructorTest test; + test.Run(); +} + +} // namespace +} // namespace test +} // namespace crashpad diff --git a/util/mac/checked_mach_address_range_test.cc b/util/mac/checked_mach_address_range_test.cc index c0126240..860bdff8 100644 --- a/util/mac/checked_mach_address_range_test.cc +++ b/util/mac/checked_mach_address_range_test.cc @@ -124,10 +124,10 @@ TEST(CheckedMachAddressRange, IsValid) { testcase.size)); CheckedMachAddressRange range_32(false, testcase.base, testcase.size); - EXPECT_EQ(ExpectationForValidity32(testcase.validity), range_32.IsValid()); + EXPECT_EQ(range_32.IsValid(), ExpectationForValidity32(testcase.validity)); CheckedMachAddressRange range_64(true, testcase.base, testcase.size); - EXPECT_EQ(ExpectationForValidity64(testcase.validity), range_64.IsValid()); + EXPECT_EQ(range_64.IsValid(), ExpectationForValidity64(testcase.validity)); } } @@ -171,8 +171,8 @@ TEST(CheckedMachAddressRange, ContainsValue) { SCOPED_TRACE( base::StringPrintf("index %zu, value 0x%llx", index, testcase.value)); - EXPECT_EQ(testcase.expectation, - parent_range_32.ContainsValue(testcase.value)); + EXPECT_EQ(parent_range_32.ContainsValue(testcase.value), + testcase.expectation); } CheckedMachAddressRange parent_range_64(true, 0x100000000, 0x1000); @@ -232,8 +232,8 @@ TEST(CheckedMachAddressRange, ContainsRange) { CheckedMachAddressRange child_range_32(false, testcase.base, testcase.size); ASSERT_TRUE(child_range_32.IsValid()); - EXPECT_EQ(testcase.expectation, - parent_range_32.ContainsRange(child_range_32)); + EXPECT_EQ(parent_range_32.ContainsRange(child_range_32), + testcase.expectation); } CheckedMachAddressRange parent_range_64(true, 0x100000000, 0x1000); diff --git a/util/mac/launchd_test.mm b/util/mac/launchd_test.mm index 649e799d..8d9db762 100644 --- a/util/mac/launchd_test.mm +++ b/util/mac/launchd_test.mm @@ -62,9 +62,9 @@ TEST(Launchd, CFPropertyToLaunchData_Integer) { NSNumber* integer_ns = integer_nses[index]; launch_data.reset(CFPropertyToLaunchData(integer_ns)); ASSERT_TRUE(launch_data.get()); - ASSERT_EQ(LAUNCH_DATA_INTEGER, LaunchDataGetType(launch_data.get())); - EXPECT_EQ([integer_ns longLongValue], - LaunchDataGetInteger(launch_data.get())) + ASSERT_EQ(LaunchDataGetType(launch_data.get()), LAUNCH_DATA_INTEGER); + EXPECT_EQ(LaunchDataGetInteger(launch_data.get()), + [integer_ns longLongValue]) << "index " << index; } } @@ -92,11 +92,11 @@ TEST(Launchd, CFPropertyToLaunchData_FloatingPoint) { NSNumber* double_ns = double_nses[index]; launch_data.reset(CFPropertyToLaunchData(double_ns)); ASSERT_TRUE(launch_data.get()); - ASSERT_EQ(LAUNCH_DATA_REAL, LaunchDataGetType(launch_data.get())); + ASSERT_EQ(LaunchDataGetType(launch_data.get()), LAUNCH_DATA_REAL); double expected_double_value = [double_ns doubleValue]; double observed_double_value = LaunchDataGetReal(launch_data.get()); bool expected_is_nan = std::isnan(expected_double_value); - EXPECT_EQ(expected_is_nan, std::isnan(observed_double_value)); + EXPECT_EQ(std::isnan(observed_double_value), expected_is_nan); if (!expected_is_nan) { EXPECT_DOUBLE_EQ(expected_double_value, observed_double_value) << "index " << index; @@ -118,7 +118,7 @@ TEST(Launchd, CFPropertyToLaunchData_Boolean) { NSNumber* bool_ns = bool_nses[index]; launch_data.reset(CFPropertyToLaunchData(bool_ns)); ASSERT_TRUE(launch_data.get()); - ASSERT_EQ(LAUNCH_DATA_BOOL, LaunchDataGetType(launch_data.get())); + ASSERT_EQ(LaunchDataGetType(launch_data.get()), LAUNCH_DATA_BOOL); if ([bool_ns boolValue]) { EXPECT_TRUE(LaunchDataGetBool(launch_data.get())); } else { @@ -142,7 +142,7 @@ TEST(Launchd, CFPropertyToLaunchData_String) { NSString* string_ns = string_nses[index]; launch_data.reset(CFPropertyToLaunchData(string_ns)); ASSERT_TRUE(launch_data.get()); - ASSERT_EQ(LAUNCH_DATA_STRING, LaunchDataGetType(launch_data.get())); + ASSERT_EQ(LaunchDataGetType(launch_data.get()), LAUNCH_DATA_STRING); EXPECT_STREQ([string_ns UTF8String], LaunchDataGetString(launch_data.get())); } @@ -158,11 +158,11 @@ TEST(Launchd, CFPropertyToLaunchData_Data) { NSData* data_ns = [NSData dataWithBytes:data_c length:sizeof(data_c)]; launch_data.reset(CFPropertyToLaunchData(data_ns)); ASSERT_TRUE(launch_data.get()); - ASSERT_EQ(LAUNCH_DATA_OPAQUE, LaunchDataGetType(launch_data.get())); - EXPECT_EQ(sizeof(data_c), LaunchDataGetOpaqueSize(launch_data.get())); + ASSERT_EQ(LaunchDataGetType(launch_data.get()), LAUNCH_DATA_OPAQUE); + EXPECT_EQ(LaunchDataGetOpaqueSize(launch_data.get()), sizeof(data_c)); EXPECT_EQ( - 0, - memcmp(LaunchDataGetOpaque(launch_data.get()), data_c, sizeof(data_c))); + memcmp(LaunchDataGetOpaque(launch_data.get()), data_c, sizeof(data_c)), + 0); } } @@ -176,13 +176,13 @@ TEST(Launchd, CFPropertyToLaunchData_Dictionary) { launch_data.reset(CFPropertyToLaunchData(dictionary_ns)); ASSERT_TRUE(launch_data.get()); - ASSERT_EQ(LAUNCH_DATA_DICTIONARY, LaunchDataGetType(launch_data.get())); - EXPECT_EQ([dictionary_ns count], LaunchDataDictGetCount(launch_data.get())); + ASSERT_EQ(LaunchDataGetType(launch_data.get()), LAUNCH_DATA_DICTIONARY); + EXPECT_EQ(LaunchDataDictGetCount(launch_data.get()), [dictionary_ns count]); launch_data_t launch_lookup_data = LaunchDataDictLookup(launch_data.get(), "key"); ASSERT_TRUE(launch_lookup_data); - ASSERT_EQ(LAUNCH_DATA_STRING, LaunchDataGetType(launch_lookup_data)); + ASSERT_EQ(LaunchDataGetType(launch_lookup_data), LAUNCH_DATA_STRING); EXPECT_STREQ("value", LaunchDataGetString(launch_lookup_data)); } } @@ -195,18 +195,18 @@ TEST(Launchd, CFPropertyToLaunchData_Array) { launch_data.reset(CFPropertyToLaunchData(array_ns)); ASSERT_TRUE(launch_data.get()); - ASSERT_EQ(LAUNCH_DATA_ARRAY, LaunchDataGetType(launch_data.get())); - EXPECT_EQ([array_ns count], LaunchDataArrayGetCount(launch_data.get())); + ASSERT_EQ(LaunchDataGetType(launch_data.get()), LAUNCH_DATA_ARRAY); + EXPECT_EQ(LaunchDataArrayGetCount(launch_data.get()), [array_ns count]); launch_data_t launch_lookup_data = LaunchDataArrayGetIndex(launch_data.get(), 0); ASSERT_TRUE(launch_lookup_data); - ASSERT_EQ(LAUNCH_DATA_STRING, LaunchDataGetType(launch_lookup_data)); + ASSERT_EQ(LaunchDataGetType(launch_lookup_data), LAUNCH_DATA_STRING); EXPECT_STREQ("element_1", LaunchDataGetString(launch_lookup_data)); launch_lookup_data = LaunchDataArrayGetIndex(launch_data.get(), 1); ASSERT_TRUE(launch_lookup_data); - ASSERT_EQ(LAUNCH_DATA_STRING, LaunchDataGetType(launch_lookup_data)); + ASSERT_EQ(LaunchDataGetType(launch_lookup_data), LAUNCH_DATA_STRING); EXPECT_STREQ("element_2", LaunchDataGetString(launch_lookup_data)); } } @@ -251,54 +251,54 @@ TEST(Launchd, CFPropertyToLaunchData_RealWorldJobDictionary) { launch_data.reset(CFPropertyToLaunchData(job_dictionary)); ASSERT_TRUE(launch_data.get()); - ASSERT_EQ(LAUNCH_DATA_DICTIONARY, LaunchDataGetType(launch_data.get())); - EXPECT_EQ(4u, LaunchDataDictGetCount(launch_data.get())); + ASSERT_EQ(LaunchDataGetType(launch_data.get()), LAUNCH_DATA_DICTIONARY); + EXPECT_EQ(LaunchDataDictGetCount(launch_data.get()), 4u); launch_data_t launch_lookup_data = LaunchDataDictLookup(launch_data.get(), LAUNCH_JOBKEY_LABEL); ASSERT_TRUE(launch_lookup_data); - ASSERT_EQ(LAUNCH_DATA_STRING, LaunchDataGetType(launch_lookup_data)); + ASSERT_EQ(LaunchDataGetType(launch_lookup_data), LAUNCH_DATA_STRING); EXPECT_STREQ("com.example.job.rebooter", LaunchDataGetString(launch_lookup_data)); launch_lookup_data = LaunchDataDictLookup(launch_data.get(), LAUNCH_JOBKEY_ONDEMAND); ASSERT_TRUE(launch_lookup_data); - ASSERT_EQ(LAUNCH_DATA_BOOL, LaunchDataGetType(launch_lookup_data)); + ASSERT_EQ(LaunchDataGetType(launch_lookup_data), LAUNCH_DATA_BOOL); EXPECT_TRUE(LaunchDataGetBool(launch_lookup_data)); launch_lookup_data = LaunchDataDictLookup(launch_data.get(), LAUNCH_JOBKEY_PROGRAMARGUMENTS); ASSERT_TRUE(launch_lookup_data); - ASSERT_EQ(LAUNCH_DATA_ARRAY, LaunchDataGetType(launch_lookup_data)); - EXPECT_EQ(3u, LaunchDataArrayGetCount(launch_lookup_data)); + ASSERT_EQ(LaunchDataGetType(launch_lookup_data), LAUNCH_DATA_ARRAY); + EXPECT_EQ(LaunchDataArrayGetCount(launch_lookup_data), 3u); launch_data_t launch_sublookup_data = LaunchDataArrayGetIndex(launch_lookup_data, 0); ASSERT_TRUE(launch_sublookup_data); - ASSERT_EQ(LAUNCH_DATA_STRING, LaunchDataGetType(launch_sublookup_data)); + ASSERT_EQ(LaunchDataGetType(launch_sublookup_data), LAUNCH_DATA_STRING); EXPECT_STREQ("/bin/bash", LaunchDataGetString(launch_sublookup_data)); launch_sublookup_data = LaunchDataArrayGetIndex(launch_lookup_data, 1); ASSERT_TRUE(launch_sublookup_data); - ASSERT_EQ(LAUNCH_DATA_STRING, LaunchDataGetType(launch_sublookup_data)); + ASSERT_EQ(LaunchDataGetType(launch_sublookup_data), LAUNCH_DATA_STRING); EXPECT_STREQ("-c", LaunchDataGetString(launch_sublookup_data)); launch_sublookup_data = LaunchDataArrayGetIndex(launch_lookup_data, 2); ASSERT_TRUE(launch_sublookup_data); - ASSERT_EQ(LAUNCH_DATA_STRING, LaunchDataGetType(launch_sublookup_data)); + ASSERT_EQ(LaunchDataGetType(launch_sublookup_data), LAUNCH_DATA_STRING); EXPECT_STREQ("/sbin/reboot", LaunchDataGetString(launch_sublookup_data)); launch_lookup_data = LaunchDataDictLookup(launch_data.get(), LAUNCH_JOBKEY_MACHSERVICES); ASSERT_TRUE(launch_lookup_data); - ASSERT_EQ(LAUNCH_DATA_DICTIONARY, LaunchDataGetType(launch_lookup_data)); - EXPECT_EQ(1u, LaunchDataDictGetCount(launch_lookup_data)); + ASSERT_EQ(LaunchDataGetType(launch_lookup_data), LAUNCH_DATA_DICTIONARY); + EXPECT_EQ(LaunchDataDictGetCount(launch_lookup_data), 1u); launch_sublookup_data = LaunchDataDictLookup( launch_lookup_data, "com.example.service.rebooter"); ASSERT_TRUE(launch_sublookup_data); - ASSERT_EQ(LAUNCH_DATA_BOOL, LaunchDataGetType(launch_sublookup_data)); + ASSERT_EQ(LaunchDataGetType(launch_sublookup_data), LAUNCH_DATA_BOOL); EXPECT_TRUE(LaunchDataGetBool(launch_sublookup_data)); } } diff --git a/util/mac/mac_util_test.mm b/util/mac/mac_util_test.mm index 5b41b420..3db871ed 100644 --- a/util/mac/mac_util_test.mm +++ b/util/mac/mac_util_test.mm @@ -61,12 +61,12 @@ void SwVers(NSString* argument, std::string* output) { NSData* data = [[pipe fileHandleForReading] readDataToEndOfFile]; [task waitUntilExit]; - ASSERT_EQ(NSTaskTerminationReasonExit, [task terminationReason]); - ASSERT_EQ(EXIT_SUCCESS, [task terminationStatus]); + ASSERT_EQ([task terminationReason], NSTaskTerminationReasonExit); + ASSERT_EQ([task terminationStatus], EXIT_SUCCESS); output->assign(reinterpret_cast([data bytes]), [data length]); - EXPECT_EQ('\n', output->at(output->size() - 1)); + EXPECT_EQ(output->at(output->size() - 1), '\n'); output->resize(output->size() - 1); } } @@ -93,19 +93,19 @@ TEST(MacUtil, MacOSXVersion) { ASSERT_NO_FATAL_FAILURE( SwVers(@"-productVersion", &expected_product_version)); - EXPECT_EQ(expected_product_version, version); + EXPECT_EQ(version, expected_product_version); std::string expected_build_version; ASSERT_NO_FATAL_FAILURE(SwVers(@"-buildVersion", &expected_build_version)); - EXPECT_EQ(expected_build_version, build); + EXPECT_EQ(build, expected_build_version); std::string expected_product_name; ASSERT_NO_FATAL_FAILURE(SwVers(@"-productName", &expected_product_name)); // Look for a space after the product name in the complete version string. expected_product_name += ' '; - EXPECT_EQ(0u, version_string.find(expected_product_name)); + EXPECT_EQ(version_string.find(expected_product_name), 0u); } TEST(MacUtil, MacOSXMinorVersion) { @@ -121,7 +121,7 @@ TEST(MacUtil, MacOSXMinorVersion) { ASSERT_TRUE( MacOSXVersion(&major, &minor, &bugfix, &build, &server, &version_string)); - EXPECT_EQ(minor, MacOSXMinorVersion()); + EXPECT_EQ(MacOSXMinorVersion(), minor); } TEST(MacUtil, MacModelAndBoard) { diff --git a/util/mac/service_management_test.mm b/util/mac/service_management_test.mm index cdfd0823..769c32f1 100644 --- a/util/mac/service_management_test.mm +++ b/util/mac/service_management_test.mm @@ -72,7 +72,7 @@ void ExpectProcessIsRunning(pid_t pid, std::string& last_arg) { } ASSERT_FALSE(job_argv.empty()); - EXPECT_EQ(last_arg, job_argv.back()); + EXPECT_EQ(job_argv.back(), last_arg); } // Ensures that the process with the specified PID is not running. Because the @@ -103,7 +103,7 @@ void ExpectProcessIsNotRunning(pid_t pid, std::string& last_arg) { } ASSERT_FALSE(job_argv.empty()); - EXPECT_NE(last_arg, job_argv.back()); + EXPECT_NE(job_argv.back(), last_arg); } TEST(ServiceManagement, SubmitRemoveJob) { @@ -145,7 +145,7 @@ TEST(ServiceManagement, SubmitRemoveJob) { // Remove the job. ASSERT_TRUE(ServiceManagementRemoveJob(kJobLabel, true)); EXPECT_FALSE(ServiceManagementIsJobLoaded(kJobLabel)); - EXPECT_EQ(0, ServiceManagementIsJobRunning(kJobLabel)); + EXPECT_EQ(ServiceManagementIsJobRunning(kJobLabel), 0); // Now that the job is unloaded, a subsequent attempt to unload it should be // an error. diff --git a/util/mac/xattr_test.cc b/util/mac/xattr_test.cc index c27ab4c1..477bb138 100644 --- a/util/mac/xattr_test.cc +++ b/util/mac/xattr_test.cc @@ -45,7 +45,7 @@ class Xattr : public testing::Test { } void TearDown() override { - EXPECT_EQ(0, unlink(path_.value().c_str())) << ErrnoMessage("unlink"); + EXPECT_EQ(unlink(path_.value().c_str()), 0) << ErrnoMessage("unlink"); } const base::FilePath& path() const { return path_; } @@ -59,7 +59,7 @@ const char kKey[] = "com.google.crashpad.test"; TEST_F(Xattr, ReadNonExistentXattr) { std::string value; - EXPECT_EQ(XattrStatus::kNoAttribute, ReadXattr(path(), kKey, &value)); + EXPECT_EQ(ReadXattr(path(), kKey, &value), XattrStatus::kNoAttribute); } TEST_F(Xattr, WriteAndReadString) { @@ -67,8 +67,8 @@ TEST_F(Xattr, WriteAndReadString) { EXPECT_TRUE(WriteXattr(path(), kKey, value)); std::string actual; - EXPECT_EQ(XattrStatus::kOK, ReadXattr(path(), kKey, &actual)); - EXPECT_EQ(value, actual); + EXPECT_EQ(ReadXattr(path(), kKey, &actual), XattrStatus::kOK); + EXPECT_EQ(actual, value); } TEST_F(Xattr, WriteAndReadVeryLongString) { @@ -76,18 +76,18 @@ TEST_F(Xattr, WriteAndReadVeryLongString) { EXPECT_TRUE(WriteXattr(path(), kKey, value)); std::string actual; - EXPECT_EQ(XattrStatus::kOK, ReadXattr(path(), kKey, &actual)); - EXPECT_EQ(value, actual); + EXPECT_EQ(ReadXattr(path(), kKey, &actual), XattrStatus::kOK); + EXPECT_EQ(actual, value); } TEST_F(Xattr, WriteAndReadBool) { EXPECT_TRUE(WriteXattrBool(path(), kKey, true)); bool actual = false; - EXPECT_EQ(XattrStatus::kOK, ReadXattrBool(path(), kKey, &actual)); + EXPECT_EQ(ReadXattrBool(path(), kKey, &actual), XattrStatus::kOK); EXPECT_TRUE(actual); EXPECT_TRUE(WriteXattrBool(path(), kKey, false)); - EXPECT_EQ(XattrStatus::kOK, ReadXattrBool(path(), kKey, &actual)); + EXPECT_EQ(ReadXattrBool(path(), kKey, &actual), XattrStatus::kOK); EXPECT_FALSE(actual); } @@ -96,13 +96,13 @@ TEST_F(Xattr, WriteAndReadInt) { int actual; EXPECT_TRUE(WriteXattrInt(path(), kKey, expected)); - EXPECT_EQ(XattrStatus::kOK, ReadXattrInt(path(), kKey, &actual)); - EXPECT_EQ(expected, actual); + EXPECT_EQ(ReadXattrInt(path(), kKey, &actual), XattrStatus::kOK); + EXPECT_EQ(actual, expected); expected = std::numeric_limits::max(); EXPECT_TRUE(WriteXattrInt(path(), kKey, expected)); - EXPECT_EQ(XattrStatus::kOK, ReadXattrInt(path(), kKey, &actual)); - EXPECT_EQ(expected, actual); + EXPECT_EQ(ReadXattrInt(path(), kKey, &actual), XattrStatus::kOK); + EXPECT_EQ(actual, expected); } TEST_F(Xattr, WriteAndReadTimeT) { @@ -110,13 +110,13 @@ TEST_F(Xattr, WriteAndReadTimeT) { time_t actual; EXPECT_TRUE(WriteXattrTimeT(path(), kKey, expected)); - EXPECT_EQ(XattrStatus::kOK, ReadXattrTimeT(path(), kKey, &actual)); - EXPECT_EQ(expected, actual); + EXPECT_EQ(ReadXattrTimeT(path(), kKey, &actual), XattrStatus::kOK); + EXPECT_EQ(actual, expected); expected = std::numeric_limits::max(); EXPECT_TRUE(WriteXattrTimeT(path(), kKey, expected)); - EXPECT_EQ(XattrStatus::kOK, ReadXattrTimeT(path(), kKey, &actual)); - EXPECT_EQ(expected, actual); + EXPECT_EQ(ReadXattrTimeT(path(), kKey, &actual), XattrStatus::kOK); + EXPECT_EQ(actual, expected); } TEST_F(Xattr, RemoveAndRead) { @@ -124,13 +124,13 @@ TEST_F(Xattr, RemoveAndRead) { EXPECT_TRUE(WriteXattr(path(), kKey, value)); std::string actual; - EXPECT_EQ(XattrStatus::kOK, ReadXattr(path(), kKey, &actual)); - EXPECT_EQ(value, actual); + EXPECT_EQ(ReadXattr(path(), kKey, &actual), XattrStatus::kOK); + EXPECT_EQ(actual, value); - EXPECT_EQ(XattrStatus::kOK, RemoveXattr(path(), kKey)); - EXPECT_EQ(XattrStatus::kNoAttribute, ReadXattr(path(), kKey, &actual)); + EXPECT_EQ(RemoveXattr(path(), kKey), XattrStatus::kOK); + EXPECT_EQ(ReadXattr(path(), kKey, &actual), XattrStatus::kNoAttribute); - EXPECT_EQ(XattrStatus::kNoAttribute, RemoveXattr(path(), kKey)); + EXPECT_EQ(RemoveXattr(path(), kKey), XattrStatus::kNoAttribute); } } // namespace diff --git a/util/mach/child_port_handshake_test.cc b/util/mach/child_port_handshake_test.cc index f77107b5..fa7ab093 100644 --- a/util/mach/child_port_handshake_test.cc +++ b/util/mach/child_port_handshake_test.cc @@ -113,12 +113,12 @@ class ChildPortHandshakeTest : public Multiprocess { case TestType::kClientChecksIn_SendRight: case TestType::kTokenIncorrectThenCorrect: - EXPECT_EQ(bootstrap_port, send_right); + EXPECT_EQ(send_right, bootstrap_port); break; case TestType::kClientChecksIn_SendOnceRight: EXPECT_TRUE(send_right.is_valid()); - EXPECT_NE(bootstrap_port, send_right); + EXPECT_NE(send_right, bootstrap_port); break; case TestType::kClientDoesNotCheckIn: @@ -219,7 +219,7 @@ class ChildPortHandshakeTest : public Multiprocess { } case TestType::kServerDies: { - ASSERT_EQ(ClientProcess::kParentClient, client_process_); + ASSERT_EQ(client_process_, ClientProcess::kParentClient); ASSERT_FALSE(child_port_handshake_.RunClient(bootstrap_port, MACH_MSG_TYPE_COPY_SEND)); break; diff --git a/util/mach/child_port_server_test.cc b/util/mach/child_port_server_test.cc index 7a8dbf77..d579ce91 100644 --- a/util/mach/child_port_server_test.cc +++ b/util/mach/child_port_server_test.cc @@ -76,14 +76,14 @@ struct MIGReply : public mig_reply_error_t { } void Verify() { - EXPECT_EQ(implicit_cast(MACH_MSGH_BITS(0, 0)), - Head.msgh_bits); - EXPECT_EQ(sizeof(*this), Head.msgh_size); - EXPECT_EQ(kMachPortNull, Head.msgh_remote_port); - EXPECT_EQ(kMachPortNull, Head.msgh_local_port); - EXPECT_EQ(10111, Head.msgh_id); - EXPECT_EQ(0, memcmp(&NDR, &NDR_record, sizeof(NDR))); - EXPECT_EQ(MIG_NO_REPLY, RetCode); + EXPECT_EQ(Head.msgh_bits, + implicit_cast(MACH_MSGH_BITS(0, 0))); + EXPECT_EQ(Head.msgh_size, sizeof(*this)); + EXPECT_EQ(Head.msgh_remote_port, kMachPortNull); + EXPECT_EQ(Head.msgh_local_port, kMachPortNull); + EXPECT_EQ(Head.msgh_id, 10111); + EXPECT_EQ(memcmp(&NDR, &NDR_record, sizeof(NDR)), 0); + EXPECT_EQ(RetCode, MIG_NO_REPLY); } }; @@ -104,13 +104,13 @@ TEST(ChildPortServer, MockChildPortCheckIn) { std::set expect_request_ids; expect_request_ids.insert(10011); // There is no constant for this. - EXPECT_EQ(expect_request_ids, server.MachMessageServerRequestIDs()); + EXPECT_EQ(server.MachMessageServerRequestIDs(), expect_request_ids); ChildPortCheckInRequest request; - EXPECT_EQ(request.Head.msgh_size, server.MachMessageServerRequestSize()); + EXPECT_EQ(server.MachMessageServerRequestSize(), request.Head.msgh_size); MIGReply reply; - EXPECT_EQ(sizeof(reply), server.MachMessageServerReplySize()); + EXPECT_EQ(server.MachMessageServerReplySize(), sizeof(reply)); EXPECT_CALL(server_interface, HandleChildPortCheckIn(kServerLocalPort, diff --git a/util/mach/composite_mach_message_server_test.cc b/util/mach/composite_mach_message_server_test.cc index 11984da9..3a37e49b 100644 --- a/util/mach/composite_mach_message_server_test.cc +++ b/util/mach/composite_mach_message_server_test.cc @@ -31,15 +31,15 @@ TEST(CompositeMachMessageServer, Empty) { EXPECT_TRUE(server.MachMessageServerRequestIDs().empty()); mach_msg_empty_rcv_t request = {}; - EXPECT_EQ(sizeof(request.header), server.MachMessageServerRequestSize()); + EXPECT_EQ(server.MachMessageServerRequestSize(), sizeof(request.header)); mig_reply_error_t reply = {}; - EXPECT_EQ(sizeof(reply), server.MachMessageServerReplySize()); + EXPECT_EQ(server.MachMessageServerReplySize(), sizeof(reply)); bool destroy_complex_request = false; EXPECT_FALSE(server.MachMessageServerFunction( &request.header, &reply.Head, &destroy_complex_request)); - EXPECT_EQ(MIG_BAD_ID, reply.RetCode); + EXPECT_EQ(reply.RetCode, MIG_BAD_ID); } class TestMachMessageHandler : public MachMessageServer::Interface { @@ -82,7 +82,7 @@ class TestMachMessageHandler : public MachMessageServer::Interface { bool MachMessageServerFunction(const mach_msg_header_t* in, mach_msg_header_t* out, bool* destroy_complex_request) override { - EXPECT_NE(request_ids_.end(), request_ids_.find(in->msgh_id)); + EXPECT_NE(request_ids_.find(in->msgh_id), request_ids_.end()); *destroy_complex_request = destroy_complex_request_; PrepareMIGReplyFromRequest(in, out); @@ -122,15 +122,15 @@ TEST(CompositeMachMessageServer, HandlerDoesNotHandle) { EXPECT_TRUE(server.MachMessageServerRequestIDs().empty()); mach_msg_empty_rcv_t request = {}; - EXPECT_EQ(sizeof(request.header), server.MachMessageServerRequestSize()); + EXPECT_EQ(server.MachMessageServerRequestSize(), sizeof(request.header)); mig_reply_error_t reply = {}; - EXPECT_EQ(sizeof(reply), server.MachMessageServerReplySize()); + EXPECT_EQ(server.MachMessageServerReplySize(), sizeof(reply)); bool destroy_complex_request = false; EXPECT_FALSE(server.MachMessageServerFunction( &request.header, &reply.Head, &destroy_complex_request)); - EXPECT_EQ(MIG_BAD_ID, reply.RetCode); + EXPECT_EQ(reply.RetCode, MIG_BAD_ID); EXPECT_FALSE(destroy_complex_request); } @@ -157,10 +157,10 @@ TEST(CompositeMachMessageServer, OneHandler) { std::set expect_request_ids; expect_request_ids.insert(kRequestID); - EXPECT_EQ(expect_request_ids, server.MachMessageServerRequestIDs()); + EXPECT_EQ(server.MachMessageServerRequestIDs(), expect_request_ids); - EXPECT_EQ(kRequestSize, server.MachMessageServerRequestSize()); - EXPECT_EQ(kReplySize, server.MachMessageServerReplySize()); + EXPECT_EQ(server.MachMessageServerRequestSize(), kRequestSize); + EXPECT_EQ(server.MachMessageServerReplySize(), kReplySize); mach_msg_empty_rcv_t request = {}; mig_reply_error_t reply = {}; @@ -170,14 +170,14 @@ TEST(CompositeMachMessageServer, OneHandler) { bool destroy_complex_request = false; EXPECT_FALSE(server.MachMessageServerFunction( &request.header, &reply.Head, &destroy_complex_request)); - EXPECT_EQ(MIG_BAD_ID, reply.RetCode); + EXPECT_EQ(reply.RetCode, MIG_BAD_ID); EXPECT_FALSE(destroy_complex_request); // Send a message with a known request ID. request.header.msgh_id = kRequestID; EXPECT_TRUE(server.MachMessageServerFunction( &request.header, &reply.Head, &destroy_complex_request)); - EXPECT_EQ(kReturnCode, reply.RetCode); + EXPECT_EQ(reply.RetCode, kReturnCode); EXPECT_TRUE(destroy_complex_request); } @@ -234,10 +234,10 @@ TEST(CompositeMachMessageServer, ThreeHandlers) { server.AddHandler(&handlers[1]); server.AddHandler(&handlers[2]); - EXPECT_EQ(expect_request_ids, server.MachMessageServerRequestIDs()); + EXPECT_EQ(server.MachMessageServerRequestIDs(), expect_request_ids); - EXPECT_EQ(kRequestSize2, server.MachMessageServerRequestSize()); - EXPECT_EQ(kReplySize2, server.MachMessageServerReplySize()); + EXPECT_EQ(server.MachMessageServerRequestSize(), kRequestSize2); + EXPECT_EQ(server.MachMessageServerReplySize(), kReplySize2); mach_msg_empty_rcv_t request = {}; mig_reply_error_t reply = {}; @@ -247,7 +247,7 @@ TEST(CompositeMachMessageServer, ThreeHandlers) { bool destroy_complex_request = false; EXPECT_FALSE(server.MachMessageServerFunction( &request.header, &reply.Head, &destroy_complex_request)); - EXPECT_EQ(MIG_BAD_ID, reply.RetCode); + EXPECT_EQ(reply.RetCode, MIG_BAD_ID); EXPECT_FALSE(destroy_complex_request); // Send messages with known request IDs. @@ -259,7 +259,7 @@ TEST(CompositeMachMessageServer, ThreeHandlers) { EXPECT_TRUE(server.MachMessageServerFunction( &request.header, &reply.Head, &destroy_complex_request)); - EXPECT_EQ(kReturnCode0, reply.RetCode); + EXPECT_EQ(reply.RetCode, kReturnCode0); EXPECT_FALSE(destroy_complex_request); } @@ -270,7 +270,7 @@ TEST(CompositeMachMessageServer, ThreeHandlers) { EXPECT_FALSE(server.MachMessageServerFunction( &request.header, &reply.Head, &destroy_complex_request)); - EXPECT_EQ(kReturnCode1, reply.RetCode); + EXPECT_EQ(reply.RetCode, kReturnCode1); EXPECT_TRUE(destroy_complex_request); } @@ -281,7 +281,7 @@ TEST(CompositeMachMessageServer, ThreeHandlers) { EXPECT_TRUE(server.MachMessageServerFunction( &request.header, &reply.Head, &destroy_complex_request)); - EXPECT_EQ(kReturnCode2, reply.RetCode); + EXPECT_EQ(reply.RetCode, kReturnCode2); EXPECT_TRUE(destroy_complex_request); } } diff --git a/util/mach/exc_client_variants_test.cc b/util/mach/exc_client_variants_test.cc index 29a272b9..3bf77bb5 100644 --- a/util/mach/exc_client_variants_test.cc +++ b/util/mach/exc_client_variants_test.cc @@ -71,15 +71,15 @@ class TestExcClientVariants : public MachMultiprocess, EXPECT_FALSE(handled_); handled_ = true; - EXPECT_EQ(behavior_, behavior); - EXPECT_EQ(LocalPort(), exception_port); + EXPECT_EQ(behavior, behavior_); + EXPECT_EQ(exception_port, LocalPort()); if (HasIdentity()) { - EXPECT_NE(THREAD_NULL, thread); - EXPECT_EQ(ChildTask(), task); + EXPECT_NE(thread, THREAD_NULL); + EXPECT_EQ(task, ChildTask()); } else { - EXPECT_EQ(THREAD_NULL, thread); - EXPECT_EQ(TASK_NULL, task); + EXPECT_EQ(thread, THREAD_NULL); + EXPECT_EQ(task, TASK_NULL); } mach_exception_code_t expect_code = exception_code_; @@ -89,29 +89,29 @@ class TestExcClientVariants : public MachMultiprocess, expect_subcode = implicit_cast(expect_subcode); } - EXPECT_EQ(exception_, exception); - EXPECT_EQ(2u, code_count); + EXPECT_EQ(exception, exception_); + EXPECT_EQ(code_count, 2u); // The code_count check above would ideally use ASSERT_EQ so that the next // conditionals would not be necessary, but ASSERT_* requires a function // returning type void, and the interface dictates otherwise here. if (code_count >= 1) { - EXPECT_EQ(expect_code, code[0]); + EXPECT_EQ(code[0], expect_code); } if (code_count >= 2) { - EXPECT_EQ(expect_subcode, code[1]); + EXPECT_EQ(code[1], expect_subcode); } if (HasState()) { - EXPECT_EQ(exception_ + 10, *flavor); - EXPECT_EQ(MACHINE_THREAD_STATE_COUNT, old_state_count); - EXPECT_NE(nullptr, old_state); - EXPECT_EQ(implicit_cast(THREAD_STATE_MAX), - *new_state_count); - EXPECT_NE(nullptr, new_state); + EXPECT_EQ(*flavor, exception_ + 10); + EXPECT_EQ(old_state_count, MACHINE_THREAD_STATE_COUNT); + EXPECT_NE(old_state, nullptr); + EXPECT_EQ(*new_state_count, + implicit_cast(THREAD_STATE_MAX)); + EXPECT_NE(new_state, nullptr); for (size_t index = 0; index < old_state_count; ++index) { - EXPECT_EQ(index, old_state[index]); + EXPECT_EQ(old_state[index], index); } // Use a flavor known to be different from the incoming flavor, for a test @@ -124,11 +124,11 @@ class TestExcClientVariants : public MachMultiprocess, new_state[index] = MACHINE_THREAD_STATE_COUNT - index; } } else { - EXPECT_EQ(THREAD_STATE_NONE, *flavor); - EXPECT_EQ(0u, old_state_count); - EXPECT_EQ(nullptr, old_state); - EXPECT_EQ(0u, *new_state_count); - EXPECT_EQ(nullptr, new_state); + EXPECT_EQ(*flavor, THREAD_STATE_NONE); + EXPECT_EQ(old_state_count, 0u); + EXPECT_EQ(old_state, nullptr); + EXPECT_EQ(*new_state_count, 0u); + EXPECT_EQ(new_state, nullptr); } return KERN_SUCCESS; @@ -147,7 +147,7 @@ class TestExcClientVariants : public MachMultiprocess, MachMessageServer::kOneShot, MachMessageServer::kReceiveLargeError, kMachMessageTimeoutWaitIndefinitely); - EXPECT_EQ(KERN_SUCCESS, kr) + EXPECT_EQ(kr, KERN_SUCCESS) << MachErrorMessage(kr, "MachMessageServer::Run"); EXPECT_TRUE(handled_); @@ -196,27 +196,28 @@ class TestExcClientVariants : public MachMultiprocess, new_state_count_p = &new_state_count; } - EXPECT_EQ(KERN_SUCCESS, UniversalExceptionRaise(behavior_, - RemotePort(), - thread, - task, - exception, - code, - arraysize(code), - flavor_p, - old_state_p, - old_state_count, - new_state_p, - new_state_count_p)); + EXPECT_EQ(UniversalExceptionRaise(behavior_, + RemotePort(), + thread, + task, + exception, + code, + arraysize(code), + flavor_p, + old_state_p, + old_state_count, + new_state_p, + new_state_count_p), + KERN_SUCCESS); if (HasState()) { // Verify the out parameters. - EXPECT_EQ(exception_ + 20, flavor); - EXPECT_EQ(MACHINE_THREAD_STATE_COUNT, new_state_count); + EXPECT_EQ(flavor, exception_ + 20); + EXPECT_EQ(new_state_count, MACHINE_THREAD_STATE_COUNT); for (size_t index = 0; index < new_state_count; ++index) { - EXPECT_EQ(MACHINE_THREAD_STATE_COUNT - index, new_state[index]); + EXPECT_EQ(new_state[index], MACHINE_THREAD_STATE_COUNT - index); } } } diff --git a/util/mach/exc_server_variants_test.cc b/util/mach/exc_server_variants_test.cc index 1a24e698..482edac3 100644 --- a/util/mach/exc_server_variants_test.cc +++ b/util/mach/exc_server_variants_test.cc @@ -123,26 +123,26 @@ struct __attribute__((packed, aligned(4))) ExceptionRaiseReply { // MachExceptionRaiseReply. Knowing which behavior is expected allows the // message ID to be checked. void Verify(exception_behavior_t behavior) { - EXPECT_EQ(implicit_cast( - MACH_MSGH_BITS(MACH_MSG_TYPE_MOVE_SEND_ONCE, 0)), - Head.msgh_bits); - EXPECT_EQ(sizeof(*this), Head.msgh_size); - EXPECT_EQ(kClientRemotePort, Head.msgh_remote_port); - EXPECT_EQ(kMachPortNull, Head.msgh_local_port); + EXPECT_EQ(Head.msgh_bits, + implicit_cast( + MACH_MSGH_BITS(MACH_MSG_TYPE_MOVE_SEND_ONCE, 0))); + EXPECT_EQ(Head.msgh_size, sizeof(*this)); + EXPECT_EQ(Head.msgh_remote_port, kClientRemotePort); + EXPECT_EQ(Head.msgh_local_port, kMachPortNull); switch (behavior) { case EXCEPTION_DEFAULT: - EXPECT_EQ(2501, Head.msgh_id); + EXPECT_EQ(Head.msgh_id, 2501); break; case EXCEPTION_DEFAULT | kMachExceptionCodes: - EXPECT_EQ(2505, Head.msgh_id); + EXPECT_EQ(Head.msgh_id, 2505); break; default: ADD_FAILURE() << "behavior " << behavior << ", Head.msgh_id " << Head.msgh_id; break; } - EXPECT_EQ(0, memcmp(&NDR, &NDR_record, sizeof(NDR))); - EXPECT_EQ(KERN_SUCCESS, RetCode); + EXPECT_EQ(memcmp(&NDR, &NDR_record, sizeof(NDR)), 0); + EXPECT_EQ(RetCode, KERN_SUCCESS); } mach_msg_header_t Head; @@ -201,34 +201,34 @@ struct __attribute__((packed, aligned(4))) ExceptionRaiseStateReply { // MachExceptionRaiseStateIdentityReply. Knowing which behavior is expected // allows the message ID to be checked. void Verify(exception_behavior_t behavior) { - EXPECT_EQ(implicit_cast( - MACH_MSGH_BITS(MACH_MSG_TYPE_MOVE_SEND_ONCE, 0)), - Head.msgh_bits); - EXPECT_EQ(sizeof(*this), Head.msgh_size); - EXPECT_EQ(kClientRemotePort, Head.msgh_remote_port); - EXPECT_EQ(kMachPortNull, Head.msgh_local_port); + EXPECT_EQ(Head.msgh_bits, + implicit_cast( + MACH_MSGH_BITS(MACH_MSG_TYPE_MOVE_SEND_ONCE, 0))); + EXPECT_EQ(Head.msgh_size, sizeof(*this)); + EXPECT_EQ(Head.msgh_remote_port, kClientRemotePort); + EXPECT_EQ(Head.msgh_local_port, kMachPortNull); switch (behavior) { case EXCEPTION_STATE: - EXPECT_EQ(2502, Head.msgh_id); + EXPECT_EQ(Head.msgh_id, 2502); break; case EXCEPTION_STATE_IDENTITY: - EXPECT_EQ(2503, Head.msgh_id); + EXPECT_EQ(Head.msgh_id, 2503); break; case EXCEPTION_STATE | kMachExceptionCodes: - EXPECT_EQ(2506, Head.msgh_id); + EXPECT_EQ(Head.msgh_id, 2506); break; case EXCEPTION_STATE_IDENTITY | kMachExceptionCodes: - EXPECT_EQ(2507, Head.msgh_id); + EXPECT_EQ(Head.msgh_id, 2507); break; default: ADD_FAILURE() << "behavior " << behavior << ", Head.msgh_id " << Head.msgh_id; break; } - EXPECT_EQ(0, memcmp(&NDR, &NDR_record, sizeof(NDR))); - EXPECT_EQ(KERN_SUCCESS, RetCode); - EXPECT_EQ(kThreadStateFlavor, flavor); - EXPECT_EQ(arraysize(new_state), new_stateCnt); + EXPECT_EQ(memcmp(&NDR, &NDR_record, sizeof(NDR)), 0); + EXPECT_EQ(RetCode, KERN_SUCCESS); + EXPECT_EQ(flavor, kThreadStateFlavor); + EXPECT_EQ(new_stateCnt, arraysize(new_state)); } mach_msg_header_t Head; @@ -441,15 +441,15 @@ struct BadIDErrorReply : public mig_reply_error_t { } void Verify(mach_msg_id_t id) { - EXPECT_EQ(implicit_cast( - MACH_MSGH_BITS(MACH_MSG_TYPE_MOVE_SEND_ONCE, 0)), - Head.msgh_bits); - EXPECT_EQ(sizeof(*this), Head.msgh_size); - EXPECT_EQ(kClientRemotePort, Head.msgh_remote_port); - EXPECT_EQ(kMachPortNull, Head.msgh_local_port); - EXPECT_EQ(id + 100, Head.msgh_id); - EXPECT_EQ(0, memcmp(&NDR, &NDR_record, sizeof(NDR))); - EXPECT_EQ(MIG_BAD_ID, RetCode); + EXPECT_EQ(Head.msgh_bits, + implicit_cast( + MACH_MSGH_BITS(MACH_MSG_TYPE_MOVE_SEND_ONCE, 0))); + EXPECT_EQ(Head.msgh_size, sizeof(*this)); + EXPECT_EQ(Head.msgh_remote_port, kClientRemotePort); + EXPECT_EQ(Head.msgh_local_port, kMachPortNull); + EXPECT_EQ(Head.msgh_id, id + 100); + EXPECT_EQ(memcmp(&NDR, &NDR_record, sizeof(NDR)), 0); + EXPECT_EQ(RetCode, MIG_BAD_ID); } }; @@ -591,7 +591,7 @@ TEST(ExcServerVariants, MockExceptionRaise) { std::set ids = universal_mach_exc_server.MachMessageServerRequestIDs(); - EXPECT_NE(ids.end(), ids.find(2401)); // There is no constant for this. + EXPECT_NE(ids.find(2401), ids.end()); // There is no constant for this. ExceptionRaiseRequest request; EXPECT_LE(request.Head.msgh_size, @@ -636,7 +636,7 @@ TEST(ExcServerVariants, MockExceptionRaiseState) { std::set ids = universal_mach_exc_server.MachMessageServerRequestIDs(); - EXPECT_NE(ids.end(), ids.find(2402)); // There is no constant for this. + EXPECT_NE(ids.find(2402), ids.end()); // There is no constant for this. ExceptionRaiseStateRequest request; EXPECT_LE(request.Head.msgh_size, @@ -685,7 +685,7 @@ TEST(ExcServerVariants, MockExceptionRaiseStateIdentity) { std::set ids = universal_mach_exc_server.MachMessageServerRequestIDs(); - EXPECT_NE(ids.end(), ids.find(2403)); // There is no constant for this. + EXPECT_NE(ids.find(2403), ids.end()); // There is no constant for this. ExceptionRaiseStateIdentityRequest request; EXPECT_LE(request.Head.msgh_size, @@ -731,7 +731,7 @@ TEST(ExcServerVariants, MockMachExceptionRaise) { std::set ids = universal_mach_exc_server.MachMessageServerRequestIDs(); - EXPECT_NE(ids.end(), ids.find(2405)); // There is no constant for this. + EXPECT_NE(ids.find(2405), ids.end()); // There is no constant for this. MachExceptionRaiseRequest request; EXPECT_LE(request.Head.msgh_size, @@ -778,7 +778,7 @@ TEST(ExcServerVariants, MockMachExceptionRaiseState) { std::set ids = universal_mach_exc_server.MachMessageServerRequestIDs(); - EXPECT_NE(ids.end(), ids.find(2406)); // There is no constant for this. + EXPECT_NE(ids.find(2406), ids.end()); // There is no constant for this. MachExceptionRaiseStateRequest request; EXPECT_LE(request.Head.msgh_size, @@ -828,7 +828,7 @@ TEST(ExcServerVariants, MockMachExceptionRaiseStateIdentity) { std::set ids = universal_mach_exc_server.MachMessageServerRequestIDs(); - EXPECT_NE(ids.end(), ids.find(2407)); // There is no constant for this. + EXPECT_NE(ids.find(2407), ids.end()); // There is no constant for this. MachExceptionRaiseStateIdentityRequest request; EXPECT_LE(request.Head.msgh_size, @@ -913,7 +913,7 @@ TEST(ExcServerVariants, MockUnknownID) { std::set ids = universal_mach_exc_server.MachMessageServerRequestIDs(); - EXPECT_EQ(ids.end(), ids.find(id)); + EXPECT_EQ(ids.find(id), ids.end()); InvalidRequest request(id); EXPECT_LE(sizeof(request), @@ -953,8 +953,8 @@ TEST(ExcServerVariants, MachMessageServerRequestIDs) { MockUniversalMachExcServer server; UniversalMachExcServer universal_mach_exc_server(&server); - EXPECT_EQ(expect_request_ids, - universal_mach_exc_server.MachMessageServerRequestIDs()); + EXPECT_EQ(universal_mach_exc_server.MachMessageServerRequestIDs(), + expect_request_ids); } class TestExcServerVariants : public MachMultiprocess, @@ -992,20 +992,20 @@ class TestExcServerVariants : public MachMultiprocess, EXPECT_FALSE(handled_); handled_ = true; - EXPECT_EQ(behavior_, behavior); + EXPECT_EQ(behavior, behavior_); - EXPECT_EQ(LocalPort(), exception_port); + EXPECT_EQ(exception_port, LocalPort()); if (ExceptionBehaviorHasIdentity(behavior)) { - EXPECT_NE(THREAD_NULL, thread); - EXPECT_EQ(ChildTask(), task); + EXPECT_NE(thread, THREAD_NULL); + EXPECT_EQ(task, ChildTask()); } else { - EXPECT_EQ(THREAD_NULL, thread); - EXPECT_EQ(TASK_NULL, task); + EXPECT_EQ(thread, THREAD_NULL); + EXPECT_EQ(task, TASK_NULL); } - EXPECT_EQ(EXC_CRASH, exception); - EXPECT_EQ(2u, code_count); + EXPECT_EQ(exception, EXC_CRASH); + EXPECT_EQ(code_count, 2u); // The exception and code_count checks above would ideally use ASSERT_EQ so // that the next conditional would not be necessary, but ASSERT_* requires a @@ -1018,24 +1018,25 @@ class TestExcServerVariants : public MachMultiprocess, const bool has_state = ExceptionBehaviorHasState(behavior); if (has_state) { - EXPECT_EQ(flavor_, *flavor); - EXPECT_EQ(state_count_, old_state_count); - EXPECT_NE(nullptr, old_state); - EXPECT_EQ(implicit_cast(THREAD_STATE_MAX), - *new_state_count); - EXPECT_NE(nullptr, new_state); + EXPECT_EQ(*flavor, flavor_); + EXPECT_EQ(old_state_count, state_count_); + EXPECT_NE(old_state, nullptr); + EXPECT_EQ(*new_state_count, + implicit_cast(THREAD_STATE_MAX)); + EXPECT_NE(new_state, nullptr); } else { - EXPECT_EQ(THREAD_STATE_NONE, *flavor); - EXPECT_EQ(0u, old_state_count); - EXPECT_EQ(nullptr, old_state); - EXPECT_EQ(0u, *new_state_count); - EXPECT_EQ(nullptr, new_state); + EXPECT_EQ(*flavor, THREAD_STATE_NONE); + EXPECT_EQ(old_state_count, 0u); + EXPECT_EQ(old_state, nullptr); + EXPECT_EQ(*new_state_count, 0u); + EXPECT_EQ(new_state, nullptr); } - EXPECT_EQ(implicit_cast(MACH_MSG_TRAILER_FORMAT_0), - trailer->msgh_trailer_type); - EXPECT_EQ(REQUESTED_TRAILER_SIZE(kMachMessageOptions), - trailer->msgh_trailer_size); + EXPECT_EQ( + trailer->msgh_trailer_type, + implicit_cast(MACH_MSG_TRAILER_FORMAT_0)); + EXPECT_EQ(trailer->msgh_trailer_size, + REQUESTED_TRAILER_SIZE(kMachMessageOptions)); ExcServerCopyState( behavior, old_state, old_state_count, new_state, new_state_count); @@ -1056,7 +1057,7 @@ class TestExcServerVariants : public MachMultiprocess, MachMessageServer::kOneShot, MachMessageServer::kReceiveLargeError, kMachMessageTimeoutWaitIndefinitely); - EXPECT_EQ(KERN_SUCCESS, kr) + EXPECT_EQ(kr, KERN_SUCCESS) << MachErrorMessage(kr, "MachMessageServer::Run"); EXPECT_TRUE(handled_); @@ -1066,7 +1067,7 @@ class TestExcServerVariants : public MachMultiprocess, // Set the parent as the exception handler for EXC_CRASH. kern_return_t kr = task_set_exception_ports( mach_task_self(), EXC_MASK_CRASH, RemotePort(), behavior_, flavor_); - ASSERT_EQ(KERN_SUCCESS, kr) + ASSERT_EQ(kr, KERN_SUCCESS) << MachErrorMessage(kr, "task_set_exception_ports"); // Now crash. @@ -1259,10 +1260,10 @@ TEST(ExcServerVariants, ExcServerSuccessfulReturnValue) { test_data.behavior, test_data.set_thread_state ? "true" : "false")); - EXPECT_EQ(test_data.kr, - ExcServerSuccessfulReturnValue(test_data.exception, + EXPECT_EQ(ExcServerSuccessfulReturnValue(test_data.exception, test_data.behavior, - test_data.set_thread_state)); + test_data.set_thread_state), + test_data.kr); } } @@ -1280,9 +1281,9 @@ TEST(ExcServerVariants, ExcServerCopyState) { old_state_count, new_state, &new_state_count); - EXPECT_EQ(arraysize(new_state), new_state_count); + EXPECT_EQ(new_state_count, arraysize(new_state)); for (size_t i = 0; i < arraysize(new_state); ++i) { - EXPECT_EQ(0u, new_state[i]) << "i " << i; + EXPECT_EQ(new_state[i], 0u) << "i " << i; } ExcServerCopyState(MACH_EXCEPTION_CODES | EXCEPTION_DEFAULT, @@ -1290,21 +1291,21 @@ TEST(ExcServerVariants, ExcServerCopyState) { old_state_count, new_state, &new_state_count); - EXPECT_EQ(arraysize(new_state), new_state_count); + EXPECT_EQ(new_state_count, arraysize(new_state)); for (size_t i = 0; i < arraysize(new_state); ++i) { - EXPECT_EQ(0u, new_state[i]) << "i " << i; + EXPECT_EQ(new_state[i], 0u) << "i " << i; } // This is a state-carrying exception where old_state_count is small. mach_msg_type_number_t copy_limit = 2; ExcServerCopyState( EXCEPTION_STATE, old_state, copy_limit, new_state, &new_state_count); - EXPECT_EQ(copy_limit, new_state_count); + EXPECT_EQ(new_state_count, copy_limit); for (size_t i = 0; i < copy_limit; ++i) { - EXPECT_EQ(old_state[i], new_state[i]) << "i " << i; + EXPECT_EQ(new_state[i], old_state[i]) << "i " << i; } for (size_t i = copy_limit; i < arraysize(new_state); ++i) { - EXPECT_EQ(0u, new_state[i]) << "i " << i; + EXPECT_EQ(new_state[i], 0u) << "i " << i; } // This is a state-carrying exception where new_state_count is small. @@ -1315,12 +1316,12 @@ TEST(ExcServerVariants, ExcServerCopyState) { old_state_count, new_state, &new_state_count); - EXPECT_EQ(copy_limit, new_state_count); + EXPECT_EQ(new_state_count, copy_limit); for (size_t i = 0; i < copy_limit; ++i) { - EXPECT_EQ(old_state[i], new_state[i]) << "i " << i; + EXPECT_EQ(new_state[i], old_state[i]) << "i " << i; } for (size_t i = copy_limit; i < arraysize(new_state); ++i) { - EXPECT_EQ(0u, new_state[i]) << "i " << i; + EXPECT_EQ(new_state[i], 0u) << "i " << i; } // This is a state-carrying exception where all of old_state is copied to @@ -1331,12 +1332,12 @@ TEST(ExcServerVariants, ExcServerCopyState) { old_state_count, new_state, &new_state_count); - EXPECT_EQ(old_state_count, new_state_count); + EXPECT_EQ(new_state_count, old_state_count); for (size_t i = 0; i < arraysize(old_state); ++i) { - EXPECT_EQ(old_state[i], new_state[i]) << "i " << i; + EXPECT_EQ(new_state[i], old_state[i]) << "i " << i; } for (size_t i = arraysize(old_state); i < arraysize(new_state); ++i) { - EXPECT_EQ(0u, new_state[i]) << "i " << i; + EXPECT_EQ(new_state[i], 0u) << "i " << i; } } diff --git a/util/mach/exception_behaviors_test.cc b/util/mach/exception_behaviors_test.cc index a4a55e26..3ccb2027 100644 --- a/util/mach/exception_behaviors_test.cc +++ b/util/mach/exception_behaviors_test.cc @@ -59,13 +59,13 @@ TEST(ExceptionBehaviors, ExceptionBehaviors) { SCOPED_TRACE(base::StringPrintf( "index %zu, behavior %d", index, test_data.behavior)); - EXPECT_EQ(test_data.state, ExceptionBehaviorHasState(test_data.behavior)); - EXPECT_EQ(test_data.identity, - ExceptionBehaviorHasIdentity(test_data.behavior)); - EXPECT_EQ(test_data.mach_exception_codes, - ExceptionBehaviorHasMachExceptionCodes(test_data.behavior)); - EXPECT_EQ(test_data.basic_behavior, - ExceptionBehaviorBasic(test_data.behavior)); + EXPECT_EQ(ExceptionBehaviorHasState(test_data.behavior), test_data.state); + EXPECT_EQ(ExceptionBehaviorHasIdentity(test_data.behavior), + test_data.identity); + EXPECT_EQ(ExceptionBehaviorHasMachExceptionCodes(test_data.behavior), + test_data.mach_exception_codes); + EXPECT_EQ(ExceptionBehaviorBasic(test_data.behavior), + test_data.basic_behavior); } } diff --git a/util/mach/exception_ports_test.cc b/util/mach/exception_ports_test.cc index f3d40029..0bdd92ec 100644 --- a/util/mach/exception_ports_test.cc +++ b/util/mach/exception_ports_test.cc @@ -69,12 +69,12 @@ void TestGetExceptionPorts(const ExceptionPorts& exception_ports, exception_ports.GetExceptionPorts(kExceptionMask, &crash_handler)); if (expect_port != MACH_PORT_NULL) { - ASSERT_EQ(1u, crash_handler.size()); + ASSERT_EQ(crash_handler.size(), 1u); - EXPECT_EQ(kExceptionMask, crash_handler[0].mask); - EXPECT_EQ(expect_port, crash_handler[0].port); - EXPECT_EQ(expect_behavior, crash_handler[0].behavior); - EXPECT_EQ(expect_flavor, crash_handler[0].flavor); + EXPECT_EQ(crash_handler[0].mask, kExceptionMask); + EXPECT_EQ(crash_handler[0].port, expect_port); + EXPECT_EQ(crash_handler[0].behavior, expect_behavior); + EXPECT_EQ(crash_handler[0].flavor, expect_flavor); } else { EXPECT_TRUE(crash_handler.empty()); } @@ -88,9 +88,9 @@ void TestGetExceptionPorts(const ExceptionPorts& exception_ports, if ((handler.mask & kExceptionMask) != 0) { EXPECT_FALSE(found); found = true; - EXPECT_EQ(expect_port, handler.port); - EXPECT_EQ(expect_behavior, handler.behavior); - EXPECT_EQ(expect_flavor, handler.flavor); + EXPECT_EQ(handler.port, expect_port); + EXPECT_EQ(handler.behavior, expect_behavior); + EXPECT_EQ(handler.flavor, expect_flavor); } } @@ -174,12 +174,12 @@ class TestExceptionPorts : public MachMultiprocess, expect_behavior = 0; } - EXPECT_EQ(expect_behavior, behavior); + EXPECT_EQ(behavior, expect_behavior); - EXPECT_EQ(LocalPort(), exception_port); + EXPECT_EQ(exception_port, LocalPort()); - EXPECT_EQ(EXC_CRASH, exception); - EXPECT_EQ(2u, code_count); + EXPECT_EQ(exception, EXC_CRASH); + EXPECT_EQ(code_count, 2u); // The exception and code_count checks above would ideally use ASSERT_EQ so // that the next conditional would not be necessary, but ASSERT_* requires a @@ -189,12 +189,12 @@ class TestExceptionPorts : public MachMultiprocess, ExcCrashRecoverOriginalException(code[0], nullptr, &signal); // The child crashed with __builtin_trap(), which shows up as SIGILL. - EXPECT_EQ(SIGILL, signal); + EXPECT_EQ(signal, SIGILL); SetExpectedChildTermination(kTerminationSignal, signal); } - EXPECT_EQ(0, AuditPIDFromMachMessageTrailer(trailer)); + EXPECT_EQ(AuditPIDFromMachMessageTrailer(trailer), 0); ExcServerCopyState( behavior, old_state, old_state_count, new_state, new_state_count); @@ -234,7 +234,7 @@ class TestExceptionPorts : public MachMultiprocess, } int rv_int = pthread_create(&thread_, nullptr, ThreadMainThunk, this); - ASSERT_EQ(0, rv_int); + ASSERT_EQ(rv_int, 0); // Wait for the new thread to be ready. init_semaphore_.Wait(); @@ -245,7 +245,7 @@ class TestExceptionPorts : public MachMultiprocess, // Wait for the parent process to say that its end is set up. CheckedReadFileExactly(test_exception_ports_->ReadPipeHandle(), &c, 1); - EXPECT_EQ('\0', c); + EXPECT_EQ(c, '\0'); // Regardless of where ExceptionPorts::SetExceptionPort() ran, // ExceptionPorts::GetExceptionPorts() can always be tested in-process. @@ -274,7 +274,7 @@ class TestExceptionPorts : public MachMultiprocess, // Reap the other thread. rv_int = pthread_join(thread_, nullptr); - ASSERT_EQ(0, rv_int); + ASSERT_EQ(rv_int, 0); } private: @@ -353,7 +353,7 @@ class TestExceptionPorts : public MachMultiprocess, // threads set up before proceeding if in kSetOutOfProcess mode. char c; CheckedReadFileExactly(ReadPipeHandle(), &c, 1); - EXPECT_EQ('\0', c); + EXPECT_EQ(c, '\0'); mach_port_t local_port = LocalPort(); @@ -367,10 +367,10 @@ class TestExceptionPorts : public MachMultiprocess, thread_act_array_t threads; mach_msg_type_number_t thread_count = 0; kern_return_t kr = task_threads(ChildTask(), &threads, &thread_count); - ASSERT_EQ(KERN_SUCCESS, kr) << MachErrorMessage(kr, "task_threads"); + ASSERT_EQ(kr, KERN_SUCCESS) << MachErrorMessage(kr, "task_threads"); ScopedForbidReturn threads_need_owners; - ASSERT_EQ(2u, thread_count); + ASSERT_EQ(thread_count, 2u); base::mac::ScopedMachSendRight main_thread(threads[0]); base::mac::ScopedMachSendRight other_thread(threads[1]); threads_need_owners.Disarm(); @@ -392,7 +392,7 @@ class TestExceptionPorts : public MachMultiprocess, // done. kr = mach_port_insert_right( mach_task_self(), local_port, local_port, MACH_MSG_TYPE_MAKE_SEND); - ASSERT_EQ(KERN_SUCCESS, kr) + ASSERT_EQ(kr, KERN_SUCCESS) << MachErrorMessage(kr, "mach_port_insert_right"); base::mac::ScopedMachSendRight send_owner(local_port); @@ -448,7 +448,7 @@ class TestExceptionPorts : public MachMultiprocess, MachMessageServer::kOneShot, MachMessageServer::kReceiveLargeError, kTimeoutMs); - EXPECT_EQ(KERN_SUCCESS, kr) + EXPECT_EQ(kr, KERN_SUCCESS) << MachErrorMessage(kr, "MachMessageServer::Run"); EXPECT_TRUE(handled_); @@ -593,7 +593,7 @@ TEST(ExceptionPorts, HostExceptionPorts) { ExceptionPorts::ExceptionHandlerVector explicit_handlers; bool rv = explicit_host_ports.GetExceptionPorts(ExcMaskValid(), &explicit_handlers); - EXPECT_EQ(expect_success, rv); + EXPECT_EQ(rv, expect_success); ExceptionPorts implicit_host_ports(ExceptionPorts::kTargetTypeHost, HOST_NULL); @@ -602,9 +602,9 @@ TEST(ExceptionPorts, HostExceptionPorts) { ExceptionPorts::ExceptionHandlerVector implicit_handlers; rv = implicit_host_ports.GetExceptionPorts(ExcMaskValid(), &implicit_handlers); - EXPECT_EQ(expect_success, rv); + EXPECT_EQ(rv, expect_success); - EXPECT_EQ(explicit_handlers.size(), implicit_handlers.size()); + EXPECT_EQ(implicit_handlers.size(), explicit_handlers.size()); } } // namespace diff --git a/util/mach/exception_types_test.cc b/util/mach/exception_types_test.cc index 4175c637..ff09164e 100644 --- a/util/mach/exception_types_test.cc +++ b/util/mach/exception_types_test.cc @@ -78,9 +78,9 @@ TEST(ExceptionTypes, ExcCrashRecoverOriginalException) { exception_type_t exception = ExcCrashRecoverOriginalException( test_data.code_0, &original_code_0, &signal); - EXPECT_EQ(test_data.exception, exception); - EXPECT_EQ(test_data.original_code_0, original_code_0); - EXPECT_EQ(test_data.signal, signal); + EXPECT_EQ(exception, test_data.exception); + EXPECT_EQ(original_code_0, test_data.original_code_0); + EXPECT_EQ(signal, test_data.signal); } // Now make sure that ExcCrashRecoverOriginalException() properly ignores @@ -88,20 +88,20 @@ TEST(ExceptionTypes, ExcCrashRecoverOriginalException) { static_assert(arraysize(kTestData) >= 1, "must have something to test"); const TestData& test_data = kTestData[0]; EXPECT_EQ( - test_data.exception, - ExcCrashRecoverOriginalException(test_data.code_0, nullptr, nullptr)); + ExcCrashRecoverOriginalException(test_data.code_0, nullptr, nullptr), + test_data.exception); mach_exception_code_t original_code_0; - EXPECT_EQ(test_data.exception, - ExcCrashRecoverOriginalException( - test_data.code_0, &original_code_0, nullptr)); - EXPECT_EQ(test_data.original_code_0, original_code_0); + EXPECT_EQ(ExcCrashRecoverOriginalException( + test_data.code_0, &original_code_0, nullptr), + test_data.exception); + EXPECT_EQ(original_code_0, test_data.original_code_0); int signal; EXPECT_EQ( - test_data.exception, - ExcCrashRecoverOriginalException(test_data.code_0, nullptr, &signal)); - EXPECT_EQ(test_data.signal, signal); + ExcCrashRecoverOriginalException(test_data.code_0, nullptr, &signal), + test_data.exception); + EXPECT_EQ(signal, test_data.signal); } TEST(ExceptionTypes, ExcCrashCouldContainException) { @@ -250,7 +250,7 @@ TEST(ExceptionTypes, ExceptionCodeForMetrics) { int32_t metrics_code = ExceptionCodeForMetrics(test_data.exception, test_data.code_0); - EXPECT_EQ(test_data.metrics_code, metrics_code); + EXPECT_EQ(metrics_code, test_data.metrics_code); } } diff --git a/util/mach/mach_extensions_test.cc b/util/mach/mach_extensions_test.cc index 358f2355..289a1999 100644 --- a/util/mach/mach_extensions_test.cc +++ b/util/mach/mach_extensions_test.cc @@ -26,40 +26,40 @@ namespace { TEST(MachExtensions, MachThreadSelf) { base::mac::ScopedMachSendRight thread_self(mach_thread_self()); - EXPECT_EQ(thread_self, MachThreadSelf()); + EXPECT_EQ(MachThreadSelf(), thread_self); } TEST(MachExtensions, NewMachPort_Receive) { base::mac::ScopedMachReceiveRight port(NewMachPort(MACH_PORT_RIGHT_RECEIVE)); - ASSERT_NE(kMachPortNull, port); + ASSERT_NE(port, kMachPortNull); mach_port_type_t type; kern_return_t kr = mach_port_type(mach_task_self(), port.get(), &type); - ASSERT_EQ(KERN_SUCCESS, kr) << MachErrorMessage(kr, "mach_port_get_type"); + ASSERT_EQ(kr, KERN_SUCCESS) << MachErrorMessage(kr, "mach_port_get_type"); - EXPECT_EQ(MACH_PORT_TYPE_RECEIVE, type); + EXPECT_EQ(type, MACH_PORT_TYPE_RECEIVE); } TEST(MachExtensions, NewMachPort_PortSet) { base::mac::ScopedMachPortSet port(NewMachPort(MACH_PORT_RIGHT_PORT_SET)); - ASSERT_NE(kMachPortNull, port); + ASSERT_NE(port, kMachPortNull); mach_port_type_t type; kern_return_t kr = mach_port_type(mach_task_self(), port.get(), &type); - ASSERT_EQ(KERN_SUCCESS, kr) << MachErrorMessage(kr, "mach_port_get_type"); + ASSERT_EQ(kr, KERN_SUCCESS) << MachErrorMessage(kr, "mach_port_get_type"); - EXPECT_EQ(MACH_PORT_TYPE_PORT_SET, type); + EXPECT_EQ(type, MACH_PORT_TYPE_PORT_SET); } TEST(MachExtensions, NewMachPort_DeadName) { base::mac::ScopedMachSendRight port(NewMachPort(MACH_PORT_RIGHT_DEAD_NAME)); - ASSERT_NE(kMachPortNull, port); + ASSERT_NE(port, kMachPortNull); mach_port_type_t type; kern_return_t kr = mach_port_type(mach_task_self(), port.get(), &type); - ASSERT_EQ(KERN_SUCCESS, kr) << MachErrorMessage(kr, "mach_port_get_type"); + ASSERT_EQ(kr, KERN_SUCCESS) << MachErrorMessage(kr, "mach_port_get_type"); - EXPECT_EQ(MACH_PORT_TYPE_DEAD_NAME, type); + EXPECT_EQ(type, MACH_PORT_TYPE_DEAD_NAME); } const exception_mask_t kExcMaskBasic = @@ -75,7 +75,7 @@ const exception_mask_t kExcMaskBasic = TEST(MachExtensions, ExcMaskAll) { const exception_mask_t exc_mask_all = ExcMaskAll(); - EXPECT_EQ(kExcMaskBasic, exc_mask_all & kExcMaskBasic); + EXPECT_EQ(exc_mask_all & kExcMaskBasic, kExcMaskBasic); EXPECT_FALSE(exc_mask_all & EXC_MASK_CRASH); EXPECT_FALSE(exc_mask_all & EXC_MASK_CORPSE_NOTIFY); @@ -97,12 +97,12 @@ TEST(MachExtensions, ExcMaskAll) { EXPECT_FALSE(ExcMaskAll() & 1); // Every bit set in ExcMaskAll() must also be set in ExcMaskValid(). - EXPECT_EQ(ExcMaskAll(), ExcMaskAll() & ExcMaskValid()); + EXPECT_EQ(ExcMaskAll() & ExcMaskValid(), ExcMaskAll()); } TEST(MachExtensions, ExcMaskValid) { const exception_mask_t exc_mask_valid = ExcMaskValid(); - EXPECT_EQ(kExcMaskBasic, exc_mask_valid & kExcMaskBasic); + EXPECT_EQ(exc_mask_valid & kExcMaskBasic, kExcMaskBasic); EXPECT_TRUE(exc_mask_valid & EXC_MASK_CRASH); @@ -144,7 +144,7 @@ TEST(MachExtensions, BootstrapCheckInAndLookUp) { { // The new service hasn’t checked in yet, so this should fail. base::mac::ScopedMachSendRight send(BootstrapLookUp(service_name)); - EXPECT_EQ(kMachPortNull, send); + EXPECT_EQ(send, kMachPortNull); // Check it in. base::mac::ScopedMachReceiveRight receive(BootstrapCheckIn(service_name)); @@ -156,12 +156,12 @@ TEST(MachExtensions, BootstrapCheckInAndLookUp) { // It shouldn’t be possible to check the service in while it’s active. base::mac::ScopedMachReceiveRight receive_2(BootstrapCheckIn(service_name)); - EXPECT_EQ(kMachPortNull, receive_2); + EXPECT_EQ(receive_2, kMachPortNull); } // The new service should be gone now. base::mac::ScopedMachSendRight send(BootstrapLookUp(service_name)); - EXPECT_EQ(kMachPortNull, send); + EXPECT_EQ(send, kMachPortNull); // It should be possible to check it in again. base::mac::ScopedMachReceiveRight receive(BootstrapCheckIn(service_name)); diff --git a/util/mach/mach_message.cc b/util/mach/mach_message.cc index 30c3a8cf..771f4603 100644 --- a/util/mach/mach_message.cc +++ b/util/mach/mach_message.cc @@ -197,14 +197,12 @@ void PrepareMIGReplyFromRequest(const mach_msg_header_t* in_header, mach_msg_header_t* out_header) { out_header->msgh_bits = MACH_MSGH_BITS(MACH_MSGH_BITS_REMOTE(in_header->msgh_bits), 0); - out_header->msgh_remote_port = in_header->msgh_remote_port; out_header->msgh_size = sizeof(mig_reply_error_t); + out_header->msgh_remote_port = in_header->msgh_remote_port; out_header->msgh_local_port = MACH_PORT_NULL; + out_header->msgh_reserved = 0; out_header->msgh_id = in_header->msgh_id + 100; reinterpret_cast(out_header)->NDR = NDR_record; - - // MIG-generated dispatch routines don’t do this, but they should. - out_header->msgh_reserved = 0; } void SetMIGReplyError(mach_msg_header_t* out_header, kern_return_t error) { diff --git a/util/mach/mach_message_server_test.cc b/util/mach/mach_message_server_test.cc index 2c4c8e1d..e42ef6a5 100644 --- a/util/mach/mach_message_server_test.cc +++ b/util/mach/mach_message_server_test.cc @@ -182,13 +182,13 @@ class TestMachMessageServer : public MachMessageServer::Interface, // Runs the test. void Test() { - EXPECT_EQ(requests_, replies_); + EXPECT_EQ(replies_, requests_); uint32_t start = requests_; Run(); - EXPECT_EQ(requests_, replies_); - EXPECT_EQ(options_.expect_server_transaction_count, requests_ - start); + EXPECT_EQ(replies_, requests_); + EXPECT_EQ(requests_ - start, options_.expect_server_transaction_count); } // MachMessageServerInterface: @@ -217,32 +217,32 @@ class TestMachMessageServer : public MachMessageServer::Interface, const mach_msg_bits_t expect_msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_MOVE_SEND, MACH_MSG_TYPE_MOVE_SEND) | (options_.client_send_complex ? MACH_MSGH_BITS_COMPLEX : 0); - EXPECT_EQ(expect_msgh_bits, request->header.msgh_bits); - EXPECT_EQ(options_.client_send_large ? sizeof(LargeRequestMessage) - : sizeof(RequestMessage), - request->header.msgh_size); + EXPECT_EQ(request->header.msgh_bits, expect_msgh_bits); + EXPECT_EQ(request->header.msgh_size, + options_.client_send_large ? sizeof(LargeRequestMessage) + : sizeof(RequestMessage)); if (options_.client_reply_port_type == Options::kReplyPortNormal) { - EXPECT_EQ(RemotePort(), request->header.msgh_remote_port); + EXPECT_EQ(request->header.msgh_remote_port, RemotePort()); } - EXPECT_EQ(LocalPort(), request->header.msgh_local_port); - EXPECT_EQ(kRequestMessageID, request->header.msgh_id); + EXPECT_EQ(request->header.msgh_local_port, LocalPort()); + EXPECT_EQ(request->header.msgh_id, kRequestMessageID); if (options_.client_send_complex) { - EXPECT_EQ(1u, request->body.msgh_descriptor_count); - EXPECT_NE(kMachPortNull, request->port_descriptor.name); + EXPECT_EQ(request->body.msgh_descriptor_count, 1u); + EXPECT_NE(request->port_descriptor.name, kMachPortNull); parent_complex_message_port_ = request->port_descriptor.name; - EXPECT_EQ(implicit_cast(MACH_MSG_TYPE_MOVE_SEND), - request->port_descriptor.disposition); + EXPECT_EQ(request->port_descriptor.disposition, + implicit_cast(MACH_MSG_TYPE_MOVE_SEND)); EXPECT_EQ( - implicit_cast(MACH_MSG_PORT_DESCRIPTOR), - request->port_descriptor.type); + request->port_descriptor.type, + implicit_cast(MACH_MSG_PORT_DESCRIPTOR)); } else { - EXPECT_EQ(0u, request->body.msgh_descriptor_count); - EXPECT_EQ(kMachPortNull, request->port_descriptor.name); - EXPECT_EQ(0u, request->port_descriptor.disposition); - EXPECT_EQ(0u, request->port_descriptor.type); + EXPECT_EQ(request->body.msgh_descriptor_count, 0u); + EXPECT_EQ(request->port_descriptor.name, kMachPortNull); + EXPECT_EQ(request->port_descriptor.disposition, 0u); + EXPECT_EQ(request->port_descriptor.type, 0u); } - EXPECT_EQ(0, memcmp(&request->ndr, &NDR_record, sizeof(NDR_record))); - EXPECT_EQ(requests_, request->number); + EXPECT_EQ(memcmp(&request->ndr, &NDR_record, sizeof(NDR_record)), 0); + EXPECT_EQ(request->number, requests_); // Look for the trailer in the right spot, depending on whether the request // message was a RequestMessage or a LargeRequestMessage. @@ -251,16 +251,17 @@ class TestMachMessageServer : public MachMessageServer::Interface, const ReceiveLargeRequestMessage* large_request = reinterpret_cast(request); for (size_t index = 0; index < sizeof(large_request->data); ++index) { - EXPECT_EQ('!', large_request->data[index]); + EXPECT_EQ(large_request->data[index], '!'); } trailer = &large_request->trailer; } else { trailer = &request->trailer; } - EXPECT_EQ(implicit_cast(MACH_MSG_TRAILER_FORMAT_0), - trailer->msgh_trailer_type); - EXPECT_EQ(MACH_MSG_TRAILER_MINIMUM_SIZE, trailer->msgh_trailer_size); + EXPECT_EQ( + trailer->msgh_trailer_type, + implicit_cast(MACH_MSG_TRAILER_FORMAT_0)); + EXPECT_EQ(trailer->msgh_trailer_size, MACH_MSG_TRAILER_MINIMUM_SIZE); ++requests_; @@ -331,7 +332,7 @@ class TestMachMessageServer : public MachMessageServer::Interface, MACH_PORT_LIMITS_INFO, reinterpret_cast(&limits), MACH_PORT_LIMITS_INFO_COUNT); - ASSERT_EQ(KERN_SUCCESS, kr) + ASSERT_EQ(kr, KERN_SUCCESS) << MachErrorMessage(kr, "mach_port_set_attributes"); } @@ -345,20 +346,20 @@ class TestMachMessageServer : public MachMessageServer::Interface, // Wait until the child is done sending what it’s going to send. char c; CheckedReadFileExactly(ReadPipeHandle(), &c, 1); - EXPECT_EQ('\0', c); + EXPECT_EQ(c, '\0'); } - ASSERT_EQ(options_.expect_server_result, - (kr = MachMessageServer::Run(this, + ASSERT_EQ((kr = MachMessageServer::Run(this, local_port, options_.server_options, options_.server_persistent, options_.server_receive_large, - options_.server_timeout_ms))) + options_.server_timeout_ms)), + options_.expect_server_result) << MachErrorMessage(kr, "MachMessageServer"); if (options_.client_send_complex) { - EXPECT_NE(kMachPortNull, parent_complex_message_port_); + EXPECT_NE(parent_complex_message_port_, kMachPortNull); mach_port_type_t type; if (!options_.expect_server_destroyed_complex) { @@ -366,13 +367,13 @@ class TestMachMessageServer : public MachMessageServer::Interface, // complex request message. kr = mach_port_type( mach_task_self(), parent_complex_message_port_, &type); - EXPECT_EQ(KERN_SUCCESS, kr) << MachErrorMessage(kr, "mach_port_type"); - EXPECT_EQ(MACH_PORT_TYPE_SEND, type); + EXPECT_EQ(kr, KERN_SUCCESS) << MachErrorMessage(kr, "mach_port_type"); + EXPECT_EQ(type, MACH_PORT_TYPE_SEND); // Destroy the resources here. kr = mach_port_deallocate(mach_task_self(), parent_complex_message_port_); - EXPECT_EQ(KERN_SUCCESS, kr) + EXPECT_EQ(kr, KERN_SUCCESS) << MachErrorMessage(kr, "mach_port_deallocate"); } @@ -382,7 +383,7 @@ class TestMachMessageServer : public MachMessageServer::Interface, // this test environment. kr = mach_port_type(mach_task_self(), parent_complex_message_port_, &type); - EXPECT_EQ(KERN_INVALID_NAME, kr) + EXPECT_EQ(kr, KERN_INVALID_NAME) << MachErrorMessage(kr, "mach_port_type"); } @@ -398,7 +399,7 @@ class TestMachMessageServer : public MachMessageServer::Interface, // Wait until the parent is done setting things up on its end. char c; CheckedReadFileExactly(ReadPipeHandle(), &c, 1); - EXPECT_EQ('\0', c); + EXPECT_EQ(c, '\0'); } for (size_t index = 0; @@ -432,7 +433,7 @@ class TestMachMessageServer : public MachMessageServer::Interface, if (options_.child_wait_for_parent_pipe_late) { char c; CheckedReadFileExactly(ReadPipeHandle(), &c, 1); - ASSERT_EQ('\0', c); + ASSERT_EQ(c, '\0'); } } @@ -505,7 +506,7 @@ class TestMachMessageServer : public MachMessageServer::Interface, MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL); - ASSERT_EQ(MACH_MSG_SUCCESS, kr) << MachErrorMessage(kr, "mach_msg"); + ASSERT_EQ(kr, MACH_MSG_SUCCESS) << MachErrorMessage(kr, "mach_msg"); } // In the child process, waits for a reply message from the server. @@ -529,20 +530,22 @@ class TestMachMessageServer : public MachMessageServer::Interface, LocalPort(), MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL); - ASSERT_EQ(MACH_MSG_SUCCESS, kr) << MachErrorMessage(kr, "mach_msg"); + ASSERT_EQ(kr, MACH_MSG_SUCCESS) << MachErrorMessage(kr, "mach_msg"); - ASSERT_EQ(implicit_cast( - MACH_MSGH_BITS(0, MACH_MSG_TYPE_MOVE_SEND)), reply.Head.msgh_bits); - ASSERT_EQ(sizeof(ReplyMessage), reply.Head.msgh_size); - ASSERT_EQ(kMachPortNull, reply.Head.msgh_remote_port); - ASSERT_EQ(LocalPort(), reply.Head.msgh_local_port); - ASSERT_EQ(kReplyMessageID, reply.Head.msgh_id); - ASSERT_EQ(0, memcmp(&reply.NDR, &NDR_record, sizeof(NDR_record))); - ASSERT_EQ(options_.server_mig_retcode, reply.RetCode); - ASSERT_EQ(replies_, reply.number); - ASSERT_EQ(implicit_cast(MACH_MSG_TRAILER_FORMAT_0), - reply.trailer.msgh_trailer_type); - ASSERT_EQ(MACH_MSG_TRAILER_MINIMUM_SIZE, reply.trailer.msgh_trailer_size); + ASSERT_EQ(reply.Head.msgh_bits, + implicit_cast( + MACH_MSGH_BITS(0, MACH_MSG_TYPE_MOVE_SEND))); + ASSERT_EQ(reply.Head.msgh_size, sizeof(ReplyMessage)); + ASSERT_EQ(reply.Head.msgh_remote_port, kMachPortNull); + ASSERT_EQ(reply.Head.msgh_local_port, LocalPort()); + ASSERT_EQ(reply.Head.msgh_id, kReplyMessageID); + ASSERT_EQ(memcmp(&reply.NDR, &NDR_record, sizeof(NDR_record)), 0); + ASSERT_EQ(reply.RetCode, options_.server_mig_retcode); + ASSERT_EQ(reply.number, replies_); + ASSERT_EQ( + reply.trailer.msgh_trailer_type, + implicit_cast(MACH_MSG_TRAILER_FORMAT_0)); + ASSERT_EQ(reply.trailer.msgh_trailer_size, MACH_MSG_TRAILER_MINIMUM_SIZE); ++replies_; } diff --git a/util/mach/mach_message_test.cc b/util/mach/mach_message_test.cc index 3e64601a..d88ca855 100644 --- a/util/mach/mach_message_test.cc +++ b/util/mach/mach_message_test.cc @@ -29,19 +29,19 @@ namespace { TEST(MachMessage, MachMessageDeadlineFromTimeout) { MachMessageDeadline deadline_0 = MachMessageDeadlineFromTimeout(kMachMessageTimeoutNonblocking); - EXPECT_EQ(kMachMessageDeadlineNonblocking, deadline_0); + EXPECT_EQ(deadline_0, kMachMessageDeadlineNonblocking); deadline_0 = MachMessageDeadlineFromTimeout(kMachMessageTimeoutWaitIndefinitely); - EXPECT_EQ(kMachMessageDeadlineWaitIndefinitely, deadline_0); + EXPECT_EQ(deadline_0, kMachMessageDeadlineWaitIndefinitely); deadline_0 = MachMessageDeadlineFromTimeout(1); MachMessageDeadline deadline_1 = MachMessageDeadlineFromTimeout(100); - EXPECT_NE(kMachMessageDeadlineNonblocking, deadline_0); - EXPECT_NE(kMachMessageDeadlineWaitIndefinitely, deadline_0); - EXPECT_NE(kMachMessageDeadlineNonblocking, deadline_1); - EXPECT_NE(kMachMessageDeadlineWaitIndefinitely, deadline_1); + EXPECT_NE(deadline_0, kMachMessageDeadlineNonblocking); + EXPECT_NE(deadline_0, kMachMessageDeadlineWaitIndefinitely); + EXPECT_NE(deadline_1, kMachMessageDeadlineNonblocking); + EXPECT_NE(deadline_1, kMachMessageDeadlineWaitIndefinitely); EXPECT_GE(deadline_1, deadline_0); } @@ -63,34 +63,34 @@ TEST(MachMessage, PrepareMIGReplyFromRequest_SetMIGReplyError) { PrepareMIGReplyFromRequest(&request, &reply.Head); - EXPECT_EQ(implicit_cast( - MACH_MSGH_BITS(MACH_MSG_TYPE_MOVE_SEND_ONCE, 0)), - reply.Head.msgh_bits); - EXPECT_EQ(sizeof(reply), reply.Head.msgh_size); - EXPECT_EQ(request.msgh_remote_port, reply.Head.msgh_remote_port); - EXPECT_EQ(kMachPortNull, reply.Head.msgh_local_port); - EXPECT_EQ(0u, reply.Head.msgh_reserved); - EXPECT_EQ(1111, reply.Head.msgh_id); - EXPECT_EQ(NDR_record.mig_vers, reply.NDR.mig_vers); - EXPECT_EQ(NDR_record.if_vers, reply.NDR.if_vers); - EXPECT_EQ(NDR_record.reserved1, reply.NDR.reserved1); - EXPECT_EQ(NDR_record.mig_encoding, reply.NDR.mig_encoding); - EXPECT_EQ(NDR_record.int_rep, reply.NDR.int_rep); - EXPECT_EQ(NDR_record.char_rep, reply.NDR.char_rep); - EXPECT_EQ(NDR_record.float_rep, reply.NDR.float_rep); - EXPECT_EQ(NDR_record.reserved2, reply.NDR.reserved2); - EXPECT_EQ(MIG_TYPE_ERROR, reply.RetCode); + EXPECT_EQ(reply.Head.msgh_bits, + implicit_cast( + MACH_MSGH_BITS(MACH_MSG_TYPE_MOVE_SEND_ONCE, 0))); + EXPECT_EQ(reply.Head.msgh_size, sizeof(reply)); + EXPECT_EQ(reply.Head.msgh_remote_port, request.msgh_remote_port); + EXPECT_EQ(reply.Head.msgh_local_port, kMachPortNull); + EXPECT_EQ(reply.Head.msgh_reserved, 0u); + EXPECT_EQ(reply.Head.msgh_id, 1111); + EXPECT_EQ(reply.NDR.mig_vers, NDR_record.mig_vers); + EXPECT_EQ(reply.NDR.if_vers, NDR_record.if_vers); + EXPECT_EQ(reply.NDR.reserved1, NDR_record.reserved1); + EXPECT_EQ(reply.NDR.mig_encoding, NDR_record.mig_encoding); + EXPECT_EQ(reply.NDR.int_rep, NDR_record.int_rep); + EXPECT_EQ(reply.NDR.char_rep, NDR_record.char_rep); + EXPECT_EQ(reply.NDR.float_rep, NDR_record.float_rep); + EXPECT_EQ(reply.NDR.reserved2, NDR_record.reserved2); + EXPECT_EQ(reply.RetCode, MIG_TYPE_ERROR); SetMIGReplyError(&reply.Head, MIG_BAD_ID); - EXPECT_EQ(MIG_BAD_ID, reply.RetCode); + EXPECT_EQ(reply.RetCode, MIG_BAD_ID); } TEST(MachMessage, MachMessageTrailerFromHeader) { mach_msg_empty_t empty; empty.send.header.msgh_size = sizeof(mach_msg_empty_send_t); - EXPECT_EQ(&empty.rcv.trailer, - MachMessageTrailerFromHeader(&empty.rcv.header)); + EXPECT_EQ(MachMessageTrailerFromHeader(&empty.rcv.header), + &empty.rcv.trailer); struct TestSendMessage : public mach_msg_header_t { uint8_t data[126]; @@ -105,12 +105,12 @@ TEST(MachMessage, MachMessageTrailerFromHeader) { TestMessage test; test.send.msgh_size = sizeof(TestSendMessage); - EXPECT_EQ(&test.receive.trailer, MachMessageTrailerFromHeader(&test.receive)); + EXPECT_EQ(MachMessageTrailerFromHeader(&test.receive), &test.receive.trailer); } TEST(MachMessage, AuditPIDFromMachMessageTrailer) { base::mac::ScopedMachReceiveRight port(NewMachPort(MACH_PORT_RIGHT_RECEIVE)); - ASSERT_NE(kMachPortNull, port); + ASSERT_NE(port, kMachPortNull); mach_msg_empty_send_t send = {}; send.header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_MAKE_SEND_ONCE, 0); @@ -124,7 +124,7 @@ TEST(MachMessage, AuditPIDFromMachMessageTrailer) { kMachMessageDeadlineNonblocking, MACH_PORT_NULL, false); - ASSERT_EQ(MACH_MSG_SUCCESS, mr) + ASSERT_EQ(mr, MACH_MSG_SUCCESS) << MachErrorMessage(mr, "MachMessageWithDeadline send"); struct EmptyReceiveMessageWithAuditTrailer : public mach_msg_empty_send_t { @@ -142,15 +142,15 @@ TEST(MachMessage, AuditPIDFromMachMessageTrailer) { kMachMessageDeadlineNonblocking, MACH_PORT_NULL, false); - ASSERT_EQ(MACH_MSG_SUCCESS, mr) + ASSERT_EQ(mr, MACH_MSG_SUCCESS) << MachErrorMessage(mr, "MachMessageWithDeadline receive"); - EXPECT_EQ(getpid(), AuditPIDFromMachMessageTrailer(&receive.trailer)); + EXPECT_EQ(AuditPIDFromMachMessageTrailer(&receive.trailer), getpid()); } TEST(MachMessage, MachMessageDestroyReceivedPort) { mach_port_t port = NewMachPort(MACH_PORT_RIGHT_RECEIVE); - ASSERT_NE(kMachPortNull, port); + ASSERT_NE(port, kMachPortNull); EXPECT_TRUE(MachMessageDestroyReceivedPort(port, MACH_MSG_TYPE_PORT_RECEIVE)); base::mac::ScopedMachReceiveRight receive( @@ -161,11 +161,11 @@ TEST(MachMessage, MachMessageDestroyReceivedPort) { MACH_MSG_TYPE_MAKE_SEND, &port, &right_type); - ASSERT_EQ(KERN_SUCCESS, kr) + ASSERT_EQ(kr, KERN_SUCCESS) << MachErrorMessage(kr, "mach_port_extract_right"); - ASSERT_EQ(receive, port); - ASSERT_EQ(implicit_cast(MACH_MSG_TYPE_PORT_SEND), - right_type); + ASSERT_EQ(port, receive); + ASSERT_EQ(right_type, + implicit_cast(MACH_MSG_TYPE_PORT_SEND)); EXPECT_TRUE(MachMessageDestroyReceivedPort(port, MACH_MSG_TYPE_PORT_SEND)); kr = mach_port_extract_right(mach_task_self(), @@ -173,12 +173,12 @@ TEST(MachMessage, MachMessageDestroyReceivedPort) { MACH_MSG_TYPE_MAKE_SEND_ONCE, &port, &right_type); - ASSERT_EQ(KERN_SUCCESS, kr) + ASSERT_EQ(kr, KERN_SUCCESS) << MachErrorMessage(kr, "mach_port_extract_right"); - ASSERT_NE(kMachPortNull, port); - EXPECT_NE(receive, port); - ASSERT_EQ(implicit_cast(MACH_MSG_TYPE_PORT_SEND_ONCE), - right_type); + ASSERT_NE(port, kMachPortNull); + EXPECT_NE(port, receive); + ASSERT_EQ(right_type, + implicit_cast(MACH_MSG_TYPE_PORT_SEND_ONCE)); EXPECT_TRUE( MachMessageDestroyReceivedPort(port, MACH_MSG_TYPE_PORT_SEND_ONCE)); @@ -187,11 +187,11 @@ TEST(MachMessage, MachMessageDestroyReceivedPort) { MACH_MSG_TYPE_MAKE_SEND, &port, &right_type); - ASSERT_EQ(KERN_SUCCESS, kr) + ASSERT_EQ(kr, KERN_SUCCESS) << MachErrorMessage(kr, "mach_port_extract_right"); - ASSERT_EQ(receive, port); - ASSERT_EQ(implicit_cast(MACH_MSG_TYPE_PORT_SEND), - right_type); + ASSERT_EQ(port, receive); + ASSERT_EQ(right_type, + implicit_cast(MACH_MSG_TYPE_PORT_SEND)); EXPECT_TRUE(MachMessageDestroyReceivedPort(port, MACH_MSG_TYPE_PORT_RECEIVE)); ignore_result(receive.release()); EXPECT_TRUE(MachMessageDestroyReceivedPort(port, MACH_MSG_TYPE_PORT_SEND)); diff --git a/util/mach/notify_server_test.cc b/util/mach/notify_server_test.cc index b0ef4a35..b5e152db 100644 --- a/util/mach/notify_server_test.cc +++ b/util/mach/notify_server_test.cc @@ -50,7 +50,7 @@ mach_port_t SendRightFromReceiveRight(mach_port_t receive_right) { kern_return_t kr = mach_port_insert_right( mach_task_self(), receive_right, receive_right, MACH_MSG_TYPE_MAKE_SEND); if (kr != KERN_SUCCESS) { - EXPECT_EQ(KERN_SUCCESS, kr) + EXPECT_EQ(kr, KERN_SUCCESS) << MachErrorMessage(kr, "mach_port_insert_right"); return MACH_PORT_NULL; } @@ -73,13 +73,13 @@ mach_port_t SendOnceRightFromReceiveRight(mach_port_t receive_right) { &send_once_right, &acquired_type); if (kr != KERN_SUCCESS) { - EXPECT_EQ(KERN_SUCCESS, kr) + EXPECT_EQ(kr, KERN_SUCCESS) << MachErrorMessage(kr, "mach_port_extract_right"); return MACH_PORT_NULL; } - EXPECT_EQ(implicit_cast(MACH_MSG_TYPE_PORT_SEND_ONCE), - acquired_type); + EXPECT_EQ(acquired_type, + implicit_cast(MACH_MSG_TYPE_PORT_SEND_ONCE)); return send_once_right; } @@ -93,7 +93,7 @@ mach_port_t SendOnceRightFromReceiveRight(mach_port_t receive_right) { //! On failure, a gtest failure will be added. void MachPortDeallocate(mach_port_t port) { kern_return_t kr = mach_port_deallocate(mach_task_self(), port); - EXPECT_EQ(KERN_SUCCESS, kr) << MachErrorMessage(kr, "mach_port_deallocate"); + EXPECT_EQ(kr, KERN_SUCCESS) << MachErrorMessage(kr, "mach_port_deallocate"); } //! \brief Determines whether a specific right is held for a Mach port. @@ -107,7 +107,7 @@ bool IsRight(mach_port_t port, mach_port_type_t right) { mach_port_type_t type; kern_return_t kr = mach_port_type(mach_task_self(), port, &type); if (kr != KERN_SUCCESS) { - EXPECT_EQ(KERN_SUCCESS, kr) << MachErrorMessage(kr, "mach_port_type"); + EXPECT_EQ(kr, KERN_SUCCESS) << MachErrorMessage(kr, "mach_port_type"); return false; } @@ -138,7 +138,7 @@ mach_port_urefs_t RightRefCount(mach_port_t port, mach_port_right_t right) { mach_port_urefs_t refs; kern_return_t kr = mach_port_get_refs(mach_task_self(), port, right, &refs); if (kr != KERN_SUCCESS) { - EXPECT_EQ(KERN_SUCCESS, kr) << MachErrorMessage(kr, "mach_port_get_refs"); + EXPECT_EQ(kr, KERN_SUCCESS) << MachErrorMessage(kr, "mach_port_get_refs"); return -1; } @@ -215,13 +215,13 @@ class NotifyServerTestBase : public testing::Test, MACH_MSG_TYPE_MAKE_SEND_ONCE, &previous); if (kr != KERN_SUCCESS) { - EXPECT_EQ(KERN_SUCCESS, kr) + EXPECT_EQ(kr, KERN_SUCCESS) << MachErrorMessage(kr, "mach_port_request_notification"); return false; } base::mac::ScopedMachSendRight previous_owner(previous); - EXPECT_EQ(kMachPortNull, previous); + EXPECT_EQ(previous, kMachPortNull); return true; } @@ -245,7 +245,7 @@ class NotifyServerTestBase : public testing::Test, MachMessageServer::kPersistent, MachMessageServer::kReceiveLargeError, kMachMessageTimeoutNonblocking); - ASSERT_EQ(MACH_RCV_TIMED_OUT, mr) + ASSERT_EQ(mr, MACH_RCV_TIMED_OUT) << MachErrorMessage(mr, "MachMessageServer::Run"); } @@ -288,17 +288,17 @@ TEST_F(NotifyServerTest, Basic) { expect_request_ids.insert(MACH_NOTIFY_NO_SENDERS); expect_request_ids.insert(MACH_NOTIFY_SEND_ONCE); expect_request_ids.insert(MACH_NOTIFY_DEAD_NAME); - EXPECT_EQ(expect_request_ids, server.MachMessageServerRequestIDs()); + EXPECT_EQ(server.MachMessageServerRequestIDs(), expect_request_ids); // The port-destroyed notification is the largest request message in the // subsystem. defines the same structure, but with a basic // trailer, so use offsetof to get the size of the basic structure without any // trailer. - EXPECT_EQ(offsetof(mach_port_destroyed_notification_t, trailer), - server.MachMessageServerRequestSize()); + EXPECT_EQ(server.MachMessageServerRequestSize(), + offsetof(mach_port_destroyed_notification_t, trailer)); mig_reply_error_t reply; - EXPECT_EQ(sizeof(reply), server.MachMessageServerReplySize()); + EXPECT_EQ(server.MachMessageServerReplySize(), sizeof(reply)); } // When no notifications are requested, nothing should happen. @@ -437,8 +437,8 @@ TEST_F(NotifyServerTest, MachNotifyNoSenders_NoNotification) { RunServer(); - EXPECT_EQ(1u, RightRefCount(receive_right.get(), MACH_PORT_RIGHT_RECEIVE)); - EXPECT_EQ(1u, RightRefCount(receive_right.get(), MACH_PORT_RIGHT_SEND)); + EXPECT_EQ(RightRefCount(receive_right.get(), MACH_PORT_RIGHT_RECEIVE), 1u); + EXPECT_EQ(RightRefCount(receive_right.get(), MACH_PORT_RIGHT_SEND), 1u); } // When a send-once right is deallocated without being used, a send-once @@ -480,7 +480,7 @@ TEST_F(NotifyServerTest, MachNotifySendOnce_ImplicitDeallocation) { MACH_PORT_NULL, 0, MACH_PORT_NULL); - ASSERT_EQ(MACH_MSG_SUCCESS, mr) << MachErrorMessage(mr, "mach_msg"); + ASSERT_EQ(mr, MACH_MSG_SUCCESS) << MachErrorMessage(mr, "mach_msg"); EXPECT_CALL(*this, DoMachNotifySendOnce(ServerPort(), @@ -527,9 +527,9 @@ TEST_F(NotifyServerTest, MachNotifyDeadName) { EXPECT_TRUE(IsRight(send_once_right.get(), MACH_PORT_TYPE_DEAD_NAME)); - EXPECT_EQ(0u, - RightRefCount(send_once_right.get(), MACH_PORT_RIGHT_SEND_ONCE)); - EXPECT_EQ(1u, DeadNameRightRefCount(send_once_right.get())); + EXPECT_EQ(RightRefCount(send_once_right.get(), MACH_PORT_RIGHT_SEND_ONCE), + 0u); + EXPECT_EQ(DeadNameRightRefCount(send_once_right.get()), 1u); } // When the receive right corresponding to a send-once right with a dead-name @@ -551,9 +551,9 @@ TEST_F(NotifyServerTest, MachNotifyDeadName_NoNotification) { EXPECT_FALSE(IsRight(send_once_right.get(), MACH_PORT_TYPE_DEAD_NAME)); - EXPECT_EQ(1u, - RightRefCount(send_once_right.get(), MACH_PORT_RIGHT_SEND_ONCE)); - EXPECT_EQ(0u, DeadNameRightRefCount(send_once_right.get())); + EXPECT_EQ(RightRefCount(send_once_right.get(), MACH_PORT_RIGHT_SEND_ONCE), + 1u); + EXPECT_EQ(DeadNameRightRefCount(send_once_right.get()), 0u); } } // namespace diff --git a/util/mach/scoped_task_suspend_test.cc b/util/mach/scoped_task_suspend_test.cc index b53b83dc..b23e6124 100644 --- a/util/mach/scoped_task_suspend_test.cc +++ b/util/mach/scoped_task_suspend_test.cc @@ -52,21 +52,21 @@ class ScopedTaskSuspendTest final : public MachMultiprocess { void MachMultiprocessParent() override { task_t child_task = ChildTask(); - EXPECT_EQ(0, SuspendCount(child_task)); + EXPECT_EQ(SuspendCount(child_task), 0); { ScopedTaskSuspend suspend(child_task); - EXPECT_EQ(1, SuspendCount(child_task)); + EXPECT_EQ(SuspendCount(child_task), 1); { ScopedTaskSuspend suspend_again(child_task); - EXPECT_EQ(2, SuspendCount(child_task)); + EXPECT_EQ(SuspendCount(child_task), 2); } - EXPECT_EQ(1, SuspendCount(child_task)); + EXPECT_EQ(SuspendCount(child_task), 1); } - EXPECT_EQ(0, SuspendCount(child_task)); + EXPECT_EQ(SuspendCount(child_task), 0); } void MachMultiprocessChild() override { diff --git a/util/mach/symbolic_constants_mach_test.cc b/util/mach/symbolic_constants_mach_test.cc index feb409bf..f3086d25 100644 --- a/util/mach/symbolic_constants_mach_test.cc +++ b/util/mach/symbolic_constants_mach_test.cc @@ -68,9 +68,9 @@ void TestSomethingToStringOnce(typename Traits::ValueType value, << ", actual " << actual; actual.assign(expect); } else { - EXPECT_EQ(expect, actual) << Traits::kValueName << " " << value; + EXPECT_EQ(actual, expect) << Traits::kValueName << " " << value; } - EXPECT_EQ(actual, actual_numeric) << Traits::kValueName << " " << value; + EXPECT_EQ(actual_numeric, actual) << Traits::kValueName << " " << value; } else { EXPECT_TRUE(actual.empty()) << Traits::kValueName << " " << value << ", actual " << actual; @@ -108,7 +108,7 @@ void TestStringToSomething(const base::StringPiece& string, << ", " << Traits::kValueName << " " << expect_value; if (actual_result) { - EXPECT_EQ(expect_value, actual_value) << "string " << string + EXPECT_EQ(actual_value, expect_value) << "string " << string << ", options " << options; } } else { @@ -346,18 +346,18 @@ TEST(SymbolicConstantsMach, ExceptionMaskToString) { kUseFullName).empty()); EXPECT_TRUE(ExceptionMaskToString(EXC_MASK_CRASH | EXC_MASK_GUARD, kUseShortName).empty()); - EXPECT_EQ("0x1400", - ExceptionMaskToString(EXC_MASK_CRASH | EXC_MASK_GUARD, - kUseFullName | kUnknownIsNumeric)); - EXPECT_EQ("0x1400", - ExceptionMaskToString(EXC_MASK_CRASH | EXC_MASK_GUARD, - kUseShortName | kUnknownIsNumeric)); - EXPECT_EQ("EXC_MASK_CRASH|EXC_MASK_GUARD", - ExceptionMaskToString(EXC_MASK_CRASH | EXC_MASK_GUARD, - kUseFullName | kUseOr)); - EXPECT_EQ("CRASH|GUARD", - ExceptionMaskToString(EXC_MASK_CRASH | EXC_MASK_GUARD, - kUseShortName | kUseOr)); + EXPECT_EQ(ExceptionMaskToString(EXC_MASK_CRASH | EXC_MASK_GUARD, + kUseFullName | kUnknownIsNumeric), + "0x1400"); + EXPECT_EQ(ExceptionMaskToString(EXC_MASK_CRASH | EXC_MASK_GUARD, + kUseShortName | kUnknownIsNumeric), + "0x1400"); + EXPECT_EQ(ExceptionMaskToString(EXC_MASK_CRASH | EXC_MASK_GUARD, + kUseFullName | kUseOr), + "EXC_MASK_CRASH|EXC_MASK_GUARD"); + EXPECT_EQ(ExceptionMaskToString(EXC_MASK_CRASH | EXC_MASK_GUARD, + kUseShortName | kUseOr), + "CRASH|GUARD"); } void TestStringToExceptionMask(const base::StringPiece& string, diff --git a/util/mach/task_memory_test.cc b/util/mach/task_memory_test.cc index 005288dd..4360d680 100644 --- a/util/mach/task_memory_test.cc +++ b/util/mach/task_memory_test.cc @@ -35,7 +35,7 @@ TEST(TaskMemory, ReadSelf) { const vm_size_t kSize = 4 * PAGE_SIZE; kern_return_t kr = vm_allocate(mach_task_self(), &address, kSize, VM_FLAGS_ANYWHERE); - ASSERT_EQ(KERN_SUCCESS, kr) << MachErrorMessage(kr, "vm_allocate"); + ASSERT_EQ(kr, KERN_SUCCESS) << MachErrorMessage(kr, "vm_allocate"); base::mac::ScopedMachVM vm_owner(address, mach_vm_round_page(kSize)); char* region = reinterpret_cast(address); @@ -51,51 +51,51 @@ TEST(TaskMemory, ReadSelf) { // Ensure that the entire region can be read. ASSERT_TRUE(memory.Read(address, kSize, &result[0])); - EXPECT_EQ(0, memcmp(region, &result[0], kSize)); + EXPECT_EQ(memcmp(region, &result[0], kSize), 0); ASSERT_TRUE((mapped = memory.ReadMapped(address, kSize))); - EXPECT_EQ(0, memcmp(region, mapped->data(), kSize)); + EXPECT_EQ(memcmp(region, mapped->data(), kSize), 0); // Ensure that a read of length 0 succeeds and doesn’t touch the result. result.assign(kSize, '\0'); std::string zeroes = result; ASSERT_TRUE(memory.Read(address, 0, &result[0])); - EXPECT_EQ(zeroes, result); + EXPECT_EQ(result, zeroes); ASSERT_TRUE((mapped = memory.ReadMapped(address, 0))); // Ensure that a read starting at an unaligned address works. ASSERT_TRUE(memory.Read(address + 1, kSize - 1, &result[0])); - EXPECT_EQ(0, memcmp(region + 1, &result[0], kSize - 1)); + EXPECT_EQ(memcmp(region + 1, &result[0], kSize - 1), 0); ASSERT_TRUE((mapped = memory.ReadMapped(address + 1, kSize - 1))); - EXPECT_EQ(0, memcmp(region + 1, mapped->data(), kSize - 1)); + EXPECT_EQ(memcmp(region + 1, mapped->data(), kSize - 1), 0); // Ensure that a read ending at an unaligned address works. ASSERT_TRUE(memory.Read(address, kSize - 1, &result[0])); - EXPECT_EQ(0, memcmp(region, &result[0], kSize - 1)); + EXPECT_EQ(memcmp(region, &result[0], kSize - 1), 0); ASSERT_TRUE((mapped = memory.ReadMapped(address, kSize - 1))); - EXPECT_EQ(0, memcmp(region, mapped->data(), kSize - 1)); + EXPECT_EQ(memcmp(region, mapped->data(), kSize - 1), 0); // Ensure that a read starting and ending at unaligned addresses works. ASSERT_TRUE(memory.Read(address + 1, kSize - 2, &result[0])); - EXPECT_EQ(0, memcmp(region + 1, &result[0], kSize - 2)); + EXPECT_EQ(memcmp(region + 1, &result[0], kSize - 2), 0); ASSERT_TRUE((mapped = memory.ReadMapped(address + 1, kSize - 2))); - EXPECT_EQ(0, memcmp(region + 1, mapped->data(), kSize - 2)); + EXPECT_EQ(memcmp(region + 1, mapped->data(), kSize - 2), 0); // Ensure that a read of exactly one page works. ASSERT_TRUE(memory.Read(address + PAGE_SIZE, PAGE_SIZE, &result[0])); - EXPECT_EQ(0, memcmp(region + PAGE_SIZE, &result[0], PAGE_SIZE)); + EXPECT_EQ(memcmp(region + PAGE_SIZE, &result[0], PAGE_SIZE), 0); ASSERT_TRUE((mapped = memory.ReadMapped(address + PAGE_SIZE, PAGE_SIZE))); - EXPECT_EQ(0, memcmp(region + PAGE_SIZE, mapped->data(), PAGE_SIZE)); + EXPECT_EQ(memcmp(region + PAGE_SIZE, mapped->data(), PAGE_SIZE), 0); // Ensure that a read of a single byte works. ASSERT_TRUE(memory.Read(address + 2, 1, &result[0])); - EXPECT_EQ(region[2], result[0]); + EXPECT_EQ(result[0], region[2]); ASSERT_TRUE((mapped = memory.ReadMapped(address + 2, 1))); - EXPECT_EQ(region[2], reinterpret_cast(mapped->data())[0]); + EXPECT_EQ(reinterpret_cast(mapped->data())[0], region[2]); // Ensure that a read of length zero works and doesn’t touch the data. result[0] = 'M'; ASSERT_TRUE(memory.Read(address + 3, 0, &result[0])); - EXPECT_EQ('M', result[0]); + EXPECT_EQ(result[0], 'M'); ASSERT_TRUE((mapped = memory.ReadMapped(address + 3, 0))); } @@ -104,7 +104,7 @@ TEST(TaskMemory, ReadSelfUnmapped) { const vm_size_t kSize = 2 * PAGE_SIZE; kern_return_t kr = vm_allocate(mach_task_self(), &address, kSize, VM_FLAGS_ANYWHERE); - ASSERT_EQ(KERN_SUCCESS, kr) << MachErrorMessage(kr, "vm_allocate"); + ASSERT_EQ(kr, KERN_SUCCESS) << MachErrorMessage(kr, "vm_allocate"); base::mac::ScopedMachVM vm_owner(address, mach_vm_round_page(kSize)); char* region = reinterpret_cast(address); @@ -116,7 +116,7 @@ TEST(TaskMemory, ReadSelfUnmapped) { kr = vm_protect( mach_task_self(), address + PAGE_SIZE, PAGE_SIZE, FALSE, VM_PROT_NONE); - ASSERT_EQ(KERN_SUCCESS, kr) << MachErrorMessage(kr, "vm_protect"); + ASSERT_EQ(kr, KERN_SUCCESS) << MachErrorMessage(kr, "vm_protect"); TaskMemory memory(mach_task_self()); std::string result(kSize, '\0'); @@ -141,7 +141,7 @@ TEST(TaskMemory, ReadSelfUnmapped) { // portion of the test may be flaky in the presence of other threads, if // another thread maps something in the region that is deallocated here. kr = vm_deallocate(mach_task_self(), address + PAGE_SIZE, PAGE_SIZE); - ASSERT_EQ(KERN_SUCCESS, kr) << MachErrorMessage(kr, "vm_deallocate"); + ASSERT_EQ(kr, KERN_SUCCESS) << MachErrorMessage(kr, "vm_deallocate"); vm_owner.reset(address, PAGE_SIZE); EXPECT_FALSE(memory.Read(address, kSize, &result[0])); @@ -176,27 +176,27 @@ TEST(TaskMemory, ReadCStringSelf) { const char kConstCharEmpty[] = ""; ASSERT_TRUE(ReadCStringSelf(&memory, kConstCharEmpty, &result)); EXPECT_TRUE(result.empty()); - EXPECT_EQ(kConstCharEmpty, result); + EXPECT_EQ(result, kConstCharEmpty); const char kConstCharShort[] = "A short const char[]"; ASSERT_TRUE(ReadCStringSelf(&memory, kConstCharShort, &result)); EXPECT_FALSE(result.empty()); - EXPECT_EQ(kConstCharShort, result); + EXPECT_EQ(result, kConstCharShort); static const char kStaticConstCharEmpty[] = ""; ASSERT_TRUE(ReadCStringSelf(&memory, kStaticConstCharEmpty, &result)); EXPECT_TRUE(result.empty()); - EXPECT_EQ(kStaticConstCharEmpty, result); + EXPECT_EQ(result, kStaticConstCharEmpty); static const char kStaticConstCharShort[] = "A short static const char[]"; ASSERT_TRUE(ReadCStringSelf(&memory, kStaticConstCharShort, &result)); EXPECT_FALSE(result.empty()); - EXPECT_EQ(kStaticConstCharShort, result); + EXPECT_EQ(result, kStaticConstCharShort); std::string string_short("A short std::string in a function"); ASSERT_TRUE(ReadCStringSelf(&memory, &string_short[0], &result)); EXPECT_FALSE(result.empty()); - EXPECT_EQ(string_short, result); + EXPECT_EQ(result, string_short); std::string string_long; const size_t kStringLongSize = 4 * PAGE_SIZE; @@ -205,11 +205,11 @@ TEST(TaskMemory, ReadCStringSelf) { // a NUL. string_long.append(1, (index % 255) + 1); } - ASSERT_EQ(kStringLongSize, string_long.size()); + ASSERT_EQ(string_long.size(), kStringLongSize); ASSERT_TRUE(ReadCStringSelf(&memory, &string_long[0], &result)); EXPECT_FALSE(result.empty()); - EXPECT_EQ(kStringLongSize, result.size()); - EXPECT_EQ(string_long, result); + EXPECT_EQ(result.size(), kStringLongSize); + EXPECT_EQ(result, string_long); } TEST(TaskMemory, ReadCStringSelfUnmapped) { @@ -217,7 +217,7 @@ TEST(TaskMemory, ReadCStringSelfUnmapped) { const vm_size_t kSize = 2 * PAGE_SIZE; kern_return_t kr = vm_allocate(mach_task_self(), &address, kSize, VM_FLAGS_ANYWHERE); - ASSERT_EQ(KERN_SUCCESS, kr) << MachErrorMessage(kr, "vm_allocate"); + ASSERT_EQ(kr, KERN_SUCCESS) << MachErrorMessage(kr, "vm_allocate"); base::mac::ScopedMachVM vm_owner(address, mach_vm_round_page(kSize)); char* region = reinterpret_cast(address); @@ -229,7 +229,7 @@ TEST(TaskMemory, ReadCStringSelfUnmapped) { kr = vm_protect( mach_task_self(), address + PAGE_SIZE, PAGE_SIZE, FALSE, VM_PROT_NONE); - ASSERT_EQ(KERN_SUCCESS, kr) << MachErrorMessage(kr, "vm_protect"); + ASSERT_EQ(kr, KERN_SUCCESS) << MachErrorMessage(kr, "vm_protect"); TaskMemory memory(mach_task_self()); std::string result; @@ -241,15 +241,15 @@ TEST(TaskMemory, ReadCStringSelfUnmapped) { std::swap(region[PAGE_SIZE - 1], terminator_or_not); ASSERT_TRUE(memory.ReadCString(address, &result)); EXPECT_FALSE(result.empty()); - EXPECT_EQ(PAGE_SIZE - 1u, result.size()); - EXPECT_EQ(region, result); + EXPECT_EQ(result.size(), PAGE_SIZE - 1u); + EXPECT_EQ(result, region); // Repeat the test with an unmapped page instead of an unreadable one. This // portion of the test may be flaky in the presence of other threads, if // another thread maps something in the region that is deallocated here. std::swap(region[PAGE_SIZE - 1], terminator_or_not); kr = vm_deallocate(mach_task_self(), address + PAGE_SIZE, PAGE_SIZE); - ASSERT_EQ(KERN_SUCCESS, kr) << MachErrorMessage(kr, "vm_deallocate"); + ASSERT_EQ(kr, KERN_SUCCESS) << MachErrorMessage(kr, "vm_deallocate"); vm_owner.reset(address, PAGE_SIZE); EXPECT_FALSE(memory.ReadCString(address, &result)); @@ -261,8 +261,8 @@ TEST(TaskMemory, ReadCStringSelfUnmapped) { std::swap(region[PAGE_SIZE - 1], terminator_or_not); ASSERT_TRUE(memory.ReadCString(address, &result)); EXPECT_FALSE(result.empty()); - EXPECT_EQ(PAGE_SIZE - 1u, result.size()); - EXPECT_EQ(region, result); + EXPECT_EQ(result.size(), PAGE_SIZE - 1u); + EXPECT_EQ(result, region); } // This function consolidates the cast from a char* to mach_vm_address_t in one @@ -283,18 +283,18 @@ TEST(TaskMemory, ReadCStringSizeLimited_ConstCharEmpty) { ASSERT_TRUE(ReadCStringSizeLimitedSelf( &memory, kConstCharEmpty, arraysize(kConstCharEmpty), &result)); EXPECT_TRUE(result.empty()); - EXPECT_EQ(kConstCharEmpty, result); + EXPECT_EQ(result, kConstCharEmpty); result.clear(); ASSERT_TRUE(ReadCStringSizeLimitedSelf( &memory, kConstCharEmpty, arraysize(kConstCharEmpty) + 1, &result)); EXPECT_TRUE(result.empty()); - EXPECT_EQ(kConstCharEmpty, result); + EXPECT_EQ(result, kConstCharEmpty); result.clear(); ASSERT_TRUE(ReadCStringSizeLimitedSelf(&memory, kConstCharEmpty, 0, &result)); EXPECT_TRUE(result.empty()); - EXPECT_EQ(kConstCharEmpty, result); + EXPECT_EQ(result, kConstCharEmpty); } TEST(TaskMemory, ReadCStringSizeLimited_ConstCharShort) { @@ -305,13 +305,13 @@ TEST(TaskMemory, ReadCStringSizeLimited_ConstCharShort) { ASSERT_TRUE(ReadCStringSizeLimitedSelf( &memory, kConstCharShort, arraysize(kConstCharShort), &result)); EXPECT_FALSE(result.empty()); - EXPECT_EQ(kConstCharShort, result); + EXPECT_EQ(result, kConstCharShort); result.clear(); ASSERT_TRUE(ReadCStringSizeLimitedSelf( &memory, kConstCharShort, arraysize(kConstCharShort) + 1, &result)); EXPECT_FALSE(result.empty()); - EXPECT_EQ(kConstCharShort, result); + EXPECT_EQ(result, kConstCharShort); ASSERT_FALSE(ReadCStringSizeLimitedSelf( &memory, kConstCharShort, arraysize(kConstCharShort) - 1, &result)); @@ -327,7 +327,7 @@ TEST(TaskMemory, ReadCStringSizeLimited_StaticConstCharEmpty) { arraysize(kStaticConstCharEmpty), &result)); EXPECT_TRUE(result.empty()); - EXPECT_EQ(kStaticConstCharEmpty, result); + EXPECT_EQ(result, kStaticConstCharEmpty); result.clear(); ASSERT_TRUE(ReadCStringSizeLimitedSelf(&memory, @@ -335,13 +335,13 @@ TEST(TaskMemory, ReadCStringSizeLimited_StaticConstCharEmpty) { arraysize(kStaticConstCharEmpty) + 1, &result)); EXPECT_TRUE(result.empty()); - EXPECT_EQ(kStaticConstCharEmpty, result); + EXPECT_EQ(result, kStaticConstCharEmpty); result.clear(); ASSERT_TRUE( ReadCStringSizeLimitedSelf(&memory, kStaticConstCharEmpty, 0, &result)); EXPECT_TRUE(result.empty()); - EXPECT_EQ(kStaticConstCharEmpty, result); + EXPECT_EQ(result, kStaticConstCharEmpty); } TEST(TaskMemory, ReadCStringSizeLimited_StaticConstCharShort) { @@ -354,7 +354,7 @@ TEST(TaskMemory, ReadCStringSizeLimited_StaticConstCharShort) { arraysize(kStaticConstCharShort), &result)); EXPECT_FALSE(result.empty()); - EXPECT_EQ(kStaticConstCharShort, result); + EXPECT_EQ(result, kStaticConstCharShort); result.clear(); ASSERT_TRUE(ReadCStringSizeLimitedSelf(&memory, @@ -362,7 +362,7 @@ TEST(TaskMemory, ReadCStringSizeLimited_StaticConstCharShort) { arraysize(kStaticConstCharShort) + 1, &result)); EXPECT_FALSE(result.empty()); - EXPECT_EQ(kStaticConstCharShort, result); + EXPECT_EQ(result, kStaticConstCharShort); ASSERT_FALSE(ReadCStringSizeLimitedSelf(&memory, kStaticConstCharShort, @@ -378,13 +378,13 @@ TEST(TaskMemory, ReadCStringSizeLimited_StringShort) { ASSERT_TRUE(ReadCStringSizeLimitedSelf( &memory, &string_short[0], string_short.size() + 1, &result)); EXPECT_FALSE(result.empty()); - EXPECT_EQ(string_short, result); + EXPECT_EQ(result, string_short); result.clear(); ASSERT_TRUE(ReadCStringSizeLimitedSelf( &memory, &string_short[0], string_short.size() + 2, &result)); EXPECT_FALSE(result.empty()); - EXPECT_EQ(string_short, result); + EXPECT_EQ(result, string_short); ASSERT_FALSE(ReadCStringSizeLimitedSelf( &memory, &string_short[0], string_short.size(), &result)); @@ -401,19 +401,19 @@ TEST(TaskMemory, ReadCStringSizeLimited_StringLong) { // a NUL. string_long.append(1, (index % 255) + 1); } - ASSERT_EQ(kStringLongSize, string_long.size()); + ASSERT_EQ(string_long.size(), kStringLongSize); ASSERT_TRUE(ReadCStringSizeLimitedSelf( &memory, &string_long[0], string_long.size() + 1, &result)); EXPECT_FALSE(result.empty()); - EXPECT_EQ(kStringLongSize, result.size()); - EXPECT_EQ(string_long, result); + EXPECT_EQ(result.size(), kStringLongSize); + EXPECT_EQ(result, string_long); result.clear(); ASSERT_TRUE(ReadCStringSizeLimitedSelf( &memory, &string_long[0], string_long.size() + 2, &result)); EXPECT_FALSE(result.empty()); - EXPECT_EQ(kStringLongSize, result.size()); - EXPECT_EQ(string_long, result); + EXPECT_EQ(result.size(), kStringLongSize); + EXPECT_EQ(result, string_long); ASSERT_FALSE(ReadCStringSizeLimitedSelf( &memory, &string_long[0], string_long.size(), &result)); @@ -464,7 +464,7 @@ TEST(TaskMemory, MappedMemoryDeallocates) { mach_vm_address_t test_address = reinterpret_cast(&kTestBuffer); ASSERT_TRUE((mapped = memory.ReadMapped(test_address, sizeof(kTestBuffer)))); - EXPECT_EQ(0, memcmp(kTestBuffer, mapped->data(), sizeof(kTestBuffer))); + EXPECT_EQ(memcmp(kTestBuffer, mapped->data(), sizeof(kTestBuffer)), 0); vm_address_t mapped_address = reinterpret_cast(mapped->data()); EXPECT_TRUE(IsAddressMapped(mapped_address)); @@ -504,19 +504,19 @@ TEST(TaskMemory, MappedMemoryReadCString) { std::string string; ASSERT_TRUE(mapped->ReadCString(0, &string)); - EXPECT_EQ("0", string); + EXPECT_EQ(string, "0"); ASSERT_TRUE(mapped->ReadCString(1, &string)); - EXPECT_EQ("", string); + EXPECT_EQ(string, ""); ASSERT_TRUE(mapped->ReadCString(2, &string)); - EXPECT_EQ("2", string); + EXPECT_EQ(string, "2"); ASSERT_TRUE(mapped->ReadCString(3, &string)); - EXPECT_EQ("", string); + EXPECT_EQ(string, ""); ASSERT_TRUE(mapped->ReadCString(4, &string)); - EXPECT_EQ("45", string); + EXPECT_EQ(string, "45"); ASSERT_TRUE(mapped->ReadCString(5, &string)); - EXPECT_EQ("5", string); + EXPECT_EQ(string, "5"); ASSERT_TRUE(mapped->ReadCString(6, &string)); - EXPECT_EQ("", string); + EXPECT_EQ(string, ""); // kTestBuffer’s NUL terminator was not read, so these will see an // unterminated string and fail. @@ -533,17 +533,17 @@ TEST(TaskMemory, MappedMemoryReadCString) { ASSERT_TRUE((mapped = memory.ReadMapped(kTestAddress, 11))); ASSERT_TRUE(mapped->ReadCString(6, &string)); - EXPECT_EQ("", string); + EXPECT_EQ(string, ""); // These should now succeed. ASSERT_TRUE(mapped->ReadCString(7, &string)); - EXPECT_EQ("789", string); + EXPECT_EQ(string, "789"); ASSERT_TRUE(mapped->ReadCString(8, &string)); - EXPECT_EQ("89", string); + EXPECT_EQ(string, "89"); ASSERT_TRUE(mapped->ReadCString(9, &string)); - EXPECT_EQ("9", string); + EXPECT_EQ(string, "9"); EXPECT_TRUE(mapped->ReadCString(10, &string)); - EXPECT_EQ("", string); + EXPECT_EQ(string, ""); // These are still out of range. EXPECT_FALSE(mapped->ReadCString(11, &string)); diff --git a/util/misc/paths.h b/util/misc/paths.h new file mode 100644 index 00000000..30bbec50 --- /dev/null +++ b/util/misc/paths.h @@ -0,0 +1,40 @@ +// Copyright 2017 The Crashpad Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef CRASHPAD_UTIL_PATHS_H_ +#define CRASHPAD_UTIL_PATHS_H_ + +#include "base/files/file_path.h" +#include "base/macros.h" + +namespace crashpad { + +//! \brief Functions to obtain paths. +class Paths { + public: + //! \brief Obtains the pathname of the currently-running executable. + //! + //! \param[out] path The pathname of the currently-running executable. + //! + //! \return `true` on success. `false` on failure, with a message logged. + //! + //! \note In test code, use test::TestPaths::Executable() instead. + static bool Executable(base::FilePath* path); + + DISALLOW_IMPLICIT_CONSTRUCTORS(Paths); +}; + +} // namespace crashpad + +#endif // CRASHPAD_UTIL_TEST_PATHS_H_ diff --git a/test/paths_linux.cc b/util/misc/paths_linux.cc similarity index 78% rename from test/paths_linux.cc rename to util/misc/paths_linux.cc index 6e6da0e0..569944bc 100644 --- a/test/paths_linux.cc +++ b/util/misc/paths_linux.cc @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -#include "test/paths.h" +#include "util/misc/paths.h" #include #include @@ -21,42 +21,41 @@ #include #include "base/logging.h" -#include "util/misc/implicit_cast.h" namespace crashpad { -namespace test { // static -base::FilePath Paths::Executable() { +bool Paths::Executable(base::FilePath* path) { // Linux does not provide a straightforward way to size the buffer before // calling readlink(). Normally, the st_size field returned by lstat() could // be used, but this is usually zero for things in /proc. // // The /proc filesystem does not provide any way to read “exe” links for - // pathnames longer than a page. See linux-4.4.27/fs/proc/base.c + // pathnames longer than a page. See linux-4.9.20/fs/proc/base.c // do_proc_readlink(), which allocates a single page to receive the path // string. Coincidentally, the page size and PATH_MAX are normally the same // value, although neither is strictly a limit on the length of a pathname. // // On Android, the smaller of the page size and PATH_MAX actually does serve // as an effective limit on the length of an executable’s pathname. See - // Android 7.0.0 bionic/linker/linker.cpp get_executable_path(), which aborts + // Android 7.1.1 bionic/linker/linker.cpp get_executable_path(), which aborts // via __libc_fatal() if the “exe” link can’t be read into a PATH_MAX-sized // buffer. - std::string exe_path(std::max(implicit_cast(sysconf(_SC_PAGESIZE)), - implicit_cast(PATH_MAX)), + std::string exe_path(std::max(getpagesize(), PATH_MAX), std::string::value_type()); ssize_t exe_path_len = readlink("/proc/self/exe", &exe_path[0], exe_path.size()); if (exe_path_len < 0) { - PLOG(FATAL) << "readlink"; + PLOG(ERROR) << "readlink"; + return false; } else if (static_cast(exe_path_len) >= exe_path.size()) { - LOG(FATAL) << "readlink"; + LOG(ERROR) << "readlink"; + return false; } exe_path.resize(exe_path_len); - return base::FilePath(exe_path); + *path = base::FilePath(exe_path); + return true; } -} // namespace test } // namespace crashpad diff --git a/test/paths_mac.cc b/util/misc/paths_mac.cc similarity index 76% rename from test/paths_mac.cc rename to util/misc/paths_mac.cc index d16049e8..036f84b5 100644 --- a/test/paths_mac.cc +++ b/util/misc/paths_mac.cc @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -#include "test/paths.h" +#include "util/misc/paths.h" #include #include @@ -20,20 +20,25 @@ #include "base/logging.h" namespace crashpad { -namespace test { // static -base::FilePath Paths::Executable() { +bool Paths::Executable(base::FilePath* path) { uint32_t executable_length = 0; _NSGetExecutablePath(nullptr, &executable_length); - CHECK_GT(executable_length, 1u); + if (executable_length <= 1) { + LOG(ERROR) << "_NSGetExecutablePath"; + return false; + } std::string executable_path(executable_length - 1, std::string::value_type()); int rv = _NSGetExecutablePath(&executable_path[0], &executable_length); - CHECK_EQ(rv, 0); + if (rv != 0) { + LOG(ERROR) << "_NSGetExecutablePath"; + return false; + } - return base::FilePath(executable_path); + *path = base::FilePath(executable_path); + return true; } -} // namespace test } // namespace crashpad diff --git a/util/misc/paths_test.cc b/util/misc/paths_test.cc new file mode 100644 index 00000000..1f373029 --- /dev/null +++ b/util/misc/paths_test.cc @@ -0,0 +1,39 @@ +// Copyright 2014 The Crashpad Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "util/misc/paths.h" + +#include "base/files/file_path.h" +#include "build/build_config.h" +#include "gtest/gtest.h" + +namespace crashpad { +namespace test { +namespace { + +TEST(Paths, Executable) { + base::FilePath executable_path; + ASSERT_TRUE(Paths::Executable(&executable_path)); + const base::FilePath executable_name(executable_path.BaseName()); +#if defined(OS_WIN) + EXPECT_EQ(executable_name.value(), + FILE_PATH_LITERAL("crashpad_util_test.exe")); +#else + EXPECT_EQ(executable_name.value(), "crashpad_util_test"); +#endif // OS_WIN +} + +} // namespace +} // namespace test +} // namespace crashpad diff --git a/test/paths_win.cc b/util/misc/paths_win.cc similarity index 72% rename from test/paths_win.cc rename to util/misc/paths_win.cc index 947acd5c..4c402fe9 100644 --- a/test/paths_win.cc +++ b/util/misc/paths_win.cc @@ -12,23 +12,29 @@ // See the License for the specific language governing permissions and // limitations under the License. -#include "test/paths.h" +#include "util/misc/paths.h" #include #include "base/logging.h" namespace crashpad { -namespace test { // static -base::FilePath Paths::Executable() { +bool Paths::Executable(base::FilePath* path) { wchar_t executable_path[_MAX_PATH]; unsigned int len = GetModuleFileName(nullptr, executable_path, arraysize(executable_path)); - PCHECK(len != 0 && len < arraysize(executable_path)) << "GetModuleFileName"; - return base::FilePath(executable_path); + if (len == 0) { + PLOG(ERROR) << "GetModuleFileName"; + return false; + } else if (len >= arraysize(executable_path)) { + LOG(ERROR) << "GetModuleFileName"; + return false; + } + + *path = base::FilePath(executable_path); + return true; } -} // namespace test } // namespace crashpad diff --git a/util/misc/random_string_test.cc b/util/misc/random_string_test.cc index bb05a2bd..b0866c06 100644 --- a/util/misc/random_string_test.cc +++ b/util/misc/random_string_test.cc @@ -33,13 +33,13 @@ TEST(RandomString, RandomString) { const std::string allowed_characters("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); size_t character_counts[26] = {}; - ASSERT_EQ(arraysize(character_counts), allowed_characters.size()); + ASSERT_EQ(allowed_characters.size(), arraysize(character_counts)); std::set strings; for (size_t i = 0; i < 256; ++i) { const std::string random_string = RandomString(); - EXPECT_EQ(16u, random_string.size()); + EXPECT_EQ(random_string.size(), 16u); // Make sure that the string is unique. It is possible, but extremely // unlikely, for there to be collisions. diff --git a/util/misc/uuid_test.cc b/util/misc/uuid_test.cc index f064c653..e550751b 100644 --- a/util/misc/uuid_test.cc +++ b/util/misc/uuid_test.cc @@ -32,18 +32,18 @@ namespace { TEST(UUID, UUID) { UUID uuid_zero; uuid_zero.InitializeToZero(); - EXPECT_EQ(0u, uuid_zero.data_1); - EXPECT_EQ(0u, uuid_zero.data_2); - EXPECT_EQ(0u, uuid_zero.data_3); - EXPECT_EQ(0u, uuid_zero.data_4[0]); - EXPECT_EQ(0u, uuid_zero.data_4[1]); - EXPECT_EQ(0u, uuid_zero.data_5[0]); - EXPECT_EQ(0u, uuid_zero.data_5[1]); - EXPECT_EQ(0u, uuid_zero.data_5[2]); - EXPECT_EQ(0u, uuid_zero.data_5[3]); - EXPECT_EQ(0u, uuid_zero.data_5[4]); - EXPECT_EQ(0u, uuid_zero.data_5[5]); - EXPECT_EQ("00000000-0000-0000-0000-000000000000", uuid_zero.ToString()); + EXPECT_EQ(uuid_zero.data_1, 0u); + EXPECT_EQ(uuid_zero.data_2, 0u); + EXPECT_EQ(uuid_zero.data_3, 0u); + EXPECT_EQ(uuid_zero.data_4[0], 0u); + EXPECT_EQ(uuid_zero.data_4[1], 0u); + EXPECT_EQ(uuid_zero.data_5[0], 0u); + EXPECT_EQ(uuid_zero.data_5[1], 0u); + EXPECT_EQ(uuid_zero.data_5[2], 0u); + EXPECT_EQ(uuid_zero.data_5[3], 0u); + EXPECT_EQ(uuid_zero.data_5[4], 0u); + EXPECT_EQ(uuid_zero.data_5[5], 0u); + EXPECT_EQ(uuid_zero.ToString(), "00000000-0000-0000-0000-000000000000"); const uint8_t kBytes[16] = {0x00, 0x01, @@ -63,18 +63,18 @@ TEST(UUID, UUID) { 0x0f}; UUID uuid; uuid.InitializeFromBytes(kBytes); - EXPECT_EQ(0x00010203u, uuid.data_1); - EXPECT_EQ(0x0405u, uuid.data_2); - EXPECT_EQ(0x0607u, uuid.data_3); - EXPECT_EQ(0x08u, uuid.data_4[0]); - EXPECT_EQ(0x09u, uuid.data_4[1]); - EXPECT_EQ(0x0au, uuid.data_5[0]); - EXPECT_EQ(0x0bu, uuid.data_5[1]); - EXPECT_EQ(0x0cu, uuid.data_5[2]); - EXPECT_EQ(0x0du, uuid.data_5[3]); - EXPECT_EQ(0x0eu, uuid.data_5[4]); - EXPECT_EQ(0x0fu, uuid.data_5[5]); - EXPECT_EQ("00010203-0405-0607-0809-0a0b0c0d0e0f", uuid.ToString()); + EXPECT_EQ(uuid.data_1, 0x00010203u); + EXPECT_EQ(uuid.data_2, 0x0405u); + EXPECT_EQ(uuid.data_3, 0x0607u); + EXPECT_EQ(uuid.data_4[0], 0x08u); + EXPECT_EQ(uuid.data_4[1], 0x09u); + EXPECT_EQ(uuid.data_5[0], 0x0au); + EXPECT_EQ(uuid.data_5[1], 0x0bu); + EXPECT_EQ(uuid.data_5[2], 0x0cu); + EXPECT_EQ(uuid.data_5[3], 0x0du); + EXPECT_EQ(uuid.data_5[4], 0x0eu); + EXPECT_EQ(uuid.data_5[5], 0x0fu); + EXPECT_EQ(uuid.ToString(), "00010203-0405-0607-0809-0a0b0c0d0e0f"); // Test both operator== and operator!=. EXPECT_FALSE(uuid == uuid_zero); @@ -82,7 +82,7 @@ TEST(UUID, UUID) { UUID uuid_2; uuid_2.InitializeFromBytes(kBytes); - EXPECT_EQ(uuid, uuid_2); + EXPECT_EQ(uuid_2, uuid); EXPECT_FALSE(uuid != uuid_2); // Make sure that operator== and operator!= check the entire UUID. @@ -108,7 +108,7 @@ TEST(UUID, UUID) { // Make sure that the UUIDs are equal again, otherwise the test above may not // have been valid. - EXPECT_EQ(uuid, uuid_2); + EXPECT_EQ(uuid_2, uuid); const uint8_t kMoreBytes[16] = {0xff, 0xee, @@ -127,36 +127,36 @@ TEST(UUID, UUID) { 0x11, 0x00}; uuid.InitializeFromBytes(kMoreBytes); - EXPECT_EQ(0xffeeddccu, uuid.data_1); - EXPECT_EQ(0xbbaau, uuid.data_2); - EXPECT_EQ(0x9988u, uuid.data_3); - EXPECT_EQ(0x77u, uuid.data_4[0]); - EXPECT_EQ(0x66u, uuid.data_4[1]); - EXPECT_EQ(0x55u, uuid.data_5[0]); - EXPECT_EQ(0x44u, uuid.data_5[1]); - EXPECT_EQ(0x33u, uuid.data_5[2]); - EXPECT_EQ(0x22u, uuid.data_5[3]); - EXPECT_EQ(0x11u, uuid.data_5[4]); - EXPECT_EQ(0x00u, uuid.data_5[5]); - EXPECT_EQ("ffeeddcc-bbaa-9988-7766-554433221100", uuid.ToString()); + EXPECT_EQ(uuid.data_1, 0xffeeddccu); + EXPECT_EQ(uuid.data_2, 0xbbaau); + EXPECT_EQ(uuid.data_3, 0x9988u); + EXPECT_EQ(uuid.data_4[0], 0x77u); + EXPECT_EQ(uuid.data_4[1], 0x66u); + EXPECT_EQ(uuid.data_5[0], 0x55u); + EXPECT_EQ(uuid.data_5[1], 0x44u); + EXPECT_EQ(uuid.data_5[2], 0x33u); + EXPECT_EQ(uuid.data_5[3], 0x22u); + EXPECT_EQ(uuid.data_5[4], 0x11u); + EXPECT_EQ(uuid.data_5[5], 0x00u); + EXPECT_EQ(uuid.ToString(), "ffeeddcc-bbaa-9988-7766-554433221100"); EXPECT_NE(uuid, uuid_2); EXPECT_NE(uuid, uuid_zero); // Test that UUID is standard layout. memset(&uuid, 0x45, 16); - EXPECT_EQ(0x45454545u, uuid.data_1); - EXPECT_EQ(0x4545u, uuid.data_2); - EXPECT_EQ(0x4545u, uuid.data_3); - EXPECT_EQ(0x45u, uuid.data_4[0]); - EXPECT_EQ(0x45u, uuid.data_4[1]); - EXPECT_EQ(0x45u, uuid.data_5[0]); - EXPECT_EQ(0x45u, uuid.data_5[1]); - EXPECT_EQ(0x45u, uuid.data_5[2]); - EXPECT_EQ(0x45u, uuid.data_5[3]); - EXPECT_EQ(0x45u, uuid.data_5[4]); - EXPECT_EQ(0x45u, uuid.data_5[5]); - EXPECT_EQ("45454545-4545-4545-4545-454545454545", uuid.ToString()); + EXPECT_EQ(uuid.data_1, 0x45454545u); + EXPECT_EQ(uuid.data_2, 0x4545u); + EXPECT_EQ(uuid.data_3, 0x4545u); + EXPECT_EQ(uuid.data_4[0], 0x45u); + EXPECT_EQ(uuid.data_4[1], 0x45u); + EXPECT_EQ(uuid.data_5[0], 0x45u); + EXPECT_EQ(uuid.data_5[1], 0x45u); + EXPECT_EQ(uuid.data_5[2], 0x45u); + EXPECT_EQ(uuid.data_5[3], 0x45u); + EXPECT_EQ(uuid.data_5[4], 0x45u); + EXPECT_EQ(uuid.data_5[5], 0x45u); + EXPECT_EQ(uuid.ToString(), "45454545-4545-4545-4545-454545454545"); UUID initialized_generated; initialized_generated.InitializeWithNew(); @@ -197,48 +197,48 @@ TEST(UUID, FromString) { UUID uuid; uuid.InitializeToZero(); - EXPECT_EQ(test_case.success, - uuid.InitializeFromString(test_case.uuid_string)); + EXPECT_EQ(uuid.InitializeFromString(test_case.uuid_string), + test_case.success); if (test_case.success) { - EXPECT_EQ(test_case.uuid_string, uuid.ToString()); + EXPECT_EQ(uuid.ToString(), test_case.uuid_string); } else { - EXPECT_EQ(empty_uuid, uuid.ToString()); + EXPECT_EQ(uuid.ToString(), empty_uuid); } } // Test for case insensitivty. UUID uuid; uuid.InitializeFromString("F32E5BDC-2681-4C73-A4E6-911FFD89B846"); - EXPECT_EQ("f32e5bdc-2681-4c73-a4e6-911ffd89b846", uuid.ToString()); + EXPECT_EQ(uuid.ToString(), "f32e5bdc-2681-4c73-a4e6-911ffd89b846"); // Mixed case. uuid.InitializeFromString("5762C15D-50b5-4171-a2e9-7429C9EC6CAB"); - EXPECT_EQ("5762c15d-50b5-4171-a2e9-7429c9ec6cab", uuid.ToString()); + EXPECT_EQ(uuid.ToString(), "5762c15d-50b5-4171-a2e9-7429c9ec6cab"); } #if defined(OS_WIN) TEST(UUID, FromSystem) { ::GUID system_uuid; - ASSERT_EQ(RPC_S_OK, UuidCreate(&system_uuid)); + ASSERT_EQ(UuidCreate(&system_uuid), RPC_S_OK); UUID uuid; uuid.InitializeFromSystemUUID(&system_uuid); RPC_WSTR system_string; - ASSERT_EQ(RPC_S_OK, UuidToString(&system_uuid, &system_string)); + ASSERT_EQ(UuidToString(&system_uuid, &system_string), RPC_S_OK); struct ScopedRpcStringFreeTraits { static RPC_WSTR* InvalidValue() { return nullptr; } static void Free(RPC_WSTR* rpc_string) { - EXPECT_EQ(RPC_S_OK, RpcStringFree(rpc_string)); + EXPECT_EQ(RpcStringFree(rpc_string), RPC_S_OK); } }; using ScopedRpcString = base::ScopedGeneric; ScopedRpcString scoped_system_string(&system_string); - EXPECT_EQ(reinterpret_cast(system_string), uuid.ToString16()); + EXPECT_EQ(uuid.ToString16(), reinterpret_cast(system_string)); } #endif // OS_WIN diff --git a/util/net/http_body_gzip_test.cc b/util/net/http_body_gzip_test.cc index a7b97b93..770f64af 100644 --- a/util/net/http_body_gzip_test.cc +++ b/util/net/http_body_gzip_test.cc @@ -38,7 +38,7 @@ class ScopedZlibInflateStream { explicit ScopedZlibInflateStream(z_stream* zlib) : zlib_(zlib) {} ~ScopedZlibInflateStream() { int zr = inflateEnd(zlib_); - EXPECT_EQ(Z_OK, zr) << "inflateEnd: " << ZlibErrorString(zr); + EXPECT_EQ(zr, Z_OK) << "inflateEnd: " << ZlibErrorString(zr); } private: @@ -65,11 +65,11 @@ void GzipInflate(const std::string& compressed, zlib.avail_out = base::checked_cast(buf_size); int zr = inflateInit2(&zlib, ZlibWindowBitsWithGzipWrapper(0)); - ASSERT_EQ(Z_OK, zr) << "inflateInit2: " << ZlibErrorString(zr); + ASSERT_EQ(zr, Z_OK) << "inflateInit2: " << ZlibErrorString(zr); ScopedZlibInflateStream zlib_inflate(&zlib); zr = inflate(&zlib, Z_FINISH); - ASSERT_EQ(Z_STREAM_END, zr) << "inflate: " << ZlibErrorString(zr); + ASSERT_EQ(zr, Z_STREAM_END) << "inflate: " << ZlibErrorString(zr); ASSERT_LE(zlib.avail_out, buf_size); decompressed->assign(reinterpret_cast(buf.get()), @@ -100,20 +100,20 @@ void TestGzipDeflateInflate(const std::string& string) { // Make sure that the stream is really at EOF. uint8_t eof_buf[16]; - ASSERT_EQ(0, gzip_stream.GetBytesBuffer(eof_buf, sizeof(eof_buf))); + ASSERT_EQ(gzip_stream.GetBytesBuffer(eof_buf, sizeof(eof_buf)), 0); std::string compressed(reinterpret_cast(buf.get()), compressed_bytes); ASSERT_GE(compressed.size(), kGzipHeaderSize); - EXPECT_EQ('\37', compressed[0]); - EXPECT_EQ('\213', compressed[1]); - EXPECT_EQ(Z_DEFLATED, compressed[2]); + EXPECT_EQ(compressed[0], '\37'); + EXPECT_EQ(compressed[1], '\213'); + EXPECT_EQ(compressed[2], Z_DEFLATED); std::string decompressed; ASSERT_NO_FATAL_FAILURE( GzipInflate(compressed, &decompressed, string.size())); - EXPECT_EQ(string, decompressed); + EXPECT_EQ(decompressed, string); // In block mode, compression should be identical. string_stream.reset(new StringHTTPBodyStream(string)); @@ -126,8 +126,8 @@ void TestGzipDeflateInflate(const std::string& string) { block_compressed.append(reinterpret_cast(block_buf), block_compressed_bytes); } - ASSERT_EQ(0, block_compressed_bytes); - EXPECT_EQ(compressed, block_compressed); + ASSERT_EQ(block_compressed_bytes, 0); + EXPECT_EQ(block_compressed, compressed); } std::string MakeString(size_t size) { diff --git a/util/net/http_body_test.cc b/util/net/http_body_test.cc index eb67f106..93f165b1 100644 --- a/util/net/http_body_test.cc +++ b/util/net/http_body_test.cc @@ -17,7 +17,7 @@ #include #include "gtest/gtest.h" -#include "test/paths.h" +#include "test/test_paths.h" #include "util/misc/implicit_cast.h" #include "util/net/http_body_test_util.h" @@ -29,7 +29,7 @@ void ExpectBufferSet(const uint8_t* actual, uint8_t expected_byte, size_t num_expected_bytes) { for (size_t i = 0; i < num_expected_bytes; ++i) { - EXPECT_EQ(expected_byte, actual[i]) << i; + EXPECT_EQ(actual[i], expected_byte) << i; } } @@ -39,7 +39,7 @@ TEST(StringHTTPBodyStream, EmptyString) { std::string empty_string; StringHTTPBodyStream stream(empty_string); - EXPECT_EQ(0, stream.GetBytesBuffer(buf, sizeof(buf))); + EXPECT_EQ(stream.GetBytesBuffer(buf, sizeof(buf)), 0); ExpectBufferSet(buf, '!', sizeof(buf)); } @@ -49,14 +49,14 @@ TEST(StringHTTPBodyStream, SmallString) { std::string string("Hello, world"); StringHTTPBodyStream stream(string); - EXPECT_EQ(implicit_cast(string.length()), - stream.GetBytesBuffer(buf, sizeof(buf))); + EXPECT_EQ(stream.GetBytesBuffer(buf, sizeof(buf)), + implicit_cast(string.length())); std::string actual(reinterpret_cast(buf), string.length()); - EXPECT_EQ(string, actual); + EXPECT_EQ(actual, string); ExpectBufferSet(buf + string.length(), '!', sizeof(buf) - string.length()); - EXPECT_EQ(0, stream.GetBytesBuffer(buf, sizeof(buf))); + EXPECT_EQ(stream.GetBytesBuffer(buf, sizeof(buf)), 0); } TEST(StringHTTPBodyStream, MultipleReads) { @@ -68,15 +68,15 @@ TEST(StringHTTPBodyStream, MultipleReads) { SCOPED_TRACE("aligned buffer boundary"); StringHTTPBodyStream stream(string); - EXPECT_EQ(2, stream.GetBytesBuffer(buf, sizeof(buf))); - EXPECT_EQ('t', buf[0]); - EXPECT_EQ('e', buf[1]); - EXPECT_EQ(2, stream.GetBytesBuffer(buf, sizeof(buf))); - EXPECT_EQ('s', buf[0]); - EXPECT_EQ('t', buf[1]); - EXPECT_EQ(0, stream.GetBytesBuffer(buf, sizeof(buf))); - EXPECT_EQ('s', buf[0]); - EXPECT_EQ('t', buf[1]); + EXPECT_EQ(stream.GetBytesBuffer(buf, sizeof(buf)), 2); + EXPECT_EQ(buf[0], 't'); + EXPECT_EQ(buf[1], 'e'); + EXPECT_EQ(stream.GetBytesBuffer(buf, sizeof(buf)), 2); + EXPECT_EQ(buf[0], 's'); + EXPECT_EQ(buf[1], 't'); + EXPECT_EQ(stream.GetBytesBuffer(buf, sizeof(buf)), 0); + EXPECT_EQ(buf[0], 's'); + EXPECT_EQ(buf[1], 't'); } { @@ -84,38 +84,38 @@ TEST(StringHTTPBodyStream, MultipleReads) { SCOPED_TRACE("unaligned buffer boundary"); StringHTTPBodyStream stream(string); - EXPECT_EQ(2, stream.GetBytesBuffer(buf, sizeof(buf))); - EXPECT_EQ('a', buf[0]); - EXPECT_EQ('b', buf[1]); - EXPECT_EQ(1, stream.GetBytesBuffer(buf, sizeof(buf))); - EXPECT_EQ('c', buf[0]); - EXPECT_EQ('b', buf[1]); // Unmodified from last read. - EXPECT_EQ(0, stream.GetBytesBuffer(buf, sizeof(buf))); - EXPECT_EQ('c', buf[0]); - EXPECT_EQ('b', buf[1]); + EXPECT_EQ(stream.GetBytesBuffer(buf, sizeof(buf)), 2); + EXPECT_EQ(buf[0], 'a'); + EXPECT_EQ(buf[1], 'b'); + EXPECT_EQ(stream.GetBytesBuffer(buf, sizeof(buf)), 1); + EXPECT_EQ(buf[0], 'c'); + EXPECT_EQ(buf[1], 'b'); // Unmodified from last read. + EXPECT_EQ(stream.GetBytesBuffer(buf, sizeof(buf)), 0); + EXPECT_EQ(buf[0], 'c'); + EXPECT_EQ(buf[1], 'b'); } } TEST(FileHTTPBodyStream, ReadASCIIFile) { - base::FilePath path = Paths::TestDataRoot().Append( + base::FilePath path = TestPaths::TestDataRoot().Append( FILE_PATH_LITERAL("util/net/testdata/ascii_http_body.txt")); FileHTTPBodyStream stream(path); std::string contents = ReadStreamToString(&stream, 32); - EXPECT_EQ("This is a test.\n", contents); + EXPECT_EQ(contents, "This is a test.\n"); // Make sure that the file is not read again after it has been read to // completion. uint8_t buf[8]; memset(buf, '!', sizeof(buf)); - EXPECT_EQ(0, stream.GetBytesBuffer(buf, sizeof(buf))); + EXPECT_EQ(stream.GetBytesBuffer(buf, sizeof(buf)), 0); ExpectBufferSet(buf, '!', sizeof(buf)); - EXPECT_EQ(0, stream.GetBytesBuffer(buf, sizeof(buf))); + EXPECT_EQ(stream.GetBytesBuffer(buf, sizeof(buf)), 0); ExpectBufferSet(buf, '!', sizeof(buf)); } TEST(FileHTTPBodyStream, ReadBinaryFile) { // HEX contents of file: |FEEDFACE A11A15|. - base::FilePath path = Paths::TestDataRoot().Append( + base::FilePath path = TestPaths::TestDataRoot().Append( FILE_PATH_LITERAL("util/net/testdata/binary_http_body.dat")); // This buffer size was chosen so that reading the file takes multiple reads. uint8_t buf[4]; @@ -123,23 +123,23 @@ TEST(FileHTTPBodyStream, ReadBinaryFile) { FileHTTPBodyStream stream(path); memset(buf, '!', sizeof(buf)); - EXPECT_EQ(4, stream.GetBytesBuffer(buf, sizeof(buf))); - EXPECT_EQ(0xfe, buf[0]); - EXPECT_EQ(0xed, buf[1]); - EXPECT_EQ(0xfa, buf[2]); - EXPECT_EQ(0xce, buf[3]); + EXPECT_EQ(stream.GetBytesBuffer(buf, sizeof(buf)), 4); + EXPECT_EQ(buf[0], 0xfe); + EXPECT_EQ(buf[1], 0xed); + EXPECT_EQ(buf[2], 0xfa); + EXPECT_EQ(buf[3], 0xce); memset(buf, '!', sizeof(buf)); - EXPECT_EQ(3, stream.GetBytesBuffer(buf, sizeof(buf))); - EXPECT_EQ(0xa1, buf[0]); - EXPECT_EQ(0x1a, buf[1]); - EXPECT_EQ(0x15, buf[2]); - EXPECT_EQ('!', buf[3]); + EXPECT_EQ(stream.GetBytesBuffer(buf, sizeof(buf)), 3); + EXPECT_EQ(buf[0], 0xa1); + EXPECT_EQ(buf[1], 0x1a); + EXPECT_EQ(buf[2], 0x15); + EXPECT_EQ(buf[3], '!'); memset(buf, '!', sizeof(buf)); - EXPECT_EQ(0, stream.GetBytesBuffer(buf, sizeof(buf))); + EXPECT_EQ(stream.GetBytesBuffer(buf, sizeof(buf)), 0); ExpectBufferSet(buf, '!', sizeof(buf)); - EXPECT_EQ(0, stream.GetBytesBuffer(buf, sizeof(buf))); + EXPECT_EQ(stream.GetBytesBuffer(buf, sizeof(buf)), 0); ExpectBufferSet(buf, '!', sizeof(buf)); } @@ -150,9 +150,9 @@ TEST(FileHTTPBodyStream, NonExistentFile) { uint8_t buf = 0xff; EXPECT_LT(stream.GetBytesBuffer(&buf, 1), 0); - EXPECT_EQ(0xff, buf); + EXPECT_EQ(buf, 0xff); EXPECT_LT(stream.GetBytesBuffer(&buf, 1), 0); - EXPECT_EQ(0xff, buf); + EXPECT_EQ(buf, 0xff); } TEST(CompositeHTTPBodyStream, TwoEmptyStrings) { @@ -164,7 +164,7 @@ TEST(CompositeHTTPBodyStream, TwoEmptyStrings) { uint8_t buf[5]; memset(buf, '!', sizeof(buf)); - EXPECT_EQ(0, stream.GetBytesBuffer(buf, sizeof(buf))); + EXPECT_EQ(stream.GetBytesBuffer(buf, sizeof(buf)), 0); ExpectBufferSet(buf, '!', sizeof(buf)); } @@ -188,7 +188,7 @@ TEST_P(CompositeHTTPBodyStreamBufferSize, ThreeStringParts) { CompositeHTTPBodyStream stream(parts); std::string actual_string = ReadStreamToString(&stream, GetParam()); - EXPECT_EQ(string1 + string2 + string3, actual_string); + EXPECT_EQ(actual_string, string1 + string2 + string3); ExpectBufferSet(reinterpret_cast(&buf[all_strings_length]), '!', 3); } @@ -199,7 +199,7 @@ TEST_P(CompositeHTTPBodyStreamBufferSize, StringsAndFile) { std::vector parts; parts.push_back(new StringHTTPBodyStream(string1)); - base::FilePath path = Paths::TestDataRoot().Append( + base::FilePath path = TestPaths::TestDataRoot().Append( FILE_PATH_LITERAL("util/net/testdata/ascii_http_body.txt")); parts.push_back(new FileHTTPBodyStream(path)); parts.push_back(new StringHTTPBodyStream(string2)); @@ -208,7 +208,7 @@ TEST_P(CompositeHTTPBodyStreamBufferSize, StringsAndFile) { std::string expected_string = string1 + "This is a test.\n" + string2; std::string actual_string = ReadStreamToString(&stream, GetParam()); - EXPECT_EQ(expected_string, actual_string); + EXPECT_EQ(actual_string, expected_string); } INSTANTIATE_TEST_CASE_P(VariableBufferSize, diff --git a/util/net/http_multipart_builder_test.cc b/util/net/http_multipart_builder_test.cc index fa20abe4..79366bc2 100644 --- a/util/net/http_multipart_builder_test.cc +++ b/util/net/http_multipart_builder_test.cc @@ -20,7 +20,7 @@ #include "gtest/gtest.h" #include "test/gtest_death_check.h" -#include "test/paths.h" +#include "test/test_paths.h" #include "util/net/http_body.h" #include "util/net/http_body_test_util.h" @@ -71,7 +71,7 @@ TEST(HTTPMultipartBuilder, ThreeStringFields) { ASSERT_TRUE(body.get()); std::string contents = ReadStreamToString(body.get()); auto lines = SplitCRLF(contents); - ASSERT_EQ(13u, lines.size()); + ASSERT_EQ(lines.size(), 13u); auto lines_it = lines.begin(); // The first line is the boundary. All subsequent boundaries must match this. @@ -79,28 +79,28 @@ TEST(HTTPMultipartBuilder, ThreeStringFields) { EXPECT_GE(boundary.length(), 1u); EXPECT_LE(boundary.length(), 70u); - EXPECT_EQ("Content-Disposition: form-data; name=\"key-three\"", *lines_it++); - EXPECT_EQ("", *lines_it++); - EXPECT_EQ(kValue3, *lines_it++); + EXPECT_EQ(*lines_it++, "Content-Disposition: form-data; name=\"key-three\""); + EXPECT_EQ(*lines_it++, ""); + EXPECT_EQ(*lines_it++, kValue3); - EXPECT_EQ(boundary, *lines_it++); - EXPECT_EQ("Content-Disposition: form-data; name=\"key1\"", *lines_it++); - EXPECT_EQ("", *lines_it++); - EXPECT_EQ(kValue1, *lines_it++); + EXPECT_EQ(*lines_it++, boundary); + EXPECT_EQ(*lines_it++, "Content-Disposition: form-data; name=\"key1\""); + EXPECT_EQ(*lines_it++, ""); + EXPECT_EQ(*lines_it++, kValue1); - EXPECT_EQ(boundary, *lines_it++); - EXPECT_EQ("Content-Disposition: form-data; name=\"key2\"", *lines_it++); - EXPECT_EQ("", *lines_it++); - EXPECT_EQ(kValue2, *lines_it++); + EXPECT_EQ(*lines_it++, boundary); + EXPECT_EQ(*lines_it++, "Content-Disposition: form-data; name=\"key2\""); + EXPECT_EQ(*lines_it++, ""); + EXPECT_EQ(*lines_it++, kValue2); - EXPECT_EQ(boundary + "--", *lines_it++); + EXPECT_EQ(*lines_it++, boundary + "--"); - EXPECT_EQ(lines.end(), lines_it); + EXPECT_EQ(lines_it, lines.end()); } TEST(HTTPMultipartBuilder, ThreeFileAttachments) { HTTPMultipartBuilder builder; - base::FilePath ascii_http_body_path = Paths::TestDataRoot().Append( + base::FilePath ascii_http_body_path = TestPaths::TestDataRoot().Append( FILE_PATH_LITERAL("util/net/testdata/ascii_http_body.txt")); builder.SetFileAttachment("first", "minidump.dmp", @@ -121,39 +121,39 @@ TEST(HTTPMultipartBuilder, ThreeFileAttachments) { ASSERT_TRUE(body.get()); std::string contents = ReadStreamToString(body.get()); auto lines = SplitCRLF(contents); - ASSERT_EQ(16u, lines.size()); + ASSERT_EQ(lines.size(), 16u); auto lines_it = lines.begin(); const std::string& boundary = *lines_it++; EXPECT_GE(boundary.length(), 1u); EXPECT_LE(boundary.length(), 70u); - EXPECT_EQ("Content-Disposition: form-data; " - "name=\"%22third 50%25 silly%22\"; filename=\"test%25foo.txt\"", - *lines_it++); - EXPECT_EQ("Content-Type: text/plain", *lines_it++); - EXPECT_EQ("", *lines_it++); - EXPECT_EQ(kFileContents, *lines_it++); + EXPECT_EQ(*lines_it++, + "Content-Disposition: form-data; " + "name=\"%22third 50%25 silly%22\"; filename=\"test%25foo.txt\""); + EXPECT_EQ(*lines_it++, "Content-Type: text/plain"); + EXPECT_EQ(*lines_it++, ""); + EXPECT_EQ(*lines_it++, kFileContents); - EXPECT_EQ(boundary, *lines_it++); - EXPECT_EQ("Content-Disposition: form-data; " - "name=\"first\"; filename=\"minidump.dmp\"", - *lines_it++); - EXPECT_EQ("Content-Type: application/octet-stream", *lines_it++); - EXPECT_EQ("", *lines_it++); - EXPECT_EQ(kFileContents, *lines_it++); + EXPECT_EQ(*lines_it++, boundary); + EXPECT_EQ(*lines_it++, + "Content-Disposition: form-data; " + "name=\"first\"; filename=\"minidump.dmp\""); + EXPECT_EQ(*lines_it++, "Content-Type: application/octet-stream"); + EXPECT_EQ(*lines_it++, ""); + EXPECT_EQ(*lines_it++, kFileContents); - EXPECT_EQ(boundary, *lines_it++); - EXPECT_EQ("Content-Disposition: form-data; " - "name=\"second\"; filename=\"minidump.dmp\"", - *lines_it++); - EXPECT_EQ("Content-Type: text/plain", *lines_it++); - EXPECT_EQ("", *lines_it++); - EXPECT_EQ(kFileContents, *lines_it++); + EXPECT_EQ(*lines_it++, boundary); + EXPECT_EQ(*lines_it++, + "Content-Disposition: form-data; " + "name=\"second\"; filename=\"minidump.dmp\""); + EXPECT_EQ(*lines_it++, "Content-Type: text/plain"); + EXPECT_EQ(*lines_it++, ""); + EXPECT_EQ(*lines_it++, kFileContents); - EXPECT_EQ(boundary + "--", *lines_it++); + EXPECT_EQ(*lines_it++, boundary + "--"); - EXPECT_EQ(lines.end(), lines_it); + EXPECT_EQ(lines_it, lines.end()); } TEST(HTTPMultipartBuilder, OverwriteFormDataWithEscapedKey) { @@ -165,20 +165,20 @@ TEST(HTTPMultipartBuilder, OverwriteFormDataWithEscapedKey) { ASSERT_TRUE(body.get()); std::string contents = ReadStreamToString(body.get()); auto lines = SplitCRLF(contents); - ASSERT_EQ(5u, lines.size()); + ASSERT_EQ(lines.size(), 5u); auto lines_it = lines.begin(); const std::string& boundary = *lines_it++; EXPECT_GE(boundary.length(), 1u); EXPECT_LE(boundary.length(), 70u); - EXPECT_EQ( - "Content-Disposition: form-data; name=\"a 100%25 %22silly%22%0d%0atest\"", - *lines_it++); - EXPECT_EQ("", *lines_it++); - EXPECT_EQ("overwrite", *lines_it++); - EXPECT_EQ(boundary + "--", *lines_it++); - EXPECT_EQ(lines.end(), lines_it); + EXPECT_EQ(*lines_it++, + "Content-Disposition: form-data; name=\"a 100%25 " + "%22silly%22%0d%0atest\""); + EXPECT_EQ(*lines_it++, ""); + EXPECT_EQ(*lines_it++, "overwrite"); + EXPECT_EQ(*lines_it++, boundary + "--"); + EXPECT_EQ(lines_it, lines.end()); } TEST(HTTPMultipartBuilder, OverwriteFileAttachment) { @@ -186,7 +186,7 @@ TEST(HTTPMultipartBuilder, OverwriteFileAttachment) { const char kValue[] = "1 2 3 test"; builder.SetFormData("a key", kValue); base::FilePath testdata_path = - Paths::TestDataRoot().Append(FILE_PATH_LITERAL("util/net/testdata")); + TestPaths::TestDataRoot().Append(FILE_PATH_LITERAL("util/net/testdata")); builder.SetFileAttachment("minidump", "minidump.dmp", testdata_path.Append(FILE_PATH_LITERAL( @@ -206,43 +206,43 @@ TEST(HTTPMultipartBuilder, OverwriteFileAttachment) { ASSERT_TRUE(body.get()); std::string contents = ReadStreamToString(body.get()); auto lines = SplitCRLF(contents); - ASSERT_EQ(15u, lines.size()); + ASSERT_EQ(lines.size(), 15u); auto lines_it = lines.begin(); const std::string& boundary = *lines_it++; EXPECT_GE(boundary.length(), 1u); EXPECT_LE(boundary.length(), 70u); - EXPECT_EQ("Content-Disposition: form-data; name=\"a key\"", *lines_it++); - EXPECT_EQ("", *lines_it++); - EXPECT_EQ(kValue, *lines_it++); + EXPECT_EQ(*lines_it++, "Content-Disposition: form-data; name=\"a key\""); + EXPECT_EQ(*lines_it++, ""); + EXPECT_EQ(*lines_it++, kValue); - EXPECT_EQ(boundary, *lines_it++); - EXPECT_EQ("Content-Disposition: form-data; " - "name=\"minidump\"; filename=\"minidump.dmp\"", - *lines_it++); - EXPECT_EQ("Content-Type: text/plain", *lines_it++); - EXPECT_EQ("", *lines_it++); - EXPECT_EQ("This is a test.\n", *lines_it++); + EXPECT_EQ(*lines_it++, boundary); + EXPECT_EQ(*lines_it++, + "Content-Disposition: form-data; " + "name=\"minidump\"; filename=\"minidump.dmp\""); + EXPECT_EQ(*lines_it++, "Content-Type: text/plain"); + EXPECT_EQ(*lines_it++, ""); + EXPECT_EQ(*lines_it++, "This is a test.\n"); - EXPECT_EQ(boundary, *lines_it++); - EXPECT_EQ("Content-Disposition: form-data; " - "name=\"minidump2\"; filename=\"minidump.dmp\"", - *lines_it++); - EXPECT_EQ("Content-Type: application/octet-stream", *lines_it++); - EXPECT_EQ("", *lines_it++); - EXPECT_EQ("\xFE\xED\xFA\xCE\xA1\x1A\x15", *lines_it++); + EXPECT_EQ(*lines_it++, boundary); + EXPECT_EQ(*lines_it++, + "Content-Disposition: form-data; " + "name=\"minidump2\"; filename=\"minidump.dmp\""); + EXPECT_EQ(*lines_it++, "Content-Type: application/octet-stream"); + EXPECT_EQ(*lines_it++, ""); + EXPECT_EQ(*lines_it++, "\xFE\xED\xFA\xCE\xA1\x1A\x15"); - EXPECT_EQ(boundary + "--", *lines_it++); + EXPECT_EQ(*lines_it++, boundary + "--"); - EXPECT_EQ(lines.end(), lines_it); + EXPECT_EQ(lines_it, lines.end()); } TEST(HTTPMultipartBuilder, SharedFormDataAndAttachmentKeyNamespace) { HTTPMultipartBuilder builder; const char kValue1[] = "11111"; builder.SetFormData("one", kValue1); - base::FilePath ascii_http_body_path = Paths::TestDataRoot().Append( + base::FilePath ascii_http_body_path = TestPaths::TestDataRoot().Append( FILE_PATH_LITERAL("util/net/testdata/ascii_http_body.txt")); builder.SetFileAttachment("minidump", "minidump.dmp", @@ -255,25 +255,25 @@ TEST(HTTPMultipartBuilder, SharedFormDataAndAttachmentKeyNamespace) { ASSERT_TRUE(body.get()); std::string contents = ReadStreamToString(body.get()); auto lines = SplitCRLF(contents); - ASSERT_EQ(9u, lines.size()); + ASSERT_EQ(lines.size(), 9u); auto lines_it = lines.begin(); const std::string& boundary = *lines_it++; EXPECT_GE(boundary.length(), 1u); EXPECT_LE(boundary.length(), 70u); - EXPECT_EQ("Content-Disposition: form-data; name=\"minidump\"", *lines_it++); - EXPECT_EQ("", *lines_it++); - EXPECT_EQ(kValue2, *lines_it++); + EXPECT_EQ(*lines_it++, "Content-Disposition: form-data; name=\"minidump\""); + EXPECT_EQ(*lines_it++, ""); + EXPECT_EQ(*lines_it++, kValue2); - EXPECT_EQ(boundary, *lines_it++); - EXPECT_EQ("Content-Disposition: form-data; name=\"one\"", *lines_it++); - EXPECT_EQ("", *lines_it++); - EXPECT_EQ(kValue1, *lines_it++); + EXPECT_EQ(*lines_it++, boundary); + EXPECT_EQ(*lines_it++, "Content-Disposition: form-data; name=\"one\""); + EXPECT_EQ(*lines_it++, ""); + EXPECT_EQ(*lines_it++, kValue1); - EXPECT_EQ(boundary + "--", *lines_it++); + EXPECT_EQ(*lines_it++, boundary + "--"); - EXPECT_EQ(lines.end(), lines_it); + EXPECT_EQ(lines_it, lines.end()); } TEST(HTTPMultipartBuilderDeathTest, AssertUnsafeMIMEType) { diff --git a/util/net/http_transport_libcurl.cc b/util/net/http_transport_libcurl.cc index 96ea7502..1a20913a 100644 --- a/util/net/http_transport_libcurl.cc +++ b/util/net/http_transport_libcurl.cc @@ -48,28 +48,64 @@ std::string UserAgent() { // as the user process’ architecture. On Linux, these names are normally // defined in each architecture’s Makefile as UTS_MACHINE, but can be // overridden in architecture-specific configuration as COMPAT_UTS_MACHINE. - // See linux-4.4.52/arch/*/Makefile and - // linux-4.4.52/arch/*/include/asm/compat.h. In turn, on some systems, these + // See linux-4.9.17/arch/*/Makefile and + // linux-4.9.17/arch/*/include/asm/compat.h. In turn, on some systems, these // names are further overridden or refined in early kernel startup code by - // modifying the string returned by linux-4.4.52/include/linux/utsname.h + // modifying the string returned by linux-4.9.17/include/linux/utsname.h // init_utsname() as noted. #if defined(ARCH_CPU_X86) - // linux-4.4.52/arch/x86/kernel/cpu/bugs.c check_bugs() sets the first digit - // to 4, 5, or 6, but no higher. Assume 6. + // linux-4.9.17/arch/x86/kernel/cpu/bugs.c check_bugs() sets the first digit + // to 4, 5, or 6, but no higher. +#if defined(__i686__) const char arch[] = "i686"; +#elif defined(__i586__) + const char arch[] = "i586"; +#elif defined(__i486__) + const char arch[] = "i486"; +#else + const char arch[] = "i386"; +#endif #elif defined(ARCH_CPU_X86_64) const char arch[] = "x86_64"; #elif defined(ARCH_CPU_ARMEL) - // linux-4.4.52/arch/arm/kernel/setup.c setup_processor() bases the string + // linux-4.9.17/arch/arm/kernel/setup.c setup_processor() bases the string // on the ARM processor name and a character identifying little- or // big-endian. The processor name comes from a definition in - // arch/arm/mm/proc-*.S. Assume armv7, little-endian. - const char arch[] = "armv7l"; + // arch/arm/mm/proc-*.S. +#if defined(__ARM_ARCH_4T__) + const char arch[] = "armv4t" +#elif defined(__ARM_ARCH_5TEJ__) + const char arch[] = "armv5tej" +#elif defined(__ARM_ARCH_5TE__) + const char arch[] = "armv5te" +#elif defined(__ARM_ARCH_5T__) + const char arch[] = "armv5t" +#elif defined(__ARM_ARCH_7M__) + const char arch[] = "armv7m" +#else + // Most ARM architectures fall into here, including all profile variants of + // armv6, armv7, armv8, with one exception, armv7m, handled above. + // xstr(__ARM_ARCH) will be the architecture revision number, such as 6, 7, + // or 8. +#define xstr(s) str(s) +#define str(s) #s + const char arch[] = "armv" xstr(__ARM_ARCH) +#undef str +#undef xstr +#endif +#if defined(ARCH_CPU_LITTLE_ENDIAN) + "l"; +#elif defined(ARCH_CPU_BIG_ENDIAN) + "b"; +#endif #elif defined(ARCH_CPU_ARM64) // ARM64 uses aarch64 or aarch64_be as directed by ELF_PLATFORM. See - // linux-4.4.52/arch/arm64/kernel/setup.c setup_arch(). Assume - // little-endian. + // linux-4.9.17/arch/arm64/kernel/setup.c setup_arch(). +#if defined(ARCH_CPU_LITTLE_ENDIAN) const char arch[] = "aarch64"; +#elif defined(ARCH_CPU_BIG_ENDIAN) + const char arch[] = "aarch64_be"; +#endif #elif defined(ARCH_CPU_MIPSEL) const char arch[] = "mips"; #elif defined(ARCH_CPU_MIPS64EL) diff --git a/util/net/http_transport_test.cc b/util/net/http_transport_test.cc index cb5c4f1f..70c3eee4 100644 --- a/util/net/http_transport_test.cc +++ b/util/net/http_transport_test.cc @@ -31,7 +31,7 @@ #include "build/build_config.h" #include "gtest/gtest.h" #include "test/multiprocess_exec.h" -#include "test/paths.h" +#include "test/test_paths.h" #include "util/file/file_io.h" #include "util/misc/random_string.h" #include "util/net/http_body.h" @@ -56,7 +56,7 @@ class HTTPTransportTestFixture : public MultiprocessExec { body_stream_(std::move(body_stream)), response_code_(http_response_code), request_validator_(request_validator) { - base::FilePath server_path = Paths::TestDataRoot().Append( + base::FilePath server_path = TestPaths::TestDataRoot().Append( FILE_PATH_LITERAL("util/net/http_transport_test_server.py")); #if defined(OS_POSIX) SetChildCommand(server_path.value(), nullptr); @@ -111,7 +111,7 @@ class HTTPTransportTestFixture : public MultiprocessExec { if (response_code_ == 200) { EXPECT_TRUE(success); std::string expect_response_body = random_string + "\r\n"; - EXPECT_EQ(expect_response_body, response_body); + EXPECT_EQ(response_body, expect_response_body); } else { EXPECT_FALSE(success); EXPECT_TRUE(response_body.empty()); @@ -142,20 +142,20 @@ void GetHeaderField(const std::string& request, const std::string& header, std::string* value) { size_t index = request.find(header); - ASSERT_NE(std::string::npos, index); + ASSERT_NE(index, std::string::npos); // Since the header is never the first line of the request, it should always // be preceded by a CRLF. - EXPECT_EQ('\n', request[index - 1]); - EXPECT_EQ('\r', request[index - 2]); + EXPECT_EQ(request[index - 1], '\n'); + EXPECT_EQ(request[index - 2], '\r'); index += header.length(); - EXPECT_EQ(':', request[index++]); + EXPECT_EQ(request[index++], ':'); // Per RFC 7230 §3.2, there can be one or more spaces or horizontal tabs. // For testing purposes, just assume one space. - EXPECT_EQ(' ', request[index++]); + EXPECT_EQ(request[index++], ' '); size_t header_end = request.find('\r', index); - ASSERT_NE(std::string::npos, header_end); + ASSERT_NE(header_end, std::string::npos); *value = request.substr(index, header_end - index); } @@ -167,13 +167,13 @@ void GetMultipartBoundary(const std::string& request, ASSERT_GE(content_type.length(), strlen(kMultipartFormData)); size_t index = strlen(kMultipartFormData); - EXPECT_EQ(kMultipartFormData, content_type.substr(0, index)); + EXPECT_EQ(content_type.substr(0, index), kMultipartFormData); - EXPECT_EQ(';', content_type[index++]); + EXPECT_EQ(content_type[index++], ';'); size_t boundary_begin = content_type.find('=', index); - ASSERT_NE(std::string::npos, boundary_begin); - EXPECT_EQ('=', content_type[boundary_begin++]); + ASSERT_NE(boundary_begin, std::string::npos); + EXPECT_EQ(content_type[boundary_begin++], '='); if (multipart_boundary) { *multipart_boundary = content_type.substr(boundary_begin); } @@ -187,23 +187,23 @@ void ValidFormData(HTTPTransportTestFixture* fixture, GetMultipartBoundary(request, &actual_boundary); const auto& content_type = fixture->headers().find(kContentType); - ASSERT_NE(fixture->headers().end(), content_type); + ASSERT_NE(content_type, fixture->headers().end()); size_t boundary = content_type->second.find(kBoundaryEq); - ASSERT_NE(std::string::npos, boundary); + ASSERT_NE(boundary, std::string::npos); std::string expected_boundary = content_type->second.substr(boundary + strlen(kBoundaryEq)); - EXPECT_EQ(expected_boundary, actual_boundary); + EXPECT_EQ(actual_boundary, expected_boundary); size_t body_start = request.find("\r\n\r\n"); - ASSERT_NE(std::string::npos, body_start); + ASSERT_NE(body_start, std::string::npos); body_start += 4; std::string expected = "--" + expected_boundary + "\r\n"; expected += "Content-Disposition: form-data; name=\"key1\"\r\n\r\n"; expected += "test\r\n"; ASSERT_LT(body_start + expected.length(), request.length()); - EXPECT_EQ(expected, request.substr(body_start, expected.length())); + EXPECT_EQ(request.substr(body_start, expected.length()), expected); body_start += expected.length(); @@ -211,8 +211,8 @@ void ValidFormData(HTTPTransportTestFixture* fixture, expected += "Content-Disposition: form-data; name=\"key2\"\r\n\r\n"; expected += "--abcdefg123\r\n"; expected += "--" + expected_boundary + "--\r\n"; - ASSERT_EQ(body_start + expected.length(), request.length()); - EXPECT_EQ(expected, request.substr(body_start)); + ASSERT_EQ(request.length(), body_start + expected.length()); + EXPECT_EQ(request.substr(body_start), expected); } TEST(HTTPTransport, ValidFormData) { @@ -248,7 +248,7 @@ void ErrorResponse(HTTPTransportTestFixture* fixture, const std::string& request) { std::string content_type; GetHeaderField(request, kContentType, &content_type); - EXPECT_EQ(kTextPlain, content_type); + EXPECT_EQ(content_type, kTextPlain); } TEST(HTTPTransport, ErrorResponse) { @@ -266,17 +266,17 @@ void UnchunkedPlainText(HTTPTransportTestFixture* fixture, const std::string& request) { std::string header_value; GetHeaderField(request, kContentType, &header_value); - EXPECT_EQ(kTextPlain, header_value); + EXPECT_EQ(header_value, kTextPlain); GetHeaderField(request, kContentLength, &header_value); const auto& content_length = fixture->headers().find(kContentLength); - ASSERT_NE(fixture->headers().end(), content_length); - EXPECT_EQ(content_length->second, header_value); + ASSERT_NE(content_length, fixture->headers().end()); + EXPECT_EQ(header_value, content_length->second); size_t body_start = request.rfind("\r\n"); - ASSERT_NE(std::string::npos, body_start); + ASSERT_NE(body_start, std::string::npos); - EXPECT_EQ(kTextBody, request.substr(body_start + 2)); + EXPECT_EQ(request.substr(body_start + 2), kTextBody); } TEST(HTTPTransport, UnchunkedPlainText) { @@ -314,7 +314,7 @@ void RunUpload33k(bool has_content_length) { 200, [](HTTPTransportTestFixture* fixture, const std::string& request) { size_t body_start = request.rfind("\r\n"); - EXPECT_EQ(33 * 1024u + 2, request.size() - body_start); + EXPECT_EQ(request.size() - body_start, 33 * 1024u + 2); }); test.Run(); } diff --git a/util/numeric/checked_address_range_test.cc b/util/numeric/checked_address_range_test.cc index 403c000f..fa7ae87d 100644 --- a/util/numeric/checked_address_range_test.cc +++ b/util/numeric/checked_address_range_test.cc @@ -128,10 +128,10 @@ TEST(CheckedAddressRange, IsValid) { testcase.size)); CheckedAddressRange range_32(false, testcase.base, testcase.size); - EXPECT_EQ(ExpectationForValidity32(testcase.validity), range_32.IsValid()); + EXPECT_EQ(range_32.IsValid(), ExpectationForValidity32(testcase.validity)); CheckedAddressRange range_64(true, testcase.base, testcase.size); - EXPECT_EQ(ExpectationForValidity64(testcase.validity), range_64.IsValid()); + EXPECT_EQ(range_64.IsValid(), ExpectationForValidity64(testcase.validity)); } } @@ -175,8 +175,8 @@ TEST(CheckedAddressRange, ContainsValue) { SCOPED_TRACE(base::StringPrintf( "index %" PRIuS ", value 0x%" PRIx64, index, testcase.value)); - EXPECT_EQ(testcase.expectation, - parent_range_32.ContainsValue(testcase.value)); + EXPECT_EQ(parent_range_32.ContainsValue(testcase.value), + testcase.expectation); } CheckedAddressRange parent_range_64(true, 0x100000000, 0x1000); @@ -237,8 +237,8 @@ TEST(CheckedAddressRange, ContainsRange) { CheckedAddressRange child_range_32(false, testcase.base, testcase.size); ASSERT_TRUE(child_range_32.IsValid()); - EXPECT_EQ(testcase.expectation, - parent_range_32.ContainsRange(child_range_32)); + EXPECT_EQ(parent_range_32.ContainsRange(child_range_32), + testcase.expectation); } CheckedAddressRange parent_range_64(true, 0x100000000, 0x1000); diff --git a/util/numeric/checked_range_test.cc b/util/numeric/checked_range_test.cc index 0b1ea32e..404b9898 100644 --- a/util/numeric/checked_range_test.cc +++ b/util/numeric/checked_range_test.cc @@ -87,7 +87,7 @@ TEST(CheckedRange, IsValid) { testcase.size)); CheckedRange range(testcase.base, testcase.size); - EXPECT_EQ(testcase.valid, range.IsValid()); + EXPECT_EQ(range.IsValid(), testcase.valid); } const int32_t kMinInt32 = std::numeric_limits::min(); @@ -149,7 +149,7 @@ TEST(CheckedRange, IsValid) { testcase.size)); CheckedRange range(testcase.base, testcase.size); - EXPECT_EQ(testcase.valid, range.IsValid()); + EXPECT_EQ(range.IsValid(), testcase.valid); } } @@ -191,7 +191,7 @@ TEST(CheckedRange, ContainsValue) { SCOPED_TRACE(base::StringPrintf( "index %" PRIuS ", value 0x%x", index, testcase.value)); - EXPECT_EQ(testcase.contains, parent_range.ContainsValue(testcase.value)); + EXPECT_EQ(parent_range.ContainsValue(testcase.value), testcase.contains); } } @@ -243,7 +243,7 @@ TEST(CheckedRange, ContainsRange) { CheckedRange child_range(testcase.base, testcase.size); ASSERT_TRUE(child_range.IsValid()); - EXPECT_EQ(testcase.contains, parent_range.ContainsRange(child_range)); + EXPECT_EQ(parent_range.ContainsRange(child_range), testcase.contains); } } @@ -296,7 +296,7 @@ TEST(CheckedRange, OverlapsRange) { CheckedRange second_range(testcase.base, testcase.size); ASSERT_TRUE(second_range.IsValid()); - EXPECT_EQ(testcase.overlaps, first_range.OverlapsRange(second_range)); + EXPECT_EQ(first_range.OverlapsRange(second_range), testcase.overlaps); } } diff --git a/util/numeric/in_range_cast_test.cc b/util/numeric/in_range_cast_test.cc index d8882bc4..6e74129f 100644 --- a/util/numeric/in_range_cast_test.cc +++ b/util/numeric/in_range_cast_test.cc @@ -29,94 +29,94 @@ const int32_t kInt32Min = std::numeric_limits::min(); const int64_t kInt64Min = std::numeric_limits::min(); TEST(InRangeCast, Uint32) { - EXPECT_EQ(0u, InRangeCast(0, 1)); - EXPECT_EQ(1u, InRangeCast(1, 1)); - EXPECT_EQ(2u, InRangeCast(2, 1)); - EXPECT_EQ(0u, InRangeCast(-1, 0)); - EXPECT_EQ(1u, InRangeCast(-1, 1)); - EXPECT_EQ(2u, InRangeCast(-1, 2)); - EXPECT_EQ(0xffffffffu, InRangeCast(0xffffffffu, 1)); - EXPECT_EQ(0xffffffffu, InRangeCast(UINT64_C(0xffffffff), 1)); - EXPECT_EQ(1u, InRangeCast(UINT64_C(0x100000000), 1)); - EXPECT_EQ(1u, InRangeCast(UINT64_C(0x100000001), 1)); - EXPECT_EQ(1u, InRangeCast(kInt32Min, 1)); - EXPECT_EQ(1u, InRangeCast(kInt64Min, 1)); - EXPECT_EQ(0xffffffffu, InRangeCast(-1, 0xffffffffu)); + EXPECT_EQ(InRangeCast(0, 1), 0u); + EXPECT_EQ(InRangeCast(1, 1), 1u); + EXPECT_EQ(InRangeCast(2, 1), 2u); + EXPECT_EQ(InRangeCast(-1, 0), 0u); + EXPECT_EQ(InRangeCast(-1, 1), 1u); + EXPECT_EQ(InRangeCast(-1, 2), 2u); + EXPECT_EQ(InRangeCast(0xffffffffu, 1), 0xffffffffu); + EXPECT_EQ(InRangeCast(UINT64_C(0xffffffff), 1), 0xffffffffu); + EXPECT_EQ(InRangeCast(UINT64_C(0x100000000), 1), 1u); + EXPECT_EQ(InRangeCast(UINT64_C(0x100000001), 1), 1u); + EXPECT_EQ(InRangeCast(kInt32Min, 1), 1u); + EXPECT_EQ(InRangeCast(kInt64Min, 1), 1u); + EXPECT_EQ(InRangeCast(-1, 0xffffffffu), 0xffffffffu); } TEST(InRangeCast, Int32) { - EXPECT_EQ(0, InRangeCast(0, 1)); - EXPECT_EQ(1, InRangeCast(1, 1)); - EXPECT_EQ(2, InRangeCast(2, 1)); - EXPECT_EQ(-1, InRangeCast(-1, 1)); - EXPECT_EQ(0x7fffffff, InRangeCast(0x7fffffff, 1)); - EXPECT_EQ(0x7fffffff, InRangeCast(0x7fffffffu, 1)); - EXPECT_EQ(1, InRangeCast(0x80000000u, 1)); - EXPECT_EQ(1, InRangeCast(0xffffffffu, 1)); - EXPECT_EQ(1, InRangeCast(INT64_C(0x80000000), 1)); - EXPECT_EQ(1, InRangeCast(INT64_C(0xffffffff), 1)); - EXPECT_EQ(1, InRangeCast(INT64_C(0x100000000), 1)); - EXPECT_EQ(kInt32Min, InRangeCast(kInt32Min, 1)); - EXPECT_EQ(kInt32Min, - InRangeCast(implicit_cast(kInt32Min), 1)); - EXPECT_EQ(1, InRangeCast(implicit_cast(kInt32Min) - 1, 1)); - EXPECT_EQ(1, InRangeCast(kInt64Min, 1)); - EXPECT_EQ(0, InRangeCast(0xffffffffu, 0)); - EXPECT_EQ(-1, InRangeCast(0xffffffffu, -1)); - EXPECT_EQ(kInt32Min, InRangeCast(0xffffffffu, kInt32Min)); - EXPECT_EQ(0x7fffffff, InRangeCast(0xffffffffu, 0x7fffffff)); + EXPECT_EQ(InRangeCast(0, 1), 0); + EXPECT_EQ(InRangeCast(1, 1), 1); + EXPECT_EQ(InRangeCast(2, 1), 2); + EXPECT_EQ(InRangeCast(-1, 1), -1); + EXPECT_EQ(InRangeCast(0x7fffffff, 1), 0x7fffffff); + EXPECT_EQ(InRangeCast(0x7fffffffu, 1), 0x7fffffff); + EXPECT_EQ(InRangeCast(0x80000000u, 1), 1); + EXPECT_EQ(InRangeCast(0xffffffffu, 1), 1); + EXPECT_EQ(InRangeCast(INT64_C(0x80000000), 1), 1); + EXPECT_EQ(InRangeCast(INT64_C(0xffffffff), 1), 1); + EXPECT_EQ(InRangeCast(INT64_C(0x100000000), 1), 1); + EXPECT_EQ(InRangeCast(kInt32Min, 1), kInt32Min); + EXPECT_EQ(InRangeCast(implicit_cast(kInt32Min), 1), + kInt32Min); + EXPECT_EQ(InRangeCast(implicit_cast(kInt32Min) - 1, 1), 1); + EXPECT_EQ(InRangeCast(kInt64Min, 1), 1); + EXPECT_EQ(InRangeCast(0xffffffffu, 0), 0); + EXPECT_EQ(InRangeCast(0xffffffffu, -1), -1); + EXPECT_EQ(InRangeCast(0xffffffffu, kInt32Min), kInt32Min); + EXPECT_EQ(InRangeCast(0xffffffffu, 0x7fffffff), 0x7fffffff); } TEST(InRangeCast, Uint64) { - EXPECT_EQ(0u, InRangeCast(0, 1)); - EXPECT_EQ(1u, InRangeCast(1, 1)); - EXPECT_EQ(2u, InRangeCast(2, 1)); - EXPECT_EQ(0u, InRangeCast(-1, 0)); - EXPECT_EQ(1u, InRangeCast(-1, 1)); - EXPECT_EQ(2u, InRangeCast(-1, 2)); - EXPECT_EQ(0xffffffffu, InRangeCast(0xffffffffu, 1)); - EXPECT_EQ(0xffffffffu, InRangeCast(UINT64_C(0xffffffff), 1)); - EXPECT_EQ(UINT64_C(0x100000000), - InRangeCast(UINT64_C(0x100000000), 1)); - EXPECT_EQ(UINT64_C(0x100000001), - InRangeCast(UINT64_C(0x100000001), 1)); - EXPECT_EQ(1u, InRangeCast(kInt32Min, 1)); - EXPECT_EQ(1u, InRangeCast(INT64_C(-1), 1)); - EXPECT_EQ(1u, InRangeCast(kInt64Min, 1)); - EXPECT_EQ(UINT64_C(0xffffffffffffffff), - InRangeCast(-1, UINT64_C(0xffffffffffffffff))); + EXPECT_EQ(InRangeCast(0, 1), 0u); + EXPECT_EQ(InRangeCast(1, 1), 1u); + EXPECT_EQ(InRangeCast(2, 1), 2u); + EXPECT_EQ(InRangeCast(-1, 0), 0u); + EXPECT_EQ(InRangeCast(-1, 1), 1u); + EXPECT_EQ(InRangeCast(-1, 2), 2u); + EXPECT_EQ(InRangeCast(0xffffffffu, 1), 0xffffffffu); + EXPECT_EQ(InRangeCast(UINT64_C(0xffffffff), 1), 0xffffffffu); + EXPECT_EQ(InRangeCast(UINT64_C(0x100000000), 1), + UINT64_C(0x100000000)); + EXPECT_EQ(InRangeCast(UINT64_C(0x100000001), 1), + UINT64_C(0x100000001)); + EXPECT_EQ(InRangeCast(kInt32Min, 1), 1u); + EXPECT_EQ(InRangeCast(INT64_C(-1), 1), 1u); + EXPECT_EQ(InRangeCast(kInt64Min, 1), 1u); + EXPECT_EQ(InRangeCast(-1, UINT64_C(0xffffffffffffffff)), + UINT64_C(0xffffffffffffffff)); } TEST(InRangeCast, Int64) { - EXPECT_EQ(0, InRangeCast(0, 1)); - EXPECT_EQ(1, InRangeCast(1, 1)); - EXPECT_EQ(2, InRangeCast(2, 1)); - EXPECT_EQ(-1, InRangeCast(-1, 1)); - EXPECT_EQ(0x7fffffff, InRangeCast(0x7fffffff, 1)); - EXPECT_EQ(0x7fffffff, InRangeCast(0x7fffffffu, 1)); - EXPECT_EQ(INT64_C(0x80000000), InRangeCast(0x80000000u, 1)); - EXPECT_EQ(INT64_C(0xffffffff), InRangeCast(0xffffffffu, 1)); - EXPECT_EQ(INT64_C(0x80000000), InRangeCast(INT64_C(0x80000000), 1)); - EXPECT_EQ(INT64_C(0xffffffff), InRangeCast(INT64_C(0xffffffff), 1)); - EXPECT_EQ(INT64_C(0x100000000), - InRangeCast(INT64_C(0x100000000), 1)); - EXPECT_EQ(INT64_C(0x7fffffffffffffff), - InRangeCast(INT64_C(0x7fffffffffffffff), 1)); - EXPECT_EQ(INT64_C(0x7fffffffffffffff), - InRangeCast(UINT64_C(0x7fffffffffffffff), 1)); - EXPECT_EQ(1, InRangeCast(UINT64_C(0x8000000000000000), 1)); - EXPECT_EQ(1, InRangeCast(UINT64_C(0xffffffffffffffff), 1)); - EXPECT_EQ(kInt32Min, InRangeCast(kInt32Min, 1)); - EXPECT_EQ(kInt32Min, - InRangeCast(implicit_cast(kInt32Min), 1)); - EXPECT_EQ(kInt64Min, InRangeCast(kInt64Min, 1)); - EXPECT_EQ(0, InRangeCast(UINT64_C(0xffffffffffffffff), 0)); - EXPECT_EQ(-1, InRangeCast(UINT64_C(0xffffffffffffffff), -1)); - EXPECT_EQ(kInt64Min, - InRangeCast(UINT64_C(0xffffffffffffffff), kInt64Min)); - EXPECT_EQ(INT64_C(0x7fffffffffffffff), - InRangeCast(UINT64_C(0xffffffffffffffff), - INT64_C(0x7fffffffffffffff))); + EXPECT_EQ(InRangeCast(0, 1), 0); + EXPECT_EQ(InRangeCast(1, 1), 1); + EXPECT_EQ(InRangeCast(2, 1), 2); + EXPECT_EQ(InRangeCast(-1, 1), -1); + EXPECT_EQ(InRangeCast(0x7fffffff, 1), 0x7fffffff); + EXPECT_EQ(InRangeCast(0x7fffffffu, 1), 0x7fffffff); + EXPECT_EQ(InRangeCast(0x80000000u, 1), INT64_C(0x80000000)); + EXPECT_EQ(InRangeCast(0xffffffffu, 1), INT64_C(0xffffffff)); + EXPECT_EQ(InRangeCast(INT64_C(0x80000000), 1), INT64_C(0x80000000)); + EXPECT_EQ(InRangeCast(INT64_C(0xffffffff), 1), INT64_C(0xffffffff)); + EXPECT_EQ(InRangeCast(INT64_C(0x100000000), 1), + INT64_C(0x100000000)); + EXPECT_EQ(InRangeCast(INT64_C(0x7fffffffffffffff), 1), + INT64_C(0x7fffffffffffffff)); + EXPECT_EQ(InRangeCast(UINT64_C(0x7fffffffffffffff), 1), + INT64_C(0x7fffffffffffffff)); + EXPECT_EQ(InRangeCast(UINT64_C(0x8000000000000000), 1), 1); + EXPECT_EQ(InRangeCast(UINT64_C(0xffffffffffffffff), 1), 1); + EXPECT_EQ(InRangeCast(kInt32Min, 1), kInt32Min); + EXPECT_EQ(InRangeCast(implicit_cast(kInt32Min), 1), + kInt32Min); + EXPECT_EQ(InRangeCast(kInt64Min, 1), kInt64Min); + EXPECT_EQ(InRangeCast(UINT64_C(0xffffffffffffffff), 0), 0); + EXPECT_EQ(InRangeCast(UINT64_C(0xffffffffffffffff), -1), -1); + EXPECT_EQ(InRangeCast(UINT64_C(0xffffffffffffffff), kInt64Min), + kInt64Min); + EXPECT_EQ(InRangeCast(UINT64_C(0xffffffffffffffff), + INT64_C(0x7fffffffffffffff)), + INT64_C(0x7fffffffffffffff)); } } // namespace diff --git a/util/numeric/int128_test.cc b/util/numeric/int128_test.cc index 90dfdb2f..e0b45999 100644 --- a/util/numeric/int128_test.cc +++ b/util/numeric/int128_test.cc @@ -35,8 +35,8 @@ TEST(Int128, UInt128) { uint128 = bit_cast(kBytes); - EXPECT_EQ(0x0706050403020100u, uint128.lo); - EXPECT_EQ(0x0f0e0d0c0b0a0908u, uint128.hi); + EXPECT_EQ(uint128.lo, 0x0706050403020100u); + EXPECT_EQ(uint128.hi, 0x0f0e0d0c0b0a0908u); } } // namespace diff --git a/util/posix/close_multiple.cc b/util/posix/close_multiple.cc index 172a8f02..908febf3 100644 --- a/util/posix/close_multiple.cc +++ b/util/posix/close_multiple.cc @@ -24,7 +24,6 @@ #include #include -#include #include "base/files/scoped_file.h" #include "base/logging.h" @@ -32,6 +31,7 @@ #include "build/build_config.h" #include "util/misc/implicit_cast.h" #include "util/numeric/safe_assignment.h" +#include "util/posix/scoped_dir.h" #if defined(OS_MACOSX) #include @@ -69,18 +69,6 @@ void CloseNowOrOnExec(int fd, bool ebadf_ok) { } } -struct ScopedDIRCloser { - void operator()(DIR* dir) const { - if (dir) { - if (closedir(dir) < 0) { - PLOG(ERROR) << "closedir"; - } - } - } -}; - -using ScopedDIR = std::unique_ptr; - // This function implements CloseMultipleNowOrOnExec() using an operating // system-specific FD directory to determine which file descriptors are open. // This is an advantage over looping over all possible file descriptors, because @@ -179,7 +167,7 @@ void CloseMultipleNowOrOnExec(int fd, int preserve_fd) { max_fd = std::max(max_fd, getdtablesize()); #endif -#if !defined(OS_LINUX) || defined(OPEN_MAX) +#if !(defined(OS_LINUX) || defined(OS_ANDROID)) || defined(OPEN_MAX) // Linux does not provide OPEN_MAX. See // https://git.kernel.org/cgit/linux/kernel/git/stable/linux-stable.git/commit/include/linux/limits.h?id=77293034696e3e0b6c8b8fc1f96be091104b3d2b. max_fd = std::max(max_fd, OPEN_MAX); diff --git a/util/posix/process_info_linux.cc b/util/posix/process_info_linux.cc index bd4202a8..60b7b7f8 100644 --- a/util/posix/process_info_linux.cc +++ b/util/posix/process_info_linux.cc @@ -21,7 +21,6 @@ #include #include #include -#include #include #include @@ -33,6 +32,7 @@ #include "base/strings/string_piece.h" #include "util/file/delimited_file_reader.h" #include "util/file/file_reader.h" +#include "util/linux/scoped_ptrace_attach.h" namespace crashpad { @@ -107,21 +107,6 @@ void TimespecToTimeval(const timespec& ts, timeval* tv) { tv->tv_usec = ts.tv_nsec / 1000; } -class ScopedPtraceDetach { - public: - explicit ScopedPtraceDetach(pid_t pid) : pid_(pid) {} - ~ScopedPtraceDetach() { - if (ptrace(PTRACE_DETACH, pid_, nullptr, nullptr) != 0) { - PLOG(ERROR) << "ptrace"; - } - } - - private: - pid_t pid_; - - DISALLOW_COPY_AND_ASSIGN(ScopedPtraceDetach); -}; - } // namespace ProcessInfo::ProcessInfo() @@ -224,12 +209,15 @@ bool ProcessInfo::Initialize(pid_t pid) { LOG(ERROR) << "format error: multiple Groups lines"; return false; } - gid_t group; - while (AdvancePastNumber(&line_c, &group)) { - supplementary_groups_.insert(group); - if (!AdvancePastPrefix(&line_c, " ")) { - LOG(ERROR) << "format error: unrecognized Groups format"; - return false; + if (!AdvancePastPrefix(&line_c, " ")) { + // In Linux 4.10, even an empty Groups: line has a trailing space. + gid_t group; + while (AdvancePastNumber(&line_c, &group)) { + supplementary_groups_.insert(group); + if (!AdvancePastPrefix(&line_c, " ")) { + LOG(ERROR) << "format error: unrecognized Groups format"; + return false; + } } } have_groups = true; @@ -330,15 +318,8 @@ bool ProcessInfo::Is64Bit(bool* is_64_bit) const { if (pid_ == getpid()) { is_64_bit_ = am_64_bit; } else { - if (ptrace(PTRACE_ATTACH, pid_, nullptr, nullptr) != 0) { - PLOG(ERROR) << "ptrace"; - return false; - } - - ScopedPtraceDetach ptrace_detach(pid_); - - if (HANDLE_EINTR(waitpid(pid_, nullptr, __WALL)) < 0) { - PLOG(ERROR) << "waitpid"; + ScopedPtraceAttach ptrace_attach; + if (!ptrace_attach.ResetAttach(pid_)) { return false; } diff --git a/util/posix/process_info_test.cc b/util/posix/process_info_test.cc index 6a1a132b..819bb549 100644 --- a/util/posix/process_info_test.cc +++ b/util/posix/process_info_test.cc @@ -14,9 +14,7 @@ #include "util/posix/process_info.h" -#include #include -#include #include #include @@ -28,6 +26,8 @@ #include "gtest/gtest.h" #include "test/errors.h" #include "test/main_arguments.h" +#include "test/multiprocess.h" +#include "util/file/file_io.h" #include "util/misc/implicit_cast.h" namespace crashpad { @@ -38,16 +38,16 @@ void TestProcessSelfOrClone(const ProcessInfo& process_info) { // There’s no system call to obtain the saved set-user ID or saved set-group // ID in an easy way. Normally, they are the same as the effective user ID and // effective group ID, so just check against those. - EXPECT_EQ(getuid(), process_info.RealUserID()); + EXPECT_EQ(process_info.RealUserID(), getuid()); const uid_t euid = geteuid(); - EXPECT_EQ(euid, process_info.EffectiveUserID()); - EXPECT_EQ(euid, process_info.SavedUserID()); + EXPECT_EQ(process_info.EffectiveUserID(), euid); + EXPECT_EQ(process_info.SavedUserID(), euid); const gid_t gid = getgid(); - EXPECT_EQ(gid, process_info.RealGroupID()); + EXPECT_EQ(process_info.RealGroupID(), gid); const gid_t egid = getegid(); - EXPECT_EQ(egid, process_info.EffectiveGroupID()); - EXPECT_EQ(egid, process_info.SavedGroupID()); + EXPECT_EQ(process_info.EffectiveGroupID(), egid); + EXPECT_EQ(process_info.SavedGroupID(), egid); // Test SupplementaryGroups(). int group_count = getgroups(0, nullptr); @@ -57,11 +57,11 @@ void TestProcessSelfOrClone(const ProcessInfo& process_info) { if (group_count > 0) { group_count = getgroups(group_vector.size(), &group_vector[0]); ASSERT_GE(group_count, 0) << ErrnoMessage("getgroups"); - ASSERT_EQ(group_vector.size(), implicit_cast(group_count)); + ASSERT_EQ(implicit_cast(group_count), group_vector.size()); } std::set group_set(group_vector.begin(), group_vector.end()); - EXPECT_EQ(group_set, process_info.SupplementaryGroups()); + EXPECT_EQ(process_info.SupplementaryGroups(), group_set); // Test AllGroups(), which is SupplementaryGroups() plus the real, effective, // and saved set-group IDs. The effective and saved set-group IDs are expected @@ -69,7 +69,7 @@ void TestProcessSelfOrClone(const ProcessInfo& process_info) { group_set.insert(gid); group_set.insert(egid); - EXPECT_EQ(group_set, process_info.AllGroups()); + EXPECT_EQ(process_info.AllGroups(), group_set); // The test executable isn’t expected to change privileges. EXPECT_FALSE(process_info.DidChangePrivileges()); @@ -104,7 +104,7 @@ void TestProcessSelfOrClone(const ProcessInfo& process_info) { // directly. ASSERT_FALSE(expect_argv.empty()); ASSERT_FALSE(argv.empty()); - EXPECT_EQ(expect_argv[0], argv[0]); + EXPECT_EQ(argv[0], expect_argv[0]); EXPECT_LE(argv.size(), expect_argv.size()); @@ -119,8 +119,8 @@ void TestProcessSelfOrClone(const ProcessInfo& process_info) { } void TestSelfProcess(const ProcessInfo& process_info) { - EXPECT_EQ(getpid(), process_info.ProcessID()); - EXPECT_EQ(getppid(), process_info.ParentProcessID()); + EXPECT_EQ(process_info.ProcessID(), getpid()); + EXPECT_EQ(process_info.ParentProcessID(), getppid()); TestProcessSelfOrClone(process_info); } @@ -145,33 +145,47 @@ TEST(ProcessInfo, Pid1) { ProcessInfo process_info; ASSERT_TRUE(process_info.Initialize(1)); - EXPECT_EQ(implicit_cast(1), process_info.ProcessID()); - EXPECT_EQ(implicit_cast(0), process_info.ParentProcessID()); - EXPECT_EQ(implicit_cast(0), process_info.RealUserID()); - EXPECT_EQ(implicit_cast(0), process_info.EffectiveUserID()); - EXPECT_EQ(implicit_cast(0), process_info.SavedUserID()); - EXPECT_EQ(implicit_cast(0), process_info.RealGroupID()); - EXPECT_EQ(implicit_cast(0), process_info.EffectiveGroupID()); - EXPECT_EQ(implicit_cast(0), process_info.SavedGroupID()); + EXPECT_EQ(process_info.ProcessID(), implicit_cast(1)); + EXPECT_EQ(process_info.ParentProcessID(), implicit_cast(0)); + EXPECT_EQ(process_info.RealUserID(), implicit_cast(0)); + EXPECT_EQ(process_info.EffectiveUserID(), implicit_cast(0)); + EXPECT_EQ(process_info.SavedUserID(), implicit_cast(0)); + EXPECT_EQ(process_info.RealGroupID(), implicit_cast(0)); + EXPECT_EQ(process_info.EffectiveGroupID(), implicit_cast(0)); + EXPECT_EQ(process_info.SavedGroupID(), implicit_cast(0)); EXPECT_FALSE(process_info.AllGroups().empty()); } -TEST(ProcessInfo, Forked) { - pid_t pid = fork(); - if (pid == 0) { - raise(SIGSTOP); - _exit(0); +class ProcessInfoForkedTest : public Multiprocess { + public: + ProcessInfoForkedTest() : Multiprocess() {} + ~ProcessInfoForkedTest() {} + + // Multiprocess: + void MultiprocessParent() override { + const pid_t pid = ChildPID(); + + ProcessInfo process_info; + ASSERT_TRUE(process_info.Initialize(pid)); + + EXPECT_EQ(process_info.ProcessID(), pid); + EXPECT_EQ(process_info.ParentProcessID(), getpid()); + + TestProcessSelfOrClone(process_info); } - ASSERT_GE(pid, 0) << ErrnoMessage("fork"); - ProcessInfo process_info; - ASSERT_TRUE(process_info.Initialize(pid)); + void MultiprocessChild() override { + // Hang around until the parent is done. + CheckedReadFileAtEOF(ReadPipeHandle()); + } - EXPECT_EQ(pid, process_info.ProcessID()); - EXPECT_EQ(getpid(), process_info.ParentProcessID()); + private: + DISALLOW_COPY_AND_ASSIGN(ProcessInfoForkedTest); +}; - TestProcessSelfOrClone(process_info); - kill(pid, SIGKILL); +TEST(ProcessInfo, Forked) { + ProcessInfoForkedTest test; + test.Run(); } } // namespace diff --git a/util/posix/scoped_dir.cc b/util/posix/scoped_dir.cc new file mode 100644 index 00000000..555900a3 --- /dev/null +++ b/util/posix/scoped_dir.cc @@ -0,0 +1,30 @@ +// Copyright 2017 The Crashpad Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "util/posix/scoped_dir.h" + +#include "base/logging.h" +#include "base/posix/eintr_wrapper.h" + +namespace crashpad { +namespace internal { + +void ScopedDIRCloser::operator()(DIR* dir) const { + if (dir && IGNORE_EINTR(closedir(dir)) != 0) { + PLOG(ERROR) << "closedir"; + } +} + +} // namespace internal +} // namespace crashpad diff --git a/util/posix/scoped_dir.h b/util/posix/scoped_dir.h new file mode 100644 index 00000000..2eade40e --- /dev/null +++ b/util/posix/scoped_dir.h @@ -0,0 +1,38 @@ +// Copyright 2017 The Crashpad Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef CRASHPAD_UTIL_POSIX_SCOPED_DIR_H_ +#define CRASHPAD_UTIL_POSIX_SCOPED_DIR_H_ + +#include + +#include + +namespace crashpad { +namespace internal { + +struct ScopedDIRCloser { + void operator()(DIR* dir) const; +}; + +} // namespace internal + +//! \brief Maintains a directory opened by `opendir`. +//! +//! On destruction, the directory will be closed by calling `closedir`. +using ScopedDIR = std::unique_ptr; + +} // namespace crashpad + +#endif // CRASHPAD_UTIL_POSIX_SCOPED_DIR_H_ diff --git a/util/posix/scoped_mmap.cc b/util/posix/scoped_mmap.cc new file mode 100644 index 00000000..4860cecb --- /dev/null +++ b/util/posix/scoped_mmap.cc @@ -0,0 +1,115 @@ +// Copyright 2017 The Crashpad Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "util/posix/scoped_mmap.h" + +#include + +#include + +#include "base/logging.h" +#include "base/numerics/safe_math.h" + +namespace { + +bool Munmap(uintptr_t addr, size_t len) { + if (munmap(reinterpret_cast(addr), len) != 0) { + PLOG(ERROR) << "munmap"; + return false; + } + + return true; +} + +} // namespace + +namespace crashpad { + +ScopedMmap::ScopedMmap() {} + +ScopedMmap::~ScopedMmap() { + if (is_valid()) { + Munmap(reinterpret_cast(addr_), len_); + } +} + +bool ScopedMmap::Reset() { + return ResetAddrLen(MAP_FAILED, 0); +} + +bool ScopedMmap::ResetAddrLen(void* addr, size_t len) { + const uintptr_t new_addr = reinterpret_cast(addr); + + if (addr == MAP_FAILED) { + DCHECK_EQ(len, 0u); + } else { + DCHECK_NE(len, 0u); + DCHECK_EQ(new_addr % getpagesize(), 0u); + DCHECK_EQ(len % getpagesize(), 0u); + DCHECK((base::CheckedNumeric(new_addr) + (len - 1)).IsValid()); + } + + bool result = true; + + if (is_valid()) { + const uintptr_t old_addr = reinterpret_cast(addr_); + if (old_addr < new_addr) { + result &= Munmap(old_addr, std::min(len_, new_addr - old_addr)); + } + if (old_addr + len_ > new_addr + len) { + uintptr_t unmap_start = std::max(old_addr, new_addr + len); + result &= Munmap(unmap_start, old_addr + len_ - unmap_start); + } + } + + addr_ = addr; + len_ = len; + + return result; +} + +bool ScopedMmap::ResetMmap(void* addr, + size_t len, + int prot, + int flags, + int fd, + off_t offset) { + // Reset() first, so that a new anonymous mapping can use the address space + // occupied by the old mapping if appropriate. The new mapping will be + // attempted even if there was something wrong with the old mapping, so don’t + // consider the return value from Reset(). + Reset(); + + void* new_addr = mmap(addr, len, prot, flags, fd, offset); + if (new_addr == MAP_FAILED) { + PLOG(ERROR) << "mmap"; + return false; + } + + // The new mapping is effective even if there was something wrong with the old + // mapping, so don’t consider the return value from ResetAddrLen(). + ResetAddrLen(new_addr, len); + return true; +} + +bool ScopedMmap::Mprotect(int prot) { + if (mprotect(addr_, len_, prot) < 0) { + PLOG(ERROR) << "mprotect"; + return false; + } + + return true; +} + +} // namespace crashpad diff --git a/util/posix/scoped_mmap.h b/util/posix/scoped_mmap.h new file mode 100644 index 00000000..5b216dee --- /dev/null +++ b/util/posix/scoped_mmap.h @@ -0,0 +1,103 @@ +// Copyright 2017 The Crashpad Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef CRASHPAD_UTIL_POSIX_SCOPED_MMAP_H_ +#define CRASHPAD_UTIL_POSIX_SCOPED_MMAP_H_ + +#include "base/macros.h" + +#include +#include + +namespace crashpad { + +//! \brief Maintains a memory-mapped region created by `mmap()`. +//! +//! On destruction, any memory-mapped region managed by an object of this class +//! will be released by calling `munmap()`. +class ScopedMmap { + public: + ScopedMmap(); + ~ScopedMmap(); + + //! \brief Releases the memory-mapped region by calling `munmap()`. + //! + //! \return `true` on success. `false` on failure, with a message logged. + bool Reset(); + + //! \brief Releases any existing memory-mapped region and sets the object to + //! maintain an already-established mapping. + //! + //! If \a addr and \a len indicate a region that overlaps with the existing + //! memory-mapped region, only the portion of the existing memory-mapped + //! region that does not overlap the new region, if any, will be released. + //! + //! \param[in] addr The base address of the existing memory-mapped region to + //! maintain. + //! \param[in] len The size of the existing memory-mapped region to maintain. + //! + //! \return `true` on success. `false` on failure, with a message logged. + bool ResetAddrLen(void* addr, size_t len); + + //! \brief Releases any existing memory-mapped region and establishes a new + //! one by calling `mmap()`. + //! + //! The parameters to this method are passed directly to `mmap()`. + //! + //! \return `true` on success. `false` on failure, with a message logged. A + //! message will also be logged on failure to release any existing + //! memory-mapped region, but this will not preclude `mmap()` from being + //! called or a new mapping from being established, and if such a call to + //! `mmap()` is successful, this method will return `true`. + bool ResetMmap(void* addr, + size_t len, + int prot, + int flags, + int fd, + off_t offset); + + //! \brief Sets the protection of the memory-mapped region by calling + //! `mprotect()`. + //! + //! \a prot is passed directly to `mprotect()`. + //! + //! \return `true` on success. `false` on failure, with a message logged. + bool Mprotect(int prot); + + //! \return Whether this object is managing a valid memory-mapped region. + bool is_valid() const { return addr_ != MAP_FAILED; } + + //! \brief Returns the base address of the memory-mapped region. + void* addr() const { return addr_; } + + //! \brief Returns the base address of the memory-mapped region, casted to + //! a type of the caller’s choosing. + template + T addr_as() const { + return reinterpret_cast(addr_); + } + + //! \brief Returns the size of the memory-mapped region. + size_t len() const { return len_; } + + private: + void* addr_ = MAP_FAILED; + size_t len_ = 0; + + DISALLOW_COPY_AND_ASSIGN(ScopedMmap); +}; + +} // namespace crashpad + +#endif // CRASHPAD_UTIL_POSIX_SCOPED_MMAP_H_ diff --git a/util/posix/scoped_mmap_test.cc b/util/posix/scoped_mmap_test.cc new file mode 100644 index 00000000..33807295 --- /dev/null +++ b/util/posix/scoped_mmap_test.cc @@ -0,0 +1,318 @@ +// Copyright 2017 The Crashpad Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "util/posix/scoped_mmap.h" + +#include +#include +#include + +#include "base/numerics/safe_conversions.h" +#include "base/rand_util.h" +#include "base/strings/stringprintf.h" +#include "gtest/gtest.h" + +namespace crashpad { +namespace test { +namespace { + +bool ScopedMmapResetMmap(ScopedMmap* mapping, size_t len) { + return mapping->ResetMmap( + nullptr, len, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); +} + +void* BareMmap(size_t len) { + return mmap( + nullptr, len, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); +} + +// A weird class. This is used to test that memory-mapped regions are freed +// as expected by calling munmap(). This is difficult to test well because once +// a region has been unmapped, the address space it formerly occupied becomes +// eligible for reuse. +// +// The strategy taken here is that a random 64-bit cookie value is written into +// a mapped region by SetUp(). While the mapping is active, Check() should not +// crash, or for a gtest expectation, Expected() and Observed() should not crash +// and should be equal. After the region is unmapped, Check() should crash, +// either because the region has been unmapped and the address not reused, the +// address has been reused but is protected against reading (unlikely), or +// because the address has been reused but the cookie value is no longer present +// there. +class TestCookie { + public: + // A weird constructor for a weird class. The member variable initialization + // assures that Check() won’t crash if called on an object that hasn’t had + // SetUp() called on it. + explicit TestCookie() : address_(&cookie_), cookie_(0) {} + + ~TestCookie() {} + + void SetUp(uint64_t* address) { + address_ = address, cookie_ = base::RandUint64(); + *address_ = cookie_; + } + + uint64_t Expected() const { return cookie_; } + uint64_t Observed() const { return *address_; } + + void Check() const { + if (Observed() != Expected()) { + __builtin_trap(); + } + } + + private: + uint64_t* address_; + uint64_t cookie_; + + DISALLOW_COPY_AND_ASSIGN(TestCookie); +}; + +TEST(ScopedMmap, Mmap) { + TestCookie cookie; + + ScopedMmap mapping; + EXPECT_FALSE(mapping.is_valid()); + EXPECT_EQ(mapping.addr(), MAP_FAILED); + EXPECT_EQ(mapping.len(), 0u); + + ASSERT_TRUE(mapping.Reset()); + EXPECT_FALSE(mapping.is_valid()); + + const size_t kPageSize = base::checked_cast(getpagesize()); + ASSERT_TRUE(ScopedMmapResetMmap(&mapping, kPageSize)); + EXPECT_TRUE(mapping.is_valid()); + EXPECT_NE(mapping.addr(), MAP_FAILED); + EXPECT_EQ(mapping.len(), kPageSize); + + cookie.SetUp(mapping.addr_as()); + EXPECT_EQ(cookie.Observed(), cookie.Expected()); + + ASSERT_TRUE(mapping.Reset()); + EXPECT_FALSE(mapping.is_valid()); +} + +TEST(ScopedMmapDeathTest, Destructor) { + TestCookie cookie; + { + ScopedMmap mapping; + + const size_t kPageSize = base::checked_cast(getpagesize()); + ASSERT_TRUE(ScopedMmapResetMmap(&mapping, kPageSize)); + EXPECT_TRUE(mapping.is_valid()); + EXPECT_NE(mapping.addr(), MAP_FAILED); + EXPECT_EQ(mapping.len(), kPageSize); + + cookie.SetUp(mapping.addr_as()); + } + + EXPECT_DEATH(cookie.Check(), ""); +} + +TEST(ScopedMmapDeathTest, Reset) { + ScopedMmap mapping; + + const size_t kPageSize = base::checked_cast(getpagesize()); + ASSERT_TRUE(ScopedMmapResetMmap(&mapping, kPageSize)); + EXPECT_TRUE(mapping.is_valid()); + EXPECT_NE(mapping.addr(), MAP_FAILED); + EXPECT_EQ(mapping.len(), kPageSize); + + TestCookie cookie; + cookie.SetUp(mapping.addr_as()); + + ASSERT_TRUE(mapping.Reset()); + + EXPECT_DEATH(cookie.Check(), ""); +} + +TEST(ScopedMmapDeathTest, ResetAddrLen_Shrink) { + ScopedMmap mapping; + + // Start with three pages mapped. + const size_t kPageSize = base::checked_cast(getpagesize()); + ASSERT_TRUE(ScopedMmapResetMmap(&mapping, 3 * kPageSize)); + EXPECT_TRUE(mapping.is_valid()); + EXPECT_NE(mapping.addr(), MAP_FAILED); + EXPECT_EQ(mapping.len(), 3 * kPageSize); + + TestCookie cookies[3]; + for (size_t index = 0; index < arraysize(cookies); ++index) { + cookies[index].SetUp(reinterpret_cast( + mapping.addr_as() + index * kPageSize)); + } + + // Reset to the second page. The first and third pages should be unmapped. + void* const new_addr = + reinterpret_cast(mapping.addr_as() + kPageSize); + ASSERT_TRUE(mapping.ResetAddrLen(new_addr, kPageSize)); + EXPECT_TRUE(mapping.is_valid()); + EXPECT_EQ(mapping.addr(), new_addr); + EXPECT_EQ(mapping.len(), kPageSize); + + EXPECT_EQ(cookies[1].Observed(), cookies[1].Expected()); + + EXPECT_DEATH(cookies[0].Check(), ""); + EXPECT_DEATH(cookies[2].Check(), ""); +} + +TEST(ScopedMmap, ResetAddrLen_Grow) { + // Start with three pages mapped, but ScopedMmap only aware of the the second + // page. + const size_t kPageSize = base::checked_cast(getpagesize()); + void* pages = BareMmap(3 * kPageSize); + ASSERT_NE(pages, MAP_FAILED); + + ScopedMmap mapping; + void* const old_addr = + reinterpret_cast(reinterpret_cast(pages) + kPageSize); + ASSERT_TRUE(mapping.ResetAddrLen(old_addr, kPageSize)); + EXPECT_TRUE(mapping.is_valid()); + EXPECT_EQ(mapping.addr(), old_addr); + EXPECT_EQ(mapping.len(), kPageSize); + + TestCookie cookies[3]; + for (size_t index = 0; index < arraysize(cookies); ++index) { + cookies[index].SetUp(reinterpret_cast( + reinterpret_cast(pages) + index * kPageSize)); + } + + // Reset to all three pages. Nothing should be unmapped until destruction. + ASSERT_TRUE(mapping.ResetAddrLen(pages, 3 * kPageSize)); + EXPECT_TRUE(mapping.is_valid()); + EXPECT_EQ(mapping.addr(), pages); + EXPECT_EQ(mapping.len(), 3 * kPageSize); + + for (size_t index = 0; index < arraysize(cookies); ++index) { + SCOPED_TRACE(base::StringPrintf("index %zu", index)); + EXPECT_EQ(cookies[index].Observed(), cookies[index].Expected()); + } +} + +TEST(ScopedMmapDeathTest, ResetAddrLen_MoveDownAndGrow) { + // Start with three pages mapped, but ScopedMmap only aware of the third page. + const size_t kPageSize = base::checked_cast(getpagesize()); + void* pages = BareMmap(3 * kPageSize); + ASSERT_NE(pages, MAP_FAILED); + + ScopedMmap mapping; + void* const old_addr = reinterpret_cast( + reinterpret_cast(pages) + 2 * kPageSize); + ASSERT_TRUE(mapping.ResetAddrLen(old_addr, kPageSize)); + EXPECT_TRUE(mapping.is_valid()); + EXPECT_EQ(mapping.addr(), old_addr); + EXPECT_EQ(mapping.len(), kPageSize); + + TestCookie cookies[3]; + for (size_t index = 0; index < arraysize(cookies); ++index) { + cookies[index].SetUp(reinterpret_cast( + reinterpret_cast(pages) + index * kPageSize)); + } + + // Reset to the first two pages. The third page should be unmapped. + ASSERT_TRUE(mapping.ResetAddrLen(pages, 2 * kPageSize)); + EXPECT_TRUE(mapping.is_valid()); + EXPECT_EQ(mapping.addr(), pages); + EXPECT_EQ(mapping.len(), 2 * kPageSize); + + EXPECT_EQ(cookies[0].Observed(), cookies[0].Expected()); + EXPECT_EQ(cookies[1].Observed(), cookies[1].Expected()); + + EXPECT_DEATH(cookies[2].Check(), ""); +} + +TEST(ScopedMmapDeathTest, ResetAddrLen_MoveUpAndShrink) { + // Start with three pages mapped, but ScopedMmap only aware of the first two + // pages. + const size_t kPageSize = base::checked_cast(getpagesize()); + void* pages = BareMmap(3 * kPageSize); + ASSERT_NE(pages, MAP_FAILED); + + ScopedMmap mapping; + ASSERT_TRUE(mapping.ResetAddrLen(pages, 2 * kPageSize)); + EXPECT_TRUE(mapping.is_valid()); + EXPECT_EQ(mapping.addr(), pages); + EXPECT_EQ(mapping.len(), 2 * kPageSize); + + TestCookie cookies[3]; + for (size_t index = 0; index < arraysize(cookies); ++index) { + cookies[index].SetUp(reinterpret_cast( + reinterpret_cast(pages) + index * kPageSize)); + } + + // Reset to the third page. The first two pages should be unmapped. + void* const new_addr = + reinterpret_cast(mapping.addr_as() + 2 * kPageSize); + ASSERT_TRUE(mapping.ResetAddrLen(new_addr, kPageSize)); + EXPECT_TRUE(mapping.is_valid()); + EXPECT_EQ(mapping.addr(), new_addr); + EXPECT_EQ(mapping.len(), kPageSize); + + EXPECT_EQ(cookies[2].Observed(), cookies[2].Expected()); + + EXPECT_DEATH(cookies[0].Check(), ""); + EXPECT_DEATH(cookies[1].Check(), ""); +} + +TEST(ScopedMmapDeathTest, ResetMmap) { + ScopedMmap mapping; + + // Calling ScopedMmap::ResetMmap() frees the existing mapping before + // establishing the new one, so the new one may wind up at the same address as + // the old. In fact, this is likely. Create a two-page mapping and replace it + // with a single-page mapping, so that the test can assure that the second + // page isn’t mapped after establishing the second mapping. + const size_t kPageSize = base::checked_cast(getpagesize()); + ASSERT_TRUE(ScopedMmapResetMmap(&mapping, 2 * kPageSize)); + EXPECT_TRUE(mapping.is_valid()); + EXPECT_NE(mapping.addr(), MAP_FAILED); + EXPECT_EQ(mapping.len(), 2 * kPageSize); + + TestCookie cookie; + cookie.SetUp( + reinterpret_cast(mapping.addr_as() + kPageSize)); + + ASSERT_TRUE(ScopedMmapResetMmap(&mapping, kPageSize)); + EXPECT_TRUE(mapping.is_valid()); + EXPECT_NE(mapping.addr(), MAP_FAILED); + EXPECT_EQ(mapping.len(), kPageSize); + + EXPECT_DEATH(cookie.Check(), ""); +} + +TEST(ScopedMmapDeathTest, Mprotect) { + ScopedMmap mapping; + + const size_t kPageSize = base::checked_cast(getpagesize()); + ASSERT_TRUE(ScopedMmapResetMmap(&mapping, kPageSize)); + EXPECT_TRUE(mapping.is_valid()); + EXPECT_NE(mapping.addr(), MAP_FAILED); + EXPECT_EQ(mapping.len(), kPageSize); + + char* addr = mapping.addr_as(); + *addr = 1; + + ASSERT_TRUE(mapping.Mprotect(PROT_READ)); + + EXPECT_DEATH(*addr = 0, ""); + + ASSERT_TRUE(mapping.Mprotect(PROT_READ | PROT_WRITE)); + EXPECT_EQ(*addr, 1); + *addr = 2; +} + +} // namespace +} // namespace test +} // namespace crashpad diff --git a/util/posix/signals_test.cc b/util/posix/signals_test.cc index 7d4fb756..5fce38cc 100644 --- a/util/posix/signals_test.cc +++ b/util/posix/signals_test.cc @@ -17,7 +17,6 @@ #include #include #include -#include #include #include #include @@ -33,6 +32,7 @@ #include "test/errors.h" #include "test/multiprocess.h" #include "test/scoped_temp_dir.h" +#include "util/posix/scoped_mmap.h" namespace crashpad { namespace test { @@ -84,7 +84,7 @@ void CauseSignal(int sig) { } case SIGBUS: { - char* mapped; + ScopedMmap mapped_file; { base::ScopedFD fd; { @@ -100,21 +100,17 @@ void CauseSignal(int sig) { _exit(kUnexpectedExitStatus); } - mapped = reinterpret_cast(mmap(nullptr, - getpagesize(), - PROT_READ | PROT_WRITE, - MAP_PRIVATE, - fd.get(), - 0)); - if (mapped == MAP_FAILED) { - PLOG(ERROR) << "mmap"; + if (!mapped_file.ResetMmap(nullptr, + getpagesize(), + PROT_READ | PROT_WRITE, + MAP_PRIVATE, + fd.get(), + 0)) { + _exit(kUnexpectedExitStatus); } } - if (mapped == MAP_FAILED) { - _exit(kUnexpectedExitStatus); - } - *mapped = 0; + *mapped_file.addr_as() = 0; _exit(kUnexpectedExitStatus); break; @@ -276,7 +272,7 @@ class SignalsTest : public Multiprocess { sigemptyset(&action.sa_mask); action.sa_flags = 0; action.sa_handler = SIG_DFL; - ASSERT_EQ(0, sigaction(sig_, &action, nullptr)) + ASSERT_EQ(sigaction(sig_, &action, nullptr), 0) << ErrnoMessage("sigaction"); break; } @@ -351,8 +347,8 @@ TEST(Signals, WillSignalReraiseAutonomously) { siginfo_t siginfo = {}; siginfo.si_signo = test_data.sig; siginfo.si_code = test_data.code; - EXPECT_EQ(test_data.result, - Signals::WillSignalReraiseAutonomously(&siginfo)); + EXPECT_EQ(Signals::WillSignalReraiseAutonomously(&siginfo), + test_data.result); } } diff --git a/util/posix/symbolic_constants_posix_test.cc b/util/posix/symbolic_constants_posix_test.cc index ddbe336e..9cb29b58 100644 --- a/util/posix/symbolic_constants_posix_test.cc +++ b/util/posix/symbolic_constants_posix_test.cc @@ -88,9 +88,9 @@ void TestSignalToStringOnce(int value, if (expect[0] == '\0') { EXPECT_FALSE(actual.empty()) << "signal " << value; } else { - EXPECT_EQ(expect, actual) << "signal " << value; + EXPECT_EQ(actual, expect) << "signal " << value; } - EXPECT_EQ(actual, actual_numeric) << "signal " << value; + EXPECT_EQ(actual_numeric, actual) << "signal " << value; } else { EXPECT_TRUE(actual.empty()) << "signal " << value << ", actual " << actual; EXPECT_FALSE(actual_numeric.empty()) @@ -147,7 +147,7 @@ void TestStringToSignal(const base::StringPiece& string, EXPECT_TRUE(actual_result) << "string " << string << ", options " << options << ", signal " << expect_value; if (actual_result) { - EXPECT_EQ(expect_value, actual_value) << "string " << string + EXPECT_EQ(actual_value, expect_value) << "string " << string << ", options " << options; } } else { diff --git a/util/stdlib/aligned_allocator_test.cc b/util/stdlib/aligned_allocator_test.cc index fe3b9e65..66ee6e6c 100644 --- a/util/stdlib/aligned_allocator_test.cc +++ b/util/stdlib/aligned_allocator_test.cc @@ -54,7 +54,7 @@ TEST(AlignedAllocator, AlignedVector) { struct ALIGNAS(32) AlignedStruct { int i; }; - ASSERT_EQ(32u, ALIGNOF(AlignedStruct)); + ASSERT_EQ(ALIGNOF(AlignedStruct), 32u); AlignedVector aligned_vector; aligned_vector.push_back(AlignedStruct()); @@ -76,7 +76,7 @@ TEST(AlignedAllocator, AlignedVector) { struct ALIGNAS(1024) BigAlignedStruct { int i; }; - ASSERT_EQ(1024u, ALIGNOF(BigAlignedStruct)); + ASSERT_EQ(ALIGNOF(BigAlignedStruct), 1024u); AlignedVector big_aligned_vector; big_aligned_vector.push_back(BigAlignedStruct()); diff --git a/util/stdlib/map_insert_test.cc b/util/stdlib/map_insert_test.cc index d3197b96..9dab8437 100644 --- a/util/stdlib/map_insert_test.cc +++ b/util/stdlib/map_insert_test.cc @@ -28,25 +28,25 @@ TEST(MapInsert, MapInsertOrReplace) { EXPECT_TRUE(MapInsertOrReplace(&map, "key", 1, &old_value)); std::map expect_map; expect_map["key"] = 1; - EXPECT_EQ(expect_map, map); + EXPECT_EQ(map, expect_map); EXPECT_FALSE(MapInsertOrReplace(&map, "key", 2, &old_value)); - EXPECT_EQ(1, old_value); + EXPECT_EQ(old_value, 1); expect_map["key"] = 2; - EXPECT_EQ(expect_map, map); + EXPECT_EQ(map, expect_map); EXPECT_TRUE(MapInsertOrReplace(&map, "another", 3, &old_value)); expect_map["another"] = 3; - EXPECT_EQ(expect_map, map); + EXPECT_EQ(map, expect_map); // Make sure nullptr is accepted as old_value. EXPECT_TRUE(MapInsertOrReplace(&map, "yet another", 5, nullptr)); expect_map["yet another"] = 5; - EXPECT_EQ(expect_map, map); + EXPECT_EQ(map, expect_map); EXPECT_FALSE(MapInsertOrReplace(&map, "yet another", 6, nullptr)); expect_map["yet another"] = 6; - EXPECT_EQ(expect_map, map); + EXPECT_EQ(map, expect_map); } } // namespace diff --git a/util/stdlib/string_number_conversion_test.cc b/util/stdlib/string_number_conversion_test.cc index c455a38d..f6634d0f 100644 --- a/util/stdlib/string_number_conversion_test.cc +++ b/util/stdlib/string_number_conversion_test.cc @@ -101,7 +101,7 @@ TEST(StringNumberConversion, StringToInt) { EXPECT_TRUE(valid) << "index " << index << ", string " << kTestData[index].string; if (valid) { - EXPECT_EQ(kTestData[index].value, value) + EXPECT_EQ(value, kTestData[index].value) << "index " << index << ", string " << kTestData[index].string; } } else { @@ -120,7 +120,7 @@ TEST(StringNumberConversion, StringToInt) { // Ensure that a NUL is not required at the end of the string. EXPECT_TRUE(StringToNumber(base::StringPiece("66", 1), &output)); - EXPECT_EQ(6, output); + EXPECT_EQ(output, 6); } TEST(StringNumberConversion, StringToUnsignedInt) { @@ -199,7 +199,7 @@ TEST(StringNumberConversion, StringToUnsignedInt) { EXPECT_TRUE(valid) << "index " << index << ", string " << kTestData[index].string; if (valid) { - EXPECT_EQ(kTestData[index].value, value) + EXPECT_EQ(value, kTestData[index].value) << "index " << index << ", string " << kTestData[index].string; } } else { @@ -218,7 +218,7 @@ TEST(StringNumberConversion, StringToUnsignedInt) { // Ensure that a NUL is not required at the end of the string. EXPECT_TRUE(StringToNumber(base::StringPiece("66", 1), &output)); - EXPECT_EQ(6u, output); + EXPECT_EQ(output, 6u); } TEST(StringNumberConversion, StringToInt64) { @@ -260,7 +260,7 @@ TEST(StringNumberConversion, StringToInt64) { EXPECT_TRUE(valid) << "index " << index << ", string " << kTestData[index].string; if (valid) { - EXPECT_EQ(kTestData[index].value, value) + EXPECT_EQ(value, kTestData[index].value) << "index " << index << ", string " << kTestData[index].string; } } else { @@ -310,7 +310,7 @@ TEST(StringNumberConversion, StringToUnsignedInt64) { EXPECT_TRUE(valid) << "index " << index << ", string " << kTestData[index].string; if (valid) { - EXPECT_EQ(kTestData[index].value, value) + EXPECT_EQ(value, kTestData[index].value) << "index " << index << ", string " << kTestData[index].string; } } else { diff --git a/util/stdlib/strlcpy_test.cc b/util/stdlib/strlcpy_test.cc index cbc61c0f..57315c3b 100644 --- a/util/stdlib/strlcpy_test.cc +++ b/util/stdlib/strlcpy_test.cc @@ -55,18 +55,18 @@ TEST(strlcpy, c16lcpy) { TestBuffer destination; memset(&destination, 0xa5, sizeof(destination)); - EXPECT_EQ(length, - c16lcpy(destination.data, + EXPECT_EQ(c16lcpy(destination.data, test_string.c_str(), - arraysize(destination.data))); + arraysize(destination.data)), + length); // Make sure that the destination buffer is NUL-terminated, and that as // much of the test string was copied as could fit. size_t expected_destination_length = std::min(length, arraysize(destination.data) - 1); - EXPECT_EQ('\0', destination.data[expected_destination_length]); - EXPECT_EQ(expected_destination_length, base::c16len(destination.data)); + EXPECT_EQ(destination.data[expected_destination_length], '\0'); + EXPECT_EQ(base::c16len(destination.data), expected_destination_length); EXPECT_TRUE(base::c16memcmp(test_string.c_str(), destination.data, expected_destination_length) == 0); diff --git a/util/stdlib/strnlen_test.cc b/util/stdlib/strnlen_test.cc index 35ca7f1a..e030fdc8 100644 --- a/util/stdlib/strnlen_test.cc +++ b/util/stdlib/strnlen_test.cc @@ -24,20 +24,20 @@ namespace { TEST(strnlen, strnlen) { const char kTestBuffer[] = "abc\0d"; - ASSERT_EQ(3u, strlen(kTestBuffer)); - EXPECT_EQ(0u, crashpad::strnlen(kTestBuffer, 0)); - EXPECT_EQ(1u, crashpad::strnlen(kTestBuffer, 1)); - EXPECT_EQ(2u, crashpad::strnlen(kTestBuffer, 2)); - EXPECT_EQ(3u, crashpad::strnlen(kTestBuffer, 3)); - EXPECT_EQ(3u, crashpad::strnlen(kTestBuffer, 4)); - EXPECT_EQ(3u, crashpad::strnlen(kTestBuffer, 5)); - EXPECT_EQ(3u, crashpad::strnlen(kTestBuffer, 6)); + ASSERT_EQ(strlen(kTestBuffer), 3u); + EXPECT_EQ(crashpad::strnlen(kTestBuffer, 0), 0u); + EXPECT_EQ(crashpad::strnlen(kTestBuffer, 1), 1u); + EXPECT_EQ(crashpad::strnlen(kTestBuffer, 2), 2u); + EXPECT_EQ(crashpad::strnlen(kTestBuffer, 3), 3u); + EXPECT_EQ(crashpad::strnlen(kTestBuffer, 4), 3u); + EXPECT_EQ(crashpad::strnlen(kTestBuffer, 5), 3u); + EXPECT_EQ(crashpad::strnlen(kTestBuffer, 6), 3u); const char kEmptyBuffer[] = "\0"; - ASSERT_EQ(0u, strlen(kEmptyBuffer)); - EXPECT_EQ(0u, crashpad::strnlen(kEmptyBuffer, 0)); - EXPECT_EQ(0u, crashpad::strnlen(kEmptyBuffer, 1)); - EXPECT_EQ(0u, crashpad::strnlen(kEmptyBuffer, 2)); + ASSERT_EQ(strlen(kEmptyBuffer), 0u); + EXPECT_EQ(crashpad::strnlen(kEmptyBuffer, 0), 0u); + EXPECT_EQ(crashpad::strnlen(kEmptyBuffer, 1), 0u); + EXPECT_EQ(crashpad::strnlen(kEmptyBuffer, 2), 0u); } } // namespace diff --git a/util/string/split_string_test.cc b/util/string/split_string_test.cc index 2da5a2ad..a260ac1b 100644 --- a/util/string/split_string_test.cc +++ b/util/string/split_string_test.cc @@ -30,30 +30,30 @@ TEST(SplitString, SplitStringFirst) { EXPECT_FALSE(SplitStringFirst("=beginequals", '=', &left, &right)); ASSERT_TRUE(SplitStringFirst("a=b", '=', &left, &right)); - EXPECT_EQ("a", left); - EXPECT_EQ("b", right); + EXPECT_EQ(left, "a"); + EXPECT_EQ(right, "b"); ASSERT_TRUE(SplitStringFirst("EndsEquals=", '=', &left, &right)); - EXPECT_EQ("EndsEquals", left); + EXPECT_EQ(left, "EndsEquals"); EXPECT_TRUE(right.empty()); ASSERT_TRUE(SplitStringFirst("key=VALUE", '=', &left, &right)); - EXPECT_EQ("key", left); - EXPECT_EQ("VALUE", right); + EXPECT_EQ(left, "key"); + EXPECT_EQ(right, "VALUE"); EXPECT_FALSE(SplitStringFirst("a=b", '|', &left, &right)); ASSERT_TRUE(SplitStringFirst("ls | less", '|', &left, &right)); - EXPECT_EQ("ls ", left); - EXPECT_EQ(" less", right); + EXPECT_EQ(left, "ls "); + EXPECT_EQ(right, " less"); ASSERT_TRUE(SplitStringFirst("when in", ' ', &left, &right)); - EXPECT_EQ("when", left); - EXPECT_EQ("in", right); + EXPECT_EQ(left, "when"); + EXPECT_EQ(right, "in"); ASSERT_TRUE(SplitStringFirst("zoo", 'o', &left, &right)); - EXPECT_EQ("z", left); - EXPECT_EQ("o", right); + EXPECT_EQ(left, "z"); + EXPECT_EQ(right, "o"); ASSERT_FALSE(SplitStringFirst("ooze", 'o', &left, &right)); } @@ -62,32 +62,32 @@ TEST(SplitString, SplitString) { std::vector parts; parts = SplitString("", '.'); - EXPECT_EQ(0u, parts.size()); + EXPECT_EQ(parts.size(), 0u); parts = SplitString(".", '.'); - ASSERT_EQ(2u, parts.size()); - EXPECT_EQ("", parts[0]); - EXPECT_EQ("", parts[1]); + ASSERT_EQ(parts.size(), 2u); + EXPECT_EQ(parts[0], ""); + EXPECT_EQ(parts[1], ""); parts = SplitString("a,b", ','); - ASSERT_EQ(2u, parts.size()); - EXPECT_EQ("a", parts[0]); - EXPECT_EQ("b", parts[1]); + ASSERT_EQ(parts.size(), 2u); + EXPECT_EQ(parts[0], "a"); + EXPECT_EQ(parts[1], "b"); parts = SplitString("zoo", 'o'); - ASSERT_EQ(3u, parts.size()); - EXPECT_EQ("z", parts[0]); - EXPECT_EQ("", parts[1]); - EXPECT_EQ("", parts[2]); + ASSERT_EQ(parts.size(), 3u); + EXPECT_EQ(parts[0], "z"); + EXPECT_EQ(parts[1], ""); + EXPECT_EQ(parts[2], ""); parts = SplitString("0x100,0x200,0x300,0x400,0x500,0x600", ','); - ASSERT_EQ(6u, parts.size()); - EXPECT_EQ("0x100", parts[0]); - EXPECT_EQ("0x200", parts[1]); - EXPECT_EQ("0x300", parts[2]); - EXPECT_EQ("0x400", parts[3]); - EXPECT_EQ("0x500", parts[4]); - EXPECT_EQ("0x600", parts[5]); + ASSERT_EQ(parts.size(), 6u); + EXPECT_EQ(parts[0], "0x100"); + EXPECT_EQ(parts[1], "0x200"); + EXPECT_EQ(parts[2], "0x300"); + EXPECT_EQ(parts[3], "0x400"); + EXPECT_EQ(parts[4], "0x500"); + EXPECT_EQ(parts[5], "0x600"); } } // namespace diff --git a/util/synchronization/semaphore_test.cc b/util/synchronization/semaphore_test.cc index 5f0563a6..fb4338c0 100644 --- a/util/synchronization/semaphore_test.cc +++ b/util/synchronization/semaphore_test.cc @@ -73,20 +73,20 @@ ThreadMain(void* argument) { void StartThread(ThreadMainInfo* info) { #if defined(OS_POSIX) int rv = pthread_create(&info->pthread, nullptr, ThreadMain, info); - ASSERT_EQ(0, rv) << "pthread_create"; + ASSERT_EQ(rv, 0) << "pthread_create"; #elif defined(OS_WIN) info->thread = CreateThread(nullptr, 0, ThreadMain, info, 0, nullptr); - ASSERT_NE(nullptr, info->thread) << "CreateThread"; + ASSERT_NE(info->thread, nullptr) << "CreateThread"; #endif // OS_POSIX } void JoinThread(ThreadMainInfo* info) { #if defined(OS_POSIX) int rv = pthread_join(info->pthread, nullptr); - EXPECT_EQ(0, rv) << "pthread_join"; + EXPECT_EQ(rv, 0) << "pthread_join"; #elif defined(OS_WIN) DWORD result = WaitForSingleObject(info->thread, INFINITE); - EXPECT_EQ(WAIT_OBJECT_0, result) << "WaitForSingleObject"; + EXPECT_EQ(result, WAIT_OBJECT_0) << "WaitForSingleObject"; #endif // OS_POSIX } diff --git a/util/thread/thread_log_messages_test.cc b/util/thread/thread_log_messages_test.cc index df5735b5..65c0b854 100644 --- a/util/thread/thread_log_messages_test.cc +++ b/util/thread/thread_log_messages_test.cc @@ -46,14 +46,14 @@ std::string MessageString(const std::string& log_message) { const char kStartChar = '['; if (log_message[0] != kStartChar) { - EXPECT_EQ(kStartChar, log_message[0]); + EXPECT_EQ(log_message[0], kStartChar); return std::string(); } const char kFindString[] = "] "; size_t pos = log_message.find(kFindString); if (pos == std::string::npos) { - EXPECT_NE(std::string::npos, pos); + EXPECT_NE(pos, std::string::npos); return std::string(); } @@ -93,9 +93,9 @@ TEST(ThreadLogMessages, Basic) { const std::vector& log_messages = thread_log_messages.log_messages(); - EXPECT_EQ(arraysize(kMessages), log_messages.size()); + EXPECT_EQ(log_messages.size(), arraysize(kMessages)); for (size_t index = 0; index < arraysize(kMessages); ++index) { - EXPECT_EQ(kMessages[index], MessageString(log_messages[index])) + EXPECT_EQ(MessageString(log_messages[index]), kMessages[index]) << "index " << index; } } @@ -110,8 +110,8 @@ TEST(ThreadLogMessages, Basic) { const std::vector& log_messages = thread_log_messages.log_messages(); - EXPECT_EQ(1u, log_messages.size()); - EXPECT_EQ(kMessage, MessageString(log_messages[0])); + EXPECT_EQ(log_messages.size(), 1u); + EXPECT_EQ(MessageString(log_messages[0]), kMessage); } { @@ -122,9 +122,9 @@ TEST(ThreadLogMessages, Basic) { const std::vector& log_messages = thread_log_messages.log_messages(); - EXPECT_EQ(1u, log_messages.size()); - EXPECT_EQ("I can't believe I streamed the whole thing.", - MessageString(log_messages[0])); + EXPECT_EQ(log_messages.size(), 1u); + EXPECT_EQ(MessageString(log_messages[0]), + "I can't believe I streamed the whole thing."); } } @@ -153,9 +153,9 @@ class LoggingTestThread : public Thread { const std::vector& log_messages = thread_log_messages.log_messages(); - ASSERT_EQ(static_cast(count_), log_messages.size()); + ASSERT_EQ(log_messages.size(), static_cast(count_)); for (size_t index = 0; index < log_messages.size(); ++index) { - EXPECT_EQ(expected_messages[index], MessageString(log_messages[index])) + EXPECT_EQ(MessageString(log_messages[index]), expected_messages[index]) << "thread_number_ " << thread_number_ << ", index " << index; } } diff --git a/util/thread/worker_thread_test.cc b/util/thread/worker_thread_test.cc index 044734c8..2070c6ad 100644 --- a/util/thread/worker_thread_test.cc +++ b/util/thread/worker_thread_test.cc @@ -81,7 +81,7 @@ TEST(WorkerThread, StopBeforeDoWork) { thread.Start(15); thread.Stop(); - EXPECT_EQ(0, delegate.work_count()); + EXPECT_EQ(delegate.work_count(), 0); } TEST(WorkerThread, Restart) { @@ -114,13 +114,13 @@ TEST(WorkerThread, DoWorkNow) { EXPECT_TRUE(thread.is_running()); delegate.WaitForWorkCount(); - EXPECT_EQ(1, delegate.work_count()); + EXPECT_EQ(delegate.work_count(), 1); delegate.SetDesiredWorkCount(2); thread.DoWorkNow(); delegate.WaitForWorkCount(); thread.Stop(); - EXPECT_EQ(2, delegate.work_count()); + EXPECT_EQ(delegate.work_count(), 2); EXPECT_GE(100 * kNanosecondsPerSecond, ClockMonotonicNanoseconds() - start); } @@ -137,7 +137,7 @@ TEST(WorkerThread, DoWorkNowAtStart) { thread.DoWorkNow(); delegate.WaitForWorkCount(); - EXPECT_EQ(1, delegate.work_count()); + EXPECT_EQ(delegate.work_count(), 1); EXPECT_GE(100 * kNanosecondsPerSecond, ClockMonotonicNanoseconds() - start); diff --git a/util/util.gyp b/util/util.gyp index 4890012a..7ef7a0ca 100644 --- a/util/util.gyp +++ b/util/util.gyp @@ -44,6 +44,11 @@ 'file/file_writer.h', 'file/string_file.cc', 'file/string_file.h', + 'linux/address_types.h', + 'linux/process_memory.cc', + 'linux/process_memory.h', + 'linux/scoped_ptrace_attach.cc', + 'linux/scoped_ptrace_attach.h', 'mac/checked_mach_address_range.h', 'mac/launchd.h', 'mac/launchd.mm', @@ -99,6 +104,10 @@ 'misc/initialization_state_dcheck.h', 'misc/metrics.cc', 'misc/metrics.h', + 'misc/paths.h', + 'misc/paths_mac.cc', + 'misc/paths_linux.cc', + 'misc/paths_win.cc', 'misc/pdb_structures.cc', 'misc/pdb_structures.h', 'misc/random_string.cc', @@ -139,6 +148,10 @@ 'posix/process_info.h', 'posix/process_info_linux.cc', 'posix/process_info_mac.cc', + 'posix/scoped_dir.cc', + 'posix/scoped_dir.h', + 'posix/scoped_mmap.cc', + 'posix/scoped_mmap.h', 'posix/signals.cc', 'posix/signals.h', 'posix/symbolic_constants_posix.cc', @@ -319,6 +332,8 @@ 'target_conditions': [ ['OS=="android"', { 'sources/': [ + ['include', '^linux/'], + ['include', '^misc/paths_linux\\.cc$'], ['include', '^posix/process_info_linux\\.cc$'], ], }], diff --git a/util/util_test.gyp b/util/util_test.gyp index 495c5e61..31323c0b 100644 --- a/util/util_test.gyp +++ b/util/util_test.gyp @@ -39,6 +39,8 @@ 'file/file_io_test.cc', 'file/file_reader_test.cc', 'file/string_file_test.cc', + 'linux/process_memory_test.cc', + 'linux/scoped_ptrace_attach_test.cc', 'mac/launchd_test.mm', 'mac/mac_util_test.mm', 'mac/service_management_test.mm', @@ -62,6 +64,7 @@ 'misc/clock_test.cc', 'misc/initialization_state_dcheck_test.cc', 'misc/initialization_state_test.cc', + 'misc/paths_test.cc', 'misc/scoped_forbid_return_test.cc', 'misc/random_string_test.cc', 'misc/uuid_test.cc', @@ -76,6 +79,7 @@ 'numeric/in_range_cast_test.cc', 'numeric/int128_test.cc', 'posix/process_info_test.cc', + 'posix/scoped_mmap_test.cc', 'posix/signals_test.cc', 'posix/symbolic_constants_posix_test.cc', 'stdlib/aligned_allocator_test.cc', @@ -135,6 +139,13 @@ ] }], ], + 'target_conditions': [ + ['OS=="android"', { + 'sources/': [ + ['include', '^linux/'], + ], + }], + ], }, ], 'conditions': [ diff --git a/util/win/capture_context_test.cc b/util/win/capture_context_test.cc index 72b25874..59bef2ff 100644 --- a/util/win/capture_context_test.cc +++ b/util/win/capture_context_test.cc @@ -39,16 +39,13 @@ void SanityCheckContext(const CONTEXT& context) { CONTEXT_INTEGER | CONTEXT_SEGMENTS | CONTEXT_FLOATING_POINT; - ASSERT_EQ(must_have, context.ContextFlags & must_have); + ASSERT_EQ(context.ContextFlags & must_have, must_have); const uint32_t may_have = CONTEXT_EXTENDED_REGISTERS; - ASSERT_EQ(0, context.ContextFlags & ~(must_have | may_have)); + ASSERT_EQ(context.ContextFlags & ~(must_have | may_have), 0); #elif defined(ARCH_CPU_X86_64) - ASSERT_EQ(CONTEXT_AMD64 | - CONTEXT_CONTROL | - CONTEXT_INTEGER | - CONTEXT_SEGMENTS | - CONTEXT_FLOATING_POINT, - context.ContextFlags); + ASSERT_EQ(context.ContextFlags, + CONTEXT_AMD64 | CONTEXT_CONTROL | CONTEXT_INTEGER | + CONTEXT_SEGMENTS | CONTEXT_FLOATING_POINT); #endif #if defined(ARCH_CPU_X86_FAMILY) @@ -61,52 +58,52 @@ void SanityCheckContext(const CONTEXT& context) { // Software Developer’s Manual, Volume 1: Basic Architecture (253665-055), // 3.4.3 “EFLAGS Register”, and AMD Architecture Programmer’s Manual, Volume // 2: System Programming (24593-3.25), 3.1.6 “RFLAGS Register”. - EXPECT_EQ(2u, context.EFlags & 0xffc0802a); + EXPECT_EQ(context.EFlags & 0xffc0802a, 2u); // CaptureContext() doesn’t capture debug registers, so make sure they read 0. - EXPECT_EQ(0, context.Dr0); - EXPECT_EQ(0, context.Dr1); - EXPECT_EQ(0, context.Dr2); - EXPECT_EQ(0, context.Dr3); - EXPECT_EQ(0, context.Dr6); - EXPECT_EQ(0, context.Dr7); + EXPECT_EQ(context.Dr0, 0); + EXPECT_EQ(context.Dr1, 0); + EXPECT_EQ(context.Dr2, 0); + EXPECT_EQ(context.Dr3, 0); + EXPECT_EQ(context.Dr6, 0); + EXPECT_EQ(context.Dr7, 0); #endif #if defined(ARCH_CPU_X86) // fxsave doesn’t write these bytes. for (size_t i = 464; i < arraysize(context.ExtendedRegisters); ++i) { SCOPED_TRACE(i); - EXPECT_EQ(0, context.ExtendedRegisters[i]); + EXPECT_EQ(context.ExtendedRegisters[i], 0); } #elif defined(ARCH_CPU_X86_64) // mxcsr shows up twice in the context structure. Make sure the values are // identical. - EXPECT_EQ(context.MxCsr, context.FltSave.MxCsr); + EXPECT_EQ(context.FltSave.MxCsr, context.MxCsr); // fxsave doesn’t write these bytes. for (size_t i = 0; i < arraysize(context.FltSave.Reserved4); ++i) { SCOPED_TRACE(i); - EXPECT_EQ(0, context.FltSave.Reserved4[i]); + EXPECT_EQ(context.FltSave.Reserved4[i], 0); } // CaptureContext() doesn’t use these fields. - EXPECT_EQ(0, context.P1Home); - EXPECT_EQ(0, context.P2Home); - EXPECT_EQ(0, context.P3Home); - EXPECT_EQ(0, context.P4Home); - EXPECT_EQ(0, context.P5Home); - EXPECT_EQ(0, context.P6Home); + EXPECT_EQ(context.P1Home, 0); + EXPECT_EQ(context.P2Home, 0); + EXPECT_EQ(context.P3Home, 0); + EXPECT_EQ(context.P4Home, 0); + EXPECT_EQ(context.P5Home, 0); + EXPECT_EQ(context.P6Home, 0); for (size_t i = 0; i < arraysize(context.VectorRegister); ++i) { SCOPED_TRACE(i); - EXPECT_EQ(0, context.VectorRegister[i].Low); - EXPECT_EQ(0, context.VectorRegister[i].High); + EXPECT_EQ(context.VectorRegister[i].Low, 0); + EXPECT_EQ(context.VectorRegister[i].High, 0); } - EXPECT_EQ(0, context.VectorControl); - EXPECT_EQ(0, context.DebugControl); - EXPECT_EQ(0, context.LastBranchToRip); - EXPECT_EQ(0, context.LastBranchFromRip); - EXPECT_EQ(0, context.LastExceptionToRip); - EXPECT_EQ(0, context.LastExceptionFromRip); + EXPECT_EQ(context.VectorControl, 0); + EXPECT_EQ(context.DebugControl, 0); + EXPECT_EQ(context.LastBranchToRip, 0); + EXPECT_EQ(context.LastBranchFromRip, 0); + EXPECT_EQ(context.LastExceptionToRip, 0); + EXPECT_EQ(context.LastExceptionFromRip, 0); #endif } @@ -170,7 +167,7 @@ void TestCaptureContext() { ASSERT_NO_FATAL_FAILURE(SanityCheckContext(context_2)); } - EXPECT_EQ(sp, StackPointerFromContext(context_2)); + EXPECT_EQ(StackPointerFromContext(context_2), sp); EXPECT_GT(ProgramCounterFromContext(context_2), pc); } diff --git a/util/win/command_line_test.cc b/util/win/command_line_test.cc index 2577d6de..95849b63 100644 --- a/util/win/command_line_test.cc +++ b/util/win/command_line_test.cc @@ -43,7 +43,7 @@ void AppendCommandLineArgumentTest(size_t argc, const wchar_t* const argv[]) { ASSERT_TRUE(test_argv) << ErrorMessage("CommandLineToArgvW"); ScopedLocalAlloc test_argv_owner(test_argv); - ASSERT_EQ(argc, test_argc); + ASSERT_EQ(test_argc, argc); for (size_t index = 0; index < argc; ++index) { EXPECT_STREQ(argv[index], test_argv[index]) << "index " << index; diff --git a/util/win/exception_handler_server_test.cc b/util/win/exception_handler_server_test.cc index e9f865be..c1a076b8 100644 --- a/util/win/exception_handler_server_test.cc +++ b/util/win/exception_handler_server_test.cc @@ -203,9 +203,9 @@ TEST_F(ExceptionHandlerServerTest, MultipleConnections) { WriteWString(handles_2->write.get(), pipe_name()); WriteWString(handles_3->write.get(), pipe_name()); - ASSERT_EQ(L"OK", ReadWString(handles_3->read.get())); - ASSERT_EQ(L"OK", ReadWString(handles_2->read.get())); - ASSERT_EQ(L"OK", ReadWString(handles_1->read.get())); + ASSERT_EQ(ReadWString(handles_3->read.get()), L"OK"); + ASSERT_EQ(ReadWString(handles_2->read.get()), L"OK"); + ASSERT_EQ(ReadWString(handles_1->read.get()), L"OK"); } } diff --git a/util/win/get_function_test.cc b/util/win/get_function_test.cc index a2217aef..a54ce7d4 100644 --- a/util/win/get_function_test.cc +++ b/util/win/get_function_test.cc @@ -26,29 +26,29 @@ namespace { TEST(GetFunction, GetFunction) { // Check equivalence of GET_FUNCTION_REQUIRED() with functions that are // available in the SDK normally. - EXPECT_EQ(&GetProcAddress, - GET_FUNCTION_REQUIRED(L"kernel32.dll", GetProcAddress)); - EXPECT_EQ(&LoadLibraryW, - GET_FUNCTION_REQUIRED(L"kernel32.dll", LoadLibraryW)); + EXPECT_EQ(GET_FUNCTION_REQUIRED(L"kernel32.dll", GetProcAddress), + &GetProcAddress); + EXPECT_EQ(GET_FUNCTION_REQUIRED(L"kernel32.dll", LoadLibraryW), + &LoadLibraryW); // Make sure that a function pointer retrieved by GET_FUNCTION_REQUIRED() can // be called and that it works correctly. const auto get_current_process_id = GET_FUNCTION_REQUIRED(L"kernel32.dll", GetCurrentProcessId); - EXPECT_EQ(&GetCurrentProcessId, get_current_process_id); + EXPECT_EQ(get_current_process_id, &GetCurrentProcessId); ASSERT_TRUE(get_current_process_id); - EXPECT_EQ(GetCurrentProcessId(), get_current_process_id()); + EXPECT_EQ(get_current_process_id(), GetCurrentProcessId()); // GET_FUNCTION_REQUIRED() and GET_FUNCTION() should behave identically when // the function is present. - EXPECT_EQ(get_current_process_id, - GET_FUNCTION(L"kernel32.dll", GetCurrentProcessId)); + EXPECT_EQ(GET_FUNCTION(L"kernel32.dll", GetCurrentProcessId), + get_current_process_id); // Using a leading :: should also work. - EXPECT_EQ(get_current_process_id, - GET_FUNCTION(L"kernel32.dll", ::GetCurrentProcessId)); - EXPECT_EQ(get_current_process_id, - GET_FUNCTION_REQUIRED(L"kernel32.dll", ::GetCurrentProcessId)); + EXPECT_EQ(GET_FUNCTION(L"kernel32.dll", ::GetCurrentProcessId), + get_current_process_id); + EXPECT_EQ(GET_FUNCTION_REQUIRED(L"kernel32.dll", ::GetCurrentProcessId), + get_current_process_id); // Try a function that’s declared in the SDK’s headers but that has no import // library. @@ -59,7 +59,7 @@ TEST(GetFunction, GetFunction) { GET_FUNCTION(L"kernel32.dll", GetNamedPipeClientProcessId); const DWORD version = GetVersion(); const DWORD major_version = LOBYTE(LOWORD(version)); - EXPECT_EQ(major_version >= 6, get_named_pipe_client_process_id != nullptr); + EXPECT_EQ(get_named_pipe_client_process_id != nullptr, major_version >= 6); // Test that GET_FUNCTION() can fail by trying a nonexistent library and a // symbol that doesn’t exist in the specified library. diff --git a/util/win/handle_test.cc b/util/win/handle_test.cc index 60e5037b..5898943d 100644 --- a/util/win/handle_test.cc +++ b/util/win/handle_test.cc @@ -25,27 +25,27 @@ namespace test { namespace { TEST(Handle, HandleToInt) { - EXPECT_EQ(0, HandleToInt(nullptr)); - EXPECT_EQ(-1, HandleToInt(INVALID_HANDLE_VALUE)); - EXPECT_EQ(1, HandleToInt(reinterpret_cast(1))); - EXPECT_EQ(std::numeric_limits::max(), - HandleToInt(reinterpret_cast( - static_cast(std::numeric_limits::max())))); - EXPECT_EQ(std::numeric_limits::min(), - HandleToInt(reinterpret_cast( - static_cast(std::numeric_limits::min())))); + EXPECT_EQ(HandleToInt(nullptr), 0); + EXPECT_EQ(HandleToInt(INVALID_HANDLE_VALUE), -1); + EXPECT_EQ(HandleToInt(reinterpret_cast(1)), 1); + EXPECT_EQ(HandleToInt(reinterpret_cast( + static_cast(std::numeric_limits::max()))), + std::numeric_limits::max()); + EXPECT_EQ(HandleToInt(reinterpret_cast( + static_cast(std::numeric_limits::min()))), + std::numeric_limits::min()); } TEST(Handle, IntToHandle) { - EXPECT_EQ(nullptr, IntToHandle(0)); - EXPECT_EQ(INVALID_HANDLE_VALUE, IntToHandle(-1)); - EXPECT_EQ(reinterpret_cast(1), IntToHandle(1)); - EXPECT_EQ(reinterpret_cast( - static_cast(std::numeric_limits::max())), - IntToHandle(std::numeric_limits::max())); - EXPECT_EQ(reinterpret_cast( - static_cast(std::numeric_limits::min())), - IntToHandle(std::numeric_limits::min())); + EXPECT_EQ(IntToHandle(0), nullptr); + EXPECT_EQ(IntToHandle(-1), INVALID_HANDLE_VALUE); + EXPECT_EQ(IntToHandle(1), reinterpret_cast(1)); + EXPECT_EQ(IntToHandle(std::numeric_limits::max()), + reinterpret_cast( + static_cast(std::numeric_limits::max()))); + EXPECT_EQ(IntToHandle(std::numeric_limits::min()), + reinterpret_cast( + static_cast(std::numeric_limits::min()))); } } // namespace diff --git a/util/win/initial_client_data_test.cc b/util/win/initial_client_data_test.cc index 5ac7be91..21212494 100644 --- a/util/win/initial_client_data_test.cc +++ b/util/win/initial_client_data_test.cc @@ -48,25 +48,24 @@ TEST(InitialClientData, RoundTrip) { 0xccccddddeeeeffffull); std::string as_string = first.StringRepresentation(); - EXPECT_EQ( - "0x123,0x456,0x789,0xabc,0xdef," - "0x7fff000012345678,0x100000,0xccccddddeeeeffff", - as_string); + EXPECT_EQ(as_string, + "0x123,0x456,0x789,0xabc,0xdef," + "0x7fff000012345678,0x100000,0xccccddddeeeeffff"); InitialClientData second; ASSERT_TRUE(second.InitializeFromString(as_string)); - EXPECT_EQ(first.request_crash_dump(), second.request_crash_dump()); - EXPECT_EQ(first.request_non_crash_dump(), second.request_non_crash_dump()); - EXPECT_EQ(first.non_crash_dump_completed(), - second.non_crash_dump_completed()); - EXPECT_EQ(first.first_pipe_instance(), second.first_pipe_instance()); - EXPECT_EQ(first.client_process(), second.client_process()); - EXPECT_EQ(first.crash_exception_information(), - second.crash_exception_information()); - EXPECT_EQ(first.non_crash_exception_information(), - second.non_crash_exception_information()); - EXPECT_EQ(first.debug_critical_section_address(), - second.debug_critical_section_address()); + EXPECT_EQ(second.request_crash_dump(), first.request_crash_dump()); + EXPECT_EQ(second.request_non_crash_dump(), first.request_non_crash_dump()); + EXPECT_EQ(second.non_crash_dump_completed(), + first.non_crash_dump_completed()); + EXPECT_EQ(second.first_pipe_instance(), first.first_pipe_instance()); + EXPECT_EQ(second.client_process(), first.client_process()); + EXPECT_EQ(second.crash_exception_information(), + first.crash_exception_information()); + EXPECT_EQ(second.non_crash_exception_information(), + first.non_crash_exception_information()); + EXPECT_EQ(second.debug_critical_section_address(), + first.debug_critical_section_address()); } } // namespace diff --git a/util/win/process_info.cc b/util/win/process_info.cc index cb2051c0..f0e455db 100644 --- a/util/win/process_info.cc +++ b/util/win/process_info.cc @@ -157,6 +157,10 @@ std::unique_ptr QueryObject( if (status == STATUS_INFO_LENGTH_MISMATCH) { DCHECK_GT(return_length, size); size = return_length; + + // Free the old buffer before attempting to allocate a new one. + buffer.reset(); + buffer.reset(new uint8_t[size]); status = crashpad::NtQueryObject( handle, object_information_class, buffer.get(), size, &return_length); @@ -167,6 +171,7 @@ std::unique_ptr QueryObject( return nullptr; } + DCHECK_LE(return_length, size); DCHECK_GE(return_length, minimum_size); return buffer; } diff --git a/util/win/process_info_test.cc b/util/win/process_info_test.cc index dfa6564d..54459424 100644 --- a/util/win/process_info_test.cc +++ b/util/win/process_info_test.cc @@ -26,8 +26,8 @@ #include "build/build_config.h" #include "gtest/gtest.h" #include "test/errors.h" -#include "test/paths.h" #include "test/scoped_temp_dir.h" +#include "test/test_paths.h" #include "test/win/child_launcher.h" #include "util/file/file_io.h" #include "util/misc/random_string.h" @@ -66,9 +66,9 @@ void VerifyAddressInInCodePage(const ProcessInfo& process_info, for (const auto& mi : memory_info) { if (mi.BaseAddress <= code_address && mi.BaseAddress + mi.RegionSize > code_address) { - EXPECT_EQ(MEM_COMMIT, mi.State); - EXPECT_EQ(PAGE_EXECUTE_READ, mi.Protect); - EXPECT_EQ(MEM_IMAGE, mi.Type); + EXPECT_EQ(mi.State, MEM_COMMIT); + EXPECT_EQ(mi.Protect, PAGE_EXECUTE_READ); + EXPECT_EQ(mi.Type, MEM_IMAGE); EXPECT_FALSE(found_region); found_region = true; } @@ -79,7 +79,7 @@ void VerifyAddressInInCodePage(const ProcessInfo& process_info, TEST(ProcessInfo, Self) { ProcessInfo process_info; ASSERT_TRUE(process_info.Initialize(GetCurrentProcess())); - EXPECT_EQ(GetCurrentProcessId(), process_info.ProcessID()); + EXPECT_EQ(process_info.ProcessID(), GetCurrentProcessId()); EXPECT_GT(process_info.ParentProcessID(), 0u); #if defined(ARCH_CPU_64_BITS) @@ -95,30 +95,29 @@ TEST(ProcessInfo, Self) { std::wstring command_line; EXPECT_TRUE(process_info.CommandLine(&command_line)); - EXPECT_EQ(std::wstring(GetCommandLine()), command_line); + EXPECT_EQ(command_line, std::wstring(GetCommandLine())); std::vector modules; EXPECT_TRUE(process_info.Modules(&modules)); ASSERT_GE(modules.size(), 2u); const wchar_t kSelfName[] = L"\\crashpad_util_test.exe"; ASSERT_GE(modules[0].name.size(), wcslen(kSelfName)); - EXPECT_EQ(kSelfName, - modules[0].name.substr(modules[0].name.size() - wcslen(kSelfName))); + EXPECT_EQ(modules[0].name.substr(modules[0].name.size() - wcslen(kSelfName)), + kSelfName); ASSERT_GE(modules[1].name.size(), wcslen(kNtdllName)); - EXPECT_EQ( - kNtdllName, - modules[1].name.substr(modules[1].name.size() - wcslen(kNtdllName))); + EXPECT_EQ(modules[1].name.substr(modules[1].name.size() - wcslen(kNtdllName)), + kNtdllName); - EXPECT_EQ(reinterpret_cast(GetModuleHandle(nullptr)), - modules[0].dll_base); - EXPECT_EQ(reinterpret_cast(GetModuleHandle(L"ntdll.dll")), - modules[1].dll_base); + EXPECT_EQ(modules[0].dll_base, + reinterpret_cast(GetModuleHandle(nullptr))); + EXPECT_EQ(modules[1].dll_base, + reinterpret_cast(GetModuleHandle(L"ntdll.dll"))); EXPECT_GT(modules[0].size, 0); EXPECT_GT(modules[1].size, 0); - EXPECT_EQ(GetTimestampForLoadedLibrary(GetModuleHandle(nullptr)), - modules[0].timestamp); + EXPECT_EQ(modules[0].timestamp, + GetTimestampForLoadedLibrary(GetModuleHandle(nullptr))); // System modules are forced to particular stamps and the file header values // don't match the on-disk times. Just make sure we got some data here. EXPECT_GT(modules[1].timestamp, 0); @@ -137,9 +136,9 @@ void TestOtherProcess(const base::string16& directory_modification) { ScopedKernelHANDLE done( CreateEvent(nullptr, true, false, done_uuid.ToString16().c_str())); - ASSERT_TRUE(done.get()); + ASSERT_TRUE(done.get()) << ErrorMessage("CreateEvent"); - base::FilePath test_executable = Paths::Executable(); + base::FilePath test_executable = TestPaths::Executable(); std::wstring child_test_executable = test_executable.DirName() @@ -162,26 +161,27 @@ void TestOtherProcess(const base::string16& directory_modification) { ASSERT_TRUE(process_info.Initialize(child.process_handle())); // Tell the test it's OK to shut down now that we've read our data. - EXPECT_TRUE(SetEvent(done.get())); + EXPECT_TRUE(SetEvent(done.get())) << ErrorMessage("SetEvent"); + + EXPECT_EQ(child.WaitForExit(), 0); std::vector modules; EXPECT_TRUE(process_info.Modules(&modules)); ASSERT_GE(modules.size(), 3u); std::wstring child_name = L"\\crashpad_util_test_process_info_test_child.exe"; ASSERT_GE(modules[0].name.size(), child_name.size()); - EXPECT_EQ(child_name, - modules[0].name.substr(modules[0].name.size() - child_name.size())); + EXPECT_EQ(modules[0].name.substr(modules[0].name.size() - child_name.size()), + child_name); ASSERT_GE(modules[1].name.size(), wcslen(kNtdllName)); - EXPECT_EQ( - kNtdllName, - modules[1].name.substr(modules[1].name.size() - wcslen(kNtdllName))); + EXPECT_EQ(modules[1].name.substr(modules[1].name.size() - wcslen(kNtdllName)), + kNtdllName); // lz32.dll is an uncommonly-used-but-always-available module that the test // binary manually loads. const wchar_t kLz32dllName[] = L"\\lz32.dll"; ASSERT_GE(modules.back().name.size(), wcslen(kLz32dllName)); - EXPECT_EQ(kLz32dllName, - modules.back().name.substr(modules.back().name.size() - - wcslen(kLz32dllName))); + EXPECT_EQ(modules.back().name.substr(modules.back().name.size() - + wcslen(kLz32dllName)), + kLz32dllName); VerifyAddressInInCodePage(process_info, code_address); } @@ -229,9 +229,9 @@ TEST(ProcessInfo, AccessibleRangesOneInside) { GetReadableRangesOfMemoryMap(CheckedRange(2, 4), memory_info); - ASSERT_EQ(1u, result.size()); - EXPECT_EQ(2, result[0].base()); - EXPECT_EQ(4, result[0].size()); + ASSERT_EQ(result.size(), 1u); + EXPECT_EQ(result[0].base(), 2); + EXPECT_EQ(result[0].size(), 4); } TEST(ProcessInfo, AccessibleRangesOneTruncatedSize) { @@ -252,9 +252,9 @@ TEST(ProcessInfo, AccessibleRangesOneTruncatedSize) { GetReadableRangesOfMemoryMap(CheckedRange(5, 10), memory_info); - ASSERT_EQ(1u, result.size()); - EXPECT_EQ(5, result[0].base()); - EXPECT_EQ(5, result[0].size()); + ASSERT_EQ(result.size(), 1u); + EXPECT_EQ(result[0].base(), 5); + EXPECT_EQ(result[0].size(), 5); } TEST(ProcessInfo, AccessibleRangesOneMovedStart) { @@ -275,9 +275,9 @@ TEST(ProcessInfo, AccessibleRangesOneMovedStart) { GetReadableRangesOfMemoryMap(CheckedRange(5, 10), memory_info); - ASSERT_EQ(1u, result.size()); - EXPECT_EQ(10, result[0].base()); - EXPECT_EQ(5, result[0].size()); + ASSERT_EQ(result.size(), 1u); + EXPECT_EQ(result[0].base(), 10); + EXPECT_EQ(result[0].size(), 5); } TEST(ProcessInfo, ReserveIsInaccessible) { @@ -298,9 +298,9 @@ TEST(ProcessInfo, ReserveIsInaccessible) { GetReadableRangesOfMemoryMap(CheckedRange(5, 10), memory_info); - ASSERT_EQ(1u, result.size()); - EXPECT_EQ(10, result[0].base()); - EXPECT_EQ(5, result[0].size()); + ASSERT_EQ(result.size(), 1u); + EXPECT_EQ(result[0].base(), 10); + EXPECT_EQ(result[0].size(), 5); } TEST(ProcessInfo, PageGuardIsInaccessible) { @@ -323,9 +323,9 @@ TEST(ProcessInfo, PageGuardIsInaccessible) { GetReadableRangesOfMemoryMap(CheckedRange(5, 10), memory_info); - ASSERT_EQ(1u, result.size()); - EXPECT_EQ(10, result[0].base()); - EXPECT_EQ(5, result[0].size()); + ASSERT_EQ(result.size(), 1u); + EXPECT_EQ(result[0].base(), 10); + EXPECT_EQ(result[0].size(), 5); } TEST(ProcessInfo, PageNoAccessIsInaccessible) { @@ -348,9 +348,9 @@ TEST(ProcessInfo, PageNoAccessIsInaccessible) { GetReadableRangesOfMemoryMap(CheckedRange(5, 10), memory_info); - ASSERT_EQ(1u, result.size()); - EXPECT_EQ(10, result[0].base()); - EXPECT_EQ(5, result[0].size()); + ASSERT_EQ(result.size(), 1u); + EXPECT_EQ(result[0].base(), 10); + EXPECT_EQ(result[0].size(), 5); } TEST(ProcessInfo, AccessibleRangesCoalesced) { @@ -376,9 +376,9 @@ TEST(ProcessInfo, AccessibleRangesCoalesced) { GetReadableRangesOfMemoryMap(CheckedRange(11, 4), memory_info); - ASSERT_EQ(1u, result.size()); - EXPECT_EQ(11, result[0].base()); - EXPECT_EQ(4, result[0].size()); + ASSERT_EQ(result.size(), 1u); + EXPECT_EQ(result[0].base(), 11); + EXPECT_EQ(result[0].size(), 4); } TEST(ProcessInfo, AccessibleRangesMiddleUnavailable) { @@ -404,11 +404,11 @@ TEST(ProcessInfo, AccessibleRangesMiddleUnavailable) { GetReadableRangesOfMemoryMap(CheckedRange(5, 45), memory_info); - ASSERT_EQ(2u, result.size()); - EXPECT_EQ(5, result[0].base()); - EXPECT_EQ(5, result[0].size()); - EXPECT_EQ(15, result[1].base()); - EXPECT_EQ(35, result[1].size()); + ASSERT_EQ(result.size(), 2u); + EXPECT_EQ(result[0].base(), 5); + EXPECT_EQ(result[0].size(), 5); + EXPECT_EQ(result[1].base(), 15); + EXPECT_EQ(result[1].size(), 35); } TEST(ProcessInfo, RequestedBeforeMap) { @@ -424,9 +424,9 @@ TEST(ProcessInfo, RequestedBeforeMap) { GetReadableRangesOfMemoryMap(CheckedRange(5, 10), memory_info); - ASSERT_EQ(1u, result.size()); - EXPECT_EQ(10, result[0].base()); - EXPECT_EQ(5, result[0].size()); + ASSERT_EQ(result.size(), 1u); + EXPECT_EQ(result[0].base(), 10); + EXPECT_EQ(result[0].size(), 5); } TEST(ProcessInfo, RequestedAfterMap) { @@ -442,9 +442,9 @@ TEST(ProcessInfo, RequestedAfterMap) { GetReadableRangesOfMemoryMap( CheckedRange(15, 100), memory_info); - ASSERT_EQ(1u, result.size()); - EXPECT_EQ(15, result[0].base()); - EXPECT_EQ(5, result[0].size()); + ASSERT_EQ(result.size(), 1u); + EXPECT_EQ(result[0].base(), 15); + EXPECT_EQ(result[0].size(), 5); } TEST(ProcessInfo, ReadableRanges) { @@ -489,11 +489,11 @@ TEST(ProcessInfo, ReadableRanges) { auto ranges = info.GetReadableRanges( CheckedRange(reserved_as_int, kBlockSize * 6)); - ASSERT_EQ(2u, ranges.size()); - EXPECT_EQ(reserved_as_int + kBlockSize, ranges[0].base()); - EXPECT_EQ(kBlockSize, ranges[0].size()); - EXPECT_EQ(reserved_as_int + (kBlockSize * 3), ranges[1].base()); - EXPECT_EQ(kBlockSize * 2, ranges[1].size()); + ASSERT_EQ(ranges.size(), 2u); + EXPECT_EQ(ranges[0].base(), reserved_as_int + kBlockSize); + EXPECT_EQ(ranges[0].size(), kBlockSize); + EXPECT_EQ(ranges[1].base(), reserved_as_int + (kBlockSize * 3)); + EXPECT_EQ(ranges[1].size(), kBlockSize * 2); // Also make sure what we think we can read corresponds with what we can // actually read. @@ -502,11 +502,11 @@ TEST(ProcessInfo, ReadableRanges) { EXPECT_TRUE(ReadProcessMemory( current_process, readable1, into.get(), kBlockSize, &bytes_read)); - EXPECT_EQ(kBlockSize, bytes_read); + EXPECT_EQ(bytes_read, kBlockSize); EXPECT_TRUE(ReadProcessMemory( current_process, readable2, into.get(), kBlockSize * 2, &bytes_read)); - EXPECT_EQ(kBlockSize * 2, bytes_read); + EXPECT_EQ(bytes_read, kBlockSize * 2); EXPECT_FALSE(ReadProcessMemory( current_process, no_access, into.get(), kBlockSize, &bytes_read)); @@ -554,9 +554,9 @@ TEST(ProcessInfo, Handles) { ASSERT_TRUE(inherited_file.is_valid()); HKEY key; - ASSERT_EQ(ERROR_SUCCESS, - RegOpenKeyEx( - HKEY_CURRENT_USER, L"SOFTWARE\\Microsoft", 0, KEY_READ, &key)); + ASSERT_EQ(RegOpenKeyEx( + HKEY_CURRENT_USER, L"SOFTWARE\\Microsoft", 0, KEY_READ, &key), + ERROR_SUCCESS); ScopedRegistryKey scoped_key(key); ASSERT_TRUE(scoped_key.is_valid()); @@ -582,47 +582,47 @@ TEST(ProcessInfo, Handles) { if (handle.handle == HandleToInt(file.get())) { EXPECT_FALSE(found_file_handle); found_file_handle = true; - EXPECT_EQ(L"File", handle.type_name); - EXPECT_EQ(1, handle.handle_count); - EXPECT_NE(0u, handle.pointer_count); - EXPECT_EQ(STANDARD_RIGHTS_READ | STANDARD_RIGHTS_WRITE | SYNCHRONIZE, - handle.granted_access & STANDARD_RIGHTS_ALL); - EXPECT_EQ(0, handle.attributes); + EXPECT_EQ(handle.type_name, L"File"); + EXPECT_EQ(handle.handle_count, 1); + EXPECT_NE(handle.pointer_count, 0u); + EXPECT_EQ(handle.granted_access & STANDARD_RIGHTS_ALL, + STANDARD_RIGHTS_READ | STANDARD_RIGHTS_WRITE | SYNCHRONIZE); + EXPECT_EQ(handle.attributes, 0); } if (handle.handle == HandleToInt(inherited_file.get())) { EXPECT_FALSE(found_inherited_file_handle); found_inherited_file_handle = true; - EXPECT_EQ(L"File", handle.type_name); - EXPECT_EQ(1, handle.handle_count); - EXPECT_NE(0u, handle.pointer_count); - EXPECT_EQ(STANDARD_RIGHTS_READ | STANDARD_RIGHTS_WRITE | SYNCHRONIZE, - handle.granted_access & STANDARD_RIGHTS_ALL); + EXPECT_EQ(handle.type_name, L"File"); + EXPECT_EQ(handle.handle_count, 1); + EXPECT_NE(handle.pointer_count, 0u); + EXPECT_EQ(handle.granted_access & STANDARD_RIGHTS_ALL, + STANDARD_RIGHTS_READ | STANDARD_RIGHTS_WRITE | SYNCHRONIZE); // OBJ_INHERIT from ntdef.h, but including that conflicts with other // headers. const int kObjInherit = 0x2; - EXPECT_EQ(kObjInherit, handle.attributes); + EXPECT_EQ(handle.attributes, kObjInherit); } if (handle.handle == HandleToInt(scoped_key.get())) { EXPECT_FALSE(found_key_handle); found_key_handle = true; - EXPECT_EQ(L"Key", handle.type_name); - EXPECT_EQ(1, handle.handle_count); - EXPECT_NE(0u, handle.pointer_count); - EXPECT_EQ(STANDARD_RIGHTS_READ, - handle.granted_access & STANDARD_RIGHTS_ALL); - EXPECT_EQ(0, handle.attributes); + EXPECT_EQ(handle.type_name, L"Key"); + EXPECT_EQ(handle.handle_count, 1); + EXPECT_NE(handle.pointer_count, 0u); + EXPECT_EQ(handle.granted_access & STANDARD_RIGHTS_ALL, + STANDARD_RIGHTS_READ); + EXPECT_EQ(handle.attributes, 0); } if (handle.handle == HandleToInt(mapping.get())) { EXPECT_FALSE(found_mapping_handle); found_mapping_handle = true; - EXPECT_EQ(L"Section", handle.type_name); - EXPECT_EQ(1, handle.handle_count); - EXPECT_NE(0u, handle.pointer_count); - EXPECT_EQ(DELETE | READ_CONTROL | WRITE_DAC | WRITE_OWNER | - STANDARD_RIGHTS_READ | STANDARD_RIGHTS_WRITE, - handle.granted_access & STANDARD_RIGHTS_ALL); - EXPECT_EQ(0, handle.attributes); + EXPECT_EQ(handle.type_name, L"Section"); + EXPECT_EQ(handle.handle_count, 1); + EXPECT_NE(handle.pointer_count, 0u); + EXPECT_EQ(handle.granted_access & STANDARD_RIGHTS_ALL, + DELETE | READ_CONTROL | WRITE_DAC | WRITE_OWNER | + STANDARD_RIGHTS_READ | STANDARD_RIGHTS_WRITE); + EXPECT_EQ(handle.attributes, 0); } } EXPECT_TRUE(found_file_handle); diff --git a/util/win/registration_protocol_win_test.cc b/util/win/registration_protocol_win_test.cc index 60e7c86c..10a5bb63 100644 --- a/util/win/registration_protocol_win_test.cc +++ b/util/win/registration_protocol_win_test.cc @@ -44,8 +44,8 @@ TEST(SecurityDescriptor, MatchesAdvapi32) { size_t created_len; const void* const created = GetSecurityDescriptorForNamedPipeInstance(&created_len); - ASSERT_EQ(sec_desc_len, created_len); - EXPECT_EQ(0, memcmp(sec_desc, created, sec_desc_len)); + ASSERT_EQ(created_len, sec_desc_len); + EXPECT_EQ(memcmp(sec_desc, created, sec_desc_len), 0); } } // namespace diff --git a/util/win/scoped_process_suspend_test.cc b/util/win/scoped_process_suspend_test.cc index f770456e..2d0f5a0b 100644 --- a/util/win/scoped_process_suspend_test.cc +++ b/util/win/scoped_process_suspend_test.cc @@ -82,7 +82,7 @@ class ScopedProcessSuspendTest final : public WinChildProcess { char c; // Wait for notification from parent. EXPECT_TRUE(LoggingReadFileExactly(ReadPipeHandle(), &c, sizeof(c))); - EXPECT_EQ(' ', c); + EXPECT_EQ(c, ' '); return EXIT_SUCCESS; }