1 /*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <gtest/gtest.h>
18
19 #include "android-base/logging.h"
20 #include "android-base/stringprintf.h"
21 #include "android-base/strings.h"
22 #include "base/globals.h"
23 #include "base/stl_util.h"
24 #include "class_linker.h"
25 #include "dex/utf.h"
26 #include "dexopt_test.h"
27 #include "intern_table-inl.h"
28 #include "noop_compiler_callbacks.h"
29 #include "oat/oat_file.h"
30
31 namespace art HIDDEN {
32 namespace gc {
33 namespace space {
34
35 class ImageSpaceTest : public CommonRuntimeTest {
36 protected:
SetUpRuntimeOptions(RuntimeOptions * options)37 void SetUpRuntimeOptions(RuntimeOptions* options) override {
38 // Disable relocation.
39 options->emplace_back("-Xnorelocate", nullptr);
40 }
41
GetFilenameBase(const std::string & full_path)42 std::string GetFilenameBase(const std::string& full_path) {
43 size_t slash_pos = full_path.rfind('/');
44 CHECK_NE(std::string::npos, slash_pos);
45 size_t dot_pos = full_path.rfind('.');
46 CHECK_NE(std::string::npos, dot_pos);
47 CHECK_GT(dot_pos, slash_pos + 1u);
48 return full_path.substr(slash_pos + 1u, dot_pos - (slash_pos + 1u));
49 }
50 };
51
TEST_F(ImageSpaceTest,StringDeduplication)52 TEST_F(ImageSpaceTest, StringDeduplication) {
53 const char* const kBaseNames[] = {"Extension1", "Extension2"};
54
55 ScratchDir scratch;
56 const std::string& scratch_dir = scratch.GetPath();
57 std::string image_dir = scratch_dir + GetInstructionSetString(kRuntimeISA);
58 int mkdir_result = mkdir(image_dir.c_str(), 0700);
59 ASSERT_EQ(0, mkdir_result);
60
61 // Prepare boot class path variables.
62 std::vector<std::string> bcp = GetLibCoreDexFileNames();
63 std::vector<std::string> bcp_locations = GetLibCoreDexLocations();
64 CHECK_EQ(bcp.size(), bcp_locations.size());
65 std::string base_bcp_string = android::base::Join(bcp, ':');
66 std::string base_bcp_locations_string = android::base::Join(bcp_locations, ':');
67 std::string base_image_location = GetImageLocation();
68
69 // Compile the two extensions independently.
70 std::vector<std::string> extension_image_locations;
71 for (const char* base_name : kBaseNames) {
72 std::string jar_name = GetTestDexFileName(base_name);
73 ArrayRef<const std::string> dex_files(&jar_name, /*size=*/1u);
74 ScratchFile profile_file;
75 GenerateBootProfile(dex_files, profile_file.GetFile());
76 std::vector<std::string> extra_args = {
77 "--profile-file=" + profile_file.GetFilename(),
78 "--runtime-arg",
79 ART_FORMAT("-Xbootclasspath:{}:{}", base_bcp_string, jar_name),
80 "--runtime-arg",
81 ART_FORMAT("-Xbootclasspath-locations:{}:{}", base_bcp_locations_string, jar_name),
82 "--boot-image=" + base_image_location,
83 };
84 std::string prefix = GetFilenameBase(base_image_location);
85 std::string error_msg;
86 bool success =
87 CompileBootImage(extra_args, ART_FORMAT("{}/{}", image_dir, prefix), dex_files, &error_msg);
88 ASSERT_TRUE(success) << error_msg;
89 bcp.push_back(jar_name);
90 bcp_locations.push_back(jar_name);
91 extension_image_locations.push_back(scratch_dir + prefix + '-' + GetFilenameBase(jar_name) +
92 ".art");
93 }
94
95 // Also compile the second extension as an app with app image.
96 const char* app_base_name = kBaseNames[std::size(kBaseNames) - 1u];
97 std::string app_jar_name = GetTestDexFileName(app_base_name);
98 std::string app_odex_name = scratch_dir + app_base_name + ".odex";
99 std::string app_image_name = scratch_dir + app_base_name + ".art";
100 {
101 ArrayRef<const std::string> dex_files(&app_jar_name, /*size=*/1u);
102 ScratchFile profile_file;
103 GenerateProfile(dex_files, profile_file.GetFile());
104 std::vector<std::string> argv;
105 std::string error_msg;
106 bool success = StartDex2OatCommandLine(&argv, &error_msg, /*use_runtime_bcp_and_image=*/false);
107 ASSERT_TRUE(success) << error_msg;
108 argv.insert(argv.end(),
109 {
110 "--profile-file=" + profile_file.GetFilename(),
111 "--runtime-arg",
112 "-Xbootclasspath:" + base_bcp_string,
113 "--runtime-arg",
114 "-Xbootclasspath-locations:" + base_bcp_locations_string,
115 "--boot-image=" + base_image_location,
116 "--dex-file=" + app_jar_name,
117 "--dex-location=" + app_jar_name,
118 "--oat-file=" + app_odex_name,
119 "--app-image-file=" + app_image_name,
120 "--initialize-app-image-classes=true",
121 });
122 success = RunDex2Oat(argv, &error_msg);
123 ASSERT_TRUE(success) << error_msg;
124 }
125
126 std::vector<std::string> full_image_locations;
127 std::vector<std::unique_ptr<gc::space::ImageSpace>> boot_image_spaces;
128 MemMap extra_reservation;
129 auto load_boot_image = [&]() REQUIRES_SHARED(Locks::mutator_lock_) {
130 boot_image_spaces.clear();
131 extra_reservation = MemMap::Invalid();
132 return ImageSpace::LoadBootImage(
133 bcp,
134 bcp_locations,
135 /*boot_class_path_files=*/{},
136 /*boot_class_path_image_files=*/{},
137 /*boot_class_path_vdex_files=*/{},
138 /*boot_class_path_oat_files=*/{},
139 full_image_locations,
140 kRuntimeISA,
141 /*relocate=*/false,
142 /*executable=*/true,
143 /*extra_reservation_size=*/0u,
144 /*allow_in_memory_compilation=*/false,
145 Runtime::GetApexVersions(ArrayRef<const std::string>(bcp_locations)),
146 &boot_image_spaces,
147 &extra_reservation);
148 };
149
150 const char test_string[] = "SharedBootImageExtensionTestString";
151 size_t test_string_length = std::size(test_string) - 1u; // Equals UTF-16 length.
152 uint32_t hash = InternTable::Utf8String::Hash(test_string_length, test_string);
153 InternTable::Utf8String utf8_test_string(test_string_length, test_string);
154 auto contains_test_string = [utf8_test_string,
155 hash](ImageSpace* space) REQUIRES_SHARED(Locks::mutator_lock_) {
156 const ImageHeader& image_header = space->GetImageHeader();
157 if (image_header.GetInternedStringsSection().Size() != 0u) {
158 const uint8_t* data = space->Begin() + image_header.GetInternedStringsSection().Offset();
159 size_t read_count;
160 InternTable::UnorderedSet temp_set(data, /*make_copy_of_data=*/false, &read_count);
161 return temp_set.FindWithHash(utf8_test_string, hash) != temp_set.end();
162 } else {
163 return false;
164 }
165 };
166
167 // Load extensions and test for the presence of the test string.
168 ScopedObjectAccess soa(Thread::Current());
169 ASSERT_EQ(2u, extension_image_locations.size());
170 full_image_locations = {
171 base_image_location, extension_image_locations[0], extension_image_locations[1]};
172 bool success = load_boot_image();
173 ASSERT_TRUE(success);
174 ASSERT_EQ(bcp.size(), boot_image_spaces.size());
175 EXPECT_TRUE(contains_test_string(boot_image_spaces[boot_image_spaces.size() - 2u].get()));
176 // The string in the second extension should be replaced and removed from interned string section.
177 EXPECT_FALSE(contains_test_string(boot_image_spaces[boot_image_spaces.size() - 1u].get()));
178
179 // Reload extensions in reverse order and test for the presence of the test string.
180 std::swap(bcp[bcp.size() - 2u], bcp[bcp.size() - 1u]);
181 std::swap(bcp_locations[bcp_locations.size() - 2u], bcp_locations[bcp_locations.size() - 1u]);
182 full_image_locations = {
183 base_image_location, extension_image_locations[1], extension_image_locations[0]};
184 success = load_boot_image();
185 ASSERT_TRUE(success);
186 ASSERT_EQ(bcp.size(), boot_image_spaces.size());
187 EXPECT_TRUE(contains_test_string(boot_image_spaces[boot_image_spaces.size() - 2u].get()));
188 // The string in the second extension should be replaced and removed from interned string section.
189 EXPECT_FALSE(contains_test_string(boot_image_spaces[boot_image_spaces.size() - 1u].get()));
190
191 // Reload the image without the second extension.
192 bcp.erase(bcp.end() - 2u);
193 bcp_locations.erase(bcp_locations.end() - 2u);
194 full_image_locations = {base_image_location, extension_image_locations[0]};
195 success = load_boot_image();
196 ASSERT_TRUE(success);
197 ASSERT_EQ(bcp.size(), boot_image_spaces.size());
198 ASSERT_TRUE(contains_test_string(boot_image_spaces[boot_image_spaces.size() - 1u].get()));
199
200 // Load the app odex file and app image.
201 std::string error_msg;
202 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/-1,
203 app_odex_name,
204 app_odex_name,
205 /*executable=*/false,
206 /*low_4gb=*/false,
207 app_jar_name,
208 &error_msg));
209 ASSERT_TRUE(odex_file != nullptr) << error_msg;
210 std::vector<ImageSpace*> non_owning_boot_image_spaces =
211 MakeNonOwningPointerVector(boot_image_spaces);
212 std::unique_ptr<ImageSpace> app_image_space;
213 {
214 ScopedThreadSuspension sts(soa.Self(), ThreadState::kNative);
215 app_image_space = ImageSpace::CreateFromAppImage(
216 app_image_name.c_str(),
217 odex_file.get(),
218 ArrayRef<ImageSpace* const>(non_owning_boot_image_spaces),
219 &error_msg);
220 }
221 ASSERT_TRUE(app_image_space != nullptr) << error_msg;
222
223 // The string in the app image should be replaced and removed from interned string section.
224 EXPECT_FALSE(contains_test_string(app_image_space.get()));
225 }
226
TEST_F(DexoptTest,ValidateOatFile)227 TEST_F(DexoptTest, ValidateOatFile) {
228 std::string dex1 = GetScratchDir() + "/Dex1.jar";
229 std::string multidex1 = GetScratchDir() + "/MultiDex1.jar";
230 std::string dex2 = GetScratchDir() + "/Dex2.jar";
231 std::string oat_location = GetScratchDir() + "/Oat.oat";
232
233 Copy(GetDexSrc1(), dex1);
234 Copy(GetMultiDexSrc1(), multidex1);
235 Copy(GetDexSrc2(), dex2);
236
237 std::string error_msg;
238 std::vector<std::string> args;
239 args.push_back("--dex-file=" + dex1);
240 args.push_back("--dex-file=" + multidex1);
241 args.push_back("--dex-file=" + dex2);
242 args.push_back("--oat-file=" + oat_location);
243 ASSERT_TRUE(Dex2Oat(args, &error_msg)) << error_msg;
244
245 std::unique_ptr<OatFile> oat(OatFile::Open(/*zip_fd=*/-1,
246 oat_location,
247 oat_location,
248 /*executable=*/false,
249 /*low_4gb=*/false,
250 &error_msg));
251 ASSERT_TRUE(oat != nullptr) << error_msg;
252
253 {
254 // Test opening the oat file also with explicit dex filenames.
255 std::vector<std::string> dex_filenames{dex1, multidex1, dex2};
256 std::unique_ptr<OatFile> oat2(OatFile::Open(/*zip_fd=*/-1,
257 oat_location,
258 oat_location,
259 /*executable=*/false,
260 /*low_4gb=*/false,
261 ArrayRef<const std::string>(dex_filenames),
262 /*dex_files=*/{},
263 /*reservation=*/nullptr,
264 &error_msg));
265 ASSERT_TRUE(oat2 != nullptr) << error_msg;
266 }
267
268 // Originally all the dex checksums should be up to date.
269 EXPECT_TRUE(ImageSpace::ValidateOatFile(*oat, &error_msg)) << error_msg;
270
271 // Invalidate the dex1 checksum.
272 Copy(GetDexSrc2(), dex1);
273 EXPECT_FALSE(ImageSpace::ValidateOatFile(*oat, &error_msg));
274
275 // Restore the dex1 checksum.
276 Copy(GetDexSrc1(), dex1);
277 EXPECT_TRUE(ImageSpace::ValidateOatFile(*oat, &error_msg)) << error_msg;
278
279 // Invalidate the non-main multidex checksum.
280 Copy(GetMultiDexSrc2(), multidex1);
281 EXPECT_FALSE(ImageSpace::ValidateOatFile(*oat, &error_msg));
282
283 // Restore the multidex checksum.
284 Copy(GetMultiDexSrc1(), multidex1);
285 EXPECT_TRUE(ImageSpace::ValidateOatFile(*oat, &error_msg)) << error_msg;
286
287 // Invalidate the dex2 checksum.
288 Copy(GetDexSrc1(), dex2);
289 EXPECT_FALSE(ImageSpace::ValidateOatFile(*oat, &error_msg));
290
291 // restore the dex2 checksum.
292 Copy(GetDexSrc2(), dex2);
293 EXPECT_TRUE(ImageSpace::ValidateOatFile(*oat, &error_msg)) << error_msg;
294
295 // Replace the multidex file with a non-multidex file.
296 Copy(GetDexSrc1(), multidex1);
297 EXPECT_FALSE(ImageSpace::ValidateOatFile(*oat, &error_msg));
298
299 // Restore the multidex file
300 Copy(GetMultiDexSrc1(), multidex1);
301 EXPECT_TRUE(ImageSpace::ValidateOatFile(*oat, &error_msg)) << error_msg;
302
303 // Replace dex1 with a multidex file.
304 Copy(GetMultiDexSrc1(), dex1);
305 EXPECT_FALSE(ImageSpace::ValidateOatFile(*oat, &error_msg));
306
307 // Restore the dex1 file.
308 Copy(GetDexSrc1(), dex1);
309 EXPECT_TRUE(ImageSpace::ValidateOatFile(*oat, &error_msg)) << error_msg;
310
311 // Remove the dex2 file.
312 EXPECT_EQ(0, unlink(dex2.c_str()));
313 EXPECT_FALSE(ImageSpace::ValidateOatFile(*oat, &error_msg));
314
315 // Restore the dex2 file.
316 Copy(GetDexSrc2(), dex2);
317 EXPECT_TRUE(ImageSpace::ValidateOatFile(*oat, &error_msg)) << error_msg;
318
319 // Remove the multidex file.
320 EXPECT_EQ(0, unlink(multidex1.c_str()));
321 EXPECT_FALSE(ImageSpace::ValidateOatFile(*oat, &error_msg));
322 }
323
324 template <bool kImage, bool kRelocate>
325 class ImageSpaceLoadingTest : public CommonRuntimeTest {
326 protected:
SetUpRuntimeOptions(RuntimeOptions * options)327 void SetUpRuntimeOptions(RuntimeOptions* options) override {
328 missing_image_base_ = std::make_unique<ScratchFile>();
329 std::string image_location = PrepareImageLocation();
330 options->emplace_back(android::base::StringPrintf("-Ximage:%s", image_location.c_str()),
331 nullptr);
332 options->emplace_back(kRelocate ? "-Xrelocate" : "-Xnorelocate", nullptr);
333 options->emplace_back("-Xallowinmemorycompilation", nullptr);
334
335 // We want to test the relocation behavior of ImageSpace. As such, don't pretend we're a
336 // compiler.
337 callbacks_.reset();
338
339 // Clear DEX2OATBOOTCLASSPATH environment variable used for boot image compilation.
340 // We don't want that environment variable to affect the behavior of this test.
341 CHECK(old_dex2oat_bcp_ == nullptr);
342 const char* old_dex2oat_bcp = getenv("DEX2OATBOOTCLASSPATH");
343 if (old_dex2oat_bcp != nullptr) {
344 old_dex2oat_bcp_.reset(strdup(old_dex2oat_bcp));
345 CHECK(old_dex2oat_bcp_ != nullptr);
346 unsetenv("DEX2OATBOOTCLASSPATH");
347 }
348 }
349
TearDown()350 void TearDown() override {
351 if (old_dex2oat_bcp_ != nullptr) {
352 int result = setenv("DEX2OATBOOTCLASSPATH", old_dex2oat_bcp_.get(), /* replace */ 0);
353 CHECK_EQ(result, 0);
354 old_dex2oat_bcp_.reset();
355 }
356 missing_image_base_.reset();
357 }
358
PrepareImageLocation()359 virtual std::string PrepareImageLocation() {
360 std::string image_location = GetCoreArtLocation();
361 if (!kImage) {
362 image_location = missing_image_base_->GetFilename() + ".art";
363 }
364 return image_location;
365 }
366
CheckImageSpaceAndOatFile(size_t space_count)367 void CheckImageSpaceAndOatFile(size_t space_count) {
368 const std::vector<ImageSpace*>& image_spaces =
369 Runtime::Current()->GetHeap()->GetBootImageSpaces();
370 ASSERT_EQ(image_spaces.size(), space_count);
371
372 for (size_t i = 0; i < space_count; i++) {
373 // This test does not support multi-image compilation.
374 ASSERT_NE(image_spaces[i]->GetImageHeader().GetImageReservationSize(), 0u);
375
376 const OatFile* oat_file = image_spaces[i]->GetOatFile();
377 ASSERT_TRUE(oat_file != nullptr);
378
379 // Compiled by JIT Zygote.
380 EXPECT_EQ(oat_file->GetCompilerFilter(), CompilerFilter::Filter::kVerify);
381 }
382 }
383
384 std::unique_ptr<ScratchFile> missing_image_base_;
385
386 private:
387 UniqueCPtr<const char[]> old_dex2oat_bcp_;
388 };
389
390 using ImageSpaceNoDex2oatTest = ImageSpaceLoadingTest</*kImage=*/true, /*kRelocate=*/true>;
TEST_F(ImageSpaceNoDex2oatTest,Test)391 TEST_F(ImageSpaceNoDex2oatTest, Test) {
392 EXPECT_FALSE(Runtime::Current()->GetHeap()->GetBootImageSpaces().empty());
393 }
394
395 using ImageSpaceNoRelocateNoDex2oatTest =
396 ImageSpaceLoadingTest</*kImage=*/true, /*kRelocate=*/false>;
TEST_F(ImageSpaceNoRelocateNoDex2oatTest,Test)397 TEST_F(ImageSpaceNoRelocateNoDex2oatTest, Test) {
398 EXPECT_FALSE(Runtime::Current()->GetHeap()->GetBootImageSpaces().empty());
399 }
400
401 using ImageSpaceNoImageNoProfileTest = ImageSpaceLoadingTest</*kImage=*/false, /*kRelocate=*/true>;
TEST_F(ImageSpaceNoImageNoProfileTest,Test)402 TEST_F(ImageSpaceNoImageNoProfileTest, Test) {
403 // Imageless mode.
404 EXPECT_TRUE(Runtime::Current()->GetHeap()->GetBootImageSpaces().empty());
405 }
406
407 class ImageSpaceLoadingSingleComponentWithProfilesTest
408 : public ImageSpaceLoadingTest</*kImage=*/false, /*kRelocate=*/true> {
409 protected:
PrepareImageLocation()410 std::string PrepareImageLocation() override {
411 std::string image_location = missing_image_base_->GetFilename() + ".art";
412 // Compiling the primary boot image into a single image is not allowed on host.
413 if (kIsTargetBuild) {
414 std::vector<std::string> dex_files(GetLibCoreDexFileNames());
415 profile1_ = std::make_unique<ScratchFile>();
416 GenerateBootProfile(ArrayRef<const std::string>(dex_files),
417 profile1_->GetFile(),
418 /*method_frequency=*/6,
419 /*type_frequency=*/6);
420 profile2_ = std::make_unique<ScratchFile>();
421 GenerateBootProfile(ArrayRef<const std::string>(dex_files),
422 profile2_->GetFile(),
423 /*method_frequency=*/8,
424 /*type_frequency=*/8);
425 image_location += "!" + profile1_->GetFilename() + "!" + profile2_->GetFilename();
426 }
427 // "/path/to/image.art!/path/to/profile1!/path/to/profile2"
428 return image_location;
429 }
430
431 private:
432 std::unique_ptr<ScratchFile> profile1_;
433 std::unique_ptr<ScratchFile> profile2_;
434 };
435
TEST_F(ImageSpaceLoadingSingleComponentWithProfilesTest,Test)436 TEST_F(ImageSpaceLoadingSingleComponentWithProfilesTest, Test) {
437 // Compiling the primary boot image into a single image is not allowed on host.
438 TEST_DISABLED_FOR_HOST();
439
440 CheckImageSpaceAndOatFile(/*space_count=*/1);
441 }
442
443 class ImageSpaceLoadingMultipleComponentsWithProfilesTest
444 : public ImageSpaceLoadingTest</*kImage=*/false, /*kRelocate=*/true> {
445 protected:
PrepareImageLocation()446 std::string PrepareImageLocation() override {
447 std::vector<std::string> dex_files(GetLibCoreDexFileNames());
448 CHECK_GE(dex_files.size(), 2);
449 std::string image_location_1 = missing_image_base_->GetFilename() + ".art";
450 std::string image_location_2 =
451 missing_image_base_->GetFilename() + "-" + Stem(dex_files[dex_files.size() - 1]) + ".art";
452 // Compiling the primary boot image into a single image is not allowed on host.
453 if (kIsTargetBuild) {
454 profile1_ = std::make_unique<ScratchFile>();
455 GenerateBootProfile(ArrayRef<const std::string>(dex_files).SubArray(
456 /*pos=*/0, /*length=*/dex_files.size() - 1),
457 profile1_->GetFile(),
458 /*method_frequency=*/6,
459 /*type_frequency=*/6);
460 image_location_1 += "!" + profile1_->GetFilename();
461 profile2_ = std::make_unique<ScratchFile>();
462 GenerateBootProfile(ArrayRef<const std::string>(dex_files).SubArray(
463 /*pos=*/dex_files.size() - 1, /*length=*/1),
464 profile2_->GetFile(),
465 /*method_frequency=*/8,
466 /*type_frequency=*/8);
467 image_location_2 += "!" + profile2_->GetFilename();
468 }
469 // "/path/to/image.art!/path/to/profile1:/path/to/image-lastdex.art!/path/to/profile2"
470 return image_location_1 + ":" + image_location_2;
471 }
472
Stem(std::string filename)473 std::string Stem(std::string filename) {
474 size_t last_slash = filename.rfind('/');
475 if (last_slash != std::string::npos) {
476 filename = filename.substr(last_slash + 1);
477 }
478 size_t last_dot = filename.rfind('.');
479 if (last_dot != std::string::npos) {
480 filename.resize(last_dot);
481 }
482 return filename;
483 }
484
485 private:
486 std::unique_ptr<ScratchFile> profile1_;
487 std::unique_ptr<ScratchFile> profile2_;
488 };
489
TEST_F(ImageSpaceLoadingMultipleComponentsWithProfilesTest,Test)490 TEST_F(ImageSpaceLoadingMultipleComponentsWithProfilesTest, Test) {
491 // Compiling the primary boot image into a single image is not allowed on host.
492 TEST_DISABLED_FOR_HOST();
493
494 CheckImageSpaceAndOatFile(/*space_count=*/1);
495 }
496
497 } // namespace space
498 } // namespace gc
499 } // namespace art
500