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 <fstream>
18 #include <regex>
19 #include <sstream>
20 #include <string>
21 #include <vector>
22 
23 #include <sys/mman.h>
24 #include <sys/wait.h>
25 #include <unistd.h>
26 
27 #include <android-base/logging.h>
28 #include <android-base/stringprintf.h>
29 #include <android-base/strings.h>
30 
31 #include "common_runtime_test.h"
32 
33 #include "base/array_ref.h"
34 #include "base/file_utils.h"
35 #include "base/macros.h"
36 #include "base/mem_map.h"
37 #include "base/unix_file/fd_file.h"
38 #include "base/utils.h"
39 #include "dex/art_dex_file_loader.h"
40 #include "dex/dex_file-inl.h"
41 #include "dex/dex_file_loader.h"
42 #include "dex/method_reference.h"
43 #include "dex/type_reference.h"
44 #include "gc/space/image_space.h"
45 #include "runtime.h"
46 #include "scoped_thread_state_change-inl.h"
47 #include "thread-current-inl.h"
48 
49 namespace art {
50 
51 // A suitable address for loading the core images.
52 constexpr uint32_t kBaseAddress = ART_BASE_ADDRESS;
53 
54 struct ImageSizes {
55   size_t art_size = 0;
56   size_t oat_size = 0;
57   size_t vdex_size = 0;
58 };
59 
operator <<(std::ostream & os,const ImageSizes & sizes)60 std::ostream& operator<<(std::ostream& os, const ImageSizes& sizes) {
61   os << "art=" << sizes.art_size << " oat=" << sizes.oat_size << " vdex=" << sizes.vdex_size;
62   return os;
63 }
64 
65 class Dex2oatImageTest : public CommonRuntimeTest {
66  public:
TearDown()67   void TearDown() override {}
68 
69  protected:
SetUpRuntimeOptions(RuntimeOptions * options)70   void SetUpRuntimeOptions(RuntimeOptions* options) override {
71     // Disable implicit dex2oat invocations when loading image spaces.
72     options->emplace_back("-Xnoimage-dex2oat", nullptr);
73   }
74 
WriteLine(File * file,std::string line)75   static void WriteLine(File* file, std::string line) {
76     line += '\n';
77     EXPECT_TRUE(file->WriteFully(&line[0], line.length()));
78   }
79 
AddRuntimeArg(std::vector<std::string> & args,const std::string & arg)80   void AddRuntimeArg(std::vector<std::string>& args, const std::string& arg) {
81     args.push_back("--runtime-arg");
82     args.push_back(arg);
83   }
84 
CompileImageAndGetSizes(ArrayRef<const std::string> dex_files,const std::vector<std::string> & extra_args)85   ImageSizes CompileImageAndGetSizes(ArrayRef<const std::string> dex_files,
86                                      const std::vector<std::string>& extra_args) {
87     ImageSizes ret;
88     ScratchDir scratch;
89     std::string filename_prefix = scratch.GetPath() + "boot";
90     std::vector<std::string> local_extra_args = extra_args;
91     local_extra_args.push_back(android::base::StringPrintf("--base=0x%08x", kBaseAddress));
92     std::string error_msg;
93     if (!CompileBootImage(local_extra_args, filename_prefix, dex_files, &error_msg)) {
94       LOG(ERROR) << "Failed to compile image " << filename_prefix << error_msg;
95     }
96     std::string art_file = filename_prefix + ".art";
97     std::string oat_file = filename_prefix + ".oat";
98     std::string vdex_file = filename_prefix + ".vdex";
99     int64_t art_size = OS::GetFileSizeBytes(art_file.c_str());
100     int64_t oat_size = OS::GetFileSizeBytes(oat_file.c_str());
101     int64_t vdex_size = OS::GetFileSizeBytes(vdex_file.c_str());
102     CHECK_GT(art_size, 0u) << art_file;
103     CHECK_GT(oat_size, 0u) << oat_file;
104     CHECK_GT(vdex_size, 0u) << vdex_file;
105     ret.art_size = art_size;
106     ret.oat_size = oat_size;
107     ret.vdex_size = vdex_size;
108     return ret;
109   }
110 
ReserveCoreImageAddressSpace(std::string * error_msg)111   MemMap ReserveCoreImageAddressSpace(/*out*/std::string* error_msg) {
112     constexpr size_t kReservationSize = 256 * MB;  // This should be enough for the compiled images.
113     // Extend to both directions for maximum relocation difference.
114     static_assert(ART_BASE_ADDRESS_MIN_DELTA < 0);
115     static_assert(ART_BASE_ADDRESS_MAX_DELTA > 0);
116     static_assert(IsAligned<kElfSegmentAlignment>(ART_BASE_ADDRESS_MIN_DELTA));
117     static_assert(IsAligned<kElfSegmentAlignment>(ART_BASE_ADDRESS_MAX_DELTA));
118     constexpr size_t kExtra = ART_BASE_ADDRESS_MAX_DELTA - ART_BASE_ADDRESS_MIN_DELTA;
119     uint32_t min_relocated_address = kBaseAddress + ART_BASE_ADDRESS_MIN_DELTA;
120     return MemMap::MapAnonymous("Reservation",
121                                 reinterpret_cast<uint8_t*>(min_relocated_address),
122                                 kReservationSize + kExtra,
123                                 PROT_NONE,
124                                 /*low_4gb=*/ true,
125                                 /*reuse=*/ false,
126                                 /*reservation=*/ nullptr,
127                                 error_msg);
128   }
129 
CopyDexFiles(const std::string & dir,std::vector<std::string> * dex_files)130   void CopyDexFiles(const std::string& dir, /*inout*/std::vector<std::string>* dex_files) {
131     CHECK(dir.ends_with("/"));
132     for (std::string& dex_file : *dex_files) {
133       size_t slash_pos = dex_file.rfind('/');
134       CHECK(OS::FileExists(dex_file.c_str())) << dex_file;
135       CHECK_NE(std::string::npos, slash_pos);
136       std::string new_location = dir + dex_file.substr(slash_pos + 1u);
137       std::ifstream src_stream(dex_file, std::ios::binary);
138       std::ofstream dst_stream(new_location, std::ios::binary);
139       dst_stream << src_stream.rdbuf();
140       dex_file = new_location;
141     }
142   }
143 
CompareFiles(const std::string & filename1,const std::string & filename2)144   bool CompareFiles(const std::string& filename1, const std::string& filename2) {
145     std::unique_ptr<File> file1(OS::OpenFileForReading(filename1.c_str()));
146     std::unique_ptr<File> file2(OS::OpenFileForReading(filename2.c_str()));
147     // Did we open the files?
148     if (file1 == nullptr || file2 == nullptr) {
149       return false;
150     }
151     // Are they non-empty and the same length?
152     if (file1->GetLength() <= 0 || file2->GetLength() != file1->GetLength()) {
153       return false;
154     }
155     return file1->Compare(file2.get()) == 0;
156   }
157 
AddAndroidRootToImageCompilerOptions()158   void AddAndroidRootToImageCompilerOptions() {
159     const char* android_root = getenv("ANDROID_ROOT");
160     CHECK(android_root != nullptr);
161     Runtime::Current()->image_compiler_options_.push_back(
162         "--android-root=" + std::string(android_root));
163   }
164 
EnableImageDex2Oat()165   void EnableImageDex2Oat() {
166     Runtime::Current()->image_dex2oat_enabled_ = true;
167   }
168 
DisableImageDex2Oat()169   void DisableImageDex2Oat() {
170     Runtime::Current()->image_dex2oat_enabled_ = false;
171   }
172 };
173 
TEST_F(Dex2oatImageTest,TestModesAndFilters)174 TEST_F(Dex2oatImageTest, TestModesAndFilters) {
175   // This test crashes on the gtest-heap-poisoning configuration
176   // (AddressSanitizer + CMS/RosAlloc + heap-poisoning); see b/111061592.
177   // Temporarily disable this test on this configuration to keep
178   // our automated build/testing green while we work on a fix.
179   TEST_DISABLED_FOR_MEMORY_TOOL_WITH_HEAP_POISONING_WITHOUT_READ_BARRIERS();
180   if (kIsTargetBuild) {
181     // This test is too slow for target builds.
182     return;
183   }
184   // Compile only a subset of the libcore dex files to make this test shorter.
185   std::vector<std::string> libcore_dex_files = GetLibCoreDexFileNames();
186   // The primary image must contain at least core-oj and core-libart to initialize the runtime.
187   ASSERT_NE(std::string::npos, libcore_dex_files[0].find("core-oj"));
188   ASSERT_NE(std::string::npos, libcore_dex_files[1].find("core-libart"));
189   ArrayRef<const std::string> dex_files =
190       ArrayRef<const std::string>(libcore_dex_files).SubArray(/*pos=*/ 0u, /*length=*/ 2u);
191 
192   ImageSizes base_sizes = CompileImageAndGetSizes(dex_files, {});
193   ImageSizes everything_sizes;
194   ImageSizes filter_sizes;
195   std::cout << "Base compile sizes " << base_sizes << std::endl;
196   // Compile all methods and classes
197   std::vector<std::string> libcore_dexes = GetLibCoreDexFileNames();
198   ArrayRef<const std::string> libcore_dexes_array(libcore_dexes);
199   {
200     ScratchFile profile_file;
201     GenerateBootProfile(libcore_dexes_array,
202                         profile_file.GetFile(),
203                         /*method_frequency=*/ 1u,
204                         /*type_frequency=*/ 1u);
205     everything_sizes = CompileImageAndGetSizes(
206         dex_files,
207         {"--profile-file=" + profile_file.GetFilename(),
208          "--compiler-filter=speed-profile"});
209     profile_file.Close();
210     std::cout << "All methods and classes sizes " << everything_sizes << std::endl;
211     // Putting all classes as image classes should increase art size
212     EXPECT_GE(everything_sizes.art_size, base_sizes.art_size);
213     // Check that dex is the same size.
214     EXPECT_EQ(everything_sizes.vdex_size, base_sizes.vdex_size);
215   }
216   static size_t kMethodFrequency = 3;
217   static size_t kTypeFrequency = 4;
218   // Test compiling fewer methods and classes.
219   {
220     ScratchFile profile_file;
221     GenerateBootProfile(libcore_dexes_array,
222                         profile_file.GetFile(),
223                         kMethodFrequency,
224                         kTypeFrequency);
225     filter_sizes = CompileImageAndGetSizes(
226         dex_files,
227         {"--profile-file=" + profile_file.GetFilename(),
228          "--compiler-filter=speed-profile"});
229     profile_file.Close();
230     std::cout << "Fewer methods and classes sizes " << filter_sizes << std::endl;
231     EXPECT_LE(filter_sizes.art_size, everything_sizes.art_size);
232     EXPECT_LE(filter_sizes.oat_size, everything_sizes.oat_size);
233     EXPECT_LE(filter_sizes.vdex_size, everything_sizes.vdex_size);
234   }
235   // Test dirty image objects.
236   {
237     ScratchFile classes;
238     VisitDexes(libcore_dexes_array,
239                VoidFunctor(),
240                [&](TypeReference ref) {
241       WriteLine(classes.GetFile(), ref.dex_file->PrettyType(ref.TypeIndex()));
242     }, /*method_frequency=*/ 1u, /*class_frequency=*/ 1u);
243     ImageSizes image_classes_sizes = CompileImageAndGetSizes(
244         dex_files,
245         {"--dirty-image-objects=" + classes.GetFilename()});
246     classes.Close();
247     std::cout << "Dirty image object sizes " << image_classes_sizes << std::endl;
248   }
249 }
250 
TEST_F(Dex2oatImageTest,TestExtension)251 TEST_F(Dex2oatImageTest, TestExtension) {
252   std::string error_msg;
253   MemMap reservation = ReserveCoreImageAddressSpace(&error_msg);
254   ASSERT_TRUE(reservation.IsValid()) << error_msg;
255 
256   ScratchDir scratch;
257   const std::string& scratch_dir = scratch.GetPath();
258   std::string image_dir = scratch_dir + GetInstructionSetString(kRuntimeISA);
259   int mkdir_result = mkdir(image_dir.c_str(), 0700);
260   ASSERT_EQ(0, mkdir_result);
261   std::string filename_prefix = image_dir + "/boot";
262 
263   // Copy the libcore dex files to a custom dir inside `scratch_dir` so that we do not
264   // accidentally load pre-compiled core images from their original directory based on BCP paths.
265   std::string jar_dir = scratch_dir + "jars";
266   mkdir_result = mkdir(jar_dir.c_str(), 0700);
267   ASSERT_EQ(0, mkdir_result);
268   jar_dir += '/';
269   std::vector<std::string> libcore_dex_files = GetLibCoreDexFileNames();
270   CopyDexFiles(jar_dir, &libcore_dex_files);
271 
272   ArrayRef<const std::string> full_bcp(libcore_dex_files);
273   size_t total_dex_files = full_bcp.size();
274   ASSERT_GE(total_dex_files, 4u);  // 2 for "head", 1 for "tail", at least one for "mid", see below.
275 
276   // The primary image must contain at least core-oj and core-libart to initialize the runtime.
277   ASSERT_NE(std::string::npos, full_bcp[0].find("core-oj"));
278   ASSERT_NE(std::string::npos, full_bcp[1].find("core-libart"));
279   ArrayRef<const std::string> head_dex_files = full_bcp.SubArray(/*pos=*/ 0u, /*length=*/ 2u);
280   // Middle part is everything else except for conscrypt.
281   ASSERT_NE(std::string::npos, full_bcp[full_bcp.size() - 1u].find("conscrypt"));
282   ArrayRef<const std::string> mid_bcp =
283       full_bcp.SubArray(/*pos=*/ 0u, /*length=*/ total_dex_files - 1u);
284   ArrayRef<const std::string> mid_dex_files = mid_bcp.SubArray(/*pos=*/ 2u);
285   // Tail is just the conscrypt.
286   ArrayRef<const std::string> tail_dex_files =
287       full_bcp.SubArray(/*pos=*/ total_dex_files - 1u, /*length=*/ 1u);
288 
289   // Prepare the "head", "mid" and "tail" names and locations.
290   std::string base_name = "boot.art";
291   std::string base_location = scratch_dir + base_name;
292   std::vector<std::string> expanded_mid = gc::space::ImageSpace::ExpandMultiImageLocations(
293       mid_dex_files.SubArray(/*pos=*/ 0u, /*length=*/ 1u),
294       base_location,
295       /*boot_image_extension=*/ true);
296   CHECK_EQ(1u, expanded_mid.size());
297   std::string mid_location = expanded_mid[0];
298   size_t mid_slash_pos = mid_location.rfind('/');
299   ASSERT_NE(std::string::npos, mid_slash_pos);
300   std::string mid_name = mid_location.substr(mid_slash_pos + 1u);
301   CHECK_EQ(1u, tail_dex_files.size());
302   std::vector<std::string> expanded_tail = gc::space::ImageSpace::ExpandMultiImageLocations(
303       tail_dex_files, base_location, /*boot_image_extension=*/ true);
304   CHECK_EQ(1u, expanded_tail.size());
305   std::string tail_location = expanded_tail[0];
306   size_t tail_slash_pos = tail_location.rfind('/');
307   ASSERT_NE(std::string::npos, tail_slash_pos);
308   std::string tail_name = tail_location.substr(tail_slash_pos + 1u);
309 
310   // Create profiles.
311   ScratchFile head_profile_file;
312   GenerateBootProfile(head_dex_files,
313                       head_profile_file.GetFile(),
314                       /*method_frequency=*/ 1u,
315                       /*type_frequency=*/ 1u);
316   const std::string& head_profile_filename = head_profile_file.GetFilename();
317   ScratchFile mid_profile_file;
318   GenerateBootProfile(mid_dex_files,
319                       mid_profile_file.GetFile(),
320                       /*method_frequency=*/ 5u,
321                       /*type_frequency=*/ 4u);
322   const std::string& mid_profile_filename = mid_profile_file.GetFilename();
323   ScratchFile tail_profile_file;
324   GenerateBootProfile(tail_dex_files,
325                       tail_profile_file.GetFile(),
326                       /*method_frequency=*/ 5u,
327                       /*type_frequency=*/ 4u);
328   const std::string& tail_profile_filename = tail_profile_file.GetFilename();
329 
330   // Compile the "head", i.e. the primary boot image.
331   std::vector<std::string> extra_args;
332   extra_args.push_back("--profile-file=" + head_profile_filename);
333   extra_args.push_back(android::base::StringPrintf("--base=0x%08x", kBaseAddress));
334   bool head_ok = CompileBootImage(extra_args, filename_prefix, head_dex_files, &error_msg);
335   ASSERT_TRUE(head_ok) << error_msg;
336 
337   // Compile the "mid", i.e. the first extension.
338   std::string mid_bcp_string = android::base::Join(mid_bcp, ':');
339   extra_args.clear();
340   extra_args.push_back("--profile-file=" + mid_profile_filename);
341   AddRuntimeArg(extra_args, "-Xbootclasspath:" + mid_bcp_string);
342   AddRuntimeArg(extra_args, "-Xbootclasspath-locations:" + mid_bcp_string);
343   extra_args.push_back("--boot-image=" + base_location);
344   bool mid_ok = CompileBootImage(extra_args, filename_prefix, mid_dex_files, &error_msg);
345   ASSERT_TRUE(mid_ok) << error_msg;
346 
347   // Try to compile the "tail" without specifying the "mid" extension. This shall fail.
348   extra_args.clear();
349   extra_args.push_back("--profile-file=" + tail_profile_filename);
350   std::string full_bcp_string = android::base::Join(full_bcp, ':');
351   AddRuntimeArg(extra_args, "-Xbootclasspath:" + full_bcp_string);
352   AddRuntimeArg(extra_args, "-Xbootclasspath-locations:" + full_bcp_string);
353   extra_args.push_back("--boot-image=" + base_location);
354   bool tail_ok = CompileBootImage(extra_args, filename_prefix, tail_dex_files, &error_msg);
355   ASSERT_FALSE(tail_ok) << error_msg;
356 
357   // Now compile the tail against both "head" and "mid".
358   CHECK(extra_args.back().starts_with("--boot-image="));
359   extra_args.back() = "--boot-image=" + base_location + ':' + mid_location;
360   tail_ok = CompileBootImage(extra_args, filename_prefix, tail_dex_files, &error_msg);
361   ASSERT_TRUE(tail_ok) << error_msg;
362 
363   // Prepare directory for the single-image test that squashes the "mid" and "tail".
364   std::string single_dir = scratch_dir + "single";
365   mkdir_result = mkdir(single_dir.c_str(), 0700);
366   ASSERT_EQ(0, mkdir_result);
367   single_dir += '/';
368   std::string single_image_dir = single_dir + GetInstructionSetString(kRuntimeISA);
369   mkdir_result = mkdir(single_image_dir.c_str(), 0700);
370   ASSERT_EQ(0, mkdir_result);
371   std::string single_filename_prefix = single_image_dir + "/boot";
372 
373   // The dex files for the single-image are everything not in the "head".
374   ArrayRef<const std::string> single_dex_files = full_bcp.SubArray(/*pos=*/ head_dex_files.size());
375 
376   // Create a smaller profile for the single-image test that squashes the "mid" and "tail".
377   ScratchFile single_profile_file;
378   GenerateBootProfile(single_dex_files,
379                       single_profile_file.GetFile(),
380                       /*method_frequency=*/ 5u,
381                       /*type_frequency=*/ 4u);
382   const std::string& single_profile_filename = single_profile_file.GetFilename();
383 
384   // Prepare the single image name and location.
385   CHECK_GE(single_dex_files.size(), 2u);
386   std::string single_base_location = single_dir + base_name;
387   std::vector<std::string> expanded_single = gc::space::ImageSpace::ExpandMultiImageLocations(
388       single_dex_files.SubArray(/*pos=*/ 0u, /*length=*/ 1u),
389       single_base_location,
390       /*boot_image_extension=*/ true);
391   CHECK_EQ(1u, expanded_single.size());
392   std::string single_location = expanded_single[0];
393   size_t single_slash_pos = single_location.rfind('/');
394   ASSERT_NE(std::string::npos, single_slash_pos);
395   std::string single_name = single_location.substr(single_slash_pos + 1u);
396   CHECK_EQ(single_name, mid_name);
397 
398   // Compile the single-image against the primary boot image.
399   extra_args.clear();
400   extra_args.push_back("--profile-file=" + single_profile_filename);
401   AddRuntimeArg(extra_args, "-Xbootclasspath:" + full_bcp_string);
402   AddRuntimeArg(extra_args, "-Xbootclasspath-locations:" + full_bcp_string);
403   extra_args.push_back("--boot-image=" + base_location);
404   extra_args.push_back("--single-image");
405   extra_args.push_back("--avoid-storing-invocation");  // For comparison below.
406   error_msg.clear();
407   bool single_ok =
408       CompileBootImage(extra_args, single_filename_prefix, single_dex_files, &error_msg);
409   ASSERT_TRUE(single_ok) << error_msg;
410 
411   reservation = MemMap::Invalid();  // Free the reserved memory for loading images.
412 
413   // Try to load the boot image with different image locations.
414   std::vector<std::string> boot_class_path = libcore_dex_files;
415   std::vector<std::unique_ptr<gc::space::ImageSpace>> boot_image_spaces;
416   bool relocate = false;
417   MemMap extra_reservation;
418   auto load = [&](const std::string& image_location) {
419     boot_image_spaces.clear();
420     extra_reservation = MemMap::Invalid();
421     ScopedObjectAccess soa(Thread::Current());
422     return gc::space::ImageSpace::LoadBootImage(
423         /*boot_class_path=*/boot_class_path,
424         /*boot_class_path_locations=*/libcore_dex_files,
425         /*boot_class_path_files=*/{},
426         /*boot_class_path_image_files=*/{},
427         /*boot_class_path_vdex_files=*/{},
428         /*boot_class_path_oat_files=*/{},
429         android::base::Split(image_location, ":"),
430         kRuntimeISA,
431         relocate,
432         /*executable=*/true,
433         /*extra_reservation_size=*/0u,
434         /*allow_in_memory_compilation=*/true,
435         Runtime::GetApexVersions(ArrayRef<const std::string>(libcore_dex_files)),
436         &boot_image_spaces,
437         &extra_reservation);
438   };
439   auto silent_load = [&](const std::string& image_location) {
440     ScopedLogSeverity quiet(LogSeverity::FATAL);
441     return load(image_location);
442   };
443 
444   for (bool r : { false, true }) {
445     relocate = r;
446 
447     // Load primary image with full path.
448     bool load_ok = load(base_location);
449     ASSERT_TRUE(load_ok) << error_msg;
450     ASSERT_FALSE(extra_reservation.IsValid());
451     ASSERT_EQ(head_dex_files.size(), boot_image_spaces.size());
452 
453     // Fail to load primary image with just the name.
454     load_ok = silent_load(base_name);
455     ASSERT_FALSE(load_ok);
456 
457     // Fail to load primary image with a search path.
458     load_ok = silent_load("*");
459     ASSERT_FALSE(load_ok);
460     load_ok = silent_load(scratch_dir + "*");
461     ASSERT_FALSE(load_ok);
462 
463     // Load the primary and first extension with full path.
464     load_ok = load(ART_FORMAT("{}:{}", base_location, mid_location));
465     ASSERT_TRUE(load_ok) << error_msg;
466     ASSERT_EQ(mid_bcp.size(), boot_image_spaces.size());
467 
468     // Load the primary with full path and fail to load first extension without full path.
469     load_ok = load(ART_FORMAT("{}:{}", base_location, mid_name));
470     ASSERT_TRUE(load_ok) << error_msg;  // Primary image loaded successfully.
471     ASSERT_EQ(head_dex_files.size(), boot_image_spaces.size());  // But only the primary image.
472 
473     // Load all the libcore images with full paths.
474     load_ok = load(ART_FORMAT("{}:{}:{}", base_location, mid_location, tail_location));
475     ASSERT_TRUE(load_ok) << error_msg;
476     ASSERT_EQ(full_bcp.size(), boot_image_spaces.size());
477 
478     // Load the primary and first extension with full paths, fail to load second extension by name.
479     load_ok = load(ART_FORMAT("{}:{}:{}", base_location, mid_location, tail_name));
480     ASSERT_TRUE(load_ok) << error_msg;
481     ASSERT_EQ(mid_bcp.size(), boot_image_spaces.size());
482 
483     // Load the primary with full path and fail to load first extension without full path,
484     // fail to load second extension because it depends on the first.
485     load_ok = load(ART_FORMAT("{}:{}:{}", base_location, mid_name, tail_location));
486     ASSERT_TRUE(load_ok) << error_msg;  // Primary image loaded successfully.
487     ASSERT_EQ(head_dex_files.size(), boot_image_spaces.size());  // But only the primary image.
488 
489     // Load the primary with full path and extensions with a specified search path.
490     load_ok = load(ART_FORMAT("{}:{}*", base_location, scratch_dir));
491     ASSERT_TRUE(load_ok) << error_msg;
492     ASSERT_EQ(full_bcp.size(), boot_image_spaces.size());
493 
494     // Load the primary with full path and fail to find extensions in BCP path.
495     load_ok = load(base_location + ":*");
496     ASSERT_TRUE(load_ok) << error_msg;
497     ASSERT_EQ(head_dex_files.size(), boot_image_spaces.size());
498   }
499 
500   // Now copy the libcore dex files to the `scratch_dir` and retry loading the boot image
501   // with BCP in the scratch_dir so that the images can be found based on BCP paths.
502   CopyDexFiles(scratch_dir, &boot_class_path);
503 
504   for (bool r : { false, true }) {
505     relocate = r;
506 
507     // Loading the primary image with just the name now succeeds.
508     bool load_ok = load(base_name);
509     ASSERT_TRUE(load_ok) << error_msg;
510     ASSERT_EQ(head_dex_files.size(), boot_image_spaces.size());
511 
512     // Loading the primary image with a search path still fails.
513     load_ok = silent_load("*");
514     ASSERT_FALSE(load_ok);
515     load_ok = silent_load(scratch_dir + "*");
516     ASSERT_FALSE(load_ok);
517 
518     // Load the primary and first extension without paths.
519     load_ok = load(ART_FORMAT("{}:{}", base_name, mid_name));
520     ASSERT_TRUE(load_ok) << error_msg;
521     ASSERT_EQ(mid_bcp.size(), boot_image_spaces.size());
522 
523     // Load the primary without path and first extension with path.
524     load_ok = load(ART_FORMAT("{}:{}", base_name, mid_location));
525     ASSERT_TRUE(load_ok) << error_msg;
526     ASSERT_EQ(mid_bcp.size(), boot_image_spaces.size());
527 
528     // Load the primary with full path and the first extension without full path.
529     load_ok = load(ART_FORMAT("{}:{}", base_location, mid_name));
530     ASSERT_TRUE(load_ok) << error_msg;  // Loaded successfully.
531     ASSERT_EQ(mid_bcp.size(), boot_image_spaces.size());  // Including the extension.
532 
533     // Load all the libcore images without paths.
534     load_ok = load(ART_FORMAT("{}:{}:{}", base_name, mid_name, tail_name));
535     ASSERT_TRUE(load_ok) << error_msg;
536     ASSERT_EQ(full_bcp.size(), boot_image_spaces.size());
537 
538     // Load the primary and first extension with full paths and second extension by name.
539     load_ok = load(ART_FORMAT("{}:{}:{}", base_location, mid_location, tail_name));
540     ASSERT_TRUE(load_ok) << error_msg;
541     ASSERT_EQ(full_bcp.size(), boot_image_spaces.size());
542 
543     // Load the primary with full path, first extension without path,
544     // and second extension with full path.
545     load_ok = load(ART_FORMAT("{}:{}:{}", base_location, mid_name, tail_location));
546     ASSERT_TRUE(load_ok) << error_msg;  // Loaded successfully.
547     ASSERT_EQ(full_bcp.size(), boot_image_spaces.size());  // Including both extensions.
548 
549     // Load the primary with full path and find both extensions in BCP path.
550     load_ok = load(base_location + ":*");
551     ASSERT_TRUE(load_ok) << error_msg;
552     ASSERT_EQ(full_bcp.size(), boot_image_spaces.size());
553 
554     // Fail to load any images with invalid image locations (named component after search paths).
555     load_ok = silent_load(ART_FORMAT("{}:*:{}", base_location, tail_location));
556     ASSERT_FALSE(load_ok);
557     load_ok = silent_load(ART_FORMAT("{}:{}*:{}", base_location, scratch_dir, tail_location));
558     ASSERT_FALSE(load_ok);
559 
560     // Load the primary and single-image extension with full path.
561     load_ok = load(ART_FORMAT("{}:{}", base_location, single_location));
562     ASSERT_TRUE(load_ok) << error_msg;
563     ASSERT_EQ(head_dex_files.size() + 1u, boot_image_spaces.size());
564 
565     // Load the primary with full path and single-image extension with a specified search path.
566     load_ok = load(ART_FORMAT("{}:{}*", base_location, single_dir));
567     ASSERT_TRUE(load_ok) << error_msg;
568     ASSERT_EQ(head_dex_files.size() + 1u, boot_image_spaces.size());
569   }
570 
571   // Recompile the single-image extension using file descriptors and compare contents.
572   std::vector<std::string> expanded_single_filename_prefix =
573       gc::space::ImageSpace::ExpandMultiImageLocations(
574           single_dex_files.SubArray(/*pos=*/ 0u, /*length=*/ 1u),
575           single_filename_prefix,
576           /*boot_image_extension=*/ true);
577   CHECK_EQ(1u, expanded_single_filename_prefix.size());
578   std::string single_ext_prefix = expanded_single_filename_prefix[0];
579   std::string single_ext_prefix2 = single_ext_prefix + "2";
580   error_msg.clear();
581   single_ok = CompileBootImage(extra_args,
582                                single_filename_prefix,
583                                single_dex_files,
584                                &error_msg,
585                                /*use_fd_prefix=*/ single_ext_prefix2);
586   ASSERT_TRUE(single_ok) << error_msg;
587   EXPECT_TRUE(CompareFiles(single_ext_prefix + ".art", single_ext_prefix2 + ".art"));
588   EXPECT_TRUE(CompareFiles(single_ext_prefix + ".vdex", single_ext_prefix2 + ".vdex"));
589   EXPECT_TRUE(CompareFiles(single_ext_prefix + ".oat", single_ext_prefix2 + ".oat"));
590 
591   // Test parsing profile specification and creating the boot image extension on-the-fly.
592   // We must set --android-root in the image compiler options.
593   AddAndroidRootToImageCompilerOptions();
594   for (bool r : { false, true }) {
595     relocate = r;
596 
597     // Load primary boot image with a profile name.
598     bool load_ok = silent_load(ART_FORMAT("{}!{}", base_location, single_profile_filename));
599     ASSERT_TRUE(load_ok);
600 
601     // Try and fail to load with invalid spec, two profile name separators.
602     load_ok =
603         silent_load(ART_FORMAT("{}:{}!!arbitrary-profile-name", base_location, single_location));
604     ASSERT_FALSE(load_ok);
605 
606     // Try and fail to load with invalid spec, missing profile name.
607     load_ok = silent_load(ART_FORMAT("{}:{}!", base_location, single_location));
608     ASSERT_FALSE(load_ok);
609 
610     // Try and fail to load with invalid spec, missing component name.
611     load_ok = silent_load(ART_FORMAT("{}:!{}", base_location, single_profile_filename));
612     ASSERT_FALSE(load_ok);
613 
614     // Load primary boot image, specifying invalid extension component and profile name.
615     load_ok = load(
616         ART_FORMAT("{}:/non-existent/{}!non-existent-profile-name", base_location, single_name));
617     ASSERT_TRUE(load_ok) << error_msg;
618     ASSERT_EQ(head_dex_files.size(), boot_image_spaces.size());
619 
620     // Load primary boot image and the single extension, specifying invalid profile name.
621     // (Load extension from file.)
622     load_ok = load(ART_FORMAT("{}:{}!non-existent-profile-name", base_location, single_location));
623     ASSERT_TRUE(load_ok) << error_msg;
624     ASSERT_EQ(head_dex_files.size() + 1u, boot_image_spaces.size());
625     ASSERT_EQ(single_dex_files.size(),
626               boot_image_spaces.back()->GetImageHeader().GetComponentCount());
627 
628     // Load primary boot image and fail to load the single extension, specifying
629     // invalid extension component name but a valid profile file.
630     // (Running dex2oat to compile extension is disabled.)
631     ASSERT_FALSE(Runtime::Current()->IsImageDex2OatEnabled());
632     load_ok = load(
633         ART_FORMAT("{}:/non-existent/{}!{}", base_location, single_name, single_profile_filename));
634     ASSERT_TRUE(load_ok) << error_msg;
635     ASSERT_EQ(head_dex_files.size(), boot_image_spaces.size());
636 
637     EnableImageDex2Oat();
638 
639     // Load primary boot image and the single extension, specifying invalid extension
640     // component name but a valid profile file. (Compile extension by running dex2oat.)
641     load_ok = load(
642         ART_FORMAT("{}:/non-existent/{}!{}", base_location, single_name, single_profile_filename));
643     ASSERT_TRUE(load_ok) << error_msg;
644     ASSERT_EQ(head_dex_files.size() + 1u, boot_image_spaces.size());
645     ASSERT_EQ(single_dex_files.size(),
646               boot_image_spaces.back()->GetImageHeader().GetComponentCount());
647 
648     // Load primary boot image and two extensions, specifying invalid extension component
649     // names but valid profile files. (Compile extensions by running dex2oat.)
650     load_ok = load(ART_FORMAT("{}:/non-existent/{}!{}:/non-existent/{}!{}",
651                               base_location,
652                               mid_name,
653                               mid_profile_filename,
654                               tail_name,
655                               tail_profile_filename));
656     ASSERT_TRUE(load_ok) << error_msg;
657     ASSERT_EQ(head_dex_files.size() + 2u, boot_image_spaces.size());
658     ASSERT_EQ(mid_dex_files.size(),
659               boot_image_spaces[head_dex_files.size()]->GetImageHeader().GetComponentCount());
660     ASSERT_EQ(tail_dex_files.size(),
661               boot_image_spaces[head_dex_files.size() + 1u]->GetImageHeader().GetComponentCount());
662 
663     // Load primary boot image and fail to load extensions, specifying invalid component
664     // names but valid profile file only for the second one. As we fail to load the first
665     // extension, the second extension has a missing dependency and cannot be compiled.
666     load_ok = load(ART_FORMAT("{}:/non-existent/{}:/non-existent/{}!{}",
667                               base_location,
668                               mid_name,
669                               tail_name,
670                               tail_profile_filename));
671     ASSERT_TRUE(load_ok) << error_msg;
672     ASSERT_EQ(head_dex_files.size(), boot_image_spaces.size());
673 
674     DisableImageDex2Oat();
675   }
676 }
677 
678 }  // namespace art
679