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 
23 #include "base/stl_util.h"
24 #include "class_linker.h"
25 #include "dexopt_test.h"
26 #include "dex/utf.h"
27 #include "intern_table-inl.h"
28 #include "noop_compiler_callbacks.h"
29 #include "oat_file.h"
30 
31 namespace art {
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, exclude core-icu4j and conscrypt
62   // which are not in the primary boot image.
63   std::vector<std::string> bcp = GetLibCoreDexFileNames();
64   std::vector<std::string> bcp_locations = GetLibCoreDexLocations();
65   CHECK_EQ(bcp.size(), bcp_locations.size());
66   ASSERT_NE(std::string::npos, bcp.back().find("conscrypt"));
67   bcp.pop_back();
68   bcp_locations.pop_back();
69   ASSERT_NE(std::string::npos, bcp.back().find("core-icu4j"));
70   bcp.pop_back();
71   bcp_locations.pop_back();
72   std::string base_bcp_string = android::base::Join(bcp, ':');
73   std::string base_bcp_locations_string = android::base::Join(bcp_locations, ':');
74   std::string base_image_location = GetImageLocation();
75 
76   // Compile the two extensions independently.
77   std::vector<std::string> extension_image_locations;
78   for (const char* base_name : kBaseNames) {
79     std::string jar_name = GetTestDexFileName(base_name);
80     ArrayRef<const std::string> dex_files(&jar_name, /*size=*/ 1u);
81     ScratchFile profile_file;
82     GenerateBootProfile(dex_files, profile_file.GetFile());
83     std::vector<std::string> extra_args = {
84         "--profile-file=" + profile_file.GetFilename(),
85         "--runtime-arg",
86         "-Xbootclasspath:" + base_bcp_string + ':' + jar_name,
87         "--runtime-arg",
88         "-Xbootclasspath-locations:" + base_bcp_locations_string + ':' + jar_name,
89         "--boot-image=" + base_image_location,
90     };
91     std::string prefix = GetFilenameBase(base_image_location);
92     std::string error_msg;
93     bool success = CompileBootImage(extra_args, image_dir + '/' + prefix, dex_files, &error_msg);
94     ASSERT_TRUE(success) << error_msg;
95     bcp.push_back(jar_name);
96     bcp_locations.push_back(jar_name);
97     extension_image_locations.push_back(
98         scratch_dir + prefix + '-' + GetFilenameBase(jar_name) + ".art");
99   }
100 
101   // Also compile the second extension as an app with app image.
102   const char* app_base_name = kBaseNames[std::size(kBaseNames) - 1u];
103   std::string app_jar_name = GetTestDexFileName(app_base_name);
104   std::string app_odex_name = scratch_dir + app_base_name + ".odex";
105   std::string app_image_name = scratch_dir + app_base_name + ".art";
106   {
107     ArrayRef<const std::string> dex_files(&app_jar_name, /*size=*/ 1u);
108     ScratchFile profile_file;
109     GenerateProfile(dex_files, profile_file.GetFile());
110     std::vector<std::string> argv;
111     std::string error_msg;
112     bool success = StartDex2OatCommandLine(&argv, &error_msg, /*use_runtime_bcp_and_image=*/ false);
113     ASSERT_TRUE(success) << error_msg;
114     argv.insert(argv.end(), {
115         "--profile-file=" + profile_file.GetFilename(),
116         "--runtime-arg",
117         "-Xbootclasspath:" + base_bcp_string,
118         "--runtime-arg",
119         "-Xbootclasspath-locations:" + base_bcp_locations_string,
120         "--boot-image=" + base_image_location,
121         "--dex-file=" + app_jar_name,
122         "--dex-location=" + app_jar_name,
123         "--oat-file=" + app_odex_name,
124         "--app-image-file=" + app_image_name,
125         "--initialize-app-image-classes=true",
126     });
127     success = RunDex2Oat(argv, &error_msg);
128     ASSERT_TRUE(success) << error_msg;
129   }
130 
131   std::string full_image_locations;
132   std::vector<std::unique_ptr<gc::space::ImageSpace>> boot_image_spaces;
133   MemMap extra_reservation;
134   auto load_boot_image = [&]() REQUIRES_SHARED(Locks::mutator_lock_) {
135     boot_image_spaces.clear();
136     extra_reservation = MemMap::Invalid();
137     return ImageSpace::LoadBootImage(bcp,
138                                      bcp_locations,
139                                      full_image_locations,
140                                      kRuntimeISA,
141                                      /*relocate=*/ false,
142                                      /*executable=*/ true,
143                                      /*extra_reservation_size=*/ 0u,
144                                      &boot_image_spaces,
145                                      &extra_reservation);
146   };
147 
148   const char test_string[] = "SharedBootImageExtensionTestString";
149   size_t test_string_length = std::size(test_string) - 1u;  // Equals UTF-16 length.
150   uint32_t hash = ComputeUtf16HashFromModifiedUtf8(test_string, test_string_length);
151   InternTable::Utf8String utf8_test_string(test_string_length, test_string, hash);
152   auto contains_test_string = [utf8_test_string](ImageSpace* space)
153       REQUIRES_SHARED(Locks::mutator_lock_) {
154     const ImageHeader& image_header = space->GetImageHeader();
155     if (image_header.GetInternedStringsSection().Size() != 0u) {
156       const uint8_t* data = space->Begin() + image_header.GetInternedStringsSection().Offset();
157       size_t read_count;
158       InternTable::UnorderedSet temp_set(data, /*make_copy_of_data=*/ false, &read_count);
159       return temp_set.find(utf8_test_string) != temp_set.end();
160     } else {
161       return false;
162     }
163   };
164 
165   // Load extensions and test for the presence of the test string.
166   ScopedObjectAccess soa(Thread::Current());
167   ASSERT_EQ(2u, extension_image_locations.size());
168   full_image_locations = base_image_location +
169                              ImageSpace::kComponentSeparator + extension_image_locations[0] +
170                              ImageSpace::kComponentSeparator + extension_image_locations[1];
171   bool success = load_boot_image();
172   ASSERT_TRUE(success);
173   ASSERT_EQ(bcp.size(), boot_image_spaces.size());
174   EXPECT_TRUE(contains_test_string(boot_image_spaces[boot_image_spaces.size() - 2u].get()));
175   // The string in the second extension should be replaced and removed from interned string section.
176   EXPECT_FALSE(contains_test_string(boot_image_spaces[boot_image_spaces.size() - 1u].get()));
177 
178   // Reload extensions in reverse order and test for the presence of the test string.
179   std::swap(bcp[bcp.size() - 2u], bcp[bcp.size() - 1u]);
180   std::swap(bcp_locations[bcp_locations.size() - 2u], bcp_locations[bcp_locations.size() - 1u]);
181   full_image_locations = base_image_location +
182                              ImageSpace::kComponentSeparator + extension_image_locations[1] +
183                              ImageSpace::kComponentSeparator + 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 =
195       base_image_location + ImageSpace::kComponentSeparator + extension_image_locations[0];
196   success = load_boot_image();
197   ASSERT_TRUE(success);
198   ASSERT_EQ(bcp.size(), boot_image_spaces.size());
199   ASSERT_TRUE(contains_test_string(boot_image_spaces[boot_image_spaces.size() - 1u].get()));
200 
201   // Load the app odex file and app image.
202   std::string error_msg;
203   std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
204                                                    app_odex_name.c_str(),
205                                                    app_odex_name.c_str(),
206                                                    /*executable=*/ false,
207                                                    /*low_4gb=*/ false,
208                                                    app_jar_name,
209                                                    &error_msg));
210   ASSERT_TRUE(odex_file != nullptr) << error_msg;
211   std::vector<ImageSpace*> non_owning_boot_image_spaces =
212       MakeNonOwningPointerVector(boot_image_spaces);
213   std::unique_ptr<ImageSpace> app_image_space = ImageSpace::CreateFromAppImage(
214       app_image_name.c_str(),
215       odex_file.get(),
216       ArrayRef<ImageSpace* const>(non_owning_boot_image_spaces),
217       &error_msg);
218   ASSERT_TRUE(app_image_space != nullptr) << error_msg;
219 
220   // The string in the app image should be replaced and removed from interned string section.
221   EXPECT_FALSE(contains_test_string(app_image_space.get()));
222 }
223 
TEST_F(DexoptTest,ValidateOatFile)224 TEST_F(DexoptTest, ValidateOatFile) {
225   std::string dex1 = GetScratchDir() + "/Dex1.jar";
226   std::string multidex1 = GetScratchDir() + "/MultiDex1.jar";
227   std::string dex2 = GetScratchDir() + "/Dex2.jar";
228   std::string oat_location = GetScratchDir() + "/Oat.oat";
229 
230   Copy(GetDexSrc1(), dex1);
231   Copy(GetMultiDexSrc1(), multidex1);
232   Copy(GetDexSrc2(), dex2);
233 
234   std::string error_msg;
235   std::vector<std::string> args;
236   args.push_back("--dex-file=" + dex1);
237   args.push_back("--dex-file=" + multidex1);
238   args.push_back("--dex-file=" + dex2);
239   args.push_back("--oat-file=" + oat_location);
240   ASSERT_TRUE(Dex2Oat(args, &error_msg)) << error_msg;
241 
242   std::unique_ptr<OatFile> oat(OatFile::Open(/*zip_fd=*/ -1,
243                                              oat_location.c_str(),
244                                              oat_location.c_str(),
245                                              /*executable=*/ false,
246                                              /*low_4gb=*/ false,
247                                              &error_msg));
248   ASSERT_TRUE(oat != nullptr) << error_msg;
249 
250   {
251     // Test opening the oat file also with explicit dex filenames.
252     std::vector<std::string> dex_filenames{ dex1, multidex1, dex2 };
253     std::unique_ptr<OatFile> oat2(OatFile::Open(/*zip_fd=*/ -1,
254                                                 oat_location.c_str(),
255                                                 oat_location.c_str(),
256                                                 /*executable=*/ false,
257                                                 /*low_4gb=*/ false,
258                                                 ArrayRef<const std::string>(dex_filenames),
259                                                 /*reservation=*/ nullptr,
260                                                 &error_msg));
261     ASSERT_TRUE(oat2 != nullptr) << error_msg;
262   }
263 
264   // Originally all the dex checksums should be up to date.
265   EXPECT_TRUE(ImageSpace::ValidateOatFile(*oat, &error_msg)) << error_msg;
266 
267   // Invalidate the dex1 checksum.
268   Copy(GetDexSrc2(), dex1);
269   EXPECT_FALSE(ImageSpace::ValidateOatFile(*oat, &error_msg));
270 
271   // Restore the dex1 checksum.
272   Copy(GetDexSrc1(), dex1);
273   EXPECT_TRUE(ImageSpace::ValidateOatFile(*oat, &error_msg)) << error_msg;
274 
275   // Invalidate the non-main multidex checksum.
276   Copy(GetMultiDexSrc2(), multidex1);
277   EXPECT_FALSE(ImageSpace::ValidateOatFile(*oat, &error_msg));
278 
279   // Restore the multidex checksum.
280   Copy(GetMultiDexSrc1(), multidex1);
281   EXPECT_TRUE(ImageSpace::ValidateOatFile(*oat, &error_msg)) << error_msg;
282 
283   // Invalidate the dex2 checksum.
284   Copy(GetDexSrc1(), dex2);
285   EXPECT_FALSE(ImageSpace::ValidateOatFile(*oat, &error_msg));
286 
287   // restore the dex2 checksum.
288   Copy(GetDexSrc2(), dex2);
289   EXPECT_TRUE(ImageSpace::ValidateOatFile(*oat, &error_msg)) << error_msg;
290 
291   // Replace the multidex file with a non-multidex file.
292   Copy(GetDexSrc1(), multidex1);
293   EXPECT_FALSE(ImageSpace::ValidateOatFile(*oat, &error_msg));
294 
295   // Restore the multidex file
296   Copy(GetMultiDexSrc1(), multidex1);
297   EXPECT_TRUE(ImageSpace::ValidateOatFile(*oat, &error_msg)) << error_msg;
298 
299   // Replace dex1 with a multidex file.
300   Copy(GetMultiDexSrc1(), dex1);
301   EXPECT_FALSE(ImageSpace::ValidateOatFile(*oat, &error_msg));
302 
303   // Restore the dex1 file.
304   Copy(GetDexSrc1(), dex1);
305   EXPECT_TRUE(ImageSpace::ValidateOatFile(*oat, &error_msg)) << error_msg;
306 
307   // Remove the dex2 file.
308   EXPECT_EQ(0, unlink(dex2.c_str()));
309   EXPECT_FALSE(ImageSpace::ValidateOatFile(*oat, &error_msg));
310 
311   // Restore the dex2 file.
312   Copy(GetDexSrc2(), dex2);
313   EXPECT_TRUE(ImageSpace::ValidateOatFile(*oat, &error_msg)) << error_msg;
314 
315   // Remove the multidex file.
316   EXPECT_EQ(0, unlink(multidex1.c_str()));
317   EXPECT_FALSE(ImageSpace::ValidateOatFile(*oat, &error_msg));
318 }
319 
TEST_F(DexoptTest,Checksums)320 TEST_F(DexoptTest, Checksums) {
321   Runtime* runtime = Runtime::Current();
322   ASSERT_TRUE(runtime != nullptr);
323   ASSERT_FALSE(runtime->GetHeap()->GetBootImageSpaces().empty());
324 
325   std::vector<std::string> bcp = runtime->GetBootClassPath();
326   std::vector<std::string> bcp_locations = runtime->GetBootClassPathLocations();
327   std::vector<const DexFile*> dex_files = runtime->GetClassLinker()->GetBootClassPath();
328 
329   std::string error_msg;
330   auto create_and_verify = [&]() {
331     std::string checksums = gc::space::ImageSpace::GetBootClassPathChecksums(
332         ArrayRef<gc::space::ImageSpace* const>(runtime->GetHeap()->GetBootImageSpaces()),
333         ArrayRef<const DexFile* const>(dex_files));
334     return gc::space::ImageSpace::VerifyBootClassPathChecksums(
335         checksums,
336         android::base::Join(bcp_locations, ':'),
337         runtime->GetImageLocation(),
338         ArrayRef<const std::string>(bcp_locations),
339         ArrayRef<const std::string>(bcp),
340         kRuntimeISA,
341         &error_msg);
342   };
343 
344   ASSERT_TRUE(create_and_verify()) << error_msg;
345 
346   std::vector<std::unique_ptr<const DexFile>> opened_dex_files;
347   for (const std::string& src : { GetDexSrc1(), GetDexSrc2() }) {
348     std::vector<std::unique_ptr<const DexFile>> new_dex_files;
349     const ArtDexFileLoader dex_file_loader;
350     ASSERT_TRUE(dex_file_loader.Open(src.c_str(),
351                                      src,
352                                      /*verify=*/ true,
353                                      /*verify_checksum=*/ false,
354                                      &error_msg,
355                                      &new_dex_files))
356         << error_msg;
357 
358     bcp.push_back(src);
359     bcp_locations.push_back(src);
360     for (std::unique_ptr<const DexFile>& df : new_dex_files) {
361       dex_files.push_back(df.get());
362       opened_dex_files.push_back(std::move(df));
363     }
364 
365     ASSERT_TRUE(create_and_verify()) << error_msg;
366   }
367 }
368 
369 template <bool kImage, bool kRelocate>
370 class ImageSpaceLoadingTest : public CommonRuntimeTest {
371  protected:
SetUpRuntimeOptions(RuntimeOptions * options)372   void SetUpRuntimeOptions(RuntimeOptions* options) override {
373     std::string image_location = GetCoreArtLocation();
374     if (!kImage) {
375       missing_image_base_ = std::make_unique<ScratchFile>();
376       image_location = missing_image_base_->GetFilename() + ".art";
377     }
378     options->emplace_back(android::base::StringPrintf("-Ximage:%s", image_location.c_str()),
379                           nullptr);
380     options->emplace_back(kRelocate ? "-Xrelocate" : "-Xnorelocate", nullptr);
381 
382     // We want to test the relocation behavior of ImageSpace. As such, don't pretend we're a
383     // compiler.
384     callbacks_.reset();
385 
386     // Clear DEX2OATBOOTCLASSPATH environment variable used for boot image compilation.
387     // We don't want that environment variable to affect the behavior of this test.
388     CHECK(old_dex2oat_bcp_ == nullptr);
389     const char* old_dex2oat_bcp = getenv("DEX2OATBOOTCLASSPATH");
390     if (old_dex2oat_bcp != nullptr) {
391       old_dex2oat_bcp_.reset(strdup(old_dex2oat_bcp));
392       CHECK(old_dex2oat_bcp_ != nullptr);
393       unsetenv("DEX2OATBOOTCLASSPATH");
394     }
395   }
396 
TearDown()397   void TearDown() override {
398     if (old_dex2oat_bcp_ != nullptr) {
399       int result = setenv("DEX2OATBOOTCLASSPATH", old_dex2oat_bcp_.get(), /* replace */ 0);
400       CHECK_EQ(result, 0);
401       old_dex2oat_bcp_.reset();
402     }
403     missing_image_base_.reset();
404   }
405 
406  private:
407   std::unique_ptr<ScratchFile> missing_image_base_;
408   UniqueCPtr<const char[]> old_dex2oat_bcp_;
409 };
410 
411 using ImageSpaceNoDex2oatTest = ImageSpaceLoadingTest<true, true>;
TEST_F(ImageSpaceNoDex2oatTest,Test)412 TEST_F(ImageSpaceNoDex2oatTest, Test) {
413   EXPECT_FALSE(Runtime::Current()->GetHeap()->GetBootImageSpaces().empty());
414 }
415 
416 using ImageSpaceNoRelocateNoDex2oatTest = ImageSpaceLoadingTest<true, false>;
TEST_F(ImageSpaceNoRelocateNoDex2oatTest,Test)417 TEST_F(ImageSpaceNoRelocateNoDex2oatTest, Test) {
418   EXPECT_FALSE(Runtime::Current()->GetHeap()->GetBootImageSpaces().empty());
419 }
420 
421 class NoAccessAndroidDataTest : public ImageSpaceLoadingTest<false, true> {
422  protected:
NoAccessAndroidDataTest()423   NoAccessAndroidDataTest() : quiet_(LogSeverity::FATAL) {}
424 
SetUpRuntimeOptions(RuntimeOptions * options)425   void SetUpRuntimeOptions(RuntimeOptions* options) override {
426     const char* android_data = getenv("ANDROID_DATA");
427     CHECK(android_data != nullptr);
428     old_android_data_ = android_data;
429     bad_android_data_ = old_android_data_ + "/no-android-data";
430     int result = setenv("ANDROID_DATA", bad_android_data_.c_str(), /* replace */ 1);
431     CHECK_EQ(result, 0) << strerror(errno);
432     result = mkdir(bad_android_data_.c_str(), /* mode */ 0700);
433     CHECK_EQ(result, 0) << strerror(errno);
434     // Create a regular file "dalvik_cache". GetDalvikCache() shall get EEXIST
435     // when trying to create a directory with the same name and creating a
436     // subdirectory for a particular architecture shall fail.
437     bad_dalvik_cache_ = bad_android_data_ + "/dalvik-cache";
438     int fd = creat(bad_dalvik_cache_.c_str(), /* mode */ 0);
439     CHECK_NE(fd, -1) << strerror(errno);
440     result = close(fd);
441     CHECK_EQ(result, 0) << strerror(errno);
442     ImageSpaceLoadingTest<false, true>::SetUpRuntimeOptions(options);
443   }
444 
TearDown()445   void TearDown() override {
446     ImageSpaceLoadingTest<false, true>::TearDown();
447     int result = unlink(bad_dalvik_cache_.c_str());
448     CHECK_EQ(result, 0) << strerror(errno);
449     result = rmdir(bad_android_data_.c_str());
450     CHECK_EQ(result, 0) << strerror(errno);
451     result = setenv("ANDROID_DATA", old_android_data_.c_str(), /* replace */ 1);
452     CHECK_EQ(result, 0) << strerror(errno);
453   }
454 
455  private:
456   ScopedLogSeverity quiet_;
457   std::string old_android_data_;
458   std::string bad_android_data_;
459   std::string bad_dalvik_cache_;
460 };
461 
TEST_F(NoAccessAndroidDataTest,Test)462 TEST_F(NoAccessAndroidDataTest, Test) {
463   EXPECT_TRUE(Runtime::Current()->GetHeap()->GetBootImageSpaces().empty());
464 }
465 
466 }  // namespace space
467 }  // namespace gc
468 }  // namespace art
469