diff options
author | 2023-03-30 12:35:16 +0000 | |
---|---|---|
committer | 2023-04-05 11:04:51 +0000 | |
commit | ba87ab5ca06eb85300b3b63f420914f76843a4a5 (patch) | |
tree | b86b5946911a42bc1bcc3cac6321e765219371c4 | |
parent | 2bb753eabb80ad9ed90dfef3693c1e72d3d9f689 (diff) |
Fix "readability-redundant-string-cstr" clang-tidy issues
Bug: 264654008
Test: m tidy-art
Change-Id: Ic852d58f106187791fa3a0d31829654de41bcb2b
31 files changed, 973 insertions, 1142 deletions
diff --git a/CPPLINT.cfg b/CPPLINT.cfg index 83288421e2..71a5a26b0e 100644 --- a/CPPLINT.cfg +++ b/CPPLINT.cfg @@ -31,3 +31,4 @@ filter=-readability/function,-readability/streams,-readability/todo filter=-runtime/printf,-runtime/references,-runtime/sizeof,-runtime/threadsafe_fn # TODO: this should be re-enabled. filter=-whitespace/line_length +filter=-whitespace/braces diff --git a/build/Android.bp b/build/Android.bp index a6f8661740..dd9be5c559 100644 --- a/build/Android.bp +++ b/build/Android.bp @@ -48,6 +48,7 @@ art_clang_tidy_errors = [ "performance-noexcept-move-constructor", "performance-unnecessary-copy-initialization", "performance-unnecessary-value-param", + "readability-redundant-string-cstr", ] art_clang_tidy_disabled = [ diff --git a/compiler/utils/assembler_test_base.h b/compiler/utils/assembler_test_base.h index 8c18e07033..73f3657413 100644 --- a/compiler/utils/assembler_test_base.h +++ b/compiler/utils/assembler_test_base.h @@ -85,7 +85,7 @@ class AssemblerTestBase : public testing::Test { // Assemble reference object file. std::string ref_obj_file = test_path(".ref.o"); - ASSERT_TRUE(Assemble(ref_asm_file.c_str(), ref_obj_file.c_str())); + ASSERT_TRUE(Assemble(ref_asm_file, ref_obj_file)); // Read the code produced by assembler from the ELF file. std::vector<uint8_t> ref_code; diff --git a/dex2oat/dex2oat.cc b/dex2oat/dex2oat.cc index a0b860f465..6c713721d8 100644 --- a/dex2oat/dex2oat.cc +++ b/dex2oat/dex2oat.cc @@ -1906,7 +1906,7 @@ class Dex2Oat final { } } - if (android::base::StartsWith(dex_location, filter.c_str())) { + if (android::base::StartsWith(dex_location, filter)) { VLOG(compiler) << "Disabling inlining from " << dex_file->GetLocation(); no_inline_from_dex_files.push_back(dex_file); break; diff --git a/dex2oat/dex2oat_test.cc b/dex2oat/dex2oat_test.cc index e444071e9c..ca76254fc1 100644 --- a/dex2oat/dex2oat_test.cc +++ b/dex2oat/dex2oat_test.cc @@ -104,14 +104,13 @@ class Dex2oatTest : public Dex2oatEnvironmentTest { return status; } - ::testing::AssertionResult GenerateOdexForTest( - const std::string& dex_location, - const std::string& odex_location, - CompilerFilter::Filter filter, - const std::vector<std::string>& extra_args = {}, - bool expect_success = true, - bool use_fd = false, - bool use_zip_fd = false) WARN_UNUSED { + ::testing::AssertionResult GenerateOdexForTest(const std::string& dex_location, + const std::string& odex_location, + CompilerFilter::Filter filter, + const std::vector<std::string>& extra_args = {}, + bool expect_success = true, + bool use_fd = false, + bool use_zip_fd = false) WARN_UNUSED { return GenerateOdexForTest(dex_location, odex_location, filter, @@ -125,47 +124,42 @@ class Dex2oatTest : public Dex2oatEnvironmentTest { bool test_accepts_odex_file_on_failure = false; template <typename T> - ::testing::AssertionResult GenerateOdexForTest( - const std::string& dex_location, - const std::string& odex_location, - CompilerFilter::Filter filter, - const std::vector<std::string>& extra_args, - bool expect_success, - bool use_fd, - bool use_zip_fd, - T check_oat) WARN_UNUSED { + ::testing::AssertionResult GenerateOdexForTest(const std::string& dex_location, + const std::string& odex_location, + CompilerFilter::Filter filter, + const std::vector<std::string>& extra_args, + bool expect_success, + bool use_fd, + bool use_zip_fd, + T check_oat) WARN_UNUSED { std::vector<std::string> dex_locations; if (use_zip_fd) { std::string loc_arg = "--zip-location=" + dex_location; - CHECK(std::any_of(extra_args.begin(), - extra_args.end(), - [&](const std::string& s) { return s == loc_arg; })); - CHECK(std::any_of(extra_args.begin(), - extra_args.end(), - [](const std::string& s) { return StartsWith(s, "--zip-fd="); })); + CHECK(std::any_of(extra_args.begin(), extra_args.end(), [&](const std::string& s) { + return s == loc_arg; + })); + CHECK(std::any_of(extra_args.begin(), extra_args.end(), [](const std::string& s) { + return StartsWith(s, "--zip-fd="); + })); } else { dex_locations.push_back(dex_location); } std::string error_msg; - int status = GenerateOdexForTestWithStatus(dex_locations, - odex_location, - filter, - &error_msg, - extra_args, - use_fd); + int status = GenerateOdexForTestWithStatus( + dex_locations, odex_location, filter, &error_msg, extra_args, use_fd); bool success = (WIFEXITED(status) && WEXITSTATUS(status) == 0); if (expect_success) { if (!success) { - return ::testing::AssertionFailure() - << "Failed to compile odex: " << error_msg << std::endl << output_; + return ::testing::AssertionFailure() << "Failed to compile odex: " << error_msg << std::endl + << output_; } // Verify the odex file was generated as expected. - std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1, - odex_location.c_str(), - odex_location.c_str(), - /*executable=*/ false, - /*low_4gb=*/ false, + std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/-1, + odex_location, + odex_location, + /*executable=*/false, + /*low_4gb=*/false, dex_location, &error_msg)); if (odex_file == nullptr) { @@ -183,11 +177,11 @@ class Dex2oatTest : public Dex2oatEnvironmentTest { if (!test_accepts_odex_file_on_failure) { // Verify there's no loadable odex file. - std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1, - odex_location.c_str(), - odex_location.c_str(), - /*executable=*/ false, - /*low_4gb=*/ false, + std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/-1, + odex_location, + odex_location, + /*executable=*/false, + /*low_4gb=*/false, dex_location, &error_msg)); if (odex_file != nullptr) { @@ -213,9 +207,8 @@ class Dex2oatTest : public Dex2oatEnvironmentTest { // to what's already huge test methods). class Dex2oatWithExpectedFilterTest : public Dex2oatTest { protected: - void CheckFilter( - CompilerFilter::Filter expected ATTRIBUTE_UNUSED, - CompilerFilter::Filter actual) override { + void CheckFilter(CompilerFilter::Filter expected ATTRIBUTE_UNUSED, + CompilerFilter::Filter actual) override { EXPECT_EQ(expected_filter_, actual); } @@ -298,27 +291,27 @@ class Dex2oatSwapTest : public Dex2oatTest { }; TEST_F(Dex2oatSwapTest, DoNotUseSwapDefaultSingleSmall) { - RunTest(/*use_fd=*/ false, /*expect_use=*/ false); - RunTest(/*use_fd=*/ true, /*expect_use=*/ false); + RunTest(/*use_fd=*/false, /*expect_use=*/false); + RunTest(/*use_fd=*/true, /*expect_use=*/false); } TEST_F(Dex2oatSwapTest, DoNotUseSwapSingle) { - RunTest(/*use_fd=*/ false, /*expect_use=*/ false, { "--swap-dex-size-threshold=0" }); - RunTest(/*use_fd=*/ true, /*expect_use=*/ false, { "--swap-dex-size-threshold=0" }); + RunTest(/*use_fd=*/false, /*expect_use=*/false, {"--swap-dex-size-threshold=0"}); + RunTest(/*use_fd=*/true, /*expect_use=*/false, {"--swap-dex-size-threshold=0"}); } TEST_F(Dex2oatSwapTest, DoNotUseSwapSmall) { - RunTest(/*use_fd=*/ false, /*expect_use=*/ false, { "--swap-dex-count-threshold=0" }); - RunTest(/*use_fd=*/ true, /*expect_use=*/ false, { "--swap-dex-count-threshold=0" }); + RunTest(/*use_fd=*/false, /*expect_use=*/false, {"--swap-dex-count-threshold=0"}); + RunTest(/*use_fd=*/true, /*expect_use=*/false, {"--swap-dex-count-threshold=0"}); } TEST_F(Dex2oatSwapTest, DoUseSwapSingleSmall) { - RunTest(/*use_fd=*/ false, - /*expect_use=*/ true, - { "--swap-dex-size-threshold=0", "--swap-dex-count-threshold=0" }); - RunTest(/*use_fd=*/ true, - /*expect_use=*/ true, - { "--swap-dex-size-threshold=0", "--swap-dex-count-threshold=0" }); + RunTest(/*use_fd=*/false, + /*expect_use=*/true, + {"--swap-dex-size-threshold=0", "--swap-dex-count-threshold=0"}); + RunTest(/*use_fd=*/true, + /*expect_use=*/true, + {"--swap-dex-size-threshold=0", "--swap-dex-count-threshold=0"}); } class Dex2oatSwapUseTest : public Dex2oatSwapTest { @@ -343,7 +336,7 @@ class Dex2oatSwapUseTest : public Dex2oatSwapTest { void GrabResult1() { if (!kIsTargetBuild) { native_alloc_1_ = ParseNativeAlloc(); - swap_1_ = ParseSwap(/*expected=*/ false); + swap_1_ = ParseSwap(/*expected=*/false); } else { native_alloc_1_ = std::numeric_limits<size_t>::max(); swap_1_ = 0; @@ -353,7 +346,7 @@ class Dex2oatSwapUseTest : public Dex2oatSwapTest { void GrabResult2() { if (!kIsTargetBuild) { native_alloc_2_ = ParseNativeAlloc(); - swap_2_ = ParseSwap(/*expected=*/ true); + swap_2_ = ParseSwap(/*expected=*/true); } else { native_alloc_2_ = 0; swap_2_ = std::numeric_limits<size_t>::max(); @@ -424,16 +417,16 @@ TEST_F(Dex2oatSwapUseTest, CheckSwapUsage) { TEST_DISABLED_FOR_X86(); TEST_DISABLED_FOR_X86_64(); - RunTest(/*use_fd=*/ false, - /*expect_use=*/ false); + RunTest(/*use_fd=*/false, + /*expect_use=*/false); GrabResult1(); std::string output_1 = output_; output_ = ""; - RunTest(/*use_fd=*/ false, - /*expect_use=*/ true, - { "--swap-dex-size-threshold=0", "--swap-dex-count-threshold=0" }); + RunTest(/*use_fd=*/false, + /*expect_use=*/true, + {"--swap-dex-size-threshold=0", "--swap-dex-count-threshold=0"}); GrabResult2(); std::string output_2 = output_; @@ -495,11 +488,11 @@ class Dex2oatVeryLargeTest : public Dex2oatTest { } // Host/target independent checks. std::string error_msg; - std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1, - odex_location.c_str(), - odex_location.c_str(), - /*executable=*/ false, - /*low_4gb=*/ false, + std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/-1, + odex_location, + odex_location, + /*executable=*/false, + /*low_4gb=*/false, dex_location, &error_msg)); ASSERT_TRUE(odex_file.get() != nullptr) << error_msg; @@ -581,13 +574,13 @@ TEST_F(Dex2oatVeryLargeTest, DontUseVeryLarge) { RunTest(CompilerFilter::kAssumeVerified, false, false); RunTest(CompilerFilter::kSpeed, false, false); - RunTest(CompilerFilter::kAssumeVerified, false, false, { "--very-large-app-threshold=10000000" }); - RunTest(CompilerFilter::kSpeed, false, false, { "--very-large-app-threshold=10000000" }); + RunTest(CompilerFilter::kAssumeVerified, false, false, {"--very-large-app-threshold=10000000"}); + RunTest(CompilerFilter::kSpeed, false, false, {"--very-large-app-threshold=10000000"}); } TEST_F(Dex2oatVeryLargeTest, UseVeryLarge) { - RunTest(CompilerFilter::kAssumeVerified, true, false, { "--very-large-app-threshold=100" }); - RunTest(CompilerFilter::kSpeed, true, true, { "--very-large-app-threshold=100" }); + RunTest(CompilerFilter::kAssumeVerified, true, false, {"--very-large-app-threshold=100"}); + RunTest(CompilerFilter::kSpeed, true, true, {"--very-large-app-threshold=100"}); } // Regressin test for b/35665292. @@ -618,13 +611,12 @@ class Dex2oatLayoutTest : public Dex2oatTest { EXPECT_EQ(dex_files.size(), 1U); std::unique_ptr<const DexFile>& dex_file = dex_files[0]; - int profile_test_fd = open(test_profile.c_str(), - O_CREAT | O_TRUNC | O_WRONLY | O_CLOEXEC, - 0644); + int profile_test_fd = + open(test_profile.c_str(), O_CREAT | O_TRUNC | O_WRONLY | O_CLOEXEC, 0644); CHECK_GE(profile_test_fd, 0); ProfileCompilationInfo info; - std::vector<dex::TypeIndex> classes;; + std::vector<dex::TypeIndex> classes; for (size_t i = 0; i < num_classes; ++i) { classes.push_back(dex::TypeIndex(class_offset + 1 + i)); } @@ -655,12 +647,8 @@ class Dex2oatLayoutTest : public Dex2oatTest { copy.push_back("--app-image-file=" + app_image_file_name); } } - ASSERT_TRUE(GenerateOdexForTest(dex_location, - odex_location, - CompilerFilter::kSpeedProfile, - copy, - expect_success, - use_fd)); + ASSERT_TRUE(GenerateOdexForTest( + dex_location, odex_location, CompilerFilter::kSpeedProfile, copy, expect_success, use_fd)); if (app_image_file != nullptr) { ASSERT_EQ(app_image_file->FlushCloseOrErase(), 0) << "Could not flush and close art file"; } @@ -701,7 +689,7 @@ class Dex2oatLayoutTest : public Dex2oatTest { void RunTest(bool app_image) { std::string dex_location = GetScratchDir() + "/DexNoOat.jar"; std::string odex_location = GetOdexDir() + "/DexOdexNoOat.odex"; - std::string app_image_file = app_image ? (GetOdexDir() + "/DexOdexNoOat.art"): ""; + std::string app_image_file = app_image ? (GetOdexDir() + "/DexOdexNoOat.art") : ""; Copy(GetDexSrc2(), dex_location); uint32_t image_file_empty_profile = 0; @@ -709,8 +697,8 @@ class Dex2oatLayoutTest : public Dex2oatTest { CompileProfileOdex(dex_location, odex_location, app_image_file, - /*use_fd=*/ false, - /*num_profile_classes=*/ 0); + /*use_fd=*/false, + /*num_profile_classes=*/0); CheckValidity(); // Don't check the result since CheckResult relies on the class being in the profile. image_file_empty_profile = GetImageObjectSectionSize(app_image_file); @@ -722,8 +710,8 @@ class Dex2oatLayoutTest : public Dex2oatTest { CompileProfileOdex(dex_location, odex_location, app_image_file, - /*use_fd=*/ false, - /*num_profile_classes=*/ 1); + /*use_fd=*/false, + /*num_profile_classes=*/1); CheckValidity(); CheckResult(dex_location, odex_location, app_image_file); CheckCompilerFilter(dex_location, odex_location, CompilerFilter::Filter::kSpeedProfile); @@ -735,16 +723,15 @@ class Dex2oatLayoutTest : public Dex2oatTest { } } - void CheckCompilerFilter( - const std::string& dex_location, - const std::string& odex_location, - CompilerFilter::Filter expected_filter) { + void CheckCompilerFilter(const std::string& dex_location, + const std::string& odex_location, + CompilerFilter::Filter expected_filter) { std::string error_msg; - std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1, - odex_location.c_str(), - odex_location.c_str(), - /*executable=*/ false, - /*low_4gb=*/ false, + std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/-1, + odex_location, + odex_location, + /*executable=*/false, + /*low_4gb=*/false, dex_location, &error_msg)); EXPECT_EQ(odex_file->GetCompilerFilter(), expected_filter); @@ -766,9 +753,9 @@ class Dex2oatLayoutTest : public Dex2oatTest { CompileProfileOdex(dex_location, odex_location, app_image_file_name, - /*use_fd=*/ true, - /*num_profile_classes=*/ 1, - { input_vdex, output_vdex }); + /*use_fd=*/true, + /*num_profile_classes=*/1, + {input_vdex, output_vdex}); EXPECT_GT(vdex_file1->GetLength(), 0u); } { @@ -778,10 +765,10 @@ class Dex2oatLayoutTest : public Dex2oatTest { CompileProfileOdex(dex_location, odex_location, app_image_file_name, - /*use_fd=*/ true, - /*num_profile_classes=*/ 1, - { input_vdex, output_vdex }, - /*expect_success=*/ true); + /*use_fd=*/true, + /*num_profile_classes=*/1, + {input_vdex, output_vdex}, + /*expect_success=*/true); EXPECT_GT(vdex_file2.GetFile()->GetLength(), 0u); } ASSERT_EQ(vdex_file1->FlushCloseOrErase(), 0) << "Could not flush and close vdex file"; @@ -793,11 +780,11 @@ class Dex2oatLayoutTest : public Dex2oatTest { const std::string& app_image_file_name) { // Host/target independent checks. std::string error_msg; - std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1, - odex_location.c_str(), - odex_location.c_str(), - /*executable=*/ false, - /*low_4gb=*/ false, + std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/-1, + odex_location, + odex_location, + /*executable=*/false, + /*low_4gb=*/false, dex_location, &error_msg)); ASSERT_TRUE(odex_file.get() != nullptr) << error_msg; @@ -858,13 +845,9 @@ class Dex2oatLayoutTest : public Dex2oatTest { } }; -TEST_F(Dex2oatLayoutTest, TestLayout) { - RunTest(/*app_image=*/ false); -} +TEST_F(Dex2oatLayoutTest, TestLayout) { RunTest(/*app_image=*/false); } -TEST_F(Dex2oatLayoutTest, TestLayoutAppImage) { - RunTest(/*app_image=*/ true); -} +TEST_F(Dex2oatLayoutTest, TestLayoutAppImage) { RunTest(/*app_image=*/true); } TEST_F(Dex2oatLayoutTest, TestLayoutAppImageMissingBootImage) { std::string dex_location = GetScratchDir() + "/DexNoOat.jar"; @@ -875,18 +858,18 @@ TEST_F(Dex2oatLayoutTest, TestLayoutAppImageMissingBootImage) { CompileProfileOdex(dex_location, odex_location, app_image_file, - /*use_fd=*/ false, - /*num_profile_classes=*/ 1, - /*extra_args=*/ {"--boot-image=/nonx/boot.art"}, - /*expect_success=*/ true); + /*use_fd=*/false, + /*num_profile_classes=*/1, + /*extra_args=*/{"--boot-image=/nonx/boot.art"}, + /*expect_success=*/true); // Verify the odex file does not require an image. std::string error_msg; - std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1, - odex_location.c_str(), - odex_location.c_str(), - /*executable=*/ false, - /*low_4gb=*/ false, + std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/-1, + odex_location, + odex_location, + /*executable=*/false, + /*low_4gb=*/false, dex_location, &error_msg)); ASSERT_TRUE(odex_file != nullptr) << "Could not open odex file: " << error_msg; @@ -984,9 +967,7 @@ TEST_F(Dex2oatLayoutTest, TestLayoutMultipleProfilesChecksumMismatch) { EXPECT_EQ(image_size_wrong_checksum, image_size_empty); } -TEST_F(Dex2oatLayoutTest, TestVdexLayout) { - RunTestVDex(); -} +TEST_F(Dex2oatLayoutTest, TestVdexLayout) { RunTestVDex(); } class Dex2oatWatchdogTest : public Dex2oatTest { protected: @@ -1001,16 +982,11 @@ class Dex2oatWatchdogTest : public Dex2oatTest { std::string swap_location = GetOdexDir() + "/Dex2OatSwapTest.odex.swap"; copy.push_back("--swap-file=" + swap_location); copy.push_back("-j512"); // Excessive idle threads just slow down dex2oat. - ASSERT_TRUE(GenerateOdexForTest(dex_location, - odex_location, - CompilerFilter::kSpeed, - copy, - expect_success)); + ASSERT_TRUE(GenerateOdexForTest( + dex_location, odex_location, CompilerFilter::kSpeed, copy, expect_success)); } - std::string GetTestDexFileName() { - return GetDexSrc1(); - } + std::string GetTestDexFileName() { return GetDexSrc1(); } }; TEST_F(Dex2oatWatchdogTest, TestWatchdogOK) { @@ -1018,7 +994,7 @@ TEST_F(Dex2oatWatchdogTest, TestWatchdogOK) { RunTest(true); // Check with ten minutes. - RunTest(true, { "--watchdog-timeout=600000" }); + RunTest(true, {"--watchdog-timeout=600000"}); } TEST_F(Dex2oatWatchdogTest, TestWatchdogTrigger) { @@ -1032,7 +1008,7 @@ TEST_F(Dex2oatWatchdogTest, TestWatchdogTrigger) { test_accepts_odex_file_on_failure = true; // Check with ten milliseconds. - RunTest(false, { "--watchdog-timeout=10" }); + RunTest(false, {"--watchdog-timeout=10"}); } class Dex2oatReturnCodeTest : public Dex2oatTest { @@ -1044,16 +1020,11 @@ class Dex2oatReturnCodeTest : public Dex2oatTest { Copy(GetTestDexFileName(), dex_location); std::string error_msg; - return GenerateOdexForTestWithStatus({dex_location}, - odex_location, - CompilerFilter::kSpeed, - &error_msg, - extra_args); + return GenerateOdexForTestWithStatus( + {dex_location}, odex_location, CompilerFilter::kSpeed, &error_msg, extra_args); } - std::string GetTestDexFileName() { - return GetDexSrc1(); - } + std::string GetTestDexFileName() { return GetDexSrc1(); } }; class Dex2oatClassLoaderContextTest : public Dex2oatTest { @@ -1088,22 +1059,16 @@ class Dex2oatClassLoaderContextTest : public Dex2oatTest { CompilerFilter::kVerify, extra_args, expected_success, - /*use_fd=*/ false, - /*use_zip_fd=*/ false, + /*use_fd=*/false, + /*use_zip_fd=*/false, check_oat)); } - std::string GetUsedDexLocation() { - return GetScratchDir() + "/Context.jar"; - } + std::string GetUsedDexLocation() { return GetScratchDir() + "/Context.jar"; } - std::string GetUsedOatLocation() { - return GetOdexDir() + "/Context.odex"; - } + std::string GetUsedOatLocation() { return GetOdexDir() + "/Context.odex"; } - std::string GetUsedImageLocation() { - return GetOdexDir() + "/Context.art"; - } + std::string GetUsedImageLocation() { return GetOdexDir() + "/Context.art"; } const char* kEmptyClassPathKey = "PCL[]"; }; @@ -1125,8 +1090,8 @@ TEST_F(Dex2oatClassLoaderContextTest, ContextWithOtherDexFiles) { std::vector<std::unique_ptr<const DexFile>> dex_files = OpenTestDexFiles("Nested"); std::string context = "PCL[" + dex_files[0]->GetLocation() + "]"; - std::string expected_classpath_key = "PCL[" + - dex_files[0]->GetLocation() + "*" + std::to_string(dex_files[0]->GetLocationChecksum()) + "]"; + std::string expected_classpath_key = "PCL[" + dex_files[0]->GetLocation() + "*" + + std::to_string(dex_files[0]->GetLocationChecksum()) + "]"; RunTest(context.c_str(), expected_classpath_key.c_str(), true); } @@ -1136,7 +1101,7 @@ TEST_F(Dex2oatClassLoaderContextTest, ContextWithResourceOnlyDexFiles) { std::string context = "PCL[" + resource_only_classpath + "]"; // Expect an empty context because resource only dex files cannot be open. - RunTest(context.c_str(), kEmptyClassPathKey , /*expected_success*/ true); + RunTest(context.c_str(), kEmptyClassPathKey, /*expected_success*/ true); } TEST_F(Dex2oatClassLoaderContextTest, ContextWithNotExistentDexFiles) { @@ -1149,10 +1114,10 @@ TEST_F(Dex2oatClassLoaderContextTest, ChainContext) { std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested"); std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex"); - std::string context = "PCL[" + GetTestDexFileName("Nested") + "];" + - "DLC[" + GetTestDexFileName("MultiDex") + "]"; + std::string context = + "PCL[" + GetTestDexFileName("Nested") + "];" + "DLC[" + GetTestDexFileName("MultiDex") + "]"; std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "];" + - "DLC[" + CreateClassPathWithChecksums(dex_files2) + "]"; + "DLC[" + CreateClassPathWithChecksums(dex_files2) + "]"; RunTest(context.c_str(), expected_classpath_key.c_str(), true); } @@ -1161,10 +1126,10 @@ TEST_F(Dex2oatClassLoaderContextTest, ContextWithSharedLibrary) { std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested"); std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex"); - std::string context = "PCL[" + GetTestDexFileName("Nested") + "]" + - "{PCL[" + GetTestDexFileName("MultiDex") + "]}"; + std::string context = + "PCL[" + GetTestDexFileName("Nested") + "]" + "{PCL[" + GetTestDexFileName("MultiDex") + "]}"; std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "]" + - "{PCL[" + CreateClassPathWithChecksums(dex_files2) + "]}"; + "{PCL[" + CreateClassPathWithChecksums(dex_files2) + "]}"; RunTest(context.c_str(), expected_classpath_key.c_str(), true); } @@ -1172,49 +1137,49 @@ TEST_F(Dex2oatClassLoaderContextTest, ContextWithSharedLibraryAndImage) { std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested"); std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex"); - std::string context = "PCL[" + GetTestDexFileName("Nested") + "]" + - "{PCL[" + GetTestDexFileName("MultiDex") + "]}"; + std::string context = + "PCL[" + GetTestDexFileName("Nested") + "]" + "{PCL[" + GetTestDexFileName("MultiDex") + "]}"; std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "]" + - "{PCL[" + CreateClassPathWithChecksums(dex_files2) + "]}"; + "{PCL[" + CreateClassPathWithChecksums(dex_files2) + "]}"; RunTest(context.c_str(), expected_classpath_key.c_str(), - /*expected_success=*/ true, - /*use_second_source=*/ false, - /*generate_image=*/ true); + /*expected_success=*/true, + /*use_second_source=*/false, + /*generate_image=*/true); } TEST_F(Dex2oatClassLoaderContextTest, ContextWithSameSharedLibrariesAndImage) { std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested"); std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex"); - std::string context = "PCL[" + GetTestDexFileName("Nested") + "]" + - "{PCL[" + GetTestDexFileName("MultiDex") + "]" + - "#PCL[" + GetTestDexFileName("MultiDex") + "]}"; + std::string context = "PCL[" + GetTestDexFileName("Nested") + "]" + "{PCL[" + + GetTestDexFileName("MultiDex") + "]" + "#PCL[" + + GetTestDexFileName("MultiDex") + "]}"; std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "]" + - "{PCL[" + CreateClassPathWithChecksums(dex_files2) + "]" + - "#PCL[" + CreateClassPathWithChecksums(dex_files2) + "]}"; + "{PCL[" + CreateClassPathWithChecksums(dex_files2) + "]" + + "#PCL[" + CreateClassPathWithChecksums(dex_files2) + "]}"; RunTest(context.c_str(), expected_classpath_key.c_str(), - /*expected_success=*/ true, - /*use_second_source=*/ false, - /*generate_image=*/ true); + /*expected_success=*/true, + /*use_second_source=*/false, + /*generate_image=*/true); } TEST_F(Dex2oatClassLoaderContextTest, ContextWithSharedLibrariesDependenciesAndImage) { std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested"); std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex"); - std::string context = "PCL[" + GetTestDexFileName("Nested") + "]" + - "{PCL[" + GetTestDexFileName("MultiDex") + "]" + - "{PCL[" + GetTestDexFileName("Nested") + "]}}"; + std::string context = "PCL[" + GetTestDexFileName("Nested") + "]" + "{PCL[" + + GetTestDexFileName("MultiDex") + "]" + "{PCL[" + + GetTestDexFileName("Nested") + "]}}"; std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "]" + - "{PCL[" + CreateClassPathWithChecksums(dex_files2) + "]" + - "{PCL[" + CreateClassPathWithChecksums(dex_files1) + "]}}"; + "{PCL[" + CreateClassPathWithChecksums(dex_files2) + "]" + + "{PCL[" + CreateClassPathWithChecksums(dex_files1) + "]}}"; RunTest(context.c_str(), expected_classpath_key.c_str(), - /*expected_success=*/ true, - /*use_second_source=*/ false, - /*generate_image=*/ true); + /*expected_success=*/true, + /*use_second_source=*/false, + /*generate_image=*/true); } class Dex2oatDeterminism : public Dex2oatTest {}; @@ -1233,12 +1198,12 @@ TEST_F(Dex2oatDeterminism, UnloadCompile) { ASSERT_GT(spaces.size(), 0u); const std::string image_location = spaces[0]->GetImageLocation(); // Without passing in an app image, it will unload in between compilations. - const int res = GenerateOdexForTestWithStatus( - GetLibCoreDexFileNames(), - base_oat_name, - CompilerFilter::Filter::kVerify, - &error_msg, - {"--force-determinism", "--avoid-storing-invocation"}); + const int res = + GenerateOdexForTestWithStatus(GetLibCoreDexFileNames(), + base_oat_name, + CompilerFilter::Filter::kVerify, + &error_msg, + {"--force-determinism", "--avoid-storing-invocation"}); ASSERT_EQ(res, 0); Copy(base_oat_name, unload_oat_name); Copy(base_vdex_name, unload_vdex_name); @@ -1303,21 +1268,14 @@ TEST_F(Dex2oatTest, LayoutSections) { std::vector<uint16_t> post_methods = {methods[0], methods[2], methods[6]}; // Here, we build the profile from the method lists. ProfileCompilationInfo info; + info.AddMethodsForDex(static_cast<Hotness::Flag>(Hotness::kFlagHot | Hotness::kFlagStartup), + dex.get(), + hot_methods.begin(), + hot_methods.end()); info.AddMethodsForDex( - static_cast<Hotness::Flag>(Hotness::kFlagHot | Hotness::kFlagStartup), - dex.get(), - hot_methods.begin(), - hot_methods.end()); - info.AddMethodsForDex( - Hotness::kFlagStartup, - dex.get(), - startup_methods.begin(), - startup_methods.end()); + Hotness::kFlagStartup, dex.get(), startup_methods.begin(), startup_methods.end()); info.AddMethodsForDex( - Hotness::kFlagPostStartup, - dex.get(), - post_methods.begin(), - post_methods.end()); + Hotness::kFlagPostStartup, dex.get(), post_methods.begin(), post_methods.end()); for (uint16_t id : hot_methods) { EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsHot()); EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsStartup()); @@ -1340,16 +1298,15 @@ TEST_F(Dex2oatTest, LayoutSections) { oat_filename, CompilerFilter::Filter::kVerify, &error_msg, - {"--profile-file=" + profile_file.GetFilename(), - "--compact-dex-level=fast"}); + {"--profile-file=" + profile_file.GetFilename(), "--compact-dex-level=fast"}); EXPECT_EQ(res, 0); // Open our generated oat file. - std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1, - oat_filename.c_str(), - oat_filename.c_str(), - /*executable=*/ false, - /*low_4gb=*/ false, + std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/-1, + oat_filename, + oat_filename, + /*executable=*/false, + /*low_4gb=*/false, dex->GetLocation(), &error_msg)); ASSERT_TRUE(odex_file != nullptr); @@ -1445,19 +1402,18 @@ TEST_F(Dex2oatTest, GenerateCompactDex) { const std::string vdex_filename = dir + "/base.vdex"; const std::string dex_location = GetTestDexFileName("MultiDex"); std::string error_msg; - const int res = GenerateOdexForTestWithStatus( - { dex_location }, - oat_filename, - CompilerFilter::Filter::kVerify, - &error_msg, - {"--compact-dex-level=fast"}); + const int res = GenerateOdexForTestWithStatus({dex_location}, + oat_filename, + CompilerFilter::Filter::kVerify, + &error_msg, + {"--compact-dex-level=fast"}); EXPECT_EQ(res, 0); // Open our generated oat file. - std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1, - oat_filename.c_str(), - oat_filename.c_str(), - /*executable=*/ false, - /*low_4gb=*/ false, + std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/-1, + oat_filename, + oat_filename, + /*executable=*/false, + /*low_4gb=*/false, dex_location, &error_msg)); ASSERT_TRUE(odex_file != nullptr); @@ -1505,20 +1461,18 @@ TEST_F(Dex2oatVerifierAbort, HardFail) { std::string out_dir = GetScratchDir(); const std::string base_oat_name = out_dir + "/base.oat"; std::string error_msg; - const int res_fail = GenerateOdexForTestWithStatus( - {dex->GetLocation()}, - base_oat_name, - CompilerFilter::Filter::kVerify, - &error_msg, - {"--abort-on-hard-verifier-error"}); + const int res_fail = GenerateOdexForTestWithStatus({dex->GetLocation()}, + base_oat_name, + CompilerFilter::Filter::kVerify, + &error_msg, + {"--abort-on-hard-verifier-error"}); EXPECT_NE(0, res_fail); - const int res_no_fail = GenerateOdexForTestWithStatus( - {dex->GetLocation()}, - base_oat_name, - CompilerFilter::Filter::kVerify, - &error_msg, - {"--no-abort-on-hard-verifier-error"}); + const int res_no_fail = GenerateOdexForTestWithStatus({dex->GetLocation()}, + base_oat_name, + CompilerFilter::Filter::kVerify, + &error_msg, + {"--no-abort-on-hard-verifier-error"}); EXPECT_EQ(0, res_no_fail); } @@ -1530,28 +1484,25 @@ TEST_F(Dex2oatDedupeCode, DedupeTest) { std::string out_dir = GetScratchDir(); const std::string base_oat_name = out_dir + "/base.oat"; size_t no_dedupe_size = 0; - ASSERT_TRUE(GenerateOdexForTest(dex->GetLocation(), - base_oat_name, - CompilerFilter::Filter::kSpeed, - { "--deduplicate-code=false" }, - /*expect_success=*/ true, - /*use_fd=*/ false, - /*use_zip_fd=*/ false, - [&no_dedupe_size](const OatFile& o) { - no_dedupe_size = o.Size(); - })); + ASSERT_TRUE( + GenerateOdexForTest(dex->GetLocation(), + base_oat_name, + CompilerFilter::Filter::kSpeed, + {"--deduplicate-code=false"}, + /*expect_success=*/true, + /*use_fd=*/false, + /*use_zip_fd=*/false, + [&no_dedupe_size](const OatFile& o) { no_dedupe_size = o.Size(); })); size_t dedupe_size = 0; ASSERT_TRUE(GenerateOdexForTest(dex->GetLocation(), base_oat_name, CompilerFilter::Filter::kSpeed, - { "--deduplicate-code=true" }, - /*expect_success=*/ true, - /*use_fd=*/ false, - /*use_zip_fd=*/ false, - [&dedupe_size](const OatFile& o) { - dedupe_size = o.Size(); - })); + {"--deduplicate-code=true"}, + /*expect_success=*/true, + /*use_fd=*/false, + /*use_zip_fd=*/false, + [&dedupe_size](const OatFile& o) { dedupe_size = o.Size(); })); EXPECT_LT(dedupe_size, no_dedupe_size); } @@ -1563,13 +1514,11 @@ TEST_F(Dex2oatTest, UncompressedTest) { ASSERT_TRUE(GenerateOdexForTest(dex->GetLocation(), base_oat_name, CompilerFilter::Filter::kVerify, - { }, - /*expect_success=*/ true, - /*use_fd=*/ false, - /*use_zip_fd=*/ false, - [](const OatFile& o) { - CHECK(!o.ContainsDexCode()); - })); + {}, + /*expect_success=*/true, + /*use_fd=*/false, + /*use_zip_fd=*/false, + [](const OatFile& o) { CHECK(!o.ContainsDexCode()); })); } TEST_F(Dex2oatTest, MissingBootImageTest) { @@ -1588,13 +1537,12 @@ TEST_F(Dex2oatTest, EmptyUncompressedDexTest) { std::string out_dir = GetScratchDir(); const std::string base_oat_name = out_dir + "/base.oat"; std::string error_msg; - int status = GenerateOdexForTestWithStatus( - { GetTestDexFileName("MainEmptyUncompressed") }, - base_oat_name, - CompilerFilter::Filter::kVerify, - &error_msg, - { }, - /*use_fd*/ false); + int status = GenerateOdexForTestWithStatus({GetTestDexFileName("MainEmptyUncompressed")}, + base_oat_name, + CompilerFilter::Filter::kVerify, + &error_msg, + {}, + /*use_fd*/ false); // Expect to fail with code 1 and not SIGSEGV or SIGABRT. ASSERT_TRUE(WIFEXITED(status)); ASSERT_EQ(WEXITSTATUS(status), 1) << error_msg; @@ -1604,13 +1552,12 @@ TEST_F(Dex2oatTest, EmptyUncompressedAlignedDexTest) { std::string out_dir = GetScratchDir(); const std::string base_oat_name = out_dir + "/base.oat"; std::string error_msg; - int status = GenerateOdexForTestWithStatus( - { GetTestDexFileName("MainEmptyUncompressedAligned") }, - base_oat_name, - CompilerFilter::Filter::kVerify, - &error_msg, - { }, - /*use_fd*/ false); + int status = GenerateOdexForTestWithStatus({GetTestDexFileName("MainEmptyUncompressedAligned")}, + base_oat_name, + CompilerFilter::Filter::kVerify, + &error_msg, + {}, + /*use_fd*/ false); // Expect to fail with code 1 and not SIGSEGV or SIGABRT. ASSERT_TRUE(WIFEXITED(status)); ASSERT_EQ(WEXITSTATUS(status), 1) << error_msg; @@ -1696,20 +1643,18 @@ TEST_F(Dex2oatTest, CompactDexGenerationFailure) { ASSERT_TRUE(GenerateOdexForTest(temp_dex.GetFilename(), oat_filename, CompilerFilter::Filter::kVerify, - { }, - /*expect_success=*/ true, - /*use_fd=*/ false, - /*use_zip_fd=*/ false, - [](const OatFile& o) { - CHECK(o.ContainsDexCode()); - })); + {}, + /*expect_success=*/true, + /*use_fd=*/false, + /*use_zip_fd=*/false, + [](const OatFile& o) { CHECK(o.ContainsDexCode()); })); // Open our generated oat file. std::string error_msg; - std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1, - oat_filename.c_str(), - oat_filename.c_str(), - /*executable=*/ false, - /*low_4gb=*/ false, + std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/-1, + oat_filename, + oat_filename, + /*executable=*/false, + /*low_4gb=*/false, temp_dex.GetFilename(), &error_msg)); ASSERT_TRUE(odex_file != nullptr); @@ -1744,11 +1689,8 @@ TEST_F(Dex2oatTest, CompactDexGenerationFailureMultiDex) { } const std::string& dex_location = apk_file.GetFilename(); const std::string odex_location = GetOdexDir() + "/output.odex"; - ASSERT_TRUE(GenerateOdexForTest(dex_location, - odex_location, - CompilerFilter::kVerify, - { "--compact-dex-level=fast" }, - true)); + ASSERT_TRUE(GenerateOdexForTest( + dex_location, odex_location, CompilerFilter::kVerify, {"--compact-dex-level=fast"}, true)); } TEST_F(Dex2oatTest, StderrLoggerOutput) { @@ -1761,7 +1703,7 @@ TEST_F(Dex2oatTest, StderrLoggerOutput) { ASSERT_TRUE(GenerateOdexForTest(dex_location, odex_location, CompilerFilter::kVerify, - { "--runtime-arg", "-Xuse-stderr-logger" }, + {"--runtime-arg", "-Xuse-stderr-logger"}, true)); // Look for some random part of dex2oat logging. With the stderr logger this should be captured, // even on device. @@ -1778,14 +1720,14 @@ TEST_F(Dex2oatTest, VerifyCompilationReason) { ASSERT_TRUE(GenerateOdexForTest(dex_location, odex_location, CompilerFilter::kVerify, - { "--compilation-reason=install" }, + {"--compilation-reason=install"}, true)); std::string error_msg; - std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1, - odex_location.c_str(), - odex_location.c_str(), - /*executable=*/ false, - /*low_4gb=*/ false, + std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/-1, + odex_location, + odex_location, + /*executable=*/false, + /*low_4gb=*/false, dex_location, &error_msg)); ASSERT_TRUE(odex_file != nullptr); @@ -1799,17 +1741,13 @@ TEST_F(Dex2oatTest, VerifyNoCompilationReason) { // Test file doesn't matter. Copy(GetDexSrc1(), dex_location); - ASSERT_TRUE(GenerateOdexForTest(dex_location, - odex_location, - CompilerFilter::kVerify, - {}, - true)); + ASSERT_TRUE(GenerateOdexForTest(dex_location, odex_location, CompilerFilter::kVerify, {}, true)); std::string error_msg; - std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1, - odex_location.c_str(), - odex_location.c_str(), - /*executable=*/ false, - /*low_4gb=*/ false, + std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/-1, + odex_location, + odex_location, + /*executable=*/false, + /*low_4gb=*/false, dex_location, &error_msg)); ASSERT_TRUE(odex_file != nullptr); @@ -1826,25 +1764,25 @@ TEST_F(Dex2oatTest, DontExtract) { ASSERT_TRUE(GenerateOdexForTest(dex_location, odex_location, CompilerFilter::Filter::kVerify, - { "--copy-dex-files=false" }, - /*expect_success=*/ true, - /*use_fd=*/ false, - /*use_zip_fd=*/ false, + {"--copy-dex-files=false"}, + /*expect_success=*/true, + /*use_fd=*/false, + /*use_zip_fd=*/false, [](const OatFile&) {})); { // Check the vdex doesn't have dex. - std::unique_ptr<VdexFile> vdex(VdexFile::Open(vdex_location.c_str(), - /*writable=*/ false, - /*low_4gb=*/ false, + std::unique_ptr<VdexFile> vdex(VdexFile::Open(vdex_location, + /*writable=*/false, + /*low_4gb=*/false, &error_msg)); ASSERT_TRUE(vdex != nullptr); EXPECT_FALSE(vdex->HasDexSection()) << output_; } - std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1, - odex_location.c_str(), - odex_location.c_str(), - /*executable=*/ false, - /*low_4gb=*/ false, + std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/-1, + odex_location, + odex_location, + /*executable=*/false, + /*low_4gb=*/false, dex_location, &error_msg)); ASSERT_TRUE(odex_file != nullptr) << dex_location; @@ -1882,18 +1820,16 @@ TEST_F(Dex2oatTest, DontExtract) { ASSERT_TRUE(GenerateOdexForTest(dex_location, odex_location, filter, - { "--dump-timings", - "--dm-file=" + dm_file.GetFilename(), - // Pass -Xuse-stderr-logger have dex2oat output in output_ on - // target. - "--runtime-arg", - "-Xuse-stderr-logger" }, - /*expect_success=*/ true, - /*use_fd=*/ false, - /*use_zip_fd=*/ false, - [](const OatFile& o) { - CHECK(o.ContainsDexCode()); - })); + {"--dump-timings", + "--dm-file=" + dm_file.GetFilename(), + // Pass -Xuse-stderr-logger have dex2oat output in output_ on + // target. + "--runtime-arg", + "-Xuse-stderr-logger"}, + /*expect_success=*/true, + /*use_fd=*/false, + /*use_zip_fd=*/false, + [](const OatFile& o) { CHECK(o.ContainsDexCode()); })); // Check the output for "Fast verify", this is printed from --dump-timings. std::istringstream iss(output_); std::string line; @@ -1933,12 +1869,11 @@ TEST_F(Dex2oatTest, CompactDexInvalidSource) { const std::string& dex_location = invalid_dex.GetFilename(); const std::string odex_location = GetOdexDir() + "/output.odex"; std::string error_msg; - int status = GenerateOdexForTestWithStatus( - {dex_location}, - odex_location, - CompilerFilter::kVerify, - &error_msg, - { "--compact-dex-level=fast" }); + int status = GenerateOdexForTestWithStatus({dex_location}, + odex_location, + CompilerFilter::kVerify, + &error_msg, + {"--compact-dex-level=fast"}); ASSERT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) != 0) << status << " " << output_; } @@ -1972,20 +1907,18 @@ TEST_F(Dex2oatTest, CompactDexInZip) { std::string error_msg; int status = 0u; - status = GenerateOdexForTestWithStatus( - { invalid_dex_zip.GetFilename() }, - GetOdexDir() + "/output_apk.odex", - CompilerFilter::kVerify, - &error_msg, - { "--compact-dex-level=fast" }); + status = GenerateOdexForTestWithStatus({invalid_dex_zip.GetFilename()}, + GetOdexDir() + "/output_apk.odex", + CompilerFilter::kVerify, + &error_msg, + {"--compact-dex-level=fast"}); ASSERT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) != 0) << status << " " << output_; - status = GenerateOdexForTestWithStatus( - { invalid_dex.GetFilename() }, - GetOdexDir() + "/output.odex", - CompilerFilter::kVerify, - &error_msg, - { "--compact-dex-level=fast" }); + status = GenerateOdexForTestWithStatus({invalid_dex.GetFilename()}, + GetOdexDir() + "/output.odex", + CompilerFilter::kVerify, + &error_msg, + {"--compact-dex-level=fast"}); ASSERT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) != 0) << status << " " << output_; } @@ -1999,25 +1932,25 @@ TEST_F(Dex2oatWithExpectedFilterTest, AppImageNoProfile) { ASSERT_TRUE(GenerateOdexForTest(GetTestDexFileName("ManyMethods"), odex_location, CompilerFilter::Filter::kSpeedProfile, - { "--app-image-fd=" + std::to_string(app_image_file.GetFd()) }, - /*expect_success=*/ true, - /*use_fd=*/ false, - /*use_zip_fd=*/ false, + {"--app-image-fd=" + std::to_string(app_image_file.GetFd())}, + /*expect_success=*/true, + /*use_fd=*/false, + /*use_zip_fd=*/false, [](const OatFile&) {})); // Open our generated oat file. std::string error_msg; - std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1, - odex_location.c_str(), - odex_location.c_str(), - /*executable=*/ false, - /*low_4gb=*/ false, + std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/-1, + odex_location, + odex_location, + /*executable=*/false, + /*low_4gb=*/false, &error_msg)); ASSERT_TRUE(odex_file != nullptr); ImageHeader header = {}; - ASSERT_TRUE(app_image_file.GetFile()->PreadFully( - reinterpret_cast<void*>(&header), - sizeof(header), - /*offset*/ 0u)) << app_image_file.GetFile()->GetLength(); + ASSERT_TRUE(app_image_file.GetFile()->PreadFully(reinterpret_cast<void*>(&header), + sizeof(header), + /*offset*/ 0u)) + << app_image_file.GetFile()->GetLength(); EXPECT_GT(header.GetImageSection(ImageHeader::kSectionObjects).Size(), 0u); EXPECT_EQ(header.GetImageSection(ImageHeader::kSectionArtMethods).Size(), 0u); EXPECT_EQ(header.GetImageSection(ImageHeader::kSectionArtFields).Size(), 0u); @@ -2036,9 +1969,9 @@ TEST_F(Dex2oatTest, ZipFd) { base_oat_name, CompilerFilter::Filter::kVerify, extra_args, - /*expect_success=*/ true, - /*use_fd=*/ false, - /*use_zip_fd=*/ true)); + /*expect_success=*/true, + /*use_fd=*/false, + /*use_zip_fd=*/true)); } TEST_F(Dex2oatWithExpectedFilterTest, AppImageEmptyDex) { @@ -2052,7 +1985,7 @@ TEST_F(Dex2oatWithExpectedFilterTest, AppImageEmptyDex) { std::vector<uint16_t> methods; std::vector<dex::TypeIndex> classes; { - MutateDexFile(temp_dex.GetFile(), GetTestDexFileName("StringLiterals"), [&] (DexFile* dex) { + MutateDexFile(temp_dex.GetFile(), GetTestDexFileName("StringLiterals"), [&](DexFile* dex) { // Modify the header to make the dex file valid but empty. DexFile::Header* header = const_cast<DexFile::Header*>(&dex->GetHeader()); header->string_ids_size_ = 0; @@ -2090,20 +2023,20 @@ TEST_F(Dex2oatWithExpectedFilterTest, AppImageEmptyDex) { ASSERT_TRUE(GenerateOdexForTest(dex_location, odex_location, CompilerFilter::Filter::kSpeedProfile, - { "--app-image-file=" + app_image_location, - "--resolve-startup-const-strings=true", - "--profile-file=" + profile_file.GetFilename()}, - /*expect_success=*/ true, - /*use_fd=*/ false, - /*use_zip_fd=*/ false, + {"--app-image-file=" + app_image_location, + "--resolve-startup-const-strings=true", + "--profile-file=" + profile_file.GetFilename()}, + /*expect_success=*/true, + /*use_fd=*/false, + /*use_zip_fd=*/false, [](const OatFile&) {})); // Open our generated oat file. std::string error_msg; - std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1, - odex_location.c_str(), - odex_location.c_str(), - /*executable=*/ false, - /*low_4gb=*/ false, + std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/-1, + odex_location, + odex_location, + /*executable=*/false, + /*low_4gb=*/false, &error_msg)); ASSERT_TRUE(odex_file != nullptr); } @@ -2138,9 +2071,9 @@ TEST_F(Dex2oatTest, DexFileFd) { base_oat_name, CompilerFilter::Filter::kVerify, extra_args, - /*expect_success=*/ true, - /*use_fd=*/ false, - /*use_zip_fd=*/ true)); + /*expect_success=*/true, + /*use_fd=*/false, + /*use_zip_fd=*/true)); } TEST_F(Dex2oatTest, AppImageResolveStrings) { @@ -2152,46 +2085,47 @@ TEST_F(Dex2oatTest, AppImageResolveStrings) { std::vector<uint16_t> methods; std::vector<dex::TypeIndex> classes; { - MutateDexFile(temp_dex.GetFile(), GetTestDexFileName("StringLiterals"), [&] (DexFile* dex) { - bool mutated_successfully = false; - // Change the dex instructions to make an opcode that spans past the end of the code item. - for (ClassAccessor accessor : dex->GetClasses()) { - if (accessor.GetDescriptor() == std::string("LStringLiterals$StartupClass;")) { - classes.push_back(accessor.GetClassIdx()); - } - for (const ClassAccessor::Method& method : accessor.GetMethods()) { - std::string method_name(dex->GetMethodName(dex->GetMethodId(method.GetIndex()))); - CodeItemInstructionAccessor instructions = method.GetInstructions(); - if (method_name == "startUpMethod2") { - // Make an instruction that runs past the end of the code item and verify that it - // doesn't cause dex2oat to crash. - ASSERT_TRUE(instructions.begin() != instructions.end()); - DexInstructionIterator last_instruction = instructions.begin(); - for (auto dex_it = instructions.begin(); dex_it != instructions.end(); ++dex_it) { - last_instruction = dex_it; + MutateDexFile( + temp_dex.GetFile(), GetTestDexFileName("StringLiterals"), [&](DexFile* dex) { + bool mutated_successfully = false; + // Change the dex instructions to make an opcode that spans past the end of the code item. + for (ClassAccessor accessor : dex->GetClasses()) { + if (accessor.GetDescriptor() == std::string("LStringLiterals$StartupClass;")) { + classes.push_back(accessor.GetClassIdx()); } - ASSERT_EQ(last_instruction->SizeInCodeUnits(), 1u); - // Set the opcode to something that will go past the end of the code item. - const_cast<Instruction&>(last_instruction.Inst()).SetOpcode( - Instruction::CONST_STRING_JUMBO); - mutated_successfully = true; - // Test that the safe iterator doesn't go past the end. - SafeDexInstructionIterator it2(instructions.begin(), instructions.end()); - while (!it2.IsErrorState()) { - ++it2; + for (const ClassAccessor::Method& method : accessor.GetMethods()) { + std::string method_name(dex->GetMethodName(dex->GetMethodId(method.GetIndex()))); + CodeItemInstructionAccessor instructions = method.GetInstructions(); + if (method_name == "startUpMethod2") { + // Make an instruction that runs past the end of the code item and verify that it + // doesn't cause dex2oat to crash. + ASSERT_TRUE(instructions.begin() != instructions.end()); + DexInstructionIterator last_instruction = instructions.begin(); + for (auto dex_it = instructions.begin(); dex_it != instructions.end(); ++dex_it) { + last_instruction = dex_it; + } + ASSERT_EQ(last_instruction->SizeInCodeUnits(), 1u); + // Set the opcode to something that will go past the end of the code item. + const_cast<Instruction&>(last_instruction.Inst()) + .SetOpcode(Instruction::CONST_STRING_JUMBO); + mutated_successfully = true; + // Test that the safe iterator doesn't go past the end. + SafeDexInstructionIterator it2(instructions.begin(), instructions.end()); + while (!it2.IsErrorState()) { + ++it2; + } + EXPECT_TRUE(it2 == last_instruction); + EXPECT_TRUE(it2 < instructions.end()); + methods.push_back(method.GetIndex()); + mutated_successfully = true; + } else if (method_name == "startUpMethod") { + methods.push_back(method.GetIndex()); + } } - EXPECT_TRUE(it2 == last_instruction); - EXPECT_TRUE(it2 < instructions.end()); - methods.push_back(method.GetIndex()); - mutated_successfully = true; - } else if (method_name == "startUpMethod") { - methods.push_back(method.GetIndex()); } - } - } - CHECK(mutated_successfully) - << "Failed to find candidate code item with only one code unit in last instruction."; - }); + CHECK(mutated_successfully) + << "Failed to find candidate code item with only one code unit in last instruction."; + }); } std::unique_ptr<const DexFile> dex_file(OpenDexFile(temp_dex.GetFilename().c_str())); { @@ -2210,38 +2144,36 @@ TEST_F(Dex2oatTest, AppImageResolveStrings) { ASSERT_TRUE(GenerateOdexForTest(dex_location, odex_location, CompilerFilter::Filter::kSpeedProfile, - { "--app-image-file=" + app_image_location, - "--resolve-startup-const-strings=true", - "--profile-file=" + profile_file.GetFilename()}, - /*expect_success=*/ true, - /*use_fd=*/ false, - /*use_zip_fd=*/ false, + {"--app-image-file=" + app_image_location, + "--resolve-startup-const-strings=true", + "--profile-file=" + profile_file.GetFilename()}, + /*expect_success=*/true, + /*use_fd=*/false, + /*use_zip_fd=*/false, [](const OatFile&) {})); // Open our generated oat file. std::string error_msg; - std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1, - odex_location.c_str(), - odex_location.c_str(), - /*executable=*/ false, - /*low_4gb=*/ false, + std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/-1, + odex_location, + odex_location, + /*executable=*/false, + /*low_4gb=*/false, &error_msg)); ASSERT_TRUE(odex_file != nullptr); // Check the strings in the app image intern table only contain the "startup" strigs. { ScopedObjectAccess soa(Thread::Current()); - std::unique_ptr<gc::space::ImageSpace> space = - gc::space::ImageSpace::CreateFromAppImage(app_image_location.c_str(), - odex_file.get(), - &error_msg); + std::unique_ptr<gc::space::ImageSpace> space = gc::space::ImageSpace::CreateFromAppImage( + app_image_location.c_str(), odex_file.get(), &error_msg); ASSERT_TRUE(space != nullptr) << error_msg; std::set<std::string> seen; InternTable intern_table; - intern_table.AddImageStringsToTable(space.get(), [&](InternTable::UnorderedSet& interns) - REQUIRES_SHARED(Locks::mutator_lock_) { - for (const GcRoot<mirror::String>& str : interns) { - seen.insert(str.Read()->ToModifiedUtf8()); - } - }); + intern_table.AddImageStringsToTable( + space.get(), [&](InternTable::UnorderedSet& interns) REQUIRES_SHARED(Locks::mutator_lock_) { + for (const GcRoot<mirror::String>& str : interns) { + seen.insert(str.Read()->ToModifiedUtf8()); + } + }); // Normal methods EXPECT_TRUE(seen.find("Loading ") != seen.end()); EXPECT_TRUE(seen.find("Starting up") != seen.end()); @@ -2259,20 +2191,23 @@ TEST_F(Dex2oatTest, AppImageResolveStrings) { std::set<std::string> app_image_strings; MutexLock mu(Thread::Current(), *Locks::intern_table_lock_); - intern_table.VisitInterns([&](const GcRoot<mirror::String>& root) - REQUIRES_SHARED(Locks::mutator_lock_) { - boot_image_strings.insert(root.Read()->ToModifiedUtf8()); - }, /*visit_boot_images=*/true, /*visit_non_boot_images=*/false); - intern_table.VisitInterns([&](const GcRoot<mirror::String>& root) - REQUIRES_SHARED(Locks::mutator_lock_) { - app_image_strings.insert(root.Read()->ToModifiedUtf8()); - }, /*visit_boot_images=*/false, /*visit_non_boot_images=*/true); + intern_table.VisitInterns( + [&](const GcRoot<mirror::String>& root) REQUIRES_SHARED(Locks::mutator_lock_) { + boot_image_strings.insert(root.Read()->ToModifiedUtf8()); + }, + /*visit_boot_images=*/true, + /*visit_non_boot_images=*/false); + intern_table.VisitInterns( + [&](const GcRoot<mirror::String>& root) REQUIRES_SHARED(Locks::mutator_lock_) { + app_image_strings.insert(root.Read()->ToModifiedUtf8()); + }, + /*visit_boot_images=*/false, + /*visit_non_boot_images=*/true); EXPECT_EQ(boot_image_strings.size(), 0u); EXPECT_TRUE(app_image_strings == seen); } } - TEST_F(Dex2oatClassLoaderContextTest, StoredClassLoaderContext) { std::vector<std::unique_ptr<const DexFile>> dex_files = OpenTestDexFiles("MultiDex"); const std::string out_dir = GetScratchDir(); @@ -2293,31 +2228,34 @@ TEST_F(Dex2oatClassLoaderContextTest, StoredClassLoaderContext) { expected_stored_context += "*" + std::to_string(dex_file->GetLocationChecksum()); ++index; } - expected_stored_context += + "]"; + expected_stored_context += "]"; // The class path should not be valid and should fail being stored. EXPECT_TRUE(GenerateOdexForTest(GetTestDexFileName("ManyMethods"), odex_location, CompilerFilter::Filter::kVerify, - { "--class-loader-context=" + stored_context }, - /*expect_success=*/ true, - /*use_fd=*/ false, - /*use_zip_fd=*/ false, + {"--class-loader-context=" + stored_context}, + /*expect_success=*/true, + /*use_fd=*/false, + /*use_zip_fd=*/false, [&](const OatFile& oat_file) { - EXPECT_NE(oat_file.GetClassLoaderContext(), stored_context) << output_; - EXPECT_NE(oat_file.GetClassLoaderContext(), valid_context) << output_; - })); + EXPECT_NE(oat_file.GetClassLoaderContext(), stored_context) + << output_; + EXPECT_NE(oat_file.GetClassLoaderContext(), valid_context) + << output_; + })); // The stored context should match what we expect even though it's invalid. - EXPECT_TRUE(GenerateOdexForTest(GetTestDexFileName("ManyMethods"), - odex_location, - CompilerFilter::Filter::kVerify, - { "--class-loader-context=" + valid_context, - "--stored-class-loader-context=" + stored_context }, - /*expect_success=*/ true, - /*use_fd=*/ false, - /*use_zip_fd=*/ false, - [&](const OatFile& oat_file) { - EXPECT_EQ(oat_file.GetClassLoaderContext(), expected_stored_context) << output_; - })); + EXPECT_TRUE(GenerateOdexForTest( + GetTestDexFileName("ManyMethods"), + odex_location, + CompilerFilter::Filter::kVerify, + {"--class-loader-context=" + valid_context, + "--stored-class-loader-context=" + stored_context}, + /*expect_success=*/true, + /*use_fd=*/false, + /*use_zip_fd=*/false, + [&](const OatFile& oat_file) { + EXPECT_EQ(oat_file.GetClassLoaderContext(), expected_stored_context) << output_; + })); } class Dex2oatISAFeaturesRuntimeDetectionTest : public Dex2oatTest { @@ -2328,15 +2266,11 @@ class Dex2oatISAFeaturesRuntimeDetectionTest : public Dex2oatTest { Copy(GetTestDexFileName(), dex_location); - ASSERT_TRUE(GenerateOdexForTest(dex_location, - odex_location, - CompilerFilter::kSpeed, - extra_args)); + ASSERT_TRUE( + GenerateOdexForTest(dex_location, odex_location, CompilerFilter::kSpeed, extra_args)); } - std::string GetTestDexFileName() { - return GetDexSrc1(); - } + std::string GetTestDexFileName() { return GetDexSrc1(); } }; TEST_F(Dex2oatISAFeaturesRuntimeDetectionTest, TestCurrentRuntimeFeaturesAsDex2OatArguments) { @@ -2362,20 +2296,19 @@ TEST_F(LinkageTest, LinkageEnabled) { std::string out_dir = GetScratchDir(); const std::string base_oat_name = out_dir + "/base.oat"; std::string error_msg; - const int res_fail = GenerateOdexForTestWithStatus( - {dex->GetLocation()}, - base_oat_name, - CompilerFilter::Filter::kSpeed, - &error_msg, - {"--check-linkage-conditions", "--crash-on-linkage-violation"}); + const int res_fail = + GenerateOdexForTestWithStatus({dex->GetLocation()}, + base_oat_name, + CompilerFilter::Filter::kSpeed, + &error_msg, + {"--check-linkage-conditions", "--crash-on-linkage-violation"}); EXPECT_NE(0, res_fail); - const int res_no_fail = GenerateOdexForTestWithStatus( - {dex->GetLocation()}, - base_oat_name, - CompilerFilter::Filter::kSpeed, - &error_msg, - {"--check-linkage-conditions"}); + const int res_no_fail = GenerateOdexForTestWithStatus({dex->GetLocation()}, + base_oat_name, + CompilerFilter::Filter::kSpeed, + &error_msg, + {"--check-linkage-conditions"}); EXPECT_EQ(0, res_no_fail); } @@ -2387,19 +2320,19 @@ TEST_F(Dex2oatTest, LoadOutOfDateOatFile) { ASSERT_TRUE(GenerateOdexForTest(dex->GetLocation(), base_oat_name, CompilerFilter::Filter::kSpeed, - { "--deduplicate-code=false" }, - /*expect_success=*/ true, - /*use_fd=*/ false, - /*use_zip_fd=*/ false)); + {"--deduplicate-code=false"}, + /*expect_success=*/true, + /*use_fd=*/false, + /*use_zip_fd=*/false)); // Check that we can open the oat file as executable. { std::string error_msg; - std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1, - base_oat_name.c_str(), - base_oat_name.c_str(), - /*executable=*/ true, - /*low_4gb=*/ false, + std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/-1, + base_oat_name, + base_oat_name, + /*executable=*/true, + /*low_4gb=*/false, dex->GetLocation(), &error_msg)); ASSERT_TRUE(odex_file != nullptr) << error_msg; @@ -2415,19 +2348,19 @@ TEST_F(Dex2oatTest, LoadOutOfDateOatFile) { { std::string error_msg; std::unique_ptr<ElfFile> elf_file(ElfFile::Open(file.get(), - /*writable=*/ false, - /*program_header_only=*/ true, - /*low_4gb=*/ false, + /*writable=*/false, + /*program_header_only=*/true, + /*low_4gb=*/false, &error_msg)); ASSERT_TRUE(elf_file != nullptr) << error_msg; ASSERT_TRUE(elf_file->Load(file.get(), - /*executable=*/ false, - /*low_4gb=*/ false, - /*reservation=*/ nullptr, - &error_msg)) << error_msg; - const uint8_t* base_address = elf_file->Is64Bit() - ? elf_file->GetImpl64()->GetBaseAddress() - : elf_file->GetImpl32()->GetBaseAddress(); + /*executable=*/false, + /*low_4gb=*/false, + /*reservation=*/nullptr, + &error_msg)) + << error_msg; + const uint8_t* base_address = elf_file->Is64Bit() ? elf_file->GetImpl64()->GetBaseAddress() : + elf_file->GetImpl32()->GetBaseAddress(); const uint8_t* oatdata = elf_file->FindDynamicSymbolAddress("oatdata"); ASSERT_TRUE(oatdata != nullptr); ASSERT_TRUE(oatdata > base_address); @@ -2472,11 +2405,11 @@ TEST_F(Dex2oatTest, LoadOutOfDateOatFile) { // Check that we reject the oat file without crashing. { std::string error_msg; - std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1, - base_oat_name.c_str(), - base_oat_name.c_str(), - /*executable=*/ true, - /*low_4gb=*/ false, + std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/-1, + base_oat_name, + base_oat_name, + /*executable=*/true, + /*low_4gb=*/false, dex->GetLocation(), &error_msg)); ASSERT_FALSE(odex_file != nullptr); diff --git a/dex2oat/dex2oat_vdex_test.cc b/dex2oat/dex2oat_vdex_test.cc index df76d58980..27fcc180a5 100644 --- a/dex2oat/dex2oat_vdex_test.cc +++ b/dex2oat/dex2oat_vdex_test.cc @@ -49,7 +49,7 @@ class Dex2oatVdexTest : public Dex2oatEnvironmentTest { args.push_back("--public-sdk=" + *public_sdk); } args.push_back("--compiler-filter=" + - CompilerFilter::NameOfFilter(CompilerFilter::Filter::kVerify)); + CompilerFilter::NameOfFilter(CompilerFilter::Filter::kVerify)); args.push_back("--runtime-arg"); args.push_back("-Xnorelocate"); if (!copy_dex_files) { @@ -65,12 +65,12 @@ class Dex2oatVdexTest : public Dex2oatEnvironmentTest { return Dex2Oat(args, &output_, &error_msg_) == 0; } - std::unique_ptr<VerifierDeps> GetVerifierDeps( - const std::string& vdex_location, const DexFile* dex_file) { + std::unique_ptr<VerifierDeps> GetVerifierDeps(const std::string& vdex_location, + const DexFile* dex_file) { // Verify the vdex file content: only the classes using public APIs should be verified. - std::unique_ptr<VdexFile> vdex(VdexFile::Open(vdex_location.c_str(), - /*writable=*/ false, - /*low_4gb=*/ false, + std::unique_ptr<VdexFile> vdex(VdexFile::Open(vdex_location, + /*writable=*/false, + /*low_4gb=*/false, &error_msg_)); // Check the vdex doesn't have dex. if (vdex->HasDexSection()) { @@ -85,7 +85,7 @@ class Dex2oatVdexTest : public Dex2oatEnvironmentTest { std::vector<const DexFile*> dex_files; dex_files.push_back(dex_file); - std::unique_ptr<VerifierDeps> deps(new VerifierDeps(dex_files, /*output_only=*/ false)); + std::unique_ptr<VerifierDeps> deps(new VerifierDeps(dex_files, /*output_only=*/false)); if (!deps->ParseStoredData(dex_files, vdex->GetVerifierDepsData())) { ::testing::AssertionFailure() << error_msg_; @@ -200,11 +200,10 @@ TEST_F(Dex2oatVdexTest, VerifyPublicSdkStubsWithDexFiles) { std::unique_ptr<const DexFile> dex_file(OpenTestDexFile("Dex2oatVdexTestDex")); // Compile the subject app using the predefined API-stubs - ASSERT_TRUE(RunDex2oat( - dex_file->GetLocation(), - GetOdex(dex_file), - /*public_sdk=*/ nullptr, - /*copy_dex_files=*/ true)); + ASSERT_TRUE(RunDex2oat(dex_file->GetLocation(), + GetOdex(dex_file), + /*public_sdk=*/nullptr, + /*copy_dex_files=*/true)); // Create the .dm file with the output. std::string dm_file = GetScratchDir() + "/base.dm"; @@ -214,12 +213,11 @@ TEST_F(Dex2oatVdexTest, VerifyPublicSdkStubsWithDexFiles) { // Recompile again with the .dm file which contains a vdex with code. // The compilation will pass, but dex2oat will not use the vdex file. - ASSERT_TRUE(RunDex2oat( - dex_file->GetLocation(), - GetOdex(dex_file, "v2"), - /*public_sdk=*/ nullptr, - /*copy_dex_files=*/ true, - extra_args)); + ASSERT_TRUE(RunDex2oat(dex_file->GetLocation(), + GetOdex(dex_file, "v2"), + /*public_sdk=*/nullptr, + /*copy_dex_files=*/true, + extra_args)); } // Check that corrupt vdex files from .dm archives are ignored. @@ -238,12 +236,12 @@ TEST_F(Dex2oatVdexTest, VerifyCorruptVdexFile) { extra_args.push_back("--dm-file=" + dm_file); // Compile the dex file. Despite having a corrupt input .vdex, we should not crash. - ASSERT_TRUE(RunDex2oat( - dex_file->GetLocation(), - GetOdex(dex_file), - /*public_sdk=*/ nullptr, - /*copy_dex_files=*/ true, - extra_args)) << output_; + ASSERT_TRUE(RunDex2oat(dex_file->GetLocation(), + GetOdex(dex_file), + /*public_sdk=*/nullptr, + /*copy_dex_files=*/true, + extra_args)) + << output_; } // Check that if the input dm a vdex with mismatching checksums the compilation fails @@ -253,11 +251,10 @@ TEST_F(Dex2oatVdexTest, VerifyInputDmWithMismatchedChecksums) { // Generate a vdex file for Dex2oatVdexTestDex. std::unique_ptr<const DexFile> dex_file(OpenTestDexFile("Dex2oatVdexTestDex")); - ASSERT_TRUE(RunDex2oat( - dex_file->GetLocation(), - GetOdex(dex_file), - /*public_sdk=*/ nullptr, - /*copy_dex_files=*/ false)); + ASSERT_TRUE(RunDex2oat(dex_file->GetLocation(), + GetOdex(dex_file), + /*public_sdk=*/nullptr, + /*copy_dex_files=*/false)); // Create the .dm file with the output. std::string dm_file = GetScratchDir() + "/base.dm"; @@ -268,12 +265,12 @@ TEST_F(Dex2oatVdexTest, VerifyInputDmWithMismatchedChecksums) { // Try to compile Main using an input dm which contains the vdex for // Dex2oatVdexTestDex. It should fail. std::unique_ptr<const DexFile> dex_file2(OpenTestDexFile("Main")); - ASSERT_FALSE(RunDex2oat( - dex_file2->GetLocation(), - GetOdex(dex_file2, "v2"), - /*public_sdk=*/ nullptr, - /*copy_dex_files=*/ false, - extra_args)) << output_; + ASSERT_FALSE(RunDex2oat(dex_file2->GetLocation(), + GetOdex(dex_file2, "v2"), + /*public_sdk=*/nullptr, + /*copy_dex_files=*/false, + extra_args)) + << output_; } } // namespace art diff --git a/dexlayout/dexdiag_test.cc b/dexlayout/dexdiag_test.cc index 27ac402120..3cd80b409f 100644 --- a/dexlayout/dexdiag_test.cc +++ b/dexlayout/dexdiag_test.cc @@ -33,9 +33,7 @@ static const char* kDexDiagBinaryName = "dexdiag"; class DexDiagTest : public CommonArtTest { protected: - void SetUp() override { - CommonArtTest::SetUp(); - } + void SetUp() override { CommonArtTest::SetUp(); } // Path to the dexdiag(d?)[32|64] binary. std::string GetDexDiagFilePath() { @@ -63,11 +61,11 @@ class DexDiagTest : public CommonArtTest { EXPECT_TRUE(!oat_location.empty()); std::cout << "==" << oat_location << std::endl; std::string error_msg; - std::unique_ptr<OatFile> oat(OatFile::Open(/*zip_fd=*/ -1, - oat_location.c_str(), - oat_location.c_str(), - /*executable=*/ false, - /*low_4gb=*/ false, + std::unique_ptr<OatFile> oat(OatFile::Open(/*zip_fd=*/-1, + oat_location, + oat_location, + /*executable=*/false, + /*low_4gb=*/false, &error_msg)); EXPECT_TRUE(oat != nullptr) << error_msg; return oat; @@ -82,8 +80,8 @@ class DexDiagTest : public CommonArtTest { // Build the command line "dexdiag <args> this_pid". std::string executable_path = GetDexDiagFilePath(); - EXPECT_TRUE(OS::FileExists(executable_path.c_str())) << executable_path - << " should be a valid file path"; + EXPECT_TRUE(OS::FileExists(executable_path.c_str())) + << executable_path << " should be a valid file path"; exec_argv.push_back(executable_path); for (const auto& arg : args) { exec_argv.push_back(arg); @@ -102,11 +100,11 @@ class DexDiagTest : public CommonArtTest { TEST_F(DexDiagTest, DexDiagHelpTest) { // TODO: test the resulting output. std::string error_msg; - ASSERT_TRUE(Exec(getpid(), { kDexDiagHelp }, &error_msg)) << "Failed to execute -- because: " - << error_msg; + ASSERT_TRUE(Exec(getpid(), {kDexDiagHelp}, &error_msg)) + << "Failed to execute -- because: " << error_msg; } -#if defined (ART_TARGET) +#if defined(ART_TARGET) TEST_F(DexDiagTest, DexDiagContainsTest) { #else TEST_F(DexDiagTest, DISABLED_DexDiagContainsTest) { @@ -114,11 +112,11 @@ TEST_F(DexDiagTest, DISABLED_DexDiagContainsTest) { std::unique_ptr<OatFile> oat = OpenOatAndVdexFiles(); // TODO: test the resulting output. std::string error_msg; - ASSERT_TRUE(Exec(getpid(), { kDexDiagContains }, &error_msg)) << "Failed to execute -- because: " - << error_msg; + ASSERT_TRUE(Exec(getpid(), {kDexDiagContains}, &error_msg)) + << "Failed to execute -- because: " << error_msg; } -#if defined (ART_TARGET) +#if defined(ART_TARGET) TEST_F(DexDiagTest, DexDiagContainsFailsTest) { #else TEST_F(DexDiagTest, DISABLED_DexDiagContainsFailsTest) { @@ -126,12 +124,11 @@ TEST_F(DexDiagTest, DISABLED_DexDiagContainsFailsTest) { std::unique_ptr<OatFile> oat = OpenOatAndVdexFiles(); // TODO: test the resulting output. std::string error_msg; - ASSERT_FALSE(Exec(getpid(), { kDexDiagContainsFails }, &error_msg)) - << "Failed to execute -- because: " - << error_msg; + ASSERT_FALSE(Exec(getpid(), {kDexDiagContainsFails}, &error_msg)) + << "Failed to execute -- because: " << error_msg; } -#if defined (ART_TARGET) +#if defined(ART_TARGET) TEST_F(DexDiagTest, DexDiagVerboseTest) { #else TEST_F(DexDiagTest, DISABLED_DexDiagVerboseTest) { @@ -139,8 +136,8 @@ TEST_F(DexDiagTest, DISABLED_DexDiagVerboseTest) { // TODO: test the resulting output. std::unique_ptr<OatFile> oat = OpenOatAndVdexFiles(); std::string error_msg; - ASSERT_TRUE(Exec(getpid(), { kDexDiagVerbose }, &error_msg)) << "Failed to execute -- because: " - << error_msg; + ASSERT_TRUE(Exec(getpid(), {kDexDiagVerbose}, &error_msg)) + << "Failed to execute -- because: " << error_msg; } } // namespace art diff --git a/dexoptanalyzer/dexoptanalyzer_test.cc b/dexoptanalyzer/dexoptanalyzer_test.cc index b6b26dbdda..15f71e8fa1 100644 --- a/dexoptanalyzer/dexoptanalyzer_test.cc +++ b/dexoptanalyzer/dexoptanalyzer_test.cc @@ -129,7 +129,7 @@ TEST_F(DexoptAnalyzerTest, OatUpToDate) { std::string dex_location = GetScratchDir() + "/OatUpToDate.jar"; std::string odex_location = GetOdexDir() + "/OatUpToDate.odex"; Copy(GetDexSrc1(), dex_location); - GenerateOdexForTest(dex_location.c_str(), odex_location.c_str(), CompilerFilter::kSpeed); + GenerateOdexForTest(dex_location, odex_location, CompilerFilter::kSpeed); Verify(dex_location, CompilerFilter::kSpeed); Verify(dex_location, CompilerFilter::kVerify); @@ -143,7 +143,7 @@ TEST_F(DexoptAnalyzerTest, ProfileOatUpToDate) { std::string dex_location = GetScratchDir() + "/ProfileOatUpToDate.jar"; std::string odex_location = GetOdexDir() + "/ProfileOatUpToDate.odex"; Copy(GetDexSrc1(), dex_location); - GenerateOdexForTest(dex_location.c_str(), odex_location.c_str(), CompilerFilter::kSpeedProfile); + GenerateOdexForTest(dex_location, odex_location, CompilerFilter::kSpeedProfile); Verify(dex_location, CompilerFilter::kSpeedProfile, ProfileAnalysisResult::kDontOptimizeSmallDelta); @@ -159,7 +159,7 @@ TEST_F(DexoptAnalyzerTest, VerifyAndEmptyProfiles) { std::string odex_location = GetOdexDir() + "/VerifyAndEmptyProfiles.odex"; Copy(GetDexSrc1(), dex_location); - GenerateOdexForTest(dex_location.c_str(), odex_location.c_str(), CompilerFilter::kVerify); + GenerateOdexForTest(dex_location, odex_location, CompilerFilter::kVerify); // If we want to speed-profile something that was verified, do it even if // the profile analysis returns kDontOptimizeSmallDelta (it means that we do have profile data, @@ -186,7 +186,7 @@ TEST_F(DexoptAnalyzerTest, Downgrade) { std::string dex_location = GetScratchDir() + "/Downgrade.jar"; std::string odex_location = GetOdexDir() + "/Downgrade.odex"; Copy(GetDexSrc1(), dex_location); - GenerateOdexForTest(dex_location.c_str(), odex_location.c_str(), CompilerFilter::kVerify); + GenerateOdexForTest(dex_location, odex_location, CompilerFilter::kVerify); Verify(dex_location, CompilerFilter::kSpeedProfile, ProfileAnalysisResult::kDontOptimizeSmallDelta, true); @@ -200,7 +200,7 @@ TEST_F(DexoptAnalyzerTest, MultiDexOatUpToDate) { std::string odex_location = GetOdexDir() + "/MultiDexOatUpToDate.odex"; Copy(GetMultiDexSrc1(), dex_location); - GenerateOdexForTest(dex_location.c_str(), odex_location.c_str(), CompilerFilter::kSpeed); + GenerateOdexForTest(dex_location, odex_location, CompilerFilter::kSpeed); Verify(dex_location, CompilerFilter::kSpeed, ProfileAnalysisResult::kDontOptimizeSmallDelta); } @@ -212,7 +212,7 @@ TEST_F(DexoptAnalyzerTest, MultiDexSecondaryOutOfDate) { // Compile code for GetMultiDexSrc1. Copy(GetMultiDexSrc1(), dex_location); - GenerateOdexForTest(dex_location.c_str(), odex_location.c_str(), CompilerFilter::kSpeed); + GenerateOdexForTest(dex_location, odex_location, CompilerFilter::kSpeed); // Now overwrite the dex file with GetMultiDexSrc2 so the secondary checksum // is out of date. @@ -230,7 +230,7 @@ TEST_F(DexoptAnalyzerTest, OatDexOutOfDate) { // We create a dex, generate an oat for it, then overwrite the dex with a // different dex to make the oat out of date. Copy(GetDexSrc1(), dex_location); - GenerateOdexForTest(dex_location.c_str(), odex_location.c_str(), CompilerFilter::kSpeed); + GenerateOdexForTest(dex_location, odex_location, CompilerFilter::kSpeed); Copy(GetDexSrc2(), dex_location); Verify(dex_location, CompilerFilter::kSpeed); @@ -243,8 +243,8 @@ TEST_F(DexoptAnalyzerTest, OatImageOutOfDate) { std::string odex_location = GetOdexDir() + "/OatImageOutOfDate.odex"; Copy(GetDexSrc1(), dex_location); - GenerateOatForTest(dex_location.c_str(), - odex_location.c_str(), + GenerateOatForTest(dex_location, + odex_location, CompilerFilter::kSpeed, /*with_alternate_image=*/true); diff --git a/libartbase/base/common_art_test.cc b/libartbase/base/common_art_test.cc index 02bfe6fd81..db0e1c157f 100644 --- a/libartbase/base/common_art_test.cc +++ b/libartbase/base/common_art_test.cc @@ -266,7 +266,7 @@ void CommonArtTestImpl::SetUpAndroidRootEnvVars() { const char* android_i18n_root_from_env = getenv("ANDROID_I18N_ROOT"); if (android_i18n_root_from_env == nullptr) { // Use ${ANDROID_I18N_OUT}/com.android.i18n for ANDROID_I18N_ROOT. - std::string android_i18n_root = android_host_out.c_str(); + std::string android_i18n_root = android_host_out; android_i18n_root += "/com.android.i18n"; setenv("ANDROID_I18N_ROOT", android_i18n_root.c_str(), 1); } @@ -277,7 +277,7 @@ void CommonArtTestImpl::SetUpAndroidRootEnvVars() { const char* android_art_root_from_env = getenv("ANDROID_ART_ROOT"); if (android_art_root_from_env == nullptr) { // Use ${ANDROID_HOST_OUT}/com.android.art for ANDROID_ART_ROOT. - std::string android_art_root = android_host_out.c_str(); + std::string android_art_root = android_host_out; android_art_root += "/com.android.art"; setenv("ANDROID_ART_ROOT", android_art_root.c_str(), 1); } @@ -288,7 +288,7 @@ void CommonArtTestImpl::SetUpAndroidRootEnvVars() { const char* android_tzdata_root_from_env = getenv("ANDROID_TZDATA_ROOT"); if (android_tzdata_root_from_env == nullptr) { // Use ${ANDROID_HOST_OUT}/com.android.tzdata for ANDROID_TZDATA_ROOT. - std::string android_tzdata_root = android_host_out.c_str(); + std::string android_tzdata_root = android_host_out; android_tzdata_root += "/com.android.tzdata"; setenv("ANDROID_TZDATA_ROOT", android_tzdata_root.c_str(), 1); } @@ -328,7 +328,7 @@ void CommonArtTestImpl::SetUp() { SetUpAndroidDataDir(android_data_); // Re-use the data temporary directory for /system_ext tests - android_system_ext_.append(android_data_.c_str()); + android_system_ext_.append(android_data_); android_system_ext_.append("/system_ext"); int mkdir_result = mkdir(android_system_ext_.c_str(), 0700); ASSERT_EQ(mkdir_result, 0); @@ -338,7 +338,7 @@ void CommonArtTestImpl::SetUp() { mkdir_result = mkdir(system_ext_framework.c_str(), 0700); ASSERT_EQ(mkdir_result, 0); - dalvik_cache_.append(android_data_.c_str()); + dalvik_cache_.append(android_data_); dalvik_cache_.append("/dalvik-cache"); mkdir_result = mkdir(dalvik_cache_.c_str(), 0700); ASSERT_EQ(mkdir_result, 0); diff --git a/libartbase/base/file_utils.cc b/libartbase/base/file_utils.cc index d2afbcc009..c337d114b7 100644 --- a/libartbase/base/file_utils.cc +++ b/libartbase/base/file_utils.cc @@ -771,7 +771,7 @@ bool LocationIsOnSystem(const std::string& location) { LOG(FATAL) << "LocationIsOnSystem is unsupported on Windows."; return false; #else - return android::base::StartsWith(location, GetAndroidRoot().c_str()); + return android::base::StartsWith(location, GetAndroidRoot()); #endif } diff --git a/libartbase/base/file_utils_test.cc b/libartbase/base/file_utils_test.cc index dff4478549..e660f35d94 100644 --- a/libartbase/base/file_utils_test.cc +++ b/libartbase/base/file_utils_test.cc @@ -36,9 +36,8 @@ class ScopedOverrideDalvikCacheSubDirectory { OverrideDalvikCacheSubDirectory(override); } - ~ScopedOverrideDalvikCacheSubDirectory() { - OverrideDalvikCacheSubDirectory("dalvik-cache"); - } + ~ScopedOverrideDalvikCacheSubDirectory() { OverrideDalvikCacheSubDirectory("dalvik-cache"); } + private: DISALLOW_COPY_AND_ASSIGN(ScopedOverrideDalvikCacheSubDirectory); }; @@ -104,7 +103,7 @@ TEST_F(FileUtilsTest, DISABLED_GetAndroidRootSafe) { // broken. On non-bionic. On bionic we can be running with a different libartbase that lives // outside of ANDROID_ROOT. UniqueCPtr<char> real_root3(realpath(android_root3.c_str(), nullptr)); -#if !defined(__BIONIC__ ) || defined(__ANDROID__) +#if !defined(__BIONIC__) || defined(__ANDROID__) UniqueCPtr<char> real_root(realpath(android_root.c_str(), nullptr)); EXPECT_STREQ(real_root.get(), real_root3.get()) << error_msg; #else @@ -158,7 +157,7 @@ TEST_F(FileUtilsTest, GetArtRootSafe) { // the test setup is broken. On non-bionic. On bionic we can be running // with a different libartbase that lives outside of ANDROID_ART_ROOT. UniqueCPtr<char> real_root3(realpath(android_art_root3.c_str(), nullptr)); -#if !defined(__BIONIC__ ) || defined(__ANDROID__) +#if !defined(__BIONIC__) || defined(__ANDROID__) UniqueCPtr<char> real_root(realpath(android_art_root.c_str(), nullptr)); EXPECT_STREQ(real_root.get(), real_root3.get()) << error_msg; #else @@ -195,11 +194,10 @@ TEST_F(FileUtilsTest, GetApexDataOatFilename) { GetApexDataOatFilename("/product/javalib/beep.jar", InstructionSet::kArm)); const std::string art_apex_jar = std::string {kAndroidArtApexDefaultPath} + "/javalib/some.jar"; - EXPECT_EQ(std::string {}, GetApexDataOatFilename(art_apex_jar.c_str(), InstructionSet::kArm)); + EXPECT_EQ(std::string{}, GetApexDataOatFilename(art_apex_jar, InstructionSet::kArm)); - const std::string i18n_jar = - std::string {kAndroidI18nApexDefaultPath} + "/javalib/core-icu4j.jar"; - EXPECT_EQ(std::string {}, GetApexDataOatFilename(i18n_jar, InstructionSet::kArm)); + const std::string i18n_jar = std::string{kAndroidI18nApexDefaultPath} + "/javalib/core-icu4j.jar"; + EXPECT_EQ(std::string{}, GetApexDataOatFilename(i18n_jar, InstructionSet::kArm)); const std::string system_jar_apexdata_oat = GetArtApexData() + "/dalvik-cache/x86/boot-lace.oat"; EXPECT_EQ(system_jar_apexdata_oat, @@ -216,13 +214,12 @@ TEST_F(FileUtilsTest, GetApexDataOdexFilename) { const std::string art_apex_jar = std::string {kAndroidArtApexDefaultPath} + "/javalib/some.jar"; EXPECT_EQ( GetArtApexData() + "/dalvik-cache/arm/apex@com.android.art@javalib@some.jar@classes.odex", - GetApexDataOdexFilename(art_apex_jar.c_str(), InstructionSet::kArm)); + GetApexDataOdexFilename(art_apex_jar, InstructionSet::kArm)); - const std::string i18n_jar = - std::string {kAndroidI18nApexDefaultPath} + "/javalib/core-icu4j.jar"; + const std::string i18n_jar = std::string{kAndroidI18nApexDefaultPath} + "/javalib/core-icu4j.jar"; EXPECT_EQ(GetArtApexData() + "/dalvik-cache/arm/apex@com.android.i18n@javalib@core-icu4j.jar@classes.odex", - GetApexDataOdexFilename(i18n_jar.c_str(), InstructionSet::kArm)); + GetApexDataOdexFilename(i18n_jar, InstructionSet::kArm)); const std::string system_jar_apexdata_odex = GetArtApexData() + "/dalvik-cache/x86/system@framework@cookie.jar@classes.odex"; @@ -234,20 +231,20 @@ TEST_F(FileUtilsTest, GetApexDataBootImage) { ScopedUnsetEnvironmentVariable android_root("ANDROID_ROOT"); ScopedUnsetEnvironmentVariable art_apex_data("ART_APEX_DATA"); - EXPECT_EQ(std::string {}, - GetApexDataBootImage(std::string {kAndroidI18nApexDefaultPath} + "/javalib/bar.jar")); + EXPECT_EQ(std::string{}, + GetApexDataBootImage(std::string{kAndroidI18nApexDefaultPath} + "/javalib/bar.jar")); // Check image location has the prefix "boot-" in front of the basename of dex location and // that image suffix is .art. const std::string system_jar = "/system/framework/disk.jar"; - const std::string boot_image = GetApexDataBootImage(system_jar.c_str()); + const std::string boot_image = GetApexDataBootImage(system_jar); EXPECT_EQ(GetArtApexData() + "/dalvik-cache/boot-disk.art", boot_image); // Check the image filename corresponds to the oat file for the same system jar. const InstructionSet isa = InstructionSet::kArm64; const std::string boot_image_filename = GetSystemImageFilename(boot_image.c_str(), isa); const std::string accompanying_oat_file = ReplaceFileExtension(boot_image_filename, "oat"); - EXPECT_EQ(accompanying_oat_file, GetApexDataOatFilename(system_jar.c_str(), isa)); + EXPECT_EQ(accompanying_oat_file, GetApexDataOatFilename(system_jar, isa)); } TEST_F(FileUtilsTest, GetApexDataImage) { @@ -308,7 +305,7 @@ TEST_F(FileUtilsTest, OverrideDalvikCacheSubDirectory) { GetApexDataOdexFilename("/data/some/code.dex", InstructionSet::kArm)); const std::string system_jar = "/system/framework/disk.jar"; - const std::string boot_image = GetApexDataBootImage(system_jar.c_str()); + const std::string boot_image = GetApexDataBootImage(system_jar); EXPECT_EQ(GetArtApexData() + "/overridden-cache/boot-disk.art", boot_image); EXPECT_EQ( @@ -327,7 +324,7 @@ TEST_F(FileUtilsTest, GetSystemOdexFilenameForApex) { const std::string apex_jar = std::string {kAndroidArtApexDefaultPath} + "/javalib/some.jar"; EXPECT_EQ( GetAndroidRoot() + "/framework/oat/arm/apex@com.android.art@javalib@some.jar@classes.odex", - GetSystemOdexFilenameForApex(apex_jar.c_str(), InstructionSet::kArm)); + GetSystemOdexFilenameForApex(apex_jar, InstructionSet::kArm)); } TEST_F(FileUtilsTest, ApexNameFromLocation) { diff --git a/oatdump/oatdump.cc b/oatdump/oatdump.cc index 6f75fbd9d5..9dd704aa06 100644 --- a/oatdump/oatdump.cc +++ b/oatdump/oatdump.cc @@ -3020,7 +3020,7 @@ class IMTDumper { table_index++; std::string p_name = ptr2->PrettyMethod(true); - if (android::base::StartsWith(p_name, method.c_str())) { + if (android::base::StartsWith(p_name, method)) { std::cerr << " Slot " << index << " (" @@ -3033,7 +3033,7 @@ class IMTDumper { } } else { std::string p_name = ptr->PrettyMethod(true); - if (android::base::StartsWith(p_name, method.c_str())) { + if (android::base::StartsWith(p_name, method)) { std::cerr << " Slot " << index << " (1)" << std::endl; std::cerr << " " << p_name << std::endl; } else { @@ -3046,7 +3046,7 @@ class IMTDumper { for (ArtMethod& iface_method : iface->GetMethods(pointer_size)) { if (ImTable::GetImtIndex(&iface_method) == index) { std::string i_name = iface_method.PrettyMethod(true); - if (android::base::StartsWith(i_name, method.c_str())) { + if (android::base::StartsWith(i_name, method)) { std::cerr << " Slot " << index << " (1)" << std::endl; std::cerr << " " << p_name << " (" << i_name << ")" << std::endl; } diff --git a/odrefresh/odr_fs_utils_test.cc b/odrefresh/odr_fs_utils_test.cc index d460be28a0..0adc1d1635 100644 --- a/odrefresh/odr_fs_utils_test.cc +++ b/odrefresh/odr_fs_utils_test.cc @@ -136,12 +136,12 @@ TEST_F(OdrFsUtilsTest, DISABLED_GetUsedSpace) { ASSERT_EQ(kFirstFileBytes, static_cast<decltype(kFirstFileBytes)>(sb.st_size)); uint64_t bytes_used = 0; - ASSERT_TRUE(GetUsedSpace(scratch_dir.GetPath().c_str(), &bytes_used)); + ASSERT_TRUE(GetUsedSpace(scratch_dir.GetPath(), &bytes_used)); const std::string second_file_path = scratch_dir.GetPath() + "/2.dat"; ASSERT_TRUE(CreateFile(second_file_path.c_str(), kSecondFileBytes)); - ASSERT_TRUE(GetUsedSpace(scratch_dir.GetPath().c_str(), &bytes_used)); + ASSERT_TRUE(GetUsedSpace(scratch_dir.GetPath(), &bytes_used)); uint64_t expected_bytes_used = RoundUp(kFirstFileBytes, sb.st_blocks * kBytesPerBlock) + RoundUp(kSecondFileBytes, sb.st_blocks * kBytesPerBlock); ASSERT_EQ(expected_bytes_used, bytes_used); @@ -152,7 +152,7 @@ TEST_F(OdrFsUtilsTest, DISABLED_GetUsedSpace) { const std::string path = android::base::StringPrintf("%s/%zu", sub_dir_path.c_str(), i); ASSERT_TRUE(CreateFile(path.c_str(), i)); expected_bytes_used += RoundUp(i, sb.st_blocks * kBytesPerBlock); - ASSERT_TRUE(GetUsedSpace(scratch_dir.GetPath().c_str(), &bytes_used)); + ASSERT_TRUE(GetUsedSpace(scratch_dir.GetPath(), &bytes_used)); ASSERT_EQ(expected_bytes_used, bytes_used); } } diff --git a/odrefresh/odrefresh.cc b/odrefresh/odrefresh.cc index 346313eb1e..86921d98b0 100644 --- a/odrefresh/odrefresh.cc +++ b/odrefresh/odrefresh.cc @@ -825,7 +825,7 @@ std::string OnDeviceRefresh::GetSystemServerImagePath(bool on_system, } else { // Typically // "/data/misc/apexdata/.../dalvik-cache/<isa>/system@framework@services.jar@classes.art". - const std::string image = GetApexDataImage(jar_path.c_str()); + const std::string image = GetApexDataImage(jar_path); return GetSystemImageFilename(image.c_str(), config_.GetSystemServerIsa()); } } @@ -1653,7 +1653,7 @@ WARN_UNUSED bool OnDeviceRefresh::CompileSystemServerArtifacts( } OdrArtifacts artifacts = OdrArtifacts::ForSystemServer(image_location); - CHECK_EQ(artifacts.OatPath(), GetApexDataOdexFilename(jar.c_str(), isa)); + CHECK_EQ(artifacts.OatPath(), GetApexDataOdexFilename(jar, isa)); const std::pair<const std::string, const char*> location_kind_pairs[] = { std::make_pair(artifacts.ImagePath(), "app-image"), diff --git a/runtime/art_method_test.cc b/runtime/art_method_test.cc index b71f8a39e4..b1e9ed3879 100644 --- a/runtime/art_method_test.cc +++ b/runtime/art_method_test.cc @@ -51,7 +51,7 @@ class ArtMethodTest : public CommonRuntimeTest { ASSERT_STREQ(value_of->GetName(), "valueOf"); std::string unbox_signature = std::string("()") + kPrimitive; ArtMethod* unbox_method = value_of->GetDeclaringClass()->FindClassMethod( - unbox_name, unbox_signature.c_str(), kRuntimePointerSize); + unbox_name, unbox_signature, kRuntimePointerSize); ASSERT_TRUE(unbox_method != nullptr); ASSERT_FALSE(unbox_method->IsStatic()); ASSERT_TRUE(value_of->GetDeclaringClass()->IsFinal()); diff --git a/runtime/class_loader_context.cc b/runtime/class_loader_context.cc index 074a819d0a..2f34f04f5b 100644 --- a/runtime/class_loader_context.cc +++ b/runtime/class_loader_context.cc @@ -63,8 +63,7 @@ static constexpr char kDexFileChecksumSeparator = '*'; static constexpr char kInMemoryDexClassLoaderDexLocationMagic[] = "<unknown>"; ClassLoaderContext::ClassLoaderContext() - : dex_files_state_(ContextDexFilesState::kDexFilesNotOpened), - owns_the_dex_files_(true) {} + : dex_files_state_(ContextDexFilesState::kDexFilesNotOpened), owns_the_dex_files_(true) {} ClassLoaderContext::ClassLoaderContext(bool owns_the_dex_files) : dex_files_state_(ContextDexFilesState::kDexFilesOpened), @@ -72,9 +71,8 @@ ClassLoaderContext::ClassLoaderContext(bool owns_the_dex_files) // Utility method to add parent and shared libraries of `info` into // the `work_list`. -static void AddToWorkList( - ClassLoaderContext::ClassLoaderInfo* info, - std::vector<ClassLoaderContext::ClassLoaderInfo*>& work_list) { +static void AddToWorkList(ClassLoaderContext::ClassLoaderInfo* info, + std::vector<ClassLoaderContext::ClassLoaderInfo*>& work_list) { if (info->parent != nullptr) { work_list.push_back(info->parent.get()); } @@ -106,9 +104,7 @@ ClassLoaderContext::~ClassLoaderContext() { } } -std::unique_ptr<ClassLoaderContext> ClassLoaderContext::Default() { - return Create(""); -} +std::unique_ptr<ClassLoaderContext> ClassLoaderContext::Default() { return Create(""); } std::unique_ptr<ClassLoaderContext> ClassLoaderContext::Create(const std::string& spec) { std::unique_ptr<ClassLoaderContext> result(new ClassLoaderContext()); @@ -127,8 +123,7 @@ static size_t FindMatchingSharedLibraryCloseMarker(const std::string& spec, uint32_t string_index = shared_library_open_index + 1; size_t shared_library_close = std::string::npos; while (counter != 0) { - shared_library_close = - spec.find_first_of(kClassLoaderSharedLibraryClosingMark, string_index); + shared_library_close = spec.find_first_of(kClassLoaderSharedLibraryClosingMark, string_index); size_t shared_library_open = spec.find_first_of(kClassLoaderSharedLibraryOpeningMark, string_index); if (shared_library_close == std::string::npos) { @@ -156,8 +151,7 @@ static size_t FindMatchingSharedLibraryCloseMarker(const std::string& spec, // "ClassLoaderType1[ClasspathElem1*Checksum1:ClasspathElem2*Checksum2...]{ClassLoaderType2[...]}". // The checksum part of the format is expected only if parse_cheksums is true. std::unique_ptr<ClassLoaderContext::ClassLoaderInfo> ClassLoaderContext::ParseClassLoaderSpec( - const std::string& class_loader_spec, - bool parse_checksums) { + const std::string& class_loader_spec, bool parse_checksums) { ClassLoaderType class_loader_type = ExtractClassLoaderType(class_loader_spec); if (class_loader_type == kInvalidClassLoader) { return nullptr; @@ -200,8 +194,8 @@ std::unique_ptr<ClassLoaderContext::ClassLoaderInfo> ClassLoaderContext::ParseCl // At this point we know the format is ok; continue and extract the classpath. // Note that class loaders with an empty class path are allowed. - std::string classpath = class_loader_spec.substr(type_str_size + 1, - closing_index - type_str_size - 1); + std::string classpath = + class_loader_spec.substr(type_str_size + 1, closing_index - type_str_size - 1); std::unique_ptr<ClassLoaderInfo> info(new ClassLoaderInfo(class_loader_type)); @@ -299,7 +293,7 @@ std::unique_ptr<ClassLoaderContext::ClassLoaderInfo> ClassLoaderContext::ParseCl } std::unique_ptr<ClassLoaderInfo> shared_library_info( - ParseInternal(shared_library_spec, parse_checksums)); + ParseInternal(shared_library_spec, parse_checksums)); if (shared_library_info == nullptr) { return nullptr; } @@ -317,11 +311,10 @@ std::unique_ptr<ClassLoaderContext::ClassLoaderInfo> ClassLoaderContext::ParseCl // Extracts the class loader type from the given spec. // Return ClassLoaderContext::kInvalidClassLoader if the class loader type is not // recognized. -ClassLoaderContext::ClassLoaderType -ClassLoaderContext::ExtractClassLoaderType(const std::string& class_loader_spec) { - const ClassLoaderType kValidTypes[] = { kPathClassLoader, - kDelegateLastClassLoader, - kInMemoryDexClassLoader }; +ClassLoaderContext::ClassLoaderType ClassLoaderContext::ExtractClassLoaderType( + const std::string& class_loader_spec) { + const ClassLoaderType kValidTypes[] = { + kPathClassLoader, kDelegateLastClassLoader, kInMemoryDexClassLoader}; for (const ClassLoaderType& type : kValidTypes) { const char* type_str = GetClassLoaderTypeName(type); if (class_loader_spec.compare(0, strlen(type_str), type_str) == 0) { @@ -348,8 +341,8 @@ bool ClassLoaderContext::Parse(const std::string& spec, bool parse_checksums) { return class_loader_chain_ != nullptr; } -ClassLoaderContext::ClassLoaderInfo* ClassLoaderContext::ParseInternal( - const std::string& spec, bool parse_checksums) { +ClassLoaderContext::ClassLoaderInfo* ClassLoaderContext::ParseInternal(const std::string& spec, + bool parse_checksums) { CHECK(!spec.empty()); std::string remaining = spec; std::unique_ptr<ClassLoaderInfo> first(nullptr); @@ -391,8 +384,8 @@ ClassLoaderContext::ClassLoaderInfo* ClassLoaderContext::ParseInternal( LOG(ERROR) << "Invalid class loader spec: " << class_loader_spec; return nullptr; } else { - remaining = remaining.substr(shared_library_close + 2, - remaining.size() - shared_library_close - 2); + remaining = + remaining.substr(shared_library_close + 2, remaining.size() - shared_library_close - 2); } } @@ -420,9 +413,12 @@ bool ClassLoaderContext::OpenDexFiles(const std::string& classpath_dir, const std::vector<int>& fds, bool only_read_checksums) { switch (dex_files_state_) { - case kDexFilesNotOpened: break; // files not opened, continue. - case kDexFilesOpenFailed: return false; // previous attempt failed. - case kDexFilesOpened: return true; // previous attempt succeed. + case kDexFilesNotOpened: + break; // files not opened, continue. + case kDexFilesOpenFailed: + return false; // previous attempt failed. + case kDexFilesOpened: + return true; // previous attempt succeed. case kDexFilesChecksumsRead: if (only_read_checksums) { return true; // we already read the checksums. @@ -531,7 +527,7 @@ bool ClassLoaderContext::OpenDexFiles(const std::string& classpath_dir, // as we have encountered while iterating over this class loader context. if (dex_file_index != fds.size()) { LOG(WARNING) << fds.size() << " FDs provided but only " << dex_file_index - << " dex files are in the class loader context"; + << " dex files are in the class loader context"; dex_files_state_ = kDexFilesOpenFailed; } @@ -558,13 +554,13 @@ bool ClassLoaderContext::RemoveLocationsFromClassPaths( ClassLoaderInfo* info = work_list.back(); work_list.pop_back(); size_t initial_size = info->classpath.size(); - auto kept_it = std::remove_if( - info->classpath.begin(), - info->classpath.end(), - [canonical_locations](const std::string& location) { - return ContainsElement(canonical_locations, - DexFileLoader::GetDexCanonicalLocation(location.c_str())); - }); + auto kept_it = std::remove_if(info->classpath.begin(), + info->classpath.end(), + [canonical_locations](const std::string& location) { + return ContainsElement( + canonical_locations, + DexFileLoader::GetDexCanonicalLocation(location.c_str())); + }); info->classpath.erase(kept_it, info->classpath.end()); if (initial_size != info->classpath.size()) { removed_locations = true; @@ -575,16 +571,16 @@ bool ClassLoaderContext::RemoveLocationsFromClassPaths( } std::string ClassLoaderContext::EncodeContextForDex2oat(const std::string& base_dir) const { - return EncodeContext(base_dir, /*for_dex2oat=*/ true, /*stored_context=*/ nullptr); + return EncodeContext(base_dir, /*for_dex2oat=*/true, /*stored_context=*/nullptr); } std::string ClassLoaderContext::EncodeContextForOatFile(const std::string& base_dir, ClassLoaderContext* stored_context) const { - return EncodeContext(base_dir, /*for_dex2oat=*/ false, stored_context); + return EncodeContext(base_dir, /*for_dex2oat=*/false, stored_context); } -std::map<std::string, std::string> -ClassLoaderContext::EncodeClassPathContexts(const std::string& base_dir) const { +std::map<std::string, std::string> ClassLoaderContext::EncodeClassPathContexts( + const std::string& base_dir) const { CheckDexFilesOpened("EncodeClassPathContexts"); if (class_loader_chain_ == nullptr) { return std::map<std::string, std::string>{}; @@ -636,8 +632,7 @@ std::string ClassLoaderContext::EncodeContext(const std::string& base_dir, if (class_loader_chain_ == nullptr) { // We can get in this situation if the context was created with a class path containing the // source dex files which were later removed (happens during run-tests). - out << GetClassLoaderTypeName(kPathClassLoader) - << kClassLoaderOpeningMark + out << GetClassLoaderTypeName(kPathClassLoader) << kClassLoaderOpeningMark << kClassLoaderClosingMark; return out.str(); } @@ -667,8 +662,7 @@ void ClassLoaderContext::EncodeClassPath(const std::string& base_dir, } if (type == kInMemoryDexClassLoader) { out << kInMemoryDexClassLoaderDexLocationMagic; - } else if (!base_dir.empty() - && location.substr(0, base_dir.length()) == base_dir) { + } else if (!base_dir.empty() && location.substr(0, base_dir.length()) == base_dir) { // Find paths that were relative and convert them back from absolute. out << location.substr(base_dir.length() + 1).c_str(); } else { @@ -703,8 +697,8 @@ void ClassLoaderContext::EncodeContextInternal(const ClassLoaderInfo& info, if (for_dex2oat) { // dex2oat only needs the base location. It cannot accept multidex locations. // So ensure we only add each file once. - bool new_insert = seen_locations.insert( - DexFileLoader::GetBaseLocation(dex_file->GetLocation())).second; + bool new_insert = + seen_locations.insert(DexFileLoader::GetBaseLocation(dex_file->GetLocation())).second; if (!new_insert) { continue; } @@ -765,12 +759,11 @@ void ClassLoaderContext::EncodeSharedLibAndParent(const ClassLoaderInfo& info, } if (info.parent != nullptr) { out << kClassLoaderSeparator; - EncodeContextInternal( - *info.parent.get(), - base_dir, - for_dex2oat, - (stored_info == nullptr ? nullptr : stored_info->parent.get()), - out); + EncodeContextInternal(*info.parent.get(), + base_dir, + for_dex2oat, + (stored_info == nullptr ? nullptr : stored_info->parent.get()), + out); } } @@ -784,7 +777,8 @@ static ObjPtr<mirror::Class> GetClassLoaderClass(ClassLoaderContext::ClassLoader return WellKnownClasses::dalvik_system_DelegateLastClassLoader.Get(); case ClassLoaderContext::kInMemoryDexClassLoader: return WellKnownClasses::dalvik_system_InMemoryDexClassLoader.Get(); - case ClassLoaderContext::kInvalidClassLoader: break; // will fail after the switch. + case ClassLoaderContext::kInvalidClassLoader: + break; // will fail after the switch. } LOG(FATAL) << "Invalid class loader type " << type; UNREACHABLE(); @@ -802,8 +796,7 @@ static ObjPtr<mirror::ClassLoader> CreateClassLoaderInternal( VariableSizedHandleScope& map_scope, std::map<std::string, Handle<mirror::ClassLoader>>& canonicalized_libraries, bool add_compilation_sources, - const std::vector<const DexFile*>& compilation_sources) - REQUIRES_SHARED(Locks::mutator_lock_) { + const std::vector<const DexFile*>& compilation_sources) REQUIRES_SHARED(Locks::mutator_lock_) { if (for_shared_library) { // Check if the shared library has already been created. auto search = canonicalized_libraries.find(FlattenClasspath(info.classpath)); @@ -816,7 +809,7 @@ static ObjPtr<mirror::ClassLoader> CreateClassLoaderInternal( MutableHandle<mirror::ObjectArray<mirror::ClassLoader>> libraries( hs.NewHandle<mirror::ObjectArray<mirror::ClassLoader>>(nullptr)); MutableHandle<mirror::ObjectArray<mirror::ClassLoader>> libraries_after( - hs.NewHandle<mirror::ObjectArray<mirror::ClassLoader>>(nullptr)); + hs.NewHandle<mirror::ObjectArray<mirror::ClassLoader>>(nullptr)); if (!info.shared_libraries.empty()) { libraries.Assign(mirror::ObjectArray<mirror::ClassLoader>::Alloc( @@ -826,15 +819,14 @@ static ObjPtr<mirror::ClassLoader> CreateClassLoaderInternal( for (uint32_t i = 0; i < info.shared_libraries.size(); ++i) { // We should only add the compilation sources to the first class loader. libraries->Set(i, - CreateClassLoaderInternal( - self, - soa, - *info.shared_libraries[i].get(), - /* for_shared_library= */ true, - map_scope, - canonicalized_libraries, - /* add_compilation_sources= */ false, - compilation_sources)); + CreateClassLoaderInternal(self, + soa, + *info.shared_libraries[i].get(), + /* for_shared_library= */ true, + map_scope, + canonicalized_libraries, + /* add_compilation_sources= */ false, + compilation_sources)); } } @@ -846,50 +838,41 @@ static ObjPtr<mirror::ClassLoader> CreateClassLoaderInternal( for (uint32_t i = 0; i < info.shared_libraries_after.size(); ++i) { // We should only add the compilation sources to the first class loader. libraries_after->Set(i, - CreateClassLoaderInternal( - self, - soa, - *info.shared_libraries_after[i].get(), - /* for_shared_library= */ true, - map_scope, - canonicalized_libraries, - /* add_compilation_sources= */ false, - compilation_sources)); + CreateClassLoaderInternal(self, + soa, + *info.shared_libraries_after[i].get(), + /* for_shared_library= */ true, + map_scope, + canonicalized_libraries, + /* add_compilation_sources= */ false, + compilation_sources)); } } MutableHandle<mirror::ClassLoader> parent = hs.NewHandle<mirror::ClassLoader>(nullptr); if (info.parent != nullptr) { // We should only add the compilation sources to the first class loader. - parent.Assign(CreateClassLoaderInternal( - self, - soa, - *info.parent.get(), - /* for_shared_library= */ false, - map_scope, - canonicalized_libraries, - /* add_compilation_sources= */ false, - compilation_sources)); - } - std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector( - info.opened_dex_files); + parent.Assign(CreateClassLoaderInternal(self, + soa, + *info.parent.get(), + /* for_shared_library= */ false, + map_scope, + canonicalized_libraries, + /* add_compilation_sources= */ false, + compilation_sources)); + } + std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(info.opened_dex_files); if (add_compilation_sources) { // For the first class loader, its classpath comes first, followed by compilation sources. // This ensures that whenever we need to resolve classes from it the classpath elements // come first. - class_path_files.insert(class_path_files.end(), - compilation_sources.begin(), - compilation_sources.end()); + class_path_files.insert( + class_path_files.end(), compilation_sources.begin(), compilation_sources.end()); } Handle<mirror::Class> loader_class = hs.NewHandle<mirror::Class>(GetClassLoaderClass(info.type)); ObjPtr<mirror::ClassLoader> loader = Runtime::Current()->GetClassLinker()->CreateWellKnownClassLoader( - self, - class_path_files, - loader_class, - parent, - libraries, - libraries_after); + self, class_path_files, loader_class, parent, libraries, libraries_after); if (for_shared_library) { canonicalized_libraries[FlattenClasspath(info.classpath)] = map_scope.NewHandle<mirror::ClassLoader>(loader); @@ -922,8 +905,7 @@ jobject ClassLoaderContext::CreateClassLoader( /* add_compilation_sources= */ true, compilation_sources); // Make it a global ref and return. - ScopedLocalRef<jobject> local_ref( - soa.Env(), soa.Env()->AddLocalReference<jobject>(loader)); + ScopedLocalRef<jobject> local_ref(soa.Env(), soa.Env()->AddLocalReference<jobject>(loader)); return soa.Env()->NewGlobalRef(local_ref.get()); } @@ -969,9 +951,12 @@ std::vector<std::string> ClassLoaderContext::FlattenDexPaths() const { const char* ClassLoaderContext::GetClassLoaderTypeName(ClassLoaderType type) { switch (type) { - case kPathClassLoader: return kPathClassLoaderString; - case kDelegateLastClassLoader: return kDelegateLastClassLoaderString; - case kInMemoryDexClassLoader: return kInMemoryDexClassLoaderString; + case kPathClassLoader: + return kPathClassLoaderString; + case kDelegateLastClassLoader: + return kDelegateLastClassLoaderString; + case kInMemoryDexClassLoader: + return kInMemoryDexClassLoaderString; default: LOG(FATAL) << "Invalid class loader type " << type; UNREACHABLE(); @@ -989,7 +974,7 @@ void ClassLoaderContext::CheckDexFilesOpened(const std::string& calling_method) static bool CollectDexFilesFromJavaDexFile(ObjPtr<mirror::Object> java_dex_file, ArtField* const cookie_field, std::vector<const DexFile*>* out_dex_files) - REQUIRES_SHARED(Locks::mutator_lock_) { + REQUIRES_SHARED(Locks::mutator_lock_) { if (java_dex_file == nullptr) { return true; } @@ -1020,7 +1005,7 @@ static bool CollectDexFilesFromJavaDexFile(ObjPtr<mirror::Object> java_dex_file, static bool CollectDexFilesFromSupportedClassLoader(Thread* self, Handle<mirror::ClassLoader> class_loader, std::vector<const DexFile*>* out_dex_files) - REQUIRES_SHARED(Locks::mutator_lock_) { + REQUIRES_SHARED(Locks::mutator_lock_) { CHECK(IsInstanceOfBaseDexClassLoader(class_loader)); // All supported class loaders inherit from BaseDexClassLoader. @@ -1114,13 +1099,12 @@ static bool GetDexFilesFromDexElementsArray( // This method is recursive (w.r.t. the class loader parent) and will stop once it reaches the // BootClassLoader. Note that the class loader chain is expected to be short. bool ClassLoaderContext::CreateInfoFromClassLoader( - ScopedObjectAccessAlreadyRunnable& soa, - Handle<mirror::ClassLoader> class_loader, - Handle<mirror::ObjectArray<mirror::Object>> dex_elements, - ClassLoaderInfo* child_info, - bool is_shared_library, - bool is_after) - REQUIRES_SHARED(Locks::mutator_lock_) { + ScopedObjectAccessAlreadyRunnable& soa, + Handle<mirror::ClassLoader> class_loader, + Handle<mirror::ObjectArray<mirror::Object>> dex_elements, + ClassLoaderInfo* child_info, + bool is_shared_library, + bool is_after) REQUIRES_SHARED(Locks::mutator_lock_) { if (ClassLinker::IsBootClassLoader(class_loader.Get())) { // Nothing to do for the boot class loader as we don't add its dex files to the context. return true; @@ -1174,9 +1158,9 @@ bool ClassLoaderContext::CreateInfoFromClassLoader( for (const DexFile* dex_file : dex_files_loaded) { // Dex location of dex files loaded with InMemoryDexClassLoader is always bogus. // Use a magic value for the classpath instead. - info->classpath.push_back((type == kInMemoryDexClassLoader) - ? kInMemoryDexClassLoaderDexLocationMagic - : dex_file->GetLocation()); + info->classpath.push_back((type == kInMemoryDexClassLoader) ? + kInMemoryDexClassLoaderDexLocationMagic : + dex_file->GetLocation()); info->checksums.push_back(dex_file->GetLocationChecksum()); info->opened_dex_files.emplace_back(dex_file); } @@ -1199,8 +1183,8 @@ bool ClassLoaderContext::CreateInfoFromClassLoader( temp_loader, null_dex_elements, info, - /*is_shared_library=*/ true, - /*is_after=*/ false)) { + /*is_shared_library=*/true, + /*is_after=*/false)) { return false; } } @@ -1217,8 +1201,8 @@ bool ClassLoaderContext::CreateInfoFromClassLoader( temp_loader, null_dex_elements, info, - /*is_shared_library=*/ true, - /*is_after=*/ true)) { + /*is_shared_library=*/true, + /*is_after=*/true)) { return false; } } @@ -1230,16 +1214,15 @@ bool ClassLoaderContext::CreateInfoFromClassLoader( parent, null_dex_elements, info, - /*is_shared_library=*/ false, - /*is_after=*/ false)) { + /*is_shared_library=*/false, + /*is_after=*/false)) { return false; } return true; } std::unique_ptr<ClassLoaderContext> ClassLoaderContext::CreateContextForClassLoader( - jobject class_loader, - jobjectArray dex_elements) { + jobject class_loader, jobjectArray dex_elements) { ScopedTrace trace(__FUNCTION__); if (class_loader == nullptr) { @@ -1251,20 +1234,20 @@ std::unique_ptr<ClassLoaderContext> ClassLoaderContext::CreateContextForClassLoa hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader)); Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements)); - std::unique_ptr<ClassLoaderContext> result(new ClassLoaderContext(/*owns_the_dex_files=*/ false)); + std::unique_ptr<ClassLoaderContext> result(new ClassLoaderContext(/*owns_the_dex_files=*/false)); if (!result->CreateInfoFromClassLoader(soa, h_class_loader, h_dex_elements, nullptr, - /*is_shared_library=*/ false, - /*is_after=*/ false)) { + /*is_shared_library=*/false, + /*is_after=*/false)) { return nullptr; } return result; } -std::map<std::string, std::string> -ClassLoaderContext::EncodeClassPathContextsForClassLoader(jobject class_loader) { +std::map<std::string, std::string> ClassLoaderContext::EncodeClassPathContextsForClassLoader( + jobject class_loader) { std::unique_ptr<ClassLoaderContext> clc = ClassLoaderContext::CreateContextForClassLoader(class_loader, nullptr); if (clc != nullptr) { @@ -1291,14 +1274,12 @@ ClassLoaderContext::EncodeClassPathContextsForClassLoader(jobject class_loader) } bool ClassLoaderContext::IsValidEncoding(const std::string& possible_encoded_class_loader_context) { - return ClassLoaderContext::Create(possible_encoded_class_loader_context.c_str()) != nullptr - || possible_encoded_class_loader_context == kUnsupportedClassLoaderContextEncoding; + return ClassLoaderContext::Create(possible_encoded_class_loader_context) != nullptr || + possible_encoded_class_loader_context == kUnsupportedClassLoaderContextEncoding; } ClassLoaderContext::VerificationResult ClassLoaderContext::VerifyClassLoaderContextMatch( - const std::string& context_spec, - bool verify_names, - bool verify_checksums) const { + const std::string& context_spec, bool verify_names, bool verify_checksums) const { ScopedTrace trace(__FUNCTION__); if (verify_names || verify_checksums) { DCHECK(dex_files_state_ == kDexFilesChecksumsRead || dex_files_state_ == kDexFilesOpened) @@ -1328,8 +1309,7 @@ static inline bool AbsolutePathHasRelativeSuffix(const std::string& path, const std::string& suffix) { DCHECK(IsAbsoluteLocation(path)); DCHECK(!IsAbsoluteLocation(suffix)); - return (path.size() > suffix.size()) && - (path[path.size() - suffix.size() - 1u] == '/') && + return (path.size() > suffix.size()) && (path[path.size() - suffix.size() - 1u] == '/') && (std::string_view(path).substr(/*pos*/ path.size() - suffix.size()) == suffix); } @@ -1394,24 +1374,23 @@ static bool AreDexNameMatching(const std::string& actual_dex_name, return dex_names_match; } -bool ClassLoaderContext::ClassLoaderInfoMatch( - const ClassLoaderInfo& info, - const ClassLoaderInfo& expected_info, - const std::string& context_spec, - bool verify_names, - bool verify_checksums) const { +bool ClassLoaderContext::ClassLoaderInfoMatch(const ClassLoaderInfo& info, + const ClassLoaderInfo& expected_info, + const std::string& context_spec, + bool verify_names, + bool verify_checksums) const { if (info.type != expected_info.type) { LOG(WARNING) << "ClassLoaderContext type mismatch" - << ". expected=" << GetClassLoaderTypeName(expected_info.type) - << ", found=" << GetClassLoaderTypeName(info.type) - << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")"; + << ". expected=" << GetClassLoaderTypeName(expected_info.type) + << ", found=" << GetClassLoaderTypeName(info.type) << " (" << context_spec << " | " + << EncodeContextForOatFile("") << ")"; return false; } if (info.classpath.size() != expected_info.classpath.size()) { LOG(WARNING) << "ClassLoaderContext classpath size mismatch" - << ". expected=" << expected_info.classpath.size() - << ", found=" << info.classpath.size() - << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")"; + << ". expected=" << expected_info.classpath.size() + << ", found=" << info.classpath.size() << " (" << context_spec << " | " + << EncodeContextForOatFile("") << ")"; return false; } @@ -1427,9 +1406,9 @@ bool ClassLoaderContext::ClassLoaderInfoMatch( // Compare the locations. if (!dex_names_match) { LOG(WARNING) << "ClassLoaderContext classpath element mismatch" - << ". expected=" << expected_info.classpath[k] - << ", found=" << info.classpath[k] - << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")"; + << ". expected=" << expected_info.classpath[k] + << ", found=" << info.classpath[k] << " (" << context_spec << " | " + << EncodeContextForOatFile("") << ")"; return false; } @@ -1437,8 +1416,8 @@ bool ClassLoaderContext::ClassLoaderInfoMatch( if (info.checksums[k] != expected_info.checksums[k]) { LOG(WARNING) << "ClassLoaderContext classpath element checksum mismatch" << ". expected=" << expected_info.checksums[k] - << ", found=" << info.checksums[k] - << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")"; + << ", found=" << info.checksums[k] << " (" << context_spec << " | " + << EncodeContextForOatFile("") << ")"; return false; } } @@ -1446,9 +1425,9 @@ bool ClassLoaderContext::ClassLoaderInfoMatch( if (info.shared_libraries.size() != expected_info.shared_libraries.size()) { LOG(WARNING) << "ClassLoaderContext shared library size mismatch. " - << "Expected=" << expected_info.shared_libraries.size() - << ", found=" << info.shared_libraries.size() - << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")"; + << "Expected=" << expected_info.shared_libraries.size() + << ", found=" << info.shared_libraries.size() << " (" << context_spec << " | " + << EncodeContextForOatFile("") << ")"; return false; } for (size_t i = 0; i < info.shared_libraries.size(); ++i) { @@ -1463,13 +1442,13 @@ bool ClassLoaderContext::ClassLoaderInfoMatch( if (info.parent.get() == nullptr) { if (expected_info.parent.get() != nullptr) { LOG(WARNING) << "ClassLoaderContext parent mismatch. " - << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")"; + << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")"; return false; } return true; } else if (expected_info.parent.get() == nullptr) { LOG(WARNING) << "ClassLoaderContext parent mismatch. " - << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")"; + << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")"; return false; } else { return ClassLoaderInfoMatch(*info.parent.get(), @@ -1499,8 +1478,8 @@ std::set<const DexFile*> ClassLoaderContext::CheckForDuplicateDexFiles( ClassLoaderInfo* info = class_loader_chain_.get(); for (size_t k = 0; k < info->classpath.size(); k++) { for (const DexFile* dex_file : dex_files_to_check) { - if (info->checksums[k] == dex_file->GetLocationChecksum() - && AreDexNameMatching(info->classpath[k], dex_file->GetLocation())) { + if (info->checksums[k] == dex_file->GetLocationChecksum() && + AreDexNameMatching(info->classpath[k], dex_file->GetLocation())) { result.insert(dex_file); } } diff --git a/runtime/dexopt_test.cc b/runtime/dexopt_test.cc index 6ba75737f5..3eee9e03e0 100644 --- a/runtime/dexopt_test.cc +++ b/runtime/dexopt_test.cc @@ -49,9 +49,7 @@ void DexoptTest::PreRuntimeCreate() { UnreserveImageSpace(); } -void DexoptTest::PostRuntimeCreate() { - ReserveImageSpace(); -} +void DexoptTest::PostRuntimeCreate() { ReserveImageSpace(); } bool DexoptTest::Dex2Oat(const std::vector<std::string>& args, std::string* error_msg) { std::vector<std::string> argv; @@ -83,9 +81,9 @@ std::string DexoptTest::GenerateAlternateImage(const std::string& scratch_dir) { int mkdir_result = mkdir(image_dir.c_str(), 0700); CHECK_EQ(0, mkdir_result) << image_dir.c_str(); - std::vector<std::string> extra_args { - "--compiler-filter=verify", - android::base::StringPrintf("--base=0x%08x", ART_BASE_ADDRESS), + std::vector<std::string> extra_args{ + "--compiler-filter=verify", + android::base::StringPrintf("--base=0x%08x", ART_BASE_ADDRESS), }; std::string filename_prefix = image_dir + "/boot-interpreter"; ArrayRef<const std::string> dex_files(libcore_dex_files); @@ -154,11 +152,11 @@ void DexoptTest::GenerateOatForTest(const std::string& dex_location, ASSERT_TRUE(Dex2Oat(args, &error_msg)) << error_msg; // Verify the odex file was generated as expected. - std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1, - oat_location.c_str(), - oat_location.c_str(), - /*executable=*/ false, - /*low_4gb=*/ false, + std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/-1, + oat_location, + oat_location, + /*executable=*/false, + /*low_4gb=*/false, dex_location, &error_msg)); ASSERT_TRUE(odex_file.get() != nullptr) << error_msg; @@ -184,7 +182,7 @@ void DexoptTest::GenerateOdexForTest(const std::string& dex_location, GenerateOatForTest(dex_location, odex_location, filter, - /*with_alternate_image=*/ false, + /*with_alternate_image=*/false, compilation_reason, extra_args); } @@ -195,15 +193,13 @@ void DexoptTest::GenerateOatForTest(const char* dex_location, std::string oat_location; std::string error_msg; ASSERT_TRUE(OatFileAssistant::DexLocationToOatFilename( - dex_location, kRuntimeISA, &oat_location, &error_msg)) << error_msg; - GenerateOatForTest(dex_location, - oat_location, - filter, - with_alternate_image); + dex_location, kRuntimeISA, &oat_location, &error_msg)) + << error_msg; + GenerateOatForTest(dex_location, oat_location, filter, with_alternate_image); } void DexoptTest::GenerateOatForTest(const char* dex_location, CompilerFilter::Filter filter) { - GenerateOatForTest(dex_location, filter, /*with_alternate_image=*/ false); + GenerateOatForTest(dex_location, filter, /*with_alternate_image=*/false); } void DexoptTest::ReserveImageSpace() { @@ -232,19 +228,17 @@ void DexoptTest::ReserveImageSpaceChunk(uintptr_t start, uintptr_t end) { reinterpret_cast<uint8_t*>(start), end - start, PROT_NONE, - /*low_4gb=*/ false, - /*reuse=*/ false, - /*reservation=*/ nullptr, + /*low_4gb=*/false, + /*reuse=*/false, + /*reservation=*/nullptr, &error_msg)); ASSERT_TRUE(image_reservation_.back().IsValid()) << error_msg; - LOG(INFO) << "Reserved space for image " << - reinterpret_cast<void*>(image_reservation_.back().Begin()) << "-" << - reinterpret_cast<void*>(image_reservation_.back().End()); + LOG(INFO) << "Reserved space for image " + << reinterpret_cast<void*>(image_reservation_.back().Begin()) << "-" + << reinterpret_cast<void*>(image_reservation_.back().End()); } } -void DexoptTest::UnreserveImageSpace() { - image_reservation_.clear(); -} +void DexoptTest::UnreserveImageSpace() { image_reservation_.clear(); } } // namespace art diff --git a/runtime/gc/space/image_space_test.cc b/runtime/gc/space/image_space_test.cc index b85560caad..d6bb86b11b 100644 --- a/runtime/gc/space/image_space_test.cc +++ b/runtime/gc/space/image_space_test.cc @@ -50,7 +50,7 @@ class ImageSpaceTest : public CommonRuntimeTest { }; TEST_F(ImageSpaceTest, StringDeduplication) { - const char* const kBaseNames[] = { "Extension1", "Extension2" }; + const char* const kBaseNames[] = {"Extension1", "Extension2"}; ScratchDir scratch; const std::string& scratch_dir = scratch.GetPath(); @@ -77,7 +77,7 @@ TEST_F(ImageSpaceTest, StringDeduplication) { std::vector<std::string> extension_image_locations; for (const char* base_name : kBaseNames) { std::string jar_name = GetTestDexFileName(base_name); - ArrayRef<const std::string> dex_files(&jar_name, /*size=*/ 1u); + ArrayRef<const std::string> dex_files(&jar_name, /*size=*/1u); ScratchFile profile_file; GenerateBootProfile(dex_files, profile_file.GetFile()); std::vector<std::string> extra_args = { @@ -94,8 +94,8 @@ TEST_F(ImageSpaceTest, StringDeduplication) { ASSERT_TRUE(success) << error_msg; bcp.push_back(jar_name); bcp_locations.push_back(jar_name); - extension_image_locations.push_back( - scratch_dir + prefix + '-' + GetFilenameBase(jar_name) + ".art"); + extension_image_locations.push_back(scratch_dir + prefix + '-' + GetFilenameBase(jar_name) + + ".art"); } // Also compile the second extension as an app with app image. @@ -104,26 +104,27 @@ TEST_F(ImageSpaceTest, StringDeduplication) { std::string app_odex_name = scratch_dir + app_base_name + ".odex"; std::string app_image_name = scratch_dir + app_base_name + ".art"; { - ArrayRef<const std::string> dex_files(&app_jar_name, /*size=*/ 1u); + ArrayRef<const std::string> dex_files(&app_jar_name, /*size=*/1u); ScratchFile profile_file; GenerateProfile(dex_files, profile_file.GetFile()); std::vector<std::string> argv; std::string error_msg; - bool success = StartDex2OatCommandLine(&argv, &error_msg, /*use_runtime_bcp_and_image=*/ false); + bool success = StartDex2OatCommandLine(&argv, &error_msg, /*use_runtime_bcp_and_image=*/false); ASSERT_TRUE(success) << error_msg; - argv.insert(argv.end(), { - "--profile-file=" + profile_file.GetFilename(), - "--runtime-arg", - "-Xbootclasspath:" + base_bcp_string, - "--runtime-arg", - "-Xbootclasspath-locations:" + base_bcp_locations_string, - "--boot-image=" + base_image_location, - "--dex-file=" + app_jar_name, - "--dex-location=" + app_jar_name, - "--oat-file=" + app_odex_name, - "--app-image-file=" + app_image_name, - "--initialize-app-image-classes=true", - }); + argv.insert(argv.end(), + { + "--profile-file=" + profile_file.GetFilename(), + "--runtime-arg", + "-Xbootclasspath:" + base_bcp_string, + "--runtime-arg", + "-Xbootclasspath-locations:" + base_bcp_locations_string, + "--boot-image=" + base_image_location, + "--dex-file=" + app_jar_name, + "--dex-location=" + app_jar_name, + "--oat-file=" + app_odex_name, + "--app-image-file=" + app_image_name, + "--initialize-app-image-classes=true", + }); success = RunDex2Oat(argv, &error_msg); ASSERT_TRUE(success) << error_msg; } @@ -136,16 +137,16 @@ TEST_F(ImageSpaceTest, StringDeduplication) { extra_reservation = MemMap::Invalid(); return ImageSpace::LoadBootImage(bcp, bcp_locations, - /*boot_class_path_fds=*/ std::vector<int>(), - /*boot_class_path_image_fds=*/ std::vector<int>(), - /*boot_class_path_vdex_fds=*/ std::vector<int>(), - /*boot_class_path_oat_fds=*/ std::vector<int>(), + /*boot_class_path_fds=*/std::vector<int>(), + /*boot_class_path_image_fds=*/std::vector<int>(), + /*boot_class_path_vdex_fds=*/std::vector<int>(), + /*boot_class_path_oat_fds=*/std::vector<int>(), full_image_locations, kRuntimeISA, - /*relocate=*/ false, - /*executable=*/ true, - /*extra_reservation_size=*/ 0u, - /*allow_in_memory_compilation=*/ false, + /*relocate=*/false, + /*executable=*/true, + /*extra_reservation_size=*/0u, + /*allow_in_memory_compilation=*/false, &boot_image_spaces, &extra_reservation); }; @@ -154,13 +155,13 @@ TEST_F(ImageSpaceTest, StringDeduplication) { size_t test_string_length = std::size(test_string) - 1u; // Equals UTF-16 length. uint32_t hash = InternTable::Utf8String::Hash(test_string_length, test_string); InternTable::Utf8String utf8_test_string(test_string_length, test_string); - auto contains_test_string = [utf8_test_string, hash](ImageSpace* space) - REQUIRES_SHARED(Locks::mutator_lock_) { + auto contains_test_string = [utf8_test_string, + hash](ImageSpace* space) REQUIRES_SHARED(Locks::mutator_lock_) { const ImageHeader& image_header = space->GetImageHeader(); if (image_header.GetInternedStringsSection().Size() != 0u) { const uint8_t* data = space->Begin() + image_header.GetInternedStringsSection().Offset(); size_t read_count; - InternTable::UnorderedSet temp_set(data, /*make_copy_of_data=*/ false, &read_count); + InternTable::UnorderedSet temp_set(data, /*make_copy_of_data=*/false, &read_count); return temp_set.FindWithHash(utf8_test_string, hash) != temp_set.end(); } else { return false; @@ -171,8 +172,7 @@ TEST_F(ImageSpaceTest, StringDeduplication) { ScopedObjectAccess soa(Thread::Current()); ASSERT_EQ(2u, extension_image_locations.size()); full_image_locations = { - base_image_location, extension_image_locations[0], extension_image_locations[1] - }; + base_image_location, extension_image_locations[0], extension_image_locations[1]}; bool success = load_boot_image(); ASSERT_TRUE(success); ASSERT_EQ(bcp.size(), boot_image_spaces.size()); @@ -184,8 +184,7 @@ TEST_F(ImageSpaceTest, StringDeduplication) { std::swap(bcp[bcp.size() - 2u], bcp[bcp.size() - 1u]); std::swap(bcp_locations[bcp_locations.size() - 2u], bcp_locations[bcp_locations.size() - 1u]); full_image_locations = { - base_image_location, extension_image_locations[1], extension_image_locations[0] - }; + base_image_location, extension_image_locations[1], extension_image_locations[0]}; success = load_boot_image(); ASSERT_TRUE(success); ASSERT_EQ(bcp.size(), boot_image_spaces.size()); @@ -204,21 +203,21 @@ TEST_F(ImageSpaceTest, StringDeduplication) { // Load the app odex file and app image. std::string error_msg; - std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1, - app_odex_name.c_str(), - app_odex_name.c_str(), - /*executable=*/ false, - /*low_4gb=*/ false, + std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/-1, + app_odex_name, + app_odex_name, + /*executable=*/false, + /*low_4gb=*/false, app_jar_name, &error_msg)); ASSERT_TRUE(odex_file != nullptr) << error_msg; std::vector<ImageSpace*> non_owning_boot_image_spaces = MakeNonOwningPointerVector(boot_image_spaces); - std::unique_ptr<ImageSpace> app_image_space = ImageSpace::CreateFromAppImage( - app_image_name.c_str(), - odex_file.get(), - ArrayRef<ImageSpace* const>(non_owning_boot_image_spaces), - &error_msg); + std::unique_ptr<ImageSpace> app_image_space = + ImageSpace::CreateFromAppImage(app_image_name.c_str(), + odex_file.get(), + ArrayRef<ImageSpace* const>(non_owning_boot_image_spaces), + &error_msg); ASSERT_TRUE(app_image_space != nullptr) << error_msg; // The string in the app image should be replaced and removed from interned string section. @@ -243,25 +242,25 @@ TEST_F(DexoptTest, ValidateOatFile) { args.push_back("--oat-file=" + oat_location); ASSERT_TRUE(Dex2Oat(args, &error_msg)) << error_msg; - std::unique_ptr<OatFile> oat(OatFile::Open(/*zip_fd=*/ -1, - oat_location.c_str(), - oat_location.c_str(), - /*executable=*/ false, - /*low_4gb=*/ false, + std::unique_ptr<OatFile> oat(OatFile::Open(/*zip_fd=*/-1, + oat_location, + oat_location, + /*executable=*/false, + /*low_4gb=*/false, &error_msg)); ASSERT_TRUE(oat != nullptr) << error_msg; { // Test opening the oat file also with explicit dex filenames. - std::vector<std::string> dex_filenames{ dex1, multidex1, dex2 }; - std::unique_ptr<OatFile> oat2(OatFile::Open(/*zip_fd=*/ -1, - oat_location.c_str(), - oat_location.c_str(), - /*executable=*/ false, - /*low_4gb=*/ false, + std::vector<std::string> dex_filenames{dex1, multidex1, dex2}; + std::unique_ptr<OatFile> oat2(OatFile::Open(/*zip_fd=*/-1, + oat_location, + oat_location, + /*executable=*/false, + /*low_4gb=*/false, ArrayRef<const std::string>(dex_filenames), - /*dex_fds=*/ ArrayRef<const int>(), - /*reservation=*/ nullptr, + /*dex_fds=*/ArrayRef<const int>(), + /*reservation=*/nullptr, &error_msg)); ASSERT_TRUE(oat2 != nullptr) << error_msg; } diff --git a/runtime/hidden_api.cc b/runtime/hidden_api.cc index 6acbe51add..9d32e51ba6 100644 --- a/runtime/hidden_api.cc +++ b/runtime/hidden_api.cc @@ -16,19 +16,19 @@ #include "hidden_api.h" -#include <nativehelper/scoped_local_ref.h> #include <atomic> #include "art_field-inl.h" #include "art_method-inl.h" -#include "class_root-inl.h" -#include "compat_framework.h" #include "base/dumpable.h" #include "base/file_utils.h" +#include "class_root-inl.h" +#include "compat_framework.h" #include "dex/class_accessor-inl.h" #include "dex/dex_file_loader.h" #include "mirror/class_ext.h" #include "mirror/proxy.h" +#include "nativehelper/scoped_local_ref.h" #include "oat_file.h" #include "scoped_thread_state_change.h" #include "stack.h" @@ -105,22 +105,21 @@ static Domain DetermineDomainFromLocation(const std::string& dex_location, // These checks will be skipped on target buildbots where ANDROID_ART_ROOT // is set to "/system". if (ArtModuleRootDistinctFromAndroidRoot()) { - if (LocationIsOnArtModule(dex_location.c_str()) || - LocationIsOnConscryptModule(dex_location.c_str()) || - LocationIsOnI18nModule(dex_location.c_str())) { + if (LocationIsOnArtModule(dex_location) || LocationIsOnConscryptModule(dex_location) || + LocationIsOnI18nModule(dex_location)) { return Domain::kCorePlatform; } - if (LocationIsOnApex(dex_location.c_str())) { + if (LocationIsOnApex(dex_location)) { return Domain::kPlatform; } } - if (LocationIsOnSystemFramework(dex_location.c_str())) { + if (LocationIsOnSystemFramework(dex_location)) { return Domain::kPlatform; } - if (LocationIsOnSystemExtFramework(dex_location.c_str())) { + if (LocationIsOnSystemExtFramework(dex_location)) { return Domain::kPlatform; } @@ -128,7 +127,7 @@ static Domain DetermineDomainFromLocation(const std::string& dex_location, if (kIsTargetBuild && !kIsTargetLinux) { // This is unexpected only when running on Android. LOG(WARNING) << "DexFile " << dex_location - << " is in boot class path but is not in a known location"; + << " is in boot class path but is not in a known location"; } return Domain::kPlatform; } @@ -150,11 +149,11 @@ void InitializeCorePlatformApiPrivateFields() { // The following fields in WellKnownClasses correspond to private fields in the Core Platform // API that cannot be otherwise expressed and propagated through tooling (b/144502743). ArtField* private_core_platform_api_fields[] = { - WellKnownClasses::java_io_FileDescriptor_descriptor, - WellKnownClasses::java_nio_Buffer_address, - WellKnownClasses::java_nio_Buffer_elementSizeShift, - WellKnownClasses::java_nio_Buffer_limit, - WellKnownClasses::java_nio_Buffer_position, + WellKnownClasses::java_io_FileDescriptor_descriptor, + WellKnownClasses::java_nio_Buffer_address, + WellKnownClasses::java_nio_Buffer_elementSizeShift, + WellKnownClasses::java_nio_Buffer_limit, + WellKnownClasses::java_nio_Buffer_position, }; ScopedObjectAccess soa(Thread::Current()); @@ -174,11 +173,10 @@ hiddenapi::AccessContext GetReflectionCallerAccessContext(Thread* self) struct FirstExternalCallerVisitor : public StackVisitor { explicit FirstExternalCallerVisitor(Thread* thread) : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames), - caller(nullptr) { - } + caller(nullptr) {} bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) { - ArtMethod *m = GetMethod(); + ArtMethod* m = GetMethod(); if (m == nullptr) { // Attached native thread. Assume this is *not* boot class path. caller = nullptr; @@ -199,8 +197,8 @@ hiddenapi::AccessContext GetReflectionCallerAccessContext(Thread* self) // NB Static initializers within java.lang.invoke are permitted and do not // need further stack inspection. ObjPtr<mirror::Class> lookup_class = GetClassRoot<mirror::MethodHandlesLookup>(); - if ((declaring_class == lookup_class || declaring_class->IsInSamePackage(lookup_class)) - && !m->IsClassInitializer()) { + if ((declaring_class == lookup_class || declaring_class->IsInSamePackage(lookup_class)) && + !m->IsClassInitializer()) { return true; } // Check for classes in the java.lang.reflect package, except for java.lang.reflect.Proxy. @@ -229,10 +227,9 @@ hiddenapi::AccessContext GetReflectionCallerAccessContext(Thread* self) // Construct AccessContext from the calling class found on the stack. // If the calling class cannot be determined, e.g. unattached threads, // we conservatively assume the caller is trusted. - ObjPtr<mirror::Class> caller = (visitor.caller == nullptr) - ? nullptr : visitor.caller->GetDeclaringClass(); - return caller.IsNull() ? AccessContext(/* is_trusted= */ true) - : AccessContext(caller); + ObjPtr<mirror::Class> caller = + (visitor.caller == nullptr) ? nullptr : visitor.caller->GetDeclaringClass(); + return caller.IsNull() ? AccessContext(/* is_trusted= */ true) : AccessContext(caller); } namespace detail { @@ -243,7 +240,7 @@ enum AccessContextFlags { // Accessed member is a field if this bit is set, else a method kMemberIsField = 1 << 0, // Indicates if access was denied to the member, instead of just printing a warning. - kAccessDenied = 1 << 1, + kAccessDenied = 1 << 1, }; MemberSignature::MemberSignature(ArtField* field) { @@ -282,10 +279,10 @@ MemberSignature::MemberSignature(const ClassAccessor::Method& method) { inline std::vector<const char*> MemberSignature::GetSignatureParts() const { if (type_ == kField) { - return { class_name_.c_str(), "->", member_name_.c_str(), ":", type_signature_.c_str() }; + return {class_name_.c_str(), "->", member_name_.c_str(), ":", type_signature_.c_str()}; } else { DCHECK_EQ(type_, kMethod); - return { class_name_.c_str(), "->", member_name_.c_str(), type_signature_.c_str() }; + return {class_name_.c_str(), "->", member_name_.c_str(), type_signature_.c_str()}; } } @@ -341,10 +338,8 @@ void MemberSignature::WarnAboutAccess(AccessMethod access_method, } bool MemberSignature::Equals(const MemberSignature& other) { - return type_ == other.type_ && - class_name_ == other.class_name_ && - member_name_ == other.member_name_ && - type_signature_ == other.type_signature_; + return type_ == other.type_ && class_name_ == other.class_name_ && + member_name_ == other.member_name_ && type_signature_ == other.type_signature_; } bool MemberSignature::MemberNameAndTypeMatch(const MemberSignature& other) { @@ -373,26 +368,25 @@ void MemberSignature::LogAccessToEventLog(uint32_t sampled_value, ScopedObjectAccess soa(Thread::Current()); StackHandleScope<2u> hs(soa.Self()); - Handle<mirror::String> package_str = hs.NewHandle( - mirror::String::AllocFromModifiedUtf8(soa.Self(), package_name.c_str())); + Handle<mirror::String> package_str = + hs.NewHandle(mirror::String::AllocFromModifiedUtf8(soa.Self(), package_name.c_str())); if (soa.Self()->IsExceptionPending()) { soa.Self()->ClearException(); LOG(ERROR) << "Unable to allocate string for package name which called hidden api"; } - Handle<mirror::String> signature_jstr = hs.NewHandle( - mirror::String::AllocFromModifiedUtf8(soa.Self(), signature_str.str().c_str())); + Handle<mirror::String> signature_jstr = + hs.NewHandle(mirror::String::AllocFromModifiedUtf8(soa.Self(), signature_str.str().c_str())); if (soa.Self()->IsExceptionPending()) { soa.Self()->ClearException(); LOG(ERROR) << "Unable to allocate string for hidden api method signature"; } WellKnownClasses::dalvik_system_VMRuntime_hiddenApiUsed - ->InvokeStatic<'V', 'I', 'L', 'L', 'I', 'Z'>( - soa.Self(), - static_cast<jint>(sampled_value), - package_str.Get(), - signature_jstr.Get(), - static_cast<jint>(access_method), - access_denied); + ->InvokeStatic<'V', 'I', 'L', 'L', 'I', 'Z'>(soa.Self(), + static_cast<jint>(sampled_value), + package_str.Get(), + signature_jstr.Get(), + static_cast<jint>(access_method), + access_denied); if (soa.Self()->IsExceptionPending()) { soa.Self()->ClearException(); LOG(ERROR) << "Unable to report hidden api usage"; @@ -438,23 +432,20 @@ void MemberSignature::NotifyHiddenApiListener(AccessMethod access_method) { } } -static ALWAYS_INLINE bool CanUpdateRuntimeFlags(ArtField*) { - return true; -} +static ALWAYS_INLINE bool CanUpdateRuntimeFlags(ArtField*) { return true; } static ALWAYS_INLINE bool CanUpdateRuntimeFlags(ArtMethod* method) { return !method->IsIntrinsic(); } -template<typename T> +template <typename T> static ALWAYS_INLINE void MaybeUpdateAccessFlags(Runtime* runtime, T* member, uint32_t flag) REQUIRES_SHARED(Locks::mutator_lock_) { // Update the access flags unless: // (a) `member` is an intrinsic // (b) this is AOT compiler, as we do not want the updated access flags in the boot/app image // (c) deduping warnings has been explicitly switched off. - if (CanUpdateRuntimeFlags(member) && - !runtime->IsAotCompiler() && + if (CanUpdateRuntimeFlags(member) && !runtime->IsAotCompiler() && runtime->ShouldDedupeHiddenApiWarnings()) { member->SetAccessFlags(member->GetAccessFlags() | flag); } @@ -485,12 +476,13 @@ static void VisitMembers(const DexFile& dex_file, accessor.VisitMethods(fn_visit, fn_visit); } -template<typename T> +template <typename T> uint32_t GetDexFlags(T* member) REQUIRES_SHARED(Locks::mutator_lock_) { static_assert(std::is_same<T, ArtField>::value || std::is_same<T, ArtMethod>::value); constexpr bool kMemberIsField = std::is_same<T, ArtField>::value; using AccessorType = typename std::conditional<std::is_same<T, ArtField>::value, - ClassAccessor::Field, ClassAccessor::Method>::type; + ClassAccessor::Field, + ClassAccessor::Method>::type; ObjPtr<mirror::Class> declaring_class = member->GetDeclaringClass(); DCHECK(!declaring_class.IsNull()) << "Attempting to access a runtime method"; @@ -545,11 +537,11 @@ uint32_t GetDexFlags(T* member) REQUIRES_SHARED(Locks::mutator_lock_) { } CHECK(flags.IsValid()) << "Could not find hiddenapi flags for " - << Dumpable<MemberSignature>(MemberSignature(member)); + << Dumpable<MemberSignature>(MemberSignature(member)); return flags.GetDexFlags(); } -template<typename T> +template <typename T> bool HandleCorePlatformApiViolation(T* member, const AccessContext& caller_context, AccessMethod access_method, @@ -559,8 +551,8 @@ bool HandleCorePlatformApiViolation(T* member, if (access_method != AccessMethod::kNone) { LOG(WARNING) << "Core platform API violation: " - << Dumpable<MemberSignature>(MemberSignature(member)) - << " from " << caller_context << " using " << access_method; + << Dumpable<MemberSignature>(MemberSignature(member)) << " from " << caller_context + << " using " << access_method; // If policy is set to just warn, add kAccCorePlatformApi to access flags of // `member` to avoid reporting the violation again next time. @@ -573,7 +565,7 @@ bool HandleCorePlatformApiViolation(T* member, return policy == EnforcementPolicy::kEnabled; } -template<typename T> +template <typename T> bool ShouldDenyAccessToMemberImpl(T* member, ApiList api_list, AccessMethod access_method) { DCHECK(member != nullptr); Runtime* runtime = Runtime::Current(); @@ -598,9 +590,8 @@ bool ShouldDenyAccessToMemberImpl(T* member, ApiList api_list, AccessMethod acce bool deny_access = false; if (hiddenApiPolicy == EnforcementPolicy::kEnabled) { - if (api_list.IsTestApi() && - (testApiPolicy == EnforcementPolicy::kDisabled || - compatFramework.IsChangeEnabled(kAllowTestApiAccess))) { + if (api_list.IsTestApi() && (testApiPolicy == EnforcementPolicy::kDisabled || + compatFramework.IsChangeEnabled(kAllowTestApiAccess))) { deny_access = false; } else { switch (api_list.GetMaxAllowedSdkVersion()) { @@ -673,7 +664,7 @@ template bool ShouldDenyAccessToMemberImpl<ArtMethod>(ArtMethod* member, AccessMethod access_method); } // namespace detail -template<typename T> +template <typename T> bool ShouldDenyAccessToMember(T* member, const std::function<AccessContext()>& fn_get_access_context, AccessMethod access_method) { @@ -766,10 +757,7 @@ bool ShouldDenyAccessToMember(T* member, // Access checks are not disabled, report the violation. // This may also add kAccCorePlatformApi to the access flags of `member` // so as to not warn again on next access. - return detail::HandleCorePlatformApiViolation(member, - caller_context, - access_method, - policy); + return detail::HandleCorePlatformApiViolation(member, caller_context, access_method, policy); } case Domain::kCorePlatform: { diff --git a/runtime/hidden_api_test.cc b/runtime/hidden_api_test.cc index c2c40c5af3..3fb447afc9 100644 --- a/runtime/hidden_api_test.cc +++ b/runtime/hidden_api_test.cc @@ -638,14 +638,14 @@ TEST_F(HiddenApiTest, CheckMemberSignatureForProxyClass) { TEST_F(HiddenApiTest, DexDomain_DataDir) { // Load file from a non-system directory and check that it is not flagged as framework. std::string data_location_path = android_data_ + "/foo.jar"; - ASSERT_FALSE(LocationIsOnSystemFramework(data_location_path.c_str())); + ASSERT_FALSE(LocationIsOnSystemFramework(data_location_path)); TestLocation(data_location_path, hiddenapi::Domain::kApplication); } TEST_F(HiddenApiTest, DexDomain_SystemDir) { // Load file from a system, non-framework directory and check that it is not flagged as framework. std::string system_location_path = GetAndroidRoot() + "/foo.jar"; - ASSERT_FALSE(LocationIsOnSystemFramework(system_location_path.c_str())); + ASSERT_FALSE(LocationIsOnSystemFramework(system_location_path)); TestLocation(system_location_path, hiddenapi::Domain::kApplication); } @@ -653,7 +653,7 @@ TEST_F(HiddenApiTest, DexDomain_SystemExtDir) { // Load file from a system_ext, non-framework directory and check that it is not flagged as // framework. std::string system_ext_location_path = android_system_ext_ + "/foo.jar"; - ASSERT_FALSE(LocationIsOnSystemExtFramework(system_ext_location_path.c_str())); + ASSERT_FALSE(LocationIsOnSystemExtFramework(system_ext_location_path)); TestLocation(system_ext_location_path, hiddenapi::Domain::kApplication); } @@ -662,7 +662,7 @@ TEST_F(HiddenApiTest, DexDomain_SystemSystemExtDir) { // framework. std::filesystem::create_directory(GetAndroidRoot() + "/system_ext"); std::string system_ext_location_path = GetAndroidRoot() + "/system_ext/foo.jar"; - ASSERT_FALSE(LocationIsOnSystemExtFramework(system_ext_location_path.c_str())); + ASSERT_FALSE(LocationIsOnSystemExtFramework(system_ext_location_path)); TestLocation(system_ext_location_path, hiddenapi::Domain::kApplication); } @@ -670,7 +670,7 @@ TEST_F(HiddenApiTest, DexDomain_SystemFrameworkDir) { // Load file from a system/framework directory and check that it is flagged as a framework dex. std::filesystem::create_directory(GetAndroidRoot() + "/framework"); std::string system_framework_location_path = GetAndroidRoot() + "/framework/foo.jar"; - ASSERT_TRUE(LocationIsOnSystemFramework(system_framework_location_path.c_str())); + ASSERT_TRUE(LocationIsOnSystemFramework(system_framework_location_path)); TestLocation(system_framework_location_path, hiddenapi::Domain::kPlatform); } @@ -678,7 +678,7 @@ TEST_F(HiddenApiTest, DexDomain_SystemExtFrameworkDir) { // Load file from a system_ext/framework directory and check that it is flagged as a framework dex. std::filesystem::create_directory(android_system_ext_ + "/framework"); std::string system_ext_framework_location_path = android_system_ext_ + "/framework/foo.jar"; - ASSERT_TRUE(LocationIsOnSystemExtFramework(system_ext_framework_location_path.c_str())); + ASSERT_TRUE(LocationIsOnSystemExtFramework(system_ext_framework_location_path)); TestLocation(system_ext_framework_location_path, hiddenapi::Domain::kPlatform); } @@ -689,14 +689,14 @@ TEST_F(HiddenApiTest, DexDomain_SystemSystemExtFrameworkDir) { std::filesystem::create_directory(GetAndroidRoot() + "/system_ext/framework"); std::string system_ext_framework_location_path = GetAndroidRoot() + "/system_ext/framework/foo.jar"; - ASSERT_TRUE(LocationIsOnSystemExtFramework(system_ext_framework_location_path.c_str())); + ASSERT_TRUE(LocationIsOnSystemExtFramework(system_ext_framework_location_path)); TestLocation(system_ext_framework_location_path, hiddenapi::Domain::kPlatform); } TEST_F(HiddenApiTest, DexDomain_DataDir_MultiDex) { // Load multidex file from a non-system directory and check that it is not flagged as framework. std::string data_multi_location_path = android_data_ + "/multifoo.jar"; - ASSERT_FALSE(LocationIsOnSystemFramework(data_multi_location_path.c_str())); + ASSERT_FALSE(LocationIsOnSystemFramework(data_multi_location_path)); TestLocation(data_multi_location_path, hiddenapi::Domain::kApplication); } @@ -704,7 +704,7 @@ TEST_F(HiddenApiTest, DexDomain_SystemDir_MultiDex) { // Load multidex file from a system, non-framework directory and check that it is not flagged // as framework. std::string system_multi_location_path = GetAndroidRoot() + "/multifoo.jar"; - ASSERT_FALSE(LocationIsOnSystemFramework(system_multi_location_path.c_str())); + ASSERT_FALSE(LocationIsOnSystemFramework(system_multi_location_path)); TestLocation(system_multi_location_path, hiddenapi::Domain::kApplication); } @@ -712,7 +712,7 @@ TEST_F(HiddenApiTest, DexDomain_SystemExtDir_MultiDex) { // Load multidex file from a system_ext, non-framework directory and check that it is not flagged // as framework. std::string system_ext_multi_location_path = android_system_ext_ + "/multifoo.jar"; - ASSERT_FALSE(LocationIsOnSystemExtFramework(system_ext_multi_location_path.c_str())); + ASSERT_FALSE(LocationIsOnSystemExtFramework(system_ext_multi_location_path)); TestLocation(system_ext_multi_location_path, hiddenapi::Domain::kApplication); } @@ -722,7 +722,7 @@ TEST_F(HiddenApiTest, DexDomain_SystemSystemExtDir_MultiDex) { std::filesystem::create_directory(GetAndroidRoot() + "/system_ext"); std::string system_ext_multi_location_path = GetAndroidRoot() + "/system_ext/multifoo.jar"; - ASSERT_FALSE(LocationIsOnSystemExtFramework(system_ext_multi_location_path.c_str())); + ASSERT_FALSE(LocationIsOnSystemExtFramework(system_ext_multi_location_path)); TestLocation(system_ext_multi_location_path, hiddenapi::Domain::kApplication); } @@ -731,7 +731,7 @@ TEST_F(HiddenApiTest, DexDomain_SystemFrameworkDir_MultiDex) { // framework dex. std::filesystem::create_directory(GetAndroidRoot() + "/framework"); std::string system_framework_multi_location_path = GetAndroidRoot() + "/framework/multifoo.jar"; - ASSERT_TRUE(LocationIsOnSystemFramework(system_framework_multi_location_path.c_str())); + ASSERT_TRUE(LocationIsOnSystemFramework(system_framework_multi_location_path)); TestLocation(system_framework_multi_location_path, hiddenapi::Domain::kPlatform); } @@ -741,7 +741,7 @@ TEST_F(HiddenApiTest, DexDomain_SystemExtFrameworkDir_MultiDex) { std::filesystem::create_directory(android_system_ext_ + "/framework"); std::string system_ext_framework_multi_location_path = android_system_ext_ + "/framework/multifoo.jar"; - ASSERT_TRUE(LocationIsOnSystemExtFramework(system_ext_framework_multi_location_path.c_str())); + ASSERT_TRUE(LocationIsOnSystemExtFramework(system_ext_framework_multi_location_path)); TestLocation(system_ext_framework_multi_location_path, hiddenapi::Domain::kPlatform); } @@ -752,7 +752,7 @@ TEST_F(HiddenApiTest, DexDomain_SystemSystemExtFrameworkDir_MultiDex) { std::filesystem::create_directory(GetAndroidRoot() + "/system_ext/framework"); std::string system_ext_framework_multi_location_path = GetAndroidRoot() + "/system_ext/framework/multifoo.jar"; - ASSERT_TRUE(LocationIsOnSystemExtFramework(system_ext_framework_multi_location_path.c_str())); + ASSERT_TRUE(LocationIsOnSystemExtFramework(system_ext_framework_multi_location_path)); TestLocation(system_ext_framework_multi_location_path, hiddenapi::Domain::kPlatform); } diff --git a/runtime/interpreter/unstarted_runtime.cc b/runtime/interpreter/unstarted_runtime.cc index cafd7c456c..32ed4300b7 100644 --- a/runtime/interpreter/unstarted_runtime.cc +++ b/runtime/interpreter/unstarted_runtime.cc @@ -1276,7 +1276,7 @@ static void UnstartedMemoryPeekArray( if (offset < 0 || offset + count > array->GetLength()) { std::string error_msg(StringPrintf("Array out of bounds in peekArray: %d/%d vs %d", offset, count, array->GetLength())); - Runtime::Current()->AbortTransactionAndThrowAbortError(self, error_msg.c_str()); + Runtime::Current()->AbortTransactionAndThrowAbortError(self, error_msg); return; } diff --git a/runtime/jit/jit.cc b/runtime/jit/jit.cc index fda5affd16..b231cce0bc 100644 --- a/runtime/jit/jit.cc +++ b/runtime/jit/jit.cc @@ -1403,7 +1403,7 @@ uint32_t Jit::CompileMethodsFromBootProfile( const std::string& profile_file, Handle<mirror::ClassLoader> class_loader, bool add_to_queue) { - unix_file::FdFile profile(profile_file.c_str(), O_RDONLY, true); + unix_file::FdFile profile(profile_file, O_RDONLY, true); if (profile.Fd() == -1) { PLOG(WARNING) << "No boot profile: " << profile_file; @@ -1453,7 +1453,7 @@ uint32_t Jit::CompileMethodsFromProfile( // We don't generate boot profiles on device, therefore we don't // need to lock the file. - unix_file::FdFile profile(profile_file.c_str(), O_RDONLY, true); + unix_file::FdFile profile(profile_file, O_RDONLY, true); if (profile.Fd() == -1) { PLOG(WARNING) << "No profile: " << profile_file; diff --git a/runtime/jit/profile_saver.cc b/runtime/jit/profile_saver.cc index e1a10b89e5..cdc4bdb5f1 100644 --- a/runtime/jit/profile_saver.cc +++ b/runtime/jit/profile_saver.cc @@ -876,7 +876,7 @@ bool ProfileSaver::ProcessProfilingInfo( } } else { // Create a file if it doesn't exist. - unix_file::FdFile file(filename.c_str(), + unix_file::FdFile file(filename, O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR, /*check_usage=*/false); diff --git a/runtime/native/java_lang_Class.cc b/runtime/native/java_lang_Class.cc index 2506ca8610..5e54f85b9d 100644 --- a/runtime/native/java_lang_Class.cc +++ b/runtime/native/java_lang_Class.cc @@ -395,7 +395,7 @@ static jobject Class_getDeclaredField(JNIEnv* env, jobject javaThis, jstring nam } // We may have a pending exception if we failed to resolve. if (!soa.Self()->IsExceptionPending()) { - ThrowNoSuchFieldException(h_klass.Get(), name_str.c_str()); + ThrowNoSuchFieldException(h_klass.Get(), name_str); } return nullptr; } diff --git a/runtime/oat_file_assistant.cc b/runtime/oat_file_assistant.cc index d324a241b7..6014409c78 100644 --- a/runtime/oat_file_assistant.cc +++ b/runtime/oat_file_assistant.cc @@ -63,7 +63,7 @@ static constexpr const char* kAnonymousDexPrefix = "Anonymous-DexFile@"; static constexpr const char* kVdexExtension = ".vdex"; static constexpr const char* kDmExtension = ".dm"; -std::ostream& operator << (std::ostream& stream, const OatFileAssistant::OatStatus status) { +std::ostream& operator<<(std::ostream& stream, const OatFileAssistant::OatStatus status) { switch (status) { case OatFileAssistant::kOatCannotOpen: stream << "kOatCannotOpen"; @@ -126,9 +126,9 @@ OatFileAssistant::OatFileAssistant(const char* dex_location, if (zip_fd < 0) { CHECK_LE(oat_fd, 0) << "zip_fd must be provided with valid oat_fd. zip_fd=" << zip_fd - << " oat_fd=" << oat_fd; + << " oat_fd=" << oat_fd; CHECK_LE(vdex_fd, 0) << "zip_fd must be provided with valid vdex_fd. zip_fd=" << zip_fd - << " vdex_fd=" << vdex_fd;; + << " vdex_fd=" << vdex_fd; CHECK(!UseFdToReadFiles()); } else { CHECK(UseFdToReadFiles()); @@ -146,7 +146,7 @@ OatFileAssistant::OatFileAssistant(const char* dex_location, if (load_executable_ && isa != kRuntimeISA) { LOG(WARNING) << "OatFileAssistant: Load executable specified, " - << "but isa is not kRuntimeISA. Will not attempt to load executable."; + << "but isa is not kRuntimeISA. Will not attempt to load executable."; load_executable_ = false; } @@ -194,14 +194,14 @@ OatFileAssistant::OatFileAssistant(const char* dex_location, GetRuntimeOptions().deny_art_apex_data_files, &oat_file_name, &error_msg)) { - oat_.Reset(oat_file_name, /*use_fd=*/ false); + oat_.Reset(oat_file_name, /*use_fd=*/false); std::string vdex_file_name = GetVdexFilename(oat_file_name); vdex_for_oat_.Reset(vdex_file_name, UseFdToReadFiles(), zip_fd, vdex_fd, oat_fd); std::string dm_file_name = GetDmFilename(dex_location); dm_for_oat_.Reset(dm_file_name, UseFdToReadFiles(), zip_fd, vdex_fd, oat_fd); } else { - LOG(WARNING) << "Failed to determine oat file name for dex location " - << dex_location_ << ": " << error_msg; + LOG(WARNING) << "Failed to determine oat file name for dex location " << dex_location_ << ": " + << error_msg; } } @@ -241,13 +241,13 @@ std::unique_ptr<OatFileAssistant> OatFileAssistant::Create( std::unique_ptr<ClassLoaderContext> tmp_context = nullptr; if (context_str.has_value()) { - tmp_context = ClassLoaderContext::Create(context_str->c_str()); + tmp_context = ClassLoaderContext::Create(context_str.value()); if (tmp_context == nullptr) { *error_msg = StringPrintf("Class loader context '%s' is invalid", context_str->c_str()); return nullptr; } - if (!tmp_context->OpenDexFiles(android::base::Dirname(filename.c_str()), + if (!tmp_context->OpenDexFiles(android::base::Dirname(filename), /*context_fds=*/{}, /*only_read_checksums=*/true)) { *error_msg = @@ -269,9 +269,7 @@ std::unique_ptr<OatFileAssistant> OatFileAssistant::Create( return assistant; } -bool OatFileAssistant::UseFdToReadFiles() { - return zip_fd_ >= 0; -} +bool OatFileAssistant::UseFdToReadFiles() { return zip_fd_ >= 0; } bool OatFileAssistant::IsInBootClassPath() { // Note: We check the current boot class path, regardless of the ISA @@ -344,9 +342,7 @@ bool OatFileAssistant::GetDexOptNeeded(CompilerFilter::Filter target_compiler_fi return dexopt_needed != kNoDexOptNeeded; } -bool OatFileAssistant::IsUpToDate() { - return GetBestInfo().Status() == kOatUpToDate; -} +bool OatFileAssistant::IsUpToDate() { return GetBestInfo().Status() == kOatUpToDate; } std::unique_ptr<OatFile> OatFileAssistant::GetBestOatFile() { return GetBestInfo().ReleaseFileForUse(); @@ -400,7 +396,7 @@ std::string OatFileAssistant::GetStatusDump() { } std::vector<std::unique_ptr<const DexFile>> OatFileAssistant::LoadDexFiles( - const OatFile &oat_file, const char *dex_location) { + const OatFile& oat_file, const char* dex_location) { std::vector<std::unique_ptr<const DexFile>> dex_files; if (LoadDexFiles(oat_file, dex_location, &dex_files)) { return dex_files; @@ -409,14 +405,13 @@ std::vector<std::unique_ptr<const DexFile>> OatFileAssistant::LoadDexFiles( } } -bool OatFileAssistant::LoadDexFiles( - const OatFile &oat_file, - const std::string& dex_location, - std::vector<std::unique_ptr<const DexFile>>* out_dex_files) { +bool OatFileAssistant::LoadDexFiles(const OatFile& oat_file, + const std::string& dex_location, + std::vector<std::unique_ptr<const DexFile>>* out_dex_files) { // Load the main dex file. std::string error_msg; - const OatDexFile* oat_dex_file = oat_file.GetOatDexFile( - dex_location.c_str(), nullptr, &error_msg); + const OatDexFile* oat_dex_file = + oat_file.GetOatDexFile(dex_location.c_str(), nullptr, &error_msg); if (oat_dex_file == nullptr) { LOG(WARNING) << error_msg; return false; @@ -457,13 +452,9 @@ std::optional<bool> OatFileAssistant::HasDexFiles(std::string* error_msg) { return !checksums->empty(); } -OatFileAssistant::OatStatus OatFileAssistant::OdexFileStatus() { - return odex_.Status(); -} +OatFileAssistant::OatStatus OatFileAssistant::OdexFileStatus() { return odex_.Status(); } -OatFileAssistant::OatStatus OatFileAssistant::OatFileStatus() { - return oat_.Status(); -} +OatFileAssistant::OatStatus OatFileAssistant::OatFileStatus() { return oat_.Status(); } bool OatFileAssistant::DexChecksumUpToDate(const OatFile& file, std::string* error_msg) { if (!file.ContainsDexCode()) { @@ -483,9 +474,8 @@ bool OatFileAssistant::DexChecksumUpToDate(const OatFile& file, std::string* err uint32_t number_of_dex_files = file.GetOatHeader().GetDexFileCount(); if (required_dex_checksums->size() != number_of_dex_files) { - *error_msg = StringPrintf("expected %zu dex files but found %u", - required_dex_checksums->size(), - number_of_dex_files); + *error_msg = StringPrintf( + "expected %zu dex files but found %u", required_dex_checksums->size(), number_of_dex_files); return false; } @@ -500,8 +490,7 @@ bool OatFileAssistant::DexChecksumUpToDate(const OatFile& file, std::string* err uint32_t actual_checksum = oat_dex_file->GetDexFileLocationChecksum(); if (expected_checksum != actual_checksum) { VLOG(oat) << "Dex checksum does not match for dex: " << dex - << ". Expected: " << expected_checksum - << ", Actual: " << actual_checksum; + << ". Expected: " << expected_checksum << ", Actual: " << actual_checksum; return false; } } @@ -574,9 +563,8 @@ bool OatFileAssistant::AnonymousDexVdexLocation(const std::vector<const DexFile: uint32_t checksum = adler32(0L, Z_NULL, 0); for (const DexFile::Header* header : headers) { - checksum = adler32_combine(checksum, - header->checksum_, - header->file_size_ - DexFile::kNumNonChecksumBytes); + checksum = adler32_combine( + checksum, header->checksum_, header->file_size_ - DexFile::kNumNonChecksumBytes); } const std::string& data_dir = Runtime::Current()->GetProcessDataDirectory(); @@ -601,7 +589,7 @@ bool OatFileAssistant::IsAnonymousVdexBasename(const std::string& basename) { DCHECK(basename.find('/') == std::string::npos); // `basename` must have format: <kAnonymousDexPrefix><checksum><kVdexExtension> if (basename.size() < strlen(kAnonymousDexPrefix) + strlen(kVdexExtension) + 1 || - !android::base::StartsWith(basename.c_str(), kAnonymousDexPrefix) || + !android::base::StartsWith(basename, kAnonymousDexPrefix) || !android::base::EndsWith(basename, kVdexExtension)) { return false; } @@ -645,7 +633,7 @@ bool OatFileAssistant::DexLocationToOdexFilename(const std::string& location, *error_msg = "Dex location " + location + " has no directory."; return false; } - std::string dir = location.substr(0, pos+1); + std::string dir = location.substr(0, pos + 1); // Add the oat directory. dir += "oat"; @@ -653,7 +641,7 @@ bool OatFileAssistant::DexLocationToOdexFilename(const std::string& location, dir += "/" + std::string(GetInstructionSetString(isa)); // Get the base part of the file without the extension. - std::string file = location.substr(pos+1); + std::string file = location.substr(pos + 1); pos = file.rfind('.'); if (pos == std::string::npos) { *error_msg = "Dex location " + location + " has no extension."; @@ -706,11 +694,11 @@ bool OatFileAssistant::DexLocationToOatFilename(const std::string& location, bool dalvik_cache_exists = false; bool is_global_cache = false; GetDalvikCache(GetInstructionSetString(isa), - /*create_if_absent=*/ true, - &dalvik_cache, - &have_android_data, - &dalvik_cache_exists, - &is_global_cache); + /*create_if_absent=*/true, + &dalvik_cache, + &have_android_data, + &dalvik_cache_exists, + &is_global_cache); if (!dalvik_cache_exists) { *error_msg = "Dalvik cache directory does not exist"; return false; @@ -868,7 +856,7 @@ bool OatFileAssistant::ValidateBootClassPathChecksums(const OatFile& oat_file) { &error_msg); if (!result) { VLOG(oat) << "Failed to verify checksums of oat file " << oat_file.GetLocation() - << " error: " << error_msg; + << " error: " << error_msg; return false; } @@ -958,12 +946,9 @@ std::unique_ptr<gc::space::ImageSpace> OatFileAssistant::OpenImageSpace(const Oa OatFileAssistant::OatFileInfo::OatFileInfo(OatFileAssistant* oat_file_assistant, bool is_oat_location) - : oat_file_assistant_(oat_file_assistant), is_oat_location_(is_oat_location) -{} + : oat_file_assistant_(oat_file_assistant), is_oat_location_(is_oat_location) {} -bool OatFileAssistant::OatFileInfo::IsOatLocation() { - return is_oat_location_; -} +bool OatFileAssistant::OatFileInfo::IsOatLocation() { return is_oat_location_; } const std::string* OatFileAssistant::OatFileInfo::Filename() { return filename_provided_ ? &filename_ : nullptr; @@ -975,9 +960,11 @@ bool OatFileAssistant::OatFileInfo::IsUseable() { case kOatCannotOpen: case kOatDexOutOfDate: case kOatContextOutOfDate: - case kOatBootImageOutOfDate: return false; + case kOatBootImageOutOfDate: + return false; - case kOatUpToDate: return true; + case kOatUpToDate: + return true; } UNREACHABLE(); } @@ -991,8 +978,8 @@ OatFileAssistant::OatStatus OatFileAssistant::OatFileInfo::Status() { status_ = kOatCannotOpen; } else { status_ = oat_file_assistant_->GivenOatFileStatus(*file); - VLOG(oat) << file->GetLocation() << " is " << status_ - << " with filter " << file->GetCompilerFilter(); + VLOG(oat) << file->GetLocation() << " is " << status_ << " with filter " + << file->GetCompilerFilter(); } } return status_; @@ -1064,15 +1051,15 @@ const OatFile* OatFileAssistant::OatFileInfo::GetFile() { vdex = VdexFile::Open(vdex_fd_, s.st_size, filename_, - /*writable=*/ false, - /*low_4gb=*/ false, + /*writable=*/false, + /*low_4gb=*/false, &error_msg); } } } else { vdex = VdexFile::Open(filename_, - /*writable=*/ false, - /*low_4gb=*/ false, + /*writable=*/false, + /*low_4gb=*/false, &error_msg); } if (vdex == nullptr) { @@ -1100,38 +1087,36 @@ const OatFile* OatFileAssistant::OatFileInfo::GetFile() { } } else { if (executable && oat_file_assistant_->only_load_trusted_executable_) { - executable = LocationIsTrusted(filename_, /*trust_art_apex_data_files=*/ true); + executable = LocationIsTrusted(filename_, /*trust_art_apex_data_files=*/true); } VLOG(oat) << "Loading " << filename_ << " with executable: " << executable; if (use_fd_) { if (oat_fd_ >= 0 && vdex_fd_ >= 0) { ArrayRef<const std::string> dex_locations(&oat_file_assistant_->dex_location_, - /*size=*/ 1u); + /*size=*/1u); file_.reset(OatFile::Open(zip_fd_, vdex_fd_, oat_fd_, - filename_.c_str(), + filename_, executable, - /*low_4gb=*/ false, + /*low_4gb=*/false, dex_locations, - /*dex_fds=*/ ArrayRef<const int>(), - /*reservation=*/ nullptr, + /*dex_fds=*/ArrayRef<const int>(), + /*reservation=*/nullptr, &error_msg)); } } else { - file_.reset(OatFile::Open(/*zip_fd=*/ -1, - filename_.c_str(), - filename_.c_str(), + file_.reset(OatFile::Open(/*zip_fd=*/-1, + filename_, + filename_, executable, - /*low_4gb=*/ false, + /*low_4gb=*/false, oat_file_assistant_->dex_location_, &error_msg)); } } if (file_.get() == nullptr) { - VLOG(oat) << "OatFileAssistant test for existing oat file " - << filename_ - << ": " << error_msg; + VLOG(oat) << "OatFileAssistant test for existing oat file " << filename_ << ": " << error_msg; } else { VLOG(oat) << "Successfully loaded " << filename_ << " with executable: " << executable; } @@ -1195,13 +1180,12 @@ bool OatFileAssistant::ClassLoaderContextIsOkay(const OatFile& oat_file) const { return true; } - ClassLoaderContext::VerificationResult matches = context_->VerifyClassLoaderContextMatch( - oat_file.GetClassLoaderContext(), - /*verify_names=*/ true, - /*verify_checksums=*/ true); + ClassLoaderContext::VerificationResult matches = + context_->VerifyClassLoaderContextMatch(oat_file.GetClassLoaderContext(), + /*verify_names=*/true, + /*verify_checksums=*/true); if (matches == ClassLoaderContext::VerificationResult::kMismatch) { - VLOG(oat) << "ClassLoaderContext check failed. Context was " - << oat_file.GetClassLoaderContext() + VLOG(oat) << "ClassLoaderContext check failed. Context was " << oat_file.GetClassLoaderContext() << ". The expected context is " << context_->EncodeContextForOatFile(android::base::Dirname(dex_location_)); return false; @@ -1220,11 +1204,8 @@ void OatFileAssistant::OatFileInfo::Reset() { status_attempted_ = false; } -void OatFileAssistant::OatFileInfo::Reset(const std::string& filename, - bool use_fd, - int zip_fd, - int vdex_fd, - int oat_fd) { +void OatFileAssistant::OatFileInfo::Reset( + const std::string& filename, bool use_fd, int zip_fd, int vdex_fd, int oat_fd) { filename_provided_ = true; filename_ = filename; use_fd_ = use_fd; @@ -1265,19 +1246,15 @@ void OatFileAssistant::GetOptimizationStatus(const std::string& filename, /*only_load_trusted_executable=*/false, ofa_context); std::string out_odex_location; // unused - std::string out_odex_status; // unused + std::string out_odex_status; // unused oat_file_assistant.GetOptimizationStatus( - &out_odex_location, - out_compilation_filter, - out_compilation_reason, - &out_odex_status); + &out_odex_location, out_compilation_filter, out_compilation_reason, &out_odex_status); } -void OatFileAssistant::GetOptimizationStatus( - std::string* out_odex_location, - std::string* out_compilation_filter, - std::string* out_compilation_reason, - std::string* out_odex_status) { +void OatFileAssistant::GetOptimizationStatus(std::string* out_odex_location, + std::string* out_compilation_filter, + std::string* out_compilation_reason, + std::string* out_odex_status) { OatFileInfo& oat_file_info = GetBestInfo(); const OatFile* oat_file = GetBestInfo().GetFile(); diff --git a/runtime/oat_file_assistant_test.cc b/runtime/oat_file_assistant_test.cc index d34e6a7555..42350dc9f8 100644 --- a/runtime/oat_file_assistant_test.cc +++ b/runtime/oat_file_assistant_test.cc @@ -618,8 +618,8 @@ TEST_P(OatFileAssistantTest, GetDexOptNeededWithFd) { std::string vdex_location = GetScratchDir() + "/OatUpToDate.vdex"; Copy(GetDexSrc1(), dex_location); - GenerateOatForTest(dex_location.c_str(), - odex_location.c_str(), + GenerateOatForTest(dex_location, + odex_location, CompilerFilter::kSpeed, /* with_alternate_image= */ false); @@ -668,8 +668,8 @@ TEST_P(OatFileAssistantTest, GetDexOptNeededWithInvalidOdexFd) { std::string vdex_location = GetScratchDir() + "/OatUpToDate.vdex"; Copy(GetDexSrc1(), dex_location); - GenerateOatForTest(dex_location.c_str(), - odex_location.c_str(), + GenerateOatForTest(dex_location, + odex_location, CompilerFilter::kSpeed, /* with_alternate_image= */ false); @@ -716,8 +716,8 @@ TEST_P(OatFileAssistantTest, GetDexOptNeededWithInvalidVdexFd) { std::string odex_location = GetScratchDir() + "/OatUpToDate.odex"; Copy(GetDexSrc1(), dex_location); - GenerateOatForTest(dex_location.c_str(), - odex_location.c_str(), + GenerateOatForTest(dex_location, + odex_location, CompilerFilter::kSpeed, /* with_alternate_image= */ false); @@ -816,8 +816,8 @@ TEST_P(OatFileAssistantTest, EmptyVdexOdex) { std::string vdex_location = GetOdexDir() + "/EmptyVdexOdex.vdex"; Copy(GetDexSrc1(), dex_location); - ScratchFile vdex_file(vdex_location.c_str()); - ScratchFile odex_file(odex_location.c_str()); + ScratchFile vdex_file(vdex_location); + ScratchFile odex_file(odex_location); auto scoped_maybe_without_runtime = ScopedMaybeWithoutRuntime(); @@ -1163,7 +1163,7 @@ TEST_P(OatFileAssistantTest, OatContextOutOfDate) { auto scoped_maybe_without_runtime = ScopedMaybeWithoutRuntime(); VerifyOptimizationStatus( - dex_location.c_str(), context.get(), "verify", "vdex", "up-to-date", /*check_context=*/true); + dex_location, context.get(), "verify", "vdex", "up-to-date", /*check_context=*/true); } // Case: We have a DEX file and an ODEX file, but no OAT file. diff --git a/runtime/oat_file_test.cc b/runtime/oat_file_test.cc index f33235732a..80265f77f5 100644 --- a/runtime/oat_file_test.cc +++ b/runtime/oat_file_test.cc @@ -18,17 +18,15 @@ #include <string> -#include <gtest/gtest.h> - #include "common_runtime_test.h" #include "dexopt_test.h" +#include "gtest/gtest.h" #include "scoped_thread_state_change-inl.h" #include "vdex_file.h" namespace art { -class OatFileTest : public DexoptTest { -}; +class OatFileTest : public DexoptTest {}; TEST_F(OatFileTest, LoadOat) { std::string dex_location = GetScratchDir() + "/LoadOat.jar"; @@ -39,12 +37,13 @@ TEST_F(OatFileTest, LoadOat) { std::string oat_location; std::string error_msg; ASSERT_TRUE(OatFileAssistant::DexLocationToOatFilename( - dex_location, kRuntimeISA, &oat_location, &error_msg)) << error_msg; - std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1, - oat_location.c_str(), - oat_location.c_str(), - /*executable=*/ false, - /*low_4gb=*/ false, + dex_location, kRuntimeISA, &oat_location, &error_msg)) + << error_msg; + std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/-1, + oat_location, + oat_location, + /*executable=*/false, + /*low_4gb=*/false, dex_location, &error_msg)); ASSERT_TRUE(odex_file.get() != nullptr); @@ -62,15 +61,16 @@ TEST_F(OatFileTest, ChangingMultiDexUncompressed) { std::string oat_location; std::string error_msg; ASSERT_TRUE(OatFileAssistant::DexLocationToOatFilename( - dex_location, kRuntimeISA, &oat_location, &error_msg)) << error_msg; + dex_location, kRuntimeISA, &oat_location, &error_msg)) + << error_msg; // Ensure we can load that file. Just a precondition. { - std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1, - oat_location.c_str(), - oat_location.c_str(), - /*executable=*/ false, - /*low_4gb=*/ false, + std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/-1, + oat_location, + oat_location, + /*executable=*/false, + /*low_4gb=*/false, dex_location, &error_msg)); ASSERT_TRUE(odex_file != nullptr); @@ -81,11 +81,11 @@ TEST_F(OatFileTest, ChangingMultiDexUncompressed) { Copy(GetTestDexFileName("MainUncompressedAligned"), dex_location); // And try to load again. - std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1, + std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/-1, oat_location, oat_location, - /*executable=*/ false, - /*low_4gb=*/ false, + /*executable=*/false, + /*low_4gb=*/false, dex_location, &error_msg)); EXPECT_TRUE(odex_file == nullptr); diff --git a/runtime/sdk_checker.cc b/runtime/sdk_checker.cc index 9097dc62a2..95023829a5 100644 --- a/runtime/sdk_checker.cc +++ b/runtime/sdk_checker.cc @@ -25,8 +25,7 @@ namespace art { SdkChecker::SdkChecker() : enabled_(true) {} -SdkChecker* SdkChecker::Create( - const std::string& public_sdk, std::string* error_msg) { +SdkChecker* SdkChecker::Create(const std::string& public_sdk, std::string* error_msg) { std::vector<std::string> dex_file_paths; Split(public_sdk, ':', &dex_file_paths); @@ -63,9 +62,7 @@ bool SdkChecker::ShouldDenyAccess(ArtMethod* art_method) const { dex::TypeIndex return_type_idx; std::vector<dex::TypeIndex> param_type_idxs; if (!dex_file->CreateTypeList( - art_method->GetSignature().ToString().c_str(), - &return_type_idx, - ¶m_type_idxs)) { + art_method->GetSignature().ToString(), &return_type_idx, ¶m_type_idxs)) { continue; } const dex::ProtoId* proto_id = dex_file->FindProtoId(return_type_idx, param_type_idxs); @@ -98,8 +95,8 @@ bool SdkChecker::ShouldDenyAccess(ArtField* art_field) const { for (const std::unique_ptr<const DexFile>& dex_file : sdk_dex_files_) { std::string declaring_class; - const dex::TypeId* declaring_type_id = dex_file->FindTypeId( - art_field->GetDeclaringClass()->GetDescriptor(&declaring_class)); + const dex::TypeId* declaring_type_id = + dex_file->FindTypeId(art_field->GetDeclaringClass()->GetDescriptor(&declaring_class)); if (declaring_type_id == nullptr) { continue; } diff --git a/runtime/verifier/verifier_deps.cc b/runtime/verifier/verifier_deps.cc index 781cf7bb79..e9e488b2f4 100644 --- a/runtime/verifier/verifier_deps.cc +++ b/runtime/verifier/verifier_deps.cc @@ -52,11 +52,8 @@ VerifierDeps::VerifierDeps(const std::vector<const DexFile*>& dex_files, bool ou // Size of `other` must be equal to size of `to_update`. static inline void BitVectorOr(std::vector<bool>& to_update, const std::vector<bool>& other) { DCHECK_EQ(to_update.size(), other.size()); - std::transform(other.begin(), - other.end(), - to_update.begin(), - to_update.begin(), - std::logical_or<bool>()); + std::transform( + other.begin(), other.end(), to_update.begin(), to_update.begin(), std::logical_or<bool>()); } void VerifierDeps::MergeWith(std::unique_ptr<VerifierDeps> other, @@ -175,8 +172,8 @@ dex::StringIndex VerifierDeps::GetIdFromString(const DexFile& dex_file, const st } } -std::string VerifierDeps::GetStringFromId(const DexFile& dex_file, dex::StringIndex string_id) - const { +std::string VerifierDeps::GetStringFromId(const DexFile& dex_file, + dex::StringIndex string_id) const { uint32_t num_ids_in_dex = dex_file.NumStringIds(); if (string_id.index_ < num_ids_in_dex) { return std::string(dex_file.StringDataByIdx(string_id)); @@ -224,10 +221,7 @@ void VerifierDeps::AddAssignability(const DexFile& dex_file, // Only perform the optimization if both types are resolved which guarantees // that they linked successfully, as required at the top of this method. if (destination_component->IsResolved() && source_component->IsResolved()) { - AddAssignability(dex_file, - class_def, - destination_component, - source_component); + AddAssignability(dex_file, class_def, destination_component, source_component); return; } } @@ -337,25 +331,29 @@ void VerifierDeps::MaybeRecordAssignability(VerifierDeps* verifier_deps, namespace { -template<typename T> inline uint32_t Encode(T in); +template <typename T> +inline uint32_t Encode(T in); -template<> inline uint32_t Encode<dex::StringIndex>(dex::StringIndex in) { +template <> +inline uint32_t Encode<dex::StringIndex>(dex::StringIndex in) { return in.index_; } -template<typename T> inline T Decode(uint32_t in); +template <typename T> +inline T Decode(uint32_t in); -template<> inline dex::StringIndex Decode<dex::StringIndex>(uint32_t in) { +template <> +inline dex::StringIndex Decode<dex::StringIndex>(uint32_t in) { return dex::StringIndex(in); } -template<typename T1, typename T2> +template <typename T1, typename T2> static inline void EncodeTuple(std::vector<uint8_t>* out, const std::tuple<T1, T2>& t) { EncodeUnsignedLeb128(out, Encode(std::get<0>(t))); EncodeUnsignedLeb128(out, Encode(std::get<1>(t))); } -template<typename T1, typename T2> +template <typename T1, typename T2> static inline bool DecodeTuple(const uint8_t** in, const uint8_t* end, std::tuple<T1, T2>* t) { uint32_t v1, v2; if (UNLIKELY(!DecodeUnsignedLeb128Checked(in, end, &v1)) || @@ -366,14 +364,14 @@ static inline bool DecodeTuple(const uint8_t** in, const uint8_t* end, std::tupl return true; } -template<typename T1, typename T2, typename T3> +template <typename T1, typename T2, typename T3> static inline void EncodeTuple(std::vector<uint8_t>* out, const std::tuple<T1, T2, T3>& t) { EncodeUnsignedLeb128(out, Encode(std::get<0>(t))); EncodeUnsignedLeb128(out, Encode(std::get<1>(t))); EncodeUnsignedLeb128(out, Encode(std::get<2>(t))); } -template<typename T1, typename T2, typename T3> +template <typename T1, typename T2, typename T3> static inline bool DecodeTuple(const uint8_t** in, const uint8_t* end, std::tuple<T1, T2, T3>* t) { uint32_t v1, v2, v3; if (UNLIKELY(!DecodeUnsignedLeb128Checked(in, end, &v1)) || @@ -393,7 +391,7 @@ static void SetUint32InUint8Array(std::vector<uint8_t>* out, (reinterpret_cast<uint32_t*>(out->data() + uint8_offset))[uint32_offset] = value; } -template<typename T> +template <typename T> static void EncodeSetVector(std::vector<uint8_t>* out, const std::vector<std::set<T>>& vector, const std::vector<bool>& verified_classes) { @@ -417,7 +415,7 @@ static void EncodeSetVector(std::vector<uint8_t>* out, SetUint32InUint8Array(out, offsets_index, class_def_index, out->size()); } -template<bool kFillSet, typename T> +template <bool kFillSet, typename T> static bool DecodeSetVector(const uint8_t** cursor, const uint8_t* start, const uint8_t* end, @@ -468,7 +466,7 @@ static inline void EncodeStringVector(std::vector<uint8_t>* out, uint32_t offsets_index = out->size(); // Make room for offsets for each string, +1 for putting the number of // strings. - out->resize(out->size() + (strings.size() + 1 ) * sizeof(uint32_t)); + out->resize(out->size() + (strings.size() + 1) * sizeof(uint32_t)); (reinterpret_cast<uint32_t*>(out->data() + offsets_index))[0] = strings.size(); uint32_t string_index = 1; for (const std::string& str : strings) { @@ -483,7 +481,7 @@ static inline void EncodeStringVector(std::vector<uint8_t>* out, } } -template<bool kFillVector> +template <bool kFillVector> static inline bool DecodeStringVector(const uint8_t** cursor, const uint8_t* start, const uint8_t* end, @@ -498,8 +496,8 @@ static inline bool DecodeStringVector(const uint8_t** cursor, for (uint32_t i = 0; i < num_strings; ++i) { uint32_t string_offset = reinterpret_cast<const uint32_t*>(offsets)[i + 1]; const char* string_start = reinterpret_cast<const char*>(start + string_offset); - const char* string_end = reinterpret_cast<const char*>( - memchr(string_start, 0, end - start - string_offset)); + const char* string_end = + reinterpret_cast<const char*>(memchr(string_start, 0, end - start - string_offset)); if (UNLIKELY(string_end == nullptr)) { return false; } @@ -537,16 +535,14 @@ bool VerifierDeps::DecodeDexFileDeps(DexFileDeps& deps, const uint8_t* data_start, const uint8_t* data_end, size_t num_class_defs) { - return - DecodeSetVector</*kFillSet=*/ !kOnlyVerifiedClasses>( - cursor, - data_start, - data_end, - &deps.assignable_types_, - &deps.verified_classes_, - num_class_defs) && - DecodeStringVector</*kFillVector=*/ !kOnlyVerifiedClasses>( - cursor, data_start, data_end, &deps.strings_); + return DecodeSetVector</*kFillSet=*/!kOnlyVerifiedClasses>(cursor, + data_start, + data_end, + &deps.assignable_types_, + &deps.verified_classes_, + num_class_defs) && + DecodeStringVector</*kFillVector=*/!kOnlyVerifiedClasses>( + cursor, data_start, data_end, &deps.strings_); } bool VerifierDeps::ParseStoredData(const std::vector<const DexFile*>& dex_files, @@ -566,11 +562,8 @@ bool VerifierDeps::ParseStoredData(const std::vector<const DexFile*>& dex_files, // Fetch the offset of this dex file's verifier data. cursor = data_start + reinterpret_cast<const uint32_t*>(data_start)[dex_file_index++]; size_t num_class_defs = dex_file->NumClassDefs(); - if (UNLIKELY(!DecodeDexFileDeps</*kOnlyVerifiedClasses=*/ false>(*deps, - &cursor, - data_start, - data_end, - num_class_defs))) { + if (UNLIKELY(!DecodeDexFileDeps</*kOnlyVerifiedClasses=*/false>( + *deps, &cursor, data_start, data_end, num_class_defs))) { LOG(ERROR) << "Failed to parse dex file dependencies for " << dex_file->GetLocation(); return false; } @@ -582,7 +575,7 @@ bool VerifierDeps::ParseStoredData(const std::vector<const DexFile*>& dex_files, bool VerifierDeps::ParseVerifiedClasses( const std::vector<const DexFile*>& dex_files, ArrayRef<const uint8_t> data, - /*out*/std::vector<std::vector<bool>>* verified_classes_per_dex) { + /*out*/ std::vector<std::vector<bool>>* verified_classes_per_dex) { DCHECK(!data.empty()); DCHECK(!dex_files.empty()); DCHECK(verified_classes_per_dex->empty()); @@ -594,16 +587,13 @@ bool VerifierDeps::ParseVerifiedClasses( const uint8_t* cursor = data_start; uint32_t dex_file_index = 0; for (const DexFile* dex_file : dex_files) { - DexFileDeps deps(/*num_class_defs=*/ 0u); // Do not initialize vectors. + DexFileDeps deps(/*num_class_defs=*/0u); // Do not initialize vectors. // Fetch the offset of this dex file's verifier data. cursor = data_start + reinterpret_cast<const uint32_t*>(data_start)[dex_file_index++]; size_t num_class_defs = dex_file->NumClassDefs(); deps.verified_classes_.resize(num_class_defs); - if (UNLIKELY(!DecodeDexFileDeps</*kOnlyVerifiedClasses=*/ true>(deps, - &cursor, - data_start, - data_end, - num_class_defs))) { + if (UNLIKELY(!DecodeDexFileDeps</*kOnlyVerifiedClasses=*/true>( + deps, &cursor, data_start, data_end, num_class_defs))) { LOG(ERROR) << "Failed to parse dex file dependencies for " << dex_file->GetLocation(); return false; } @@ -640,8 +630,7 @@ bool VerifierDeps::Equals(const VerifierDeps& rhs) const { } bool VerifierDeps::DexFileDeps::Equals(const VerifierDeps::DexFileDeps& rhs) const { - return (strings_ == rhs.strings_) && - (assignable_types_ == rhs.assignable_types_) && + return (strings_ == rhs.strings_) && (assignable_types_ == rhs.assignable_types_) && (verified_classes_ == rhs.verified_classes_); } @@ -653,18 +642,12 @@ void VerifierDeps::Dump(VariableIndentationOutputStream* vios) const { for (const auto& dep : dex_deps_) { dex_deps.emplace_back(dep.first, dep.second.get()); } - std::sort( - dex_deps.begin(), - dex_deps.end(), - [](const DepsEntry& lhs, const DepsEntry& rhs) { - return lhs.first->GetLocation() < rhs.first->GetLocation(); - }); + std::sort(dex_deps.begin(), dex_deps.end(), [](const DepsEntry& lhs, const DepsEntry& rhs) { + return lhs.first->GetLocation() < rhs.first->GetLocation(); + }); for (const auto& dep : dex_deps) { const DexFile& dex_file = *dep.first; - vios->Stream() - << "Dependencies of " - << dex_file.GetLocation() - << ":\n"; + vios->Stream() << "Dependencies of " << dex_file.GetLocation() << ":\n"; ScopedIndentation indent(vios); @@ -673,24 +656,18 @@ void VerifierDeps::Dump(VariableIndentationOutputStream* vios) const { } for (size_t idx = 0; idx < dep.second->assignable_types_.size(); idx++) { - vios->Stream() - << "Dependencies of " - << dex_file.GetClassDescriptor(dex_file.GetClassDef(idx)) - << ":\n"; + vios->Stream() << "Dependencies of " << dex_file.GetClassDescriptor(dex_file.GetClassDef(idx)) + << ":\n"; for (const TypeAssignability& entry : dep.second->assignable_types_[idx]) { - vios->Stream() - << GetStringFromId(dex_file, entry.GetSource()) - << " must be assignable to " - << GetStringFromId(dex_file, entry.GetDestination()) - << "\n"; + vios->Stream() << GetStringFromId(dex_file, entry.GetSource()) << " must be assignable to " + << GetStringFromId(dex_file, entry.GetDestination()) << "\n"; } } for (size_t idx = 0; idx < dep.second->verified_classes_.size(); idx++) { if (!dep.second->verified_classes_[idx]) { - vios->Stream() - << dex_file.GetClassDescriptor(dex_file.GetClassDef(idx)) - << " will be verified at runtime\n"; + vios->Stream() << dex_file.GetClassDescriptor(dex_file.GetClassDef(idx)) + << " will be verified at runtime\n"; } } } @@ -738,10 +715,9 @@ bool VerifierDeps::VerifyAssignability(Handle<mirror::ClassLoader> class_loader, for (const auto& entry : vec) { const std::string& destination_desc = GetStringFromId(dex_file, entry.GetDestination()); destination.Assign( - FindClassAndClearException(class_linker, self, destination_desc.c_str(), class_loader)); + FindClassAndClearException(class_linker, self, destination_desc, class_loader)); const std::string& source_desc = GetStringFromId(dex_file, entry.GetSource()); - source.Assign( - FindClassAndClearException(class_linker, self, source_desc.c_str(), class_loader)); + source.Assign(FindClassAndClearException(class_linker, self, source_desc, class_loader)); if (destination == nullptr || source == nullptr) { // We currently don't use assignability information for unresolved @@ -771,17 +747,12 @@ void VerifierDeps::ClearData(const std::vector<const DexFile*>& dex_files) { } } - bool VerifierDeps::VerifyDexFile(Handle<mirror::ClassLoader> class_loader, const DexFile& dex_file, const DexFileDeps& deps, Thread* self, /* out */ std::string* error_msg) const { - return VerifyAssignability(class_loader, - dex_file, - deps.assignable_types_, - self, - error_msg); + return VerifyAssignability(class_loader, dex_file, deps.assignable_types_, self, error_msg); } } // namespace verifier diff --git a/tools/dexanalyze/dexanalyze.cc b/tools/dexanalyze/dexanalyze.cc index 0a3cd8c8a8..79602aacbc 100644 --- a/tools/dexanalyze/dexanalyze.cc +++ b/tools/dexanalyze/dexanalyze.cc @@ -203,7 +203,7 @@ class DexAnalyze { for (const std::string& filename : options.filenames_) { std::string content; // TODO: once added, use an API to android::base to read a std::vector<uint8_t>. - if (!android::base::ReadFileToString(filename.c_str(), &content)) { + if (!android::base::ReadFileToString(filename, &content)) { LOG(ERROR) << "ReadFileToString failed for " + filename << std::endl; return kExitCodeFailedToOpenFile; } diff --git a/tools/veridex/veridex.cc b/tools/veridex/veridex.cc index 2ef236d70e..d2a32e6db1 100644 --- a/tools/veridex/veridex.cc +++ b/tools/veridex/veridex.cc @@ -297,7 +297,7 @@ class Veridex { } // TODO: once added, use an api to android::base to read a std::vector<uint8_t>. - if (!android::base::ReadFileToString(filename.c_str(), &content)) { + if (!android::base::ReadFileToString(filename, &content)) { *error_msg = "ReadFileToString failed for " + filename; return false; } @@ -306,7 +306,7 @@ class Veridex { static constexpr bool kVerifyChecksum = true; static constexpr bool kRunDexFileVerifier = true; DexFileLoader dex_file_loader( - reinterpret_cast<const uint8_t*>(content.data()), content.size(), filename.c_str()); + reinterpret_cast<const uint8_t*>(content.data()), content.size(), filename); if (!dex_file_loader.Open( kRunDexFileVerifier, kVerifyChecksum, &error_code, error_msg, dex_files)) { if (error_code == DexFileLoaderErrorCode::kEntryNotFound) { |