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.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 implicit dex2oat invocations when loading image spaces.
39     options->emplace_back("-Xnoimage-dex2oat", nullptr);
40     // Disable relocation.
41     options->emplace_back("-Xnorelocate", nullptr);
42   }
43 
GetFilenameBase(const std::string & full_path)44   std::string GetFilenameBase(const std::string& full_path) {
45     size_t slash_pos = full_path.rfind('/');
46     CHECK_NE(std::string::npos, slash_pos);
47     size_t dot_pos = full_path.rfind('.');
48     CHECK_NE(std::string::npos, dot_pos);
49     CHECK_GT(dot_pos, slash_pos + 1u);
50     return full_path.substr(slash_pos + 1u, dot_pos - (slash_pos + 1u));
51   }
52 };
53 
TEST_F(ImageSpaceTest,StringDeduplication)54 TEST_F(ImageSpaceTest, StringDeduplication) {
55   const char* const kBaseNames[] = { "Extension1", "Extension2" };
56 
57   ScratchDir scratch;
58   const std::string& scratch_dir = scratch.GetPath();
59   std::string image_dir = scratch_dir + GetInstructionSetString(kRuntimeISA);
60   int mkdir_result = mkdir(image_dir.c_str(), 0700);
61   ASSERT_EQ(0, mkdir_result);
62 
63   // Prepare boot class path variables, exclude conscrypt which is not in the primary boot image.
64   std::vector<std::string> bcp = GetLibCoreDexFileNames();
65   std::vector<std::string> bcp_locations = GetLibCoreDexLocations();
66   CHECK_EQ(bcp.size(), bcp_locations.size());
67   ASSERT_NE(std::string::npos, bcp.back().find("conscrypt"));
68   bcp.pop_back();
69   bcp_locations.pop_back();
70   std::string base_bcp_string = android::base::Join(bcp, ':');
71   std::string base_bcp_locations_string = android::base::Join(bcp_locations, ':');
72   std::string base_image_location = GetImageLocation();
73 
74   // Compile the two extensions independently.
75   std::vector<std::string> extension_image_locations;
76   for (const char* base_name : kBaseNames) {
77     std::string jar_name = GetTestDexFileName(base_name);
78     ArrayRef<const std::string> dex_files(&jar_name, /*size=*/ 1u);
79     ScratchFile profile_file;
80     GenerateProfile(dex_files, profile_file.GetFile());
81     std::vector<std::string> extra_args = {
82         "--profile-file=" + profile_file.GetFilename(),
83         "--runtime-arg",
84         "-Xbootclasspath:" + base_bcp_string + ':' + jar_name,
85         "--runtime-arg",
86         "-Xbootclasspath-locations:" + base_bcp_locations_string + ':' + jar_name,
87         "--boot-image=" + base_image_location,
88     };
89     std::string prefix = GetFilenameBase(base_image_location);
90     std::string error_msg;
91     bool success = CompileBootImage(extra_args, image_dir + '/' + prefix, dex_files, &error_msg);
92     ASSERT_TRUE(success) << error_msg;
93     bcp.push_back(jar_name);
94     bcp_locations.push_back(jar_name);
95     extension_image_locations.push_back(
96         scratch_dir + prefix + '-' + GetFilenameBase(jar_name) + ".art");
97   }
98 
99   // Also compile the second extension as an app with app image.
100   const char* app_base_name = kBaseNames[std::size(kBaseNames) - 1u];
101   std::string app_jar_name = GetTestDexFileName(app_base_name);
102   std::string app_odex_name = scratch_dir + app_base_name + ".odex";
103   std::string app_image_name = scratch_dir + app_base_name + ".art";
104   {
105     ArrayRef<const std::string> dex_files(&app_jar_name, /*size=*/ 1u);
106     ScratchFile profile_file;
107     GenerateProfile(dex_files, profile_file.GetFile());
108     std::vector<std::string> argv;
109     std::string error_msg;
110     bool success = StartDex2OatCommandLine(&argv, &error_msg, /*use_runtime_bcp_and_image=*/ false);
111     ASSERT_TRUE(success) << error_msg;
112     argv.insert(argv.end(), {
113         "--profile-file=" + profile_file.GetFilename(),
114         "--runtime-arg",
115         "-Xbootclasspath:" + base_bcp_string,
116         "--runtime-arg",
117         "-Xbootclasspath-locations:" + base_bcp_locations_string,
118         "--boot-image=" + base_image_location,
119         "--dex-file=" + app_jar_name,
120         "--dex-location=" + app_jar_name,
121         "--oat-file=" + app_odex_name,
122         "--app-image-file=" + app_image_name,
123         "--initialize-app-image-classes=true",
124     });
125     success = RunDex2Oat(argv, &error_msg);
126     ASSERT_TRUE(success) << error_msg;
127   }
128 
129   std::string full_image_locations;
130   std::vector<std::unique_ptr<gc::space::ImageSpace>> boot_image_spaces;
131   MemMap extra_reservation;
132   auto load_boot_image = [&]() REQUIRES_SHARED(Locks::mutator_lock_) {
133     boot_image_spaces.clear();
134     extra_reservation = MemMap::Invalid();
135     return ImageSpace::LoadBootImage(bcp,
136                                      bcp_locations,
137                                      full_image_locations,
138                                      kRuntimeISA,
139                                      ImageSpaceLoadingOrder::kSystemFirst,
140                                      /*relocate=*/ false,
141                                      /*executable=*/ true,
142                                      /*is_zygote=*/ false,
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         gc::space::ImageSpaceLoadingOrder::kSystemFirst,
342         &error_msg);
343   };
344 
345   ASSERT_TRUE(create_and_verify()) << error_msg;
346 
347   std::vector<std::unique_ptr<const DexFile>> opened_dex_files;
348   for (const std::string& src : { GetDexSrc1(), GetDexSrc2() }) {
349     std::vector<std::unique_ptr<const DexFile>> new_dex_files;
350     const ArtDexFileLoader dex_file_loader;
351     ASSERT_TRUE(dex_file_loader.Open(src.c_str(),
352                                      src,
353                                      /*verify=*/ true,
354                                      /*verify_checksum=*/ false,
355                                      &error_msg,
356                                      &new_dex_files))
357         << error_msg;
358 
359     bcp.push_back(src);
360     bcp_locations.push_back(src);
361     for (std::unique_ptr<const DexFile>& df : new_dex_files) {
362       dex_files.push_back(df.get());
363       opened_dex_files.push_back(std::move(df));
364     }
365 
366     ASSERT_TRUE(create_and_verify()) << error_msg;
367   }
368 }
369 
370 template <bool kImage, bool kRelocate, bool kImageDex2oat>
371 class ImageSpaceLoadingTest : public CommonRuntimeTest {
372  protected:
SetUpRuntimeOptions(RuntimeOptions * options)373   void SetUpRuntimeOptions(RuntimeOptions* options) override {
374     std::string image_location = GetCoreArtLocation();
375     if (!kImage) {
376       missing_image_base_ = std::make_unique<ScratchFile>();
377       image_location = missing_image_base_->GetFilename() + ".art";
378     }
379     options->emplace_back(android::base::StringPrintf("-Ximage:%s", image_location.c_str()),
380                           nullptr);
381     options->emplace_back(kRelocate ? "-Xrelocate" : "-Xnorelocate", nullptr);
382     options->emplace_back(kImageDex2oat ? "-Ximage-dex2oat" : "-Xnoimage-dex2oat", nullptr);
383 
384     // We want to test the relocation behavior of ImageSpace. As such, don't pretend we're a
385     // compiler.
386     callbacks_.reset();
387 
388     // Clear DEX2OATBOOTCLASSPATH environment variable used for boot image compilation.
389     // We don't want that environment variable to affect the behavior of this test.
390     CHECK(old_dex2oat_bcp_ == nullptr);
391     const char* old_dex2oat_bcp = getenv("DEX2OATBOOTCLASSPATH");
392     if (old_dex2oat_bcp != nullptr) {
393       old_dex2oat_bcp_.reset(strdup(old_dex2oat_bcp));
394       CHECK(old_dex2oat_bcp_ != nullptr);
395       unsetenv("DEX2OATBOOTCLASSPATH");
396     }
397   }
398 
TearDown()399   void TearDown() override {
400     if (old_dex2oat_bcp_ != nullptr) {
401       int result = setenv("DEX2OATBOOTCLASSPATH", old_dex2oat_bcp_.get(), /* replace */ 0);
402       CHECK_EQ(result, 0);
403       old_dex2oat_bcp_.reset();
404     }
405     missing_image_base_.reset();
406   }
407 
408  private:
409   std::unique_ptr<ScratchFile> missing_image_base_;
410   UniqueCPtr<const char[]> old_dex2oat_bcp_;
411 };
412 
413 using ImageSpaceDex2oatTest = ImageSpaceLoadingTest<false, true, true>;
TEST_F(ImageSpaceDex2oatTest,Test)414 TEST_F(ImageSpaceDex2oatTest, Test) {
415   EXPECT_FALSE(Runtime::Current()->GetHeap()->GetBootImageSpaces().empty());
416 }
417 
418 using ImageSpaceNoDex2oatTest = ImageSpaceLoadingTest<true, true, false>;
TEST_F(ImageSpaceNoDex2oatTest,Test)419 TEST_F(ImageSpaceNoDex2oatTest, Test) {
420   EXPECT_FALSE(Runtime::Current()->GetHeap()->GetBootImageSpaces().empty());
421 }
422 
423 using ImageSpaceNoRelocateNoDex2oatTest = ImageSpaceLoadingTest<true, false, false>;
TEST_F(ImageSpaceNoRelocateNoDex2oatTest,Test)424 TEST_F(ImageSpaceNoRelocateNoDex2oatTest, Test) {
425   EXPECT_FALSE(Runtime::Current()->GetHeap()->GetBootImageSpaces().empty());
426 }
427 
428 class NoAccessAndroidDataTest : public ImageSpaceLoadingTest<false, true, true> {
429  protected:
NoAccessAndroidDataTest()430   NoAccessAndroidDataTest() : quiet_(LogSeverity::FATAL) {}
431 
SetUpRuntimeOptions(RuntimeOptions * options)432   void SetUpRuntimeOptions(RuntimeOptions* options) override {
433     const char* android_data = getenv("ANDROID_DATA");
434     CHECK(android_data != nullptr);
435     old_android_data_ = android_data;
436     bad_android_data_ = old_android_data_ + "/no-android-data";
437     int result = setenv("ANDROID_DATA", bad_android_data_.c_str(), /* replace */ 1);
438     CHECK_EQ(result, 0) << strerror(errno);
439     result = mkdir(bad_android_data_.c_str(), /* mode */ 0700);
440     CHECK_EQ(result, 0) << strerror(errno);
441     // Create a regular file "dalvik_cache". GetDalvikCache() shall get EEXIST
442     // when trying to create a directory with the same name and creating a
443     // subdirectory for a particular architecture shall fail.
444     bad_dalvik_cache_ = bad_android_data_ + "/dalvik-cache";
445     int fd = creat(bad_dalvik_cache_.c_str(), /* mode */ 0);
446     CHECK_NE(fd, -1) << strerror(errno);
447     result = close(fd);
448     CHECK_EQ(result, 0) << strerror(errno);
449     ImageSpaceLoadingTest<false, true, true>::SetUpRuntimeOptions(options);
450   }
451 
TearDown()452   void TearDown() override {
453     ImageSpaceLoadingTest<false, true, true>::TearDown();
454     int result = unlink(bad_dalvik_cache_.c_str());
455     CHECK_EQ(result, 0) << strerror(errno);
456     result = rmdir(bad_android_data_.c_str());
457     CHECK_EQ(result, 0) << strerror(errno);
458     result = setenv("ANDROID_DATA", old_android_data_.c_str(), /* replace */ 1);
459     CHECK_EQ(result, 0) << strerror(errno);
460   }
461 
462  private:
463   ScopedLogSeverity quiet_;
464   std::string old_android_data_;
465   std::string bad_android_data_;
466   std::string bad_dalvik_cache_;
467 };
468 
TEST_F(NoAccessAndroidDataTest,Test)469 TEST_F(NoAccessAndroidDataTest, Test) {
470   EXPECT_TRUE(Runtime::Current()->GetHeap()->GetBootImageSpaces().empty());
471 }
472 
473 }  // namespace space
474 }  // namespace gc
475 }  // namespace art
476