1 /*
2  * Copyright (C) 2016 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 <algorithm>
18 #include <regex>
19 #include <sstream>
20 #include <string>
21 #include <vector>
22 
23 #include <sys/wait.h>
24 #include <unistd.h>
25 
26 #include <android-base/logging.h>
27 #include <android-base/macros.h>
28 #include <android-base/stringprintf.h>
29 
30 #include "common_runtime_test.h"
31 
32 #include "arch/instruction_set_features.h"
33 #include "base/macros.h"
34 #include "base/mutex-inl.h"
35 #include "base/string_view_cpp20.h"
36 #include "base/utils.h"
37 #include "base/zip_archive.h"
38 #include "dex/art_dex_file_loader.h"
39 #include "dex/base64_test_util.h"
40 #include "dex/bytecode_utils.h"
41 #include "dex/class_accessor-inl.h"
42 #include "dex/code_item_accessors-inl.h"
43 #include "dex/dex_file-inl.h"
44 #include "dex/dex_file_loader.h"
45 #include "dex2oat_environment_test.h"
46 #include "dex2oat_return_codes.h"
47 #include "gc_root-inl.h"
48 #include "intern_table-inl.h"
49 #include "oat.h"
50 #include "oat_file.h"
51 #include "profile/profile_compilation_info.h"
52 #include "vdex_file.h"
53 #include "ziparchive/zip_writer.h"
54 
55 namespace art {
56 
57 static constexpr bool kDebugArgs = false;
58 static const char* kDisableCompactDex = "--compact-dex-level=none";
59 
60 using android::base::StringPrintf;
61 
62 class Dex2oatTest : public Dex2oatEnvironmentTest {
63  public:
TearDown()64   void TearDown() override {
65     Dex2oatEnvironmentTest::TearDown();
66 
67     output_ = "";
68     error_msg_ = "";
69     success_ = false;
70   }
71 
72  protected:
GenerateOdexForTestWithStatus(const std::vector<std::string> & dex_locations,const std::string & odex_location,CompilerFilter::Filter filter,std::string * error_msg,const std::vector<std::string> & extra_args={},bool use_fd=false)73   int GenerateOdexForTestWithStatus(const std::vector<std::string>& dex_locations,
74                                     const std::string& odex_location,
75                                     CompilerFilter::Filter filter,
76                                     std::string* error_msg,
77                                     const std::vector<std::string>& extra_args = {},
78                                     bool use_fd = false) {
79     std::unique_ptr<File> oat_file;
80     std::vector<std::string> args;
81     // Add dex file args.
82     for (const std::string& dex_location : dex_locations) {
83       args.push_back("--dex-file=" + dex_location);
84     }
85     if (use_fd) {
86       oat_file.reset(OS::CreateEmptyFile(odex_location.c_str()));
87       CHECK(oat_file != nullptr) << odex_location;
88       args.push_back("--oat-fd=" + std::to_string(oat_file->Fd()));
89       args.push_back("--oat-location=" + odex_location);
90     } else {
91       args.push_back("--oat-file=" + odex_location);
92     }
93     args.push_back("--compiler-filter=" + CompilerFilter::NameOfFilter(filter));
94     args.push_back("--runtime-arg");
95     args.push_back("-Xnorelocate");
96 
97     // Unless otherwise stated, use a small amount of threads, so that potential aborts are
98     // shorter. This can be overridden with extra_args.
99     args.push_back("-j4");
100 
101     args.insert(args.end(), extra_args.begin(), extra_args.end());
102 
103     int status = Dex2Oat(args, error_msg);
104     if (oat_file != nullptr) {
105       CHECK_EQ(oat_file->FlushClose(), 0) << "Could not flush and close oat file";
106     }
107     return status;
108   }
109 
GenerateOdexForTest(const std::string & dex_location,const std::string & odex_location,CompilerFilter::Filter filter,const std::vector<std::string> & extra_args={},bool expect_success=true,bool use_fd=false,bool use_zip_fd=false)110   ::testing::AssertionResult GenerateOdexForTest(
111       const std::string& dex_location,
112       const std::string& odex_location,
113       CompilerFilter::Filter filter,
114       const std::vector<std::string>& extra_args = {},
115       bool expect_success = true,
116       bool use_fd = false,
117       bool use_zip_fd = false) WARN_UNUSED {
118     return GenerateOdexForTest(dex_location,
119                                odex_location,
120                                filter,
121                                extra_args,
122                                expect_success,
123                                use_fd,
124                                use_zip_fd,
__anon390640650102(const OatFile&) 125                                [](const OatFile&) {});
126   }
127 
128   bool test_accepts_odex_file_on_failure = false;
129 
130   template <typename T>
GenerateOdexForTest(const std::string & dex_location,const std::string & odex_location,CompilerFilter::Filter filter,const std::vector<std::string> & extra_args,bool expect_success,bool use_fd,bool use_zip_fd,T check_oat)131   ::testing::AssertionResult GenerateOdexForTest(
132       const std::string& dex_location,
133       const std::string& odex_location,
134       CompilerFilter::Filter filter,
135       const std::vector<std::string>& extra_args,
136       bool expect_success,
137       bool use_fd,
138       bool use_zip_fd,
139       T check_oat) WARN_UNUSED {
140     std::vector<std::string> dex_locations;
141     if (use_zip_fd) {
142       std::string loc_arg = "--zip-location=" + dex_location;
143       CHECK(std::any_of(extra_args.begin(),
144                         extra_args.end(),
145                         [&](const std::string& s) { return s == loc_arg; }));
146       CHECK(std::any_of(extra_args.begin(),
147                         extra_args.end(),
148                         [](const std::string& s) { return StartsWith(s, "--zip-fd="); }));
149     } else {
150       dex_locations.push_back(dex_location);
151     }
152     std::string error_msg;
153     int status = GenerateOdexForTestWithStatus(dex_locations,
154                                                odex_location,
155                                                filter,
156                                                &error_msg,
157                                                extra_args,
158                                                use_fd);
159     bool success = (WIFEXITED(status) && WEXITSTATUS(status) == 0);
160     if (expect_success) {
161       if (!success) {
162         return ::testing::AssertionFailure()
163             << "Failed to compile odex: " << error_msg << std::endl << output_;
164       }
165 
166       // Verify the odex file was generated as expected.
167       std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
168                                                        odex_location.c_str(),
169                                                        odex_location.c_str(),
170                                                        /*executable=*/ false,
171                                                        /*low_4gb=*/ false,
172                                                        dex_location,
173                                                        &error_msg));
174       if (odex_file == nullptr) {
175         return ::testing::AssertionFailure() << "Could not open odex file: " << error_msg;
176       }
177 
178       CheckFilter(filter, odex_file->GetCompilerFilter());
179       check_oat(*(odex_file.get()));
180     } else {
181       if (success) {
182         return ::testing::AssertionFailure() << "Succeeded to compile odex: " << output_;
183       }
184 
185       error_msg_ = error_msg;
186 
187       if (!test_accepts_odex_file_on_failure) {
188         // Verify there's no loadable odex file.
189         std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
190                                                          odex_location.c_str(),
191                                                          odex_location.c_str(),
192                                                          /*executable=*/ false,
193                                                          /*low_4gb=*/ false,
194                                                          dex_location,
195                                                          &error_msg));
196         if (odex_file != nullptr) {
197           return ::testing::AssertionFailure() << "Could open odex file: " << error_msg;
198         }
199       }
200     }
201     return ::testing::AssertionSuccess();
202   }
203 
204   // Check the input compiler filter against the generated oat file's filter. May be overridden
205   // in subclasses when equality is not expected.
CheckFilter(CompilerFilter::Filter expected,CompilerFilter::Filter actual)206   virtual void CheckFilter(CompilerFilter::Filter expected, CompilerFilter::Filter actual) {
207     EXPECT_EQ(expected, actual);
208   }
209 
Dex2Oat(const std::vector<std::string> & dex2oat_args,std::string * error_msg)210   int Dex2Oat(const std::vector<std::string>& dex2oat_args, std::string* error_msg) {
211     std::vector<std::string> argv;
212     if (!CommonRuntimeTest::StartDex2OatCommandLine(&argv, error_msg)) {
213       return false;
214     }
215 
216     Runtime* runtime = Runtime::Current();
217     if (!runtime->IsVerificationEnabled()) {
218       argv.push_back("--compiler-filter=assume-verified");
219     }
220 
221     if (runtime->MustRelocateIfPossible()) {
222       argv.push_back("--runtime-arg");
223       argv.push_back("-Xrelocate");
224     } else {
225       argv.push_back("--runtime-arg");
226       argv.push_back("-Xnorelocate");
227     }
228 
229     if (!kIsTargetBuild) {
230       argv.push_back("--host");
231     }
232 
233     argv.insert(argv.end(), dex2oat_args.begin(), dex2oat_args.end());
234 
235     // We must set --android-root.
236     const char* android_root = getenv("ANDROID_ROOT");
237     CHECK(android_root != nullptr);
238     argv.push_back("--android-root=" + std::string(android_root));
239 
240     if (kDebugArgs) {
241       std::string all_args;
242       for (const std::string& arg : argv) {
243         all_args += arg + " ";
244       }
245       LOG(ERROR) << all_args;
246     }
247 
248     // We need dex2oat to actually log things.
249     auto post_fork_fn = []() { return setenv("ANDROID_LOG_TAGS", "*:d", 1) == 0; };
250     ForkAndExecResult res = ForkAndExec(argv, post_fork_fn, &output_);
251     if (res.stage != ForkAndExecResult::kFinished) {
252       *error_msg = strerror(errno);
253       return -1;
254     }
255     success_ = res.StandardSuccess();
256     return res.status_code;
257   }
258 
259   std::string output_ = "";
260   std::string error_msg_ = "";
261   bool success_ = false;
262 };
263 
264 class Dex2oatSwapTest : public Dex2oatTest {
265  protected:
RunTest(bool use_fd,bool expect_use,const std::vector<std::string> & extra_args={})266   void RunTest(bool use_fd, bool expect_use, const std::vector<std::string>& extra_args = {}) {
267     std::string dex_location = GetScratchDir() + "/Dex2OatSwapTest.jar";
268     std::string odex_location = GetOdexDir() + "/Dex2OatSwapTest.odex";
269 
270     Copy(GetTestDexFileName(), dex_location);
271 
272     std::vector<std::string> copy(extra_args);
273 
274     std::unique_ptr<ScratchFile> sf;
275     if (use_fd) {
276       sf.reset(new ScratchFile());
277       copy.push_back(android::base::StringPrintf("--swap-fd=%d", sf->GetFd()));
278     } else {
279       std::string swap_location = GetOdexDir() + "/Dex2OatSwapTest.odex.swap";
280       copy.push_back("--swap-file=" + swap_location);
281     }
282     ASSERT_TRUE(GenerateOdexForTest(dex_location, odex_location, CompilerFilter::kSpeed, copy));
283 
284     CheckValidity();
285     ASSERT_TRUE(success_);
286     CheckResult(expect_use);
287   }
288 
GetTestDexFileName()289   virtual std::string GetTestDexFileName() {
290     return Dex2oatEnvironmentTest::GetTestDexFileName("VerifierDeps");
291   }
292 
CheckResult(bool expect_use)293   virtual void CheckResult(bool expect_use) {
294     if (kIsTargetBuild) {
295       CheckTargetResult(expect_use);
296     } else {
297       CheckHostResult(expect_use);
298     }
299   }
300 
CheckTargetResult(bool expect_use ATTRIBUTE_UNUSED)301   virtual void CheckTargetResult(bool expect_use ATTRIBUTE_UNUSED) {
302     // TODO: Ignore for now, as we won't capture any output (it goes to the logcat). We may do
303     //       something for variants with file descriptor where we can control the lifetime of
304     //       the swap file and thus take a look at it.
305   }
306 
CheckHostResult(bool expect_use)307   virtual void CheckHostResult(bool expect_use) {
308     if (!kIsTargetBuild) {
309       if (expect_use) {
310         EXPECT_NE(output_.find("Large app, accepted running with swap."), std::string::npos)
311             << output_;
312       } else {
313         EXPECT_EQ(output_.find("Large app, accepted running with swap."), std::string::npos)
314             << output_;
315       }
316     }
317   }
318 
319   // Check whether the dex2oat run was really successful.
CheckValidity()320   virtual void CheckValidity() {
321     if (kIsTargetBuild) {
322       CheckTargetValidity();
323     } else {
324       CheckHostValidity();
325     }
326   }
327 
CheckTargetValidity()328   virtual void CheckTargetValidity() {
329     // TODO: Ignore for now, as we won't capture any output (it goes to the logcat). We may do
330     //       something for variants with file descriptor where we can control the lifetime of
331     //       the swap file and thus take a look at it.
332   }
333 
334   // On the host, we can get the dex2oat output. Here, look for "dex2oat took."
CheckHostValidity()335   virtual void CheckHostValidity() {
336     EXPECT_NE(output_.find("dex2oat took"), std::string::npos) << output_;
337   }
338 };
339 
TEST_F(Dex2oatSwapTest,DoNotUseSwapDefaultSingleSmall)340 TEST_F(Dex2oatSwapTest, DoNotUseSwapDefaultSingleSmall) {
341   RunTest(/*use_fd=*/ false, /*expect_use=*/ false);
342   RunTest(/*use_fd=*/ true, /*expect_use=*/ false);
343 }
344 
TEST_F(Dex2oatSwapTest,DoNotUseSwapSingle)345 TEST_F(Dex2oatSwapTest, DoNotUseSwapSingle) {
346   RunTest(/*use_fd=*/ false, /*expect_use=*/ false, { "--swap-dex-size-threshold=0" });
347   RunTest(/*use_fd=*/ true, /*expect_use=*/ false, { "--swap-dex-size-threshold=0" });
348 }
349 
TEST_F(Dex2oatSwapTest,DoNotUseSwapSmall)350 TEST_F(Dex2oatSwapTest, DoNotUseSwapSmall) {
351   RunTest(/*use_fd=*/ false, /*expect_use=*/ false, { "--swap-dex-count-threshold=0" });
352   RunTest(/*use_fd=*/ true, /*expect_use=*/ false, { "--swap-dex-count-threshold=0" });
353 }
354 
TEST_F(Dex2oatSwapTest,DoUseSwapSingleSmall)355 TEST_F(Dex2oatSwapTest, DoUseSwapSingleSmall) {
356   RunTest(/*use_fd=*/ false,
357           /*expect_use=*/ true,
358           { "--swap-dex-size-threshold=0", "--swap-dex-count-threshold=0" });
359   RunTest(/*use_fd=*/ true,
360           /*expect_use=*/ true,
361           { "--swap-dex-size-threshold=0", "--swap-dex-count-threshold=0" });
362 }
363 
364 class Dex2oatSwapUseTest : public Dex2oatSwapTest {
365  protected:
CheckHostResult(bool expect_use)366   void CheckHostResult(bool expect_use) override {
367     if (!kIsTargetBuild) {
368       if (expect_use) {
369         EXPECT_NE(output_.find("Large app, accepted running with swap."), std::string::npos)
370             << output_;
371       } else {
372         EXPECT_EQ(output_.find("Large app, accepted running with swap."), std::string::npos)
373             << output_;
374       }
375     }
376   }
377 
GetTestDexFileName()378   std::string GetTestDexFileName() override {
379     // Use Statics as it has a handful of functions.
380     return CommonRuntimeTest::GetTestDexFileName("Statics");
381   }
382 
GrabResult1()383   void GrabResult1() {
384     if (!kIsTargetBuild) {
385       native_alloc_1_ = ParseNativeAlloc();
386       swap_1_ = ParseSwap(/*expected=*/ false);
387     } else {
388       native_alloc_1_ = std::numeric_limits<size_t>::max();
389       swap_1_ = 0;
390     }
391   }
392 
GrabResult2()393   void GrabResult2() {
394     if (!kIsTargetBuild) {
395       native_alloc_2_ = ParseNativeAlloc();
396       swap_2_ = ParseSwap(/*expected=*/ true);
397     } else {
398       native_alloc_2_ = 0;
399       swap_2_ = std::numeric_limits<size_t>::max();
400     }
401   }
402 
403  private:
ParseNativeAlloc()404   size_t ParseNativeAlloc() {
405     std::regex native_alloc_regex("dex2oat took.*native alloc=[^ ]+ \\(([0-9]+)B\\)");
406     std::smatch native_alloc_match;
407     bool found = std::regex_search(output_, native_alloc_match, native_alloc_regex);
408     if (!found) {
409       EXPECT_TRUE(found);
410       return 0;
411     }
412     if (native_alloc_match.size() != 2U) {
413       EXPECT_EQ(native_alloc_match.size(), 2U);
414       return 0;
415     }
416 
417     std::istringstream stream(native_alloc_match[1].str());
418     size_t value;
419     stream >> value;
420 
421     return value;
422   }
423 
ParseSwap(bool expected)424   size_t ParseSwap(bool expected) {
425     std::regex swap_regex("dex2oat took[^\\n]+swap=[^ ]+ \\(([0-9]+)B\\)");
426     std::smatch swap_match;
427     bool found = std::regex_search(output_, swap_match, swap_regex);
428     if (found != expected) {
429       EXPECT_EQ(expected, found);
430       return 0;
431     }
432 
433     if (!found) {
434       return 0;
435     }
436 
437     if (swap_match.size() != 2U) {
438       EXPECT_EQ(swap_match.size(), 2U);
439       return 0;
440     }
441 
442     std::istringstream stream(swap_match[1].str());
443     size_t value;
444     stream >> value;
445 
446     return value;
447   }
448 
449  protected:
450   size_t native_alloc_1_;
451   size_t native_alloc_2_;
452 
453   size_t swap_1_;
454   size_t swap_2_;
455 };
456 
TEST_F(Dex2oatSwapUseTest,CheckSwapUsage)457 TEST_F(Dex2oatSwapUseTest, CheckSwapUsage) {
458   // Native memory usage isn't correctly tracked when running under ASan.
459   TEST_DISABLED_FOR_MEMORY_TOOL();
460 
461   // The `native_alloc_2_ >= native_alloc_1_` assertion below may not
462   // hold true on some x86 or x86_64 systems; disable this test while we
463   // investigate (b/29259363).
464   TEST_DISABLED_FOR_X86();
465   TEST_DISABLED_FOR_X86_64();
466 
467   RunTest(/*use_fd=*/ false,
468           /*expect_use=*/ false);
469   GrabResult1();
470   std::string output_1 = output_;
471 
472   output_ = "";
473 
474   RunTest(/*use_fd=*/ false,
475           /*expect_use=*/ true,
476           { "--swap-dex-size-threshold=0", "--swap-dex-count-threshold=0" });
477   GrabResult2();
478   std::string output_2 = output_;
479 
480   if (native_alloc_2_ >= native_alloc_1_ || swap_1_ >= swap_2_) {
481     EXPECT_LT(native_alloc_2_, native_alloc_1_);
482     EXPECT_LT(swap_1_, swap_2_);
483 
484     LOG(ERROR) << output_1;
485     LOG(ERROR) << output_2;
486   }
487 }
488 
489 class Dex2oatVeryLargeTest : public Dex2oatTest {
490  protected:
CheckFilter(CompilerFilter::Filter input ATTRIBUTE_UNUSED,CompilerFilter::Filter result ATTRIBUTE_UNUSED)491   void CheckFilter(CompilerFilter::Filter input ATTRIBUTE_UNUSED,
492                    CompilerFilter::Filter result ATTRIBUTE_UNUSED) override {
493     // Ignore, we'll do our own checks.
494   }
495 
RunTest(CompilerFilter::Filter filter,bool expect_large,bool expect_downgrade,const std::vector<std::string> & extra_args={})496   void RunTest(CompilerFilter::Filter filter,
497                bool expect_large,
498                bool expect_downgrade,
499                const std::vector<std::string>& extra_args = {}) {
500     std::string dex_location = GetScratchDir() + "/DexNoOat.jar";
501     std::string odex_location = GetOdexDir() + "/DexOdexNoOat.odex";
502     std::string app_image_file = GetScratchDir() + "/Test.art";
503 
504     Copy(GetDexSrc1(), dex_location);
505 
506     std::vector<std::string> new_args(extra_args);
507     new_args.push_back("--app-image-file=" + app_image_file);
508     ASSERT_TRUE(GenerateOdexForTest(dex_location, odex_location, filter, new_args));
509 
510     CheckValidity();
511     ASSERT_TRUE(success_);
512     CheckResult(dex_location,
513                 odex_location,
514                 app_image_file,
515                 filter,
516                 expect_large,
517                 expect_downgrade);
518   }
519 
CheckResult(const std::string & dex_location,const std::string & odex_location,const std::string & app_image_file,CompilerFilter::Filter filter,bool expect_large,bool expect_downgrade)520   void CheckResult(const std::string& dex_location,
521                    const std::string& odex_location,
522                    const std::string& app_image_file,
523                    CompilerFilter::Filter filter,
524                    bool expect_large,
525                    bool expect_downgrade) {
526     if (expect_downgrade) {
527       EXPECT_TRUE(expect_large);
528     }
529     // Host/target independent checks.
530     std::string error_msg;
531     std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
532                                                      odex_location.c_str(),
533                                                      odex_location.c_str(),
534                                                      /*executable=*/ false,
535                                                      /*low_4gb=*/ false,
536                                                      dex_location,
537                                                      &error_msg));
538     ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
539     EXPECT_GT(app_image_file.length(), 0u);
540     std::unique_ptr<File> file(OS::OpenFileForReading(app_image_file.c_str()));
541     if (expect_large) {
542       // Note: we cannot check the following
543       // EXPECT_FALSE(CompilerFilter::IsAotCompilationEnabled(odex_file->GetCompilerFilter()));
544       // The reason is that the filter override currently happens when the dex files are
545       // loaded in dex2oat, which is after the oat file has been started. Thus, the header
546       // store cannot be changed, and the original filter is set in stone.
547 
548       for (const OatDexFile* oat_dex_file : odex_file->GetOatDexFiles()) {
549         std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
550         ASSERT_TRUE(dex_file != nullptr);
551         uint32_t class_def_count = dex_file->NumClassDefs();
552         ASSERT_LT(class_def_count, std::numeric_limits<uint16_t>::max());
553         for (uint16_t class_def_index = 0; class_def_index < class_def_count; ++class_def_index) {
554           OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
555           EXPECT_EQ(oat_class.GetType(), OatClassType::kOatClassNoneCompiled);
556         }
557       }
558 
559       // If the input filter was "below," it should have been used.
560       if (!CompilerFilter::IsAsGoodAs(CompilerFilter::kExtract, filter)) {
561         EXPECT_EQ(odex_file->GetCompilerFilter(), filter);
562       }
563 
564       // If expect large, make sure the app image isn't generated or is empty.
565       if (file != nullptr) {
566         EXPECT_EQ(file->GetLength(), 0u);
567       }
568     } else {
569       EXPECT_EQ(odex_file->GetCompilerFilter(), filter);
570       ASSERT_TRUE(file != nullptr) << app_image_file;
571       EXPECT_GT(file->GetLength(), 0u);
572     }
573 
574     // Host/target dependent checks.
575     if (kIsTargetBuild) {
576       CheckTargetResult(expect_downgrade);
577     } else {
578       CheckHostResult(expect_downgrade);
579     }
580   }
581 
CheckTargetResult(bool expect_downgrade ATTRIBUTE_UNUSED)582   void CheckTargetResult(bool expect_downgrade ATTRIBUTE_UNUSED) {
583     // TODO: Ignore for now. May do something for fd things.
584   }
585 
CheckHostResult(bool expect_downgrade)586   void CheckHostResult(bool expect_downgrade) {
587     if (!kIsTargetBuild) {
588       if (expect_downgrade) {
589         EXPECT_NE(output_.find("Very large app, downgrading to"), std::string::npos) << output_;
590       } else {
591         EXPECT_EQ(output_.find("Very large app, downgrading to"), std::string::npos) << output_;
592       }
593     }
594   }
595 
596   // Check whether the dex2oat run was really successful.
CheckValidity()597   void CheckValidity() {
598     if (kIsTargetBuild) {
599       CheckTargetValidity();
600     } else {
601       CheckHostValidity();
602     }
603   }
604 
CheckTargetValidity()605   void CheckTargetValidity() {
606     // TODO: Ignore for now.
607   }
608 
609   // On the host, we can get the dex2oat output. Here, look for "dex2oat took."
CheckHostValidity()610   void CheckHostValidity() {
611     EXPECT_NE(output_.find("dex2oat took"), std::string::npos) << output_;
612   }
613 };
614 
TEST_F(Dex2oatVeryLargeTest,DontUseVeryLarge)615 TEST_F(Dex2oatVeryLargeTest, DontUseVeryLarge) {
616   RunTest(CompilerFilter::kAssumeVerified, false, false);
617   RunTest(CompilerFilter::kExtract, false, false);
618   RunTest(CompilerFilter::kQuicken, false, false);
619   RunTest(CompilerFilter::kSpeed, false, false);
620 
621   RunTest(CompilerFilter::kAssumeVerified, false, false, { "--very-large-app-threshold=10000000" });
622   RunTest(CompilerFilter::kExtract, false, false, { "--very-large-app-threshold=10000000" });
623   RunTest(CompilerFilter::kQuicken, false, false, { "--very-large-app-threshold=10000000" });
624   RunTest(CompilerFilter::kSpeed, false, false, { "--very-large-app-threshold=10000000" });
625 }
626 
TEST_F(Dex2oatVeryLargeTest,UseVeryLarge)627 TEST_F(Dex2oatVeryLargeTest, UseVeryLarge) {
628   RunTest(CompilerFilter::kAssumeVerified, true, false, { "--very-large-app-threshold=100" });
629   RunTest(CompilerFilter::kExtract, true, false, { "--very-large-app-threshold=100" });
630   RunTest(CompilerFilter::kQuicken, true, true, { "--very-large-app-threshold=100" });
631   RunTest(CompilerFilter::kSpeed, true, true, { "--very-large-app-threshold=100" });
632 }
633 
634 // Regressin test for b/35665292.
TEST_F(Dex2oatVeryLargeTest,SpeedProfileNoProfile)635 TEST_F(Dex2oatVeryLargeTest, SpeedProfileNoProfile) {
636   // Test that dex2oat doesn't crash with speed-profile but no input profile.
637   RunTest(CompilerFilter::kSpeedProfile, false, false);
638 }
639 
640 class Dex2oatLayoutTest : public Dex2oatTest {
641  protected:
CheckFilter(CompilerFilter::Filter input ATTRIBUTE_UNUSED,CompilerFilter::Filter result ATTRIBUTE_UNUSED)642   void CheckFilter(CompilerFilter::Filter input ATTRIBUTE_UNUSED,
643                    CompilerFilter::Filter result ATTRIBUTE_UNUSED) override {
644     // Ignore, we'll do our own checks.
645   }
646 
647   // Emits a profile with a single dex file with the given location and classes ranging
648   // from 0 to num_classes.
GenerateProfile(const std::string & test_profile,const DexFile * dex,size_t num_classes)649   void GenerateProfile(const std::string& test_profile,
650                        const DexFile* dex,
651                        size_t num_classes) {
652     int profile_test_fd = open(test_profile.c_str(),
653                                O_CREAT | O_TRUNC | O_WRONLY | O_CLOEXEC,
654                                0644);
655     CHECK_GE(profile_test_fd, 0);
656 
657     ProfileCompilationInfo info;
658     std::vector<dex::TypeIndex> classes;;
659     for (size_t i = 0; i < num_classes; ++i) {
660       classes.push_back(dex::TypeIndex(1 + i));
661     }
662     info.AddClassesForDex(dex, classes.begin(), classes.end());
663     bool result = info.Save(profile_test_fd);
664     close(profile_test_fd);
665     ASSERT_TRUE(result);
666   }
667 
CompileProfileOdex(const std::string & dex_location,const std::string & odex_location,const std::string & app_image_file_name,bool use_fd,size_t num_profile_classes,const std::vector<std::string> & extra_args={},bool expect_success=true)668   void CompileProfileOdex(const std::string& dex_location,
669                           const std::string& odex_location,
670                           const std::string& app_image_file_name,
671                           bool use_fd,
672                           size_t num_profile_classes,
673                           const std::vector<std::string>& extra_args = {},
674                           bool expect_success = true) {
675     const std::string profile_location = GetScratchDir() + "/primary.prof";
676     const char* location = dex_location.c_str();
677     std::string error_msg;
678     std::vector<std::unique_ptr<const DexFile>> dex_files;
679     const ArtDexFileLoader dex_file_loader;
680     ASSERT_TRUE(dex_file_loader.Open(
681         location, location, /*verify=*/ true, /*verify_checksum=*/ true, &error_msg, &dex_files));
682     EXPECT_EQ(dex_files.size(), 1U);
683     std::unique_ptr<const DexFile>& dex_file = dex_files[0];
684     GenerateProfile(profile_location, dex_file.get(), num_profile_classes);
685     std::vector<std::string> copy(extra_args);
686     copy.push_back("--profile-file=" + profile_location);
687     std::unique_ptr<File> app_image_file;
688     if (!app_image_file_name.empty()) {
689       if (use_fd) {
690         app_image_file.reset(OS::CreateEmptyFile(app_image_file_name.c_str()));
691         copy.push_back("--app-image-fd=" + std::to_string(app_image_file->Fd()));
692       } else {
693         copy.push_back("--app-image-file=" + app_image_file_name);
694       }
695     }
696     ASSERT_TRUE(GenerateOdexForTest(dex_location,
697                                     odex_location,
698                                     CompilerFilter::kSpeedProfile,
699                                     copy,
700                                     expect_success,
701                                     use_fd));
702     if (app_image_file != nullptr) {
703       ASSERT_EQ(app_image_file->FlushCloseOrErase(), 0) << "Could not flush and close art file";
704     }
705   }
706 
GetImageObjectSectionSize(const std::string & image_file_name)707   uint64_t GetImageObjectSectionSize(const std::string& image_file_name) {
708     EXPECT_FALSE(image_file_name.empty());
709     std::unique_ptr<File> file(OS::OpenFileForReading(image_file_name.c_str()));
710     CHECK(file != nullptr);
711     ImageHeader image_header;
712     const bool success = file->ReadFully(&image_header, sizeof(image_header));
713     CHECK(success);
714     CHECK(image_header.IsValid());
715     ReaderMutexLock mu(Thread::Current(), *Locks::mutator_lock_);
716     return image_header.GetObjectsSection().Size();
717   }
718 
RunTest(bool app_image)719   void RunTest(bool app_image) {
720     std::string dex_location = GetScratchDir() + "/DexNoOat.jar";
721     std::string odex_location = GetOdexDir() + "/DexOdexNoOat.odex";
722     std::string app_image_file = app_image ? (GetOdexDir() + "/DexOdexNoOat.art"): "";
723     Copy(GetDexSrc2(), dex_location);
724 
725     uint64_t image_file_empty_profile = 0;
726     if (app_image) {
727       CompileProfileOdex(dex_location,
728                          odex_location,
729                          app_image_file,
730                          /*use_fd=*/ false,
731                          /*num_profile_classes=*/ 0);
732       CheckValidity();
733       ASSERT_TRUE(success_);
734       // Don't check the result since CheckResult relies on the class being in the profile.
735       image_file_empty_profile = GetImageObjectSectionSize(app_image_file);
736       EXPECT_GT(image_file_empty_profile, 0u);
737     }
738 
739     // Small profile.
740     CompileProfileOdex(dex_location,
741                        odex_location,
742                        app_image_file,
743                        /*use_fd=*/ false,
744                        /*num_profile_classes=*/ 1);
745     CheckValidity();
746     ASSERT_TRUE(success_);
747     CheckResult(dex_location, odex_location, app_image_file);
748 
749     if (app_image) {
750       // Test that the profile made a difference by adding more classes.
751       const uint64_t image_file_small_profile = GetImageObjectSectionSize(app_image_file);
752       ASSERT_LT(image_file_empty_profile, image_file_small_profile);
753     }
754   }
755 
RunTestVDex()756   void RunTestVDex() {
757     std::string dex_location = GetScratchDir() + "/DexNoOat.jar";
758     std::string odex_location = GetOdexDir() + "/DexOdexNoOat.odex";
759     std::string vdex_location = GetOdexDir() + "/DexOdexNoOat.vdex";
760     std::string app_image_file_name = GetOdexDir() + "/DexOdexNoOat.art";
761     Copy(GetDexSrc2(), dex_location);
762 
763     std::unique_ptr<File> vdex_file1(OS::CreateEmptyFile(vdex_location.c_str()));
764     CHECK(vdex_file1 != nullptr) << vdex_location;
765     ScratchFile vdex_file2;
766     {
767       std::string input_vdex = "--input-vdex-fd=-1";
768       std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file1->Fd());
769       CompileProfileOdex(dex_location,
770                          odex_location,
771                          app_image_file_name,
772                          /*use_fd=*/ true,
773                          /*num_profile_classes=*/ 1,
774                          { input_vdex, output_vdex });
775       EXPECT_GT(vdex_file1->GetLength(), 0u);
776     }
777     {
778       // Test that vdex and dexlayout fail gracefully.
779       std::string input_vdex = StringPrintf("--input-vdex-fd=%d", vdex_file1->Fd());
780       std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file2.GetFd());
781       CompileProfileOdex(dex_location,
782                          odex_location,
783                          app_image_file_name,
784                          /*use_fd=*/ true,
785                          /*num_profile_classes=*/ 1,
786                          { input_vdex, output_vdex },
787                          /*expect_success=*/ true);
788       EXPECT_GT(vdex_file2.GetFile()->GetLength(), 0u);
789     }
790     ASSERT_EQ(vdex_file1->FlushCloseOrErase(), 0) << "Could not flush and close vdex file";
791     CheckValidity();
792     ASSERT_TRUE(success_);
793   }
794 
CheckResult(const std::string & dex_location,const std::string & odex_location,const std::string & app_image_file_name)795   void CheckResult(const std::string& dex_location,
796                    const std::string& odex_location,
797                    const std::string& app_image_file_name) {
798     // Host/target independent checks.
799     std::string error_msg;
800     std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
801                                                      odex_location.c_str(),
802                                                      odex_location.c_str(),
803                                                      /*executable=*/ false,
804                                                      /*low_4gb=*/ false,
805                                                      dex_location,
806                                                      &error_msg));
807     ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
808 
809     const char* location = dex_location.c_str();
810     std::vector<std::unique_ptr<const DexFile>> dex_files;
811     const ArtDexFileLoader dex_file_loader;
812     ASSERT_TRUE(dex_file_loader.Open(
813         location, location, /*verify=*/ true, /*verify_checksum=*/ true, &error_msg, &dex_files));
814     EXPECT_EQ(dex_files.size(), 1U);
815     std::unique_ptr<const DexFile>& old_dex_file = dex_files[0];
816 
817     for (const OatDexFile* oat_dex_file : odex_file->GetOatDexFiles()) {
818       std::unique_ptr<const DexFile> new_dex_file = oat_dex_file->OpenDexFile(&error_msg);
819       ASSERT_TRUE(new_dex_file != nullptr);
820       uint32_t class_def_count = new_dex_file->NumClassDefs();
821       ASSERT_LT(class_def_count, std::numeric_limits<uint16_t>::max());
822       ASSERT_GE(class_def_count, 2U);
823 
824       // Make sure the indexes stay the same.
825       std::string old_class0 = old_dex_file->PrettyType(old_dex_file->GetClassDef(0).class_idx_);
826       std::string old_class1 = old_dex_file->PrettyType(old_dex_file->GetClassDef(1).class_idx_);
827       std::string new_class0 = new_dex_file->PrettyType(new_dex_file->GetClassDef(0).class_idx_);
828       std::string new_class1 = new_dex_file->PrettyType(new_dex_file->GetClassDef(1).class_idx_);
829       EXPECT_EQ(old_class0, new_class0);
830       EXPECT_EQ(old_class1, new_class1);
831     }
832 
833     EXPECT_EQ(odex_file->GetCompilerFilter(), CompilerFilter::kSpeedProfile);
834 
835     if (!app_image_file_name.empty()) {
836       // Go peek at the image header to make sure it was large enough to contain the class.
837       std::unique_ptr<File> file(OS::OpenFileForReading(app_image_file_name.c_str()));
838       ImageHeader image_header;
839       bool success = file->ReadFully(&image_header, sizeof(image_header));
840       ASSERT_TRUE(success);
841       ASSERT_TRUE(image_header.IsValid());
842       EXPECT_GT(image_header.GetObjectsSection().Size(), 0u);
843     }
844   }
845 
846   // Check whether the dex2oat run was really successful.
CheckValidity()847   void CheckValidity() {
848     if (kIsTargetBuild) {
849       CheckTargetValidity();
850     } else {
851       CheckHostValidity();
852     }
853   }
854 
CheckTargetValidity()855   void CheckTargetValidity() {
856     // TODO: Ignore for now.
857   }
858 
859   // On the host, we can get the dex2oat output. Here, look for "dex2oat took."
CheckHostValidity()860   void CheckHostValidity() {
861     EXPECT_NE(output_.find("dex2oat took"), std::string::npos) << output_;
862   }
863 };
864 
TEST_F(Dex2oatLayoutTest,TestLayout)865 TEST_F(Dex2oatLayoutTest, TestLayout) {
866   RunTest(/*app_image=*/ false);
867 }
868 
TEST_F(Dex2oatLayoutTest,TestLayoutAppImage)869 TEST_F(Dex2oatLayoutTest, TestLayoutAppImage) {
870   RunTest(/*app_image=*/ true);
871 }
872 
TEST_F(Dex2oatLayoutTest,TestVdexLayout)873 TEST_F(Dex2oatLayoutTest, TestVdexLayout) {
874   RunTestVDex();
875 }
876 
877 class Dex2oatUnquickenTest : public Dex2oatTest {
878  protected:
RunUnquickenMultiDex()879   void RunUnquickenMultiDex() {
880     std::string dex_location = GetScratchDir() + "/UnquickenMultiDex.jar";
881     std::string odex_location = GetOdexDir() + "/UnquickenMultiDex.odex";
882     std::string vdex_location = GetOdexDir() + "/UnquickenMultiDex.vdex";
883     Copy(GetTestDexFileName("MultiDex"), dex_location);
884 
885     std::unique_ptr<File> vdex_file1(OS::CreateEmptyFile(vdex_location.c_str()));
886     CHECK(vdex_file1 != nullptr) << vdex_location;
887     // Quicken the dex file into a vdex file.
888     {
889       std::string input_vdex = "--input-vdex-fd=-1";
890       std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file1->Fd());
891       ASSERT_TRUE(GenerateOdexForTest(dex_location,
892                                       odex_location,
893                                       CompilerFilter::kQuicken,
894                                       { input_vdex, output_vdex },
895                                       /* expect_success= */ true,
896                                       /* use_fd= */ true));
897       EXPECT_GT(vdex_file1->GetLength(), 0u);
898     }
899     // Get the dex file checksums.
900     std::vector<uint32_t> checksums1;
901     GetDexFileChecksums(dex_location, odex_location, &checksums1);
902     // Unquicken by running the verify compiler filter on the vdex file.
903     {
904       std::string input_vdex = StringPrintf("--input-vdex-fd=%d", vdex_file1->Fd());
905       std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file1->Fd());
906       ASSERT_TRUE(GenerateOdexForTest(dex_location,
907                                       odex_location,
908                                       CompilerFilter::kVerify,
909                                       { input_vdex, output_vdex, kDisableCompactDex },
910                                       /* expect_success= */ true,
911                                       /* use_fd= */ true));
912     }
913     ASSERT_EQ(vdex_file1->FlushCloseOrErase(), 0) << "Could not flush and close vdex file";
914     CheckResult(dex_location, odex_location);
915     // Verify that the checksums did not change.
916     std::vector<uint32_t> checksums2;
917     GetDexFileChecksums(dex_location, odex_location, &checksums2);
918     ASSERT_EQ(checksums1.size(), checksums2.size());
919     for (size_t i = 0; i != checksums1.size(); ++i) {
920       EXPECT_EQ(checksums1[i], checksums2[i]) << i;
921     }
922     ASSERT_TRUE(success_);
923   }
924 
RunUnquickenMultiDexCDex()925   void RunUnquickenMultiDexCDex() {
926     std::string dex_location = GetScratchDir() + "/UnquickenMultiDex.jar";
927     std::string odex_location = GetOdexDir() + "/UnquickenMultiDex.odex";
928     std::string odex_location2 = GetOdexDir() + "/UnquickenMultiDex2.odex";
929     std::string vdex_location = GetOdexDir() + "/UnquickenMultiDex.vdex";
930     std::string vdex_location2 = GetOdexDir() + "/UnquickenMultiDex2.vdex";
931     Copy(GetTestDexFileName("MultiDex"), dex_location);
932 
933     std::unique_ptr<File> vdex_file1(OS::CreateEmptyFile(vdex_location.c_str()));
934     std::unique_ptr<File> vdex_file2(OS::CreateEmptyFile(vdex_location2.c_str()));
935     CHECK(vdex_file1 != nullptr) << vdex_location;
936     CHECK(vdex_file2 != nullptr) << vdex_location2;
937 
938     // Quicken the dex file into a vdex file.
939     {
940       std::string input_vdex = "--input-vdex-fd=-1";
941       std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file1->Fd());
942       ASSERT_TRUE(GenerateOdexForTest(dex_location,
943                                       odex_location,
944                                       CompilerFilter::kQuicken,
945                                       { input_vdex, output_vdex, "--compact-dex-level=fast"},
946                                       /* expect_success= */ true,
947                                       /* use_fd= */ true));
948       EXPECT_GT(vdex_file1->GetLength(), 0u);
949     }
950     // Unquicken by running the verify compiler filter on the vdex file.
951     {
952       std::string input_vdex = StringPrintf("--input-vdex-fd=%d", vdex_file1->Fd());
953       std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file2->Fd());
954       ASSERT_TRUE(GenerateOdexForTest(dex_location,
955                                       odex_location2,
956                                       CompilerFilter::kVerify,
957                                       { input_vdex, output_vdex, "--compact-dex-level=none"},
958                                       /* expect_success= */ true,
959                                       /* use_fd= */ true));
960     }
961     ASSERT_EQ(vdex_file1->FlushCloseOrErase(), 0) << "Could not flush and close vdex file";
962     ASSERT_EQ(vdex_file2->FlushCloseOrErase(), 0) << "Could not flush and close vdex file";
963     CheckResult(dex_location, odex_location2);
964     ASSERT_TRUE(success_);
965   }
966 
CheckResult(const std::string & dex_location,const std::string & odex_location)967   void CheckResult(const std::string& dex_location, const std::string& odex_location) {
968     std::string error_msg;
969     std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
970                                                      odex_location.c_str(),
971                                                      odex_location.c_str(),
972                                                      /*executable=*/ false,
973                                                      /*low_4gb=*/ false,
974                                                      dex_location,
975                                                      &error_msg));
976     ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
977     ASSERT_GE(odex_file->GetOatDexFiles().size(), 1u);
978 
979     // Iterate over the dex files and ensure there is no quickened instruction.
980     for (const OatDexFile* oat_dex_file : odex_file->GetOatDexFiles()) {
981       std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
982       for (ClassAccessor accessor : dex_file->GetClasses()) {
983         for (const ClassAccessor::Method& method : accessor.GetMethods()) {
984           for (const DexInstructionPcPair& inst : method.GetInstructions()) {
985             ASSERT_FALSE(inst->IsQuickened()) << inst->Opcode() << " " << output_;
986           }
987         }
988       }
989     }
990   }
991 
GetDexFileChecksums(const std::string & dex_location,const std::string & odex_location,std::vector<uint32_t> * checksums)992   void GetDexFileChecksums(const std::string& dex_location,
993                            const std::string& odex_location,
994                            /*out*/std::vector<uint32_t>* checksums) {
995     std::string error_msg;
996     std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
997                                                      odex_location.c_str(),
998                                                      odex_location.c_str(),
999                                                      /*executable=*/ false,
1000                                                      /*low_4gb=*/ false,
1001                                                      dex_location,
1002                                                      &error_msg));
1003     ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
1004     ASSERT_GE(odex_file->GetOatDexFiles().size(), 1u);
1005     for (const OatDexFile* oat_dex_file : odex_file->GetOatDexFiles()) {
1006       checksums->push_back(oat_dex_file->GetDexFileLocationChecksum());
1007     }
1008   }
1009 };
1010 
TEST_F(Dex2oatUnquickenTest,UnquickenMultiDex)1011 TEST_F(Dex2oatUnquickenTest, UnquickenMultiDex) {
1012   RunUnquickenMultiDex();
1013 }
1014 
TEST_F(Dex2oatUnquickenTest,UnquickenMultiDexCDex)1015 TEST_F(Dex2oatUnquickenTest, UnquickenMultiDexCDex) {
1016   RunUnquickenMultiDexCDex();
1017 }
1018 
1019 class Dex2oatWatchdogTest : public Dex2oatTest {
1020  protected:
RunTest(bool expect_success,const std::vector<std::string> & extra_args={})1021   void RunTest(bool expect_success, const std::vector<std::string>& extra_args = {}) {
1022     std::string dex_location = GetScratchDir() + "/Dex2OatSwapTest.jar";
1023     std::string odex_location = GetOdexDir() + "/Dex2OatSwapTest.odex";
1024 
1025     Copy(GetTestDexFileName(), dex_location);
1026 
1027     std::vector<std::string> copy(extra_args);
1028 
1029     std::string swap_location = GetOdexDir() + "/Dex2OatSwapTest.odex.swap";
1030     copy.push_back("--swap-file=" + swap_location);
1031     copy.push_back("-j512");  // Excessive idle threads just slow down dex2oat.
1032     ASSERT_TRUE(GenerateOdexForTest(dex_location,
1033                                     odex_location,
1034                                     CompilerFilter::kSpeed,
1035                                     copy,
1036                                     expect_success));
1037   }
1038 
GetTestDexFileName()1039   std::string GetTestDexFileName() {
1040     return GetDexSrc1();
1041   }
1042 };
1043 
TEST_F(Dex2oatWatchdogTest,TestWatchdogOK)1044 TEST_F(Dex2oatWatchdogTest, TestWatchdogOK) {
1045   // Check with default.
1046   RunTest(true);
1047 
1048   // Check with ten minutes.
1049   RunTest(true, { "--watchdog-timeout=600000" });
1050 }
1051 
TEST_F(Dex2oatWatchdogTest,TestWatchdogTrigger)1052 TEST_F(Dex2oatWatchdogTest, TestWatchdogTrigger) {
1053   // This test is frequently interrupted by signal_dumper on host (x86);
1054   // disable it while we investigate (b/121352534).
1055   TEST_DISABLED_FOR_X86();
1056 
1057   // The watchdog is independent of dex2oat and will not delete intermediates. It is possible
1058   // that the compilation succeeds and the file is completely written by the time the watchdog
1059   // kills dex2oat (but the dex2oat threads must have been scheduled pretty badly).
1060   test_accepts_odex_file_on_failure = true;
1061 
1062   // Check with ten milliseconds.
1063   RunTest(false, { "--watchdog-timeout=10" });
1064 }
1065 
1066 class Dex2oatReturnCodeTest : public Dex2oatTest {
1067  protected:
RunTest(const std::vector<std::string> & extra_args={})1068   int RunTest(const std::vector<std::string>& extra_args = {}) {
1069     std::string dex_location = GetScratchDir() + "/Dex2OatSwapTest.jar";
1070     std::string odex_location = GetOdexDir() + "/Dex2OatSwapTest.odex";
1071 
1072     Copy(GetTestDexFileName(), dex_location);
1073 
1074     std::string error_msg;
1075     return GenerateOdexForTestWithStatus({dex_location},
1076                                          odex_location,
1077                                          CompilerFilter::kSpeed,
1078                                          &error_msg,
1079                                          extra_args);
1080   }
1081 
GetTestDexFileName()1082   std::string GetTestDexFileName() {
1083     return GetDexSrc1();
1084   }
1085 };
1086 
1087 class Dex2oatClassLoaderContextTest : public Dex2oatTest {
1088  protected:
RunTest(const char * class_loader_context,const char * expected_classpath_key,bool expected_success,bool use_second_source=false,bool generate_image=false)1089   void RunTest(const char* class_loader_context,
1090                const char* expected_classpath_key,
1091                bool expected_success,
1092                bool use_second_source = false,
1093                bool generate_image = false) {
1094     std::string dex_location = GetUsedDexLocation();
1095     std::string odex_location = GetUsedOatLocation();
1096 
1097     Copy(use_second_source ? GetDexSrc2() : GetDexSrc1(), dex_location);
1098 
1099     std::string error_msg;
1100     std::vector<std::string> extra_args;
1101     if (class_loader_context != nullptr) {
1102       extra_args.push_back(std::string("--class-loader-context=") + class_loader_context);
1103     }
1104     if (generate_image) {
1105       extra_args.push_back(std::string("--app-image-file=") + GetUsedImageLocation());
1106     }
1107     auto check_oat = [expected_classpath_key](const OatFile& oat_file) {
1108       ASSERT_TRUE(expected_classpath_key != nullptr);
1109       const char* classpath = oat_file.GetOatHeader().GetStoreValueByKey(OatHeader::kClassPathKey);
1110       ASSERT_TRUE(classpath != nullptr);
1111       ASSERT_STREQ(expected_classpath_key, classpath);
1112     };
1113 
1114     ASSERT_TRUE(GenerateOdexForTest(dex_location,
1115                                     odex_location,
1116                                     CompilerFilter::kQuicken,
1117                                     extra_args,
1118                                     expected_success,
1119                                     /*use_fd=*/ false,
1120                                     /*use_zip_fd=*/ false,
1121                                     check_oat));
1122   }
1123 
GetUsedDexLocation()1124   std::string GetUsedDexLocation() {
1125     return GetScratchDir() + "/Context.jar";
1126   }
1127 
GetUsedOatLocation()1128   std::string GetUsedOatLocation() {
1129     return GetOdexDir() + "/Context.odex";
1130   }
1131 
GetUsedImageLocation()1132   std::string GetUsedImageLocation() {
1133     return GetOdexDir() + "/Context.art";
1134   }
1135 
1136   const char* kEmptyClassPathKey = "PCL[]";
1137 };
1138 
TEST_F(Dex2oatClassLoaderContextTest,InvalidContext)1139 TEST_F(Dex2oatClassLoaderContextTest, InvalidContext) {
1140   RunTest("Invalid[]", /*expected_classpath_key*/ nullptr, /*expected_success*/ false);
1141 }
1142 
TEST_F(Dex2oatClassLoaderContextTest,EmptyContext)1143 TEST_F(Dex2oatClassLoaderContextTest, EmptyContext) {
1144   RunTest("PCL[]", kEmptyClassPathKey, /*expected_success*/ true);
1145 }
1146 
TEST_F(Dex2oatClassLoaderContextTest,SpecialContext)1147 TEST_F(Dex2oatClassLoaderContextTest, SpecialContext) {
1148   RunTest(OatFile::kSpecialSharedLibrary,
1149           OatFile::kSpecialSharedLibrary,
1150           /*expected_success*/ true);
1151 }
1152 
TEST_F(Dex2oatClassLoaderContextTest,ContextWithTheSourceDexFiles)1153 TEST_F(Dex2oatClassLoaderContextTest, ContextWithTheSourceDexFiles) {
1154   std::string context = "PCL[" + GetUsedDexLocation() + "]";
1155   RunTest(context.c_str(), kEmptyClassPathKey, /*expected_success*/ true);
1156 }
1157 
TEST_F(Dex2oatClassLoaderContextTest,ContextWithOtherDexFiles)1158 TEST_F(Dex2oatClassLoaderContextTest, ContextWithOtherDexFiles) {
1159   std::vector<std::unique_ptr<const DexFile>> dex_files = OpenTestDexFiles("Nested");
1160 
1161   std::string context = "PCL[" + dex_files[0]->GetLocation() + "]";
1162   std::string expected_classpath_key = "PCL[" +
1163       dex_files[0]->GetLocation() + "*" + std::to_string(dex_files[0]->GetLocationChecksum()) + "]";
1164   RunTest(context.c_str(), expected_classpath_key.c_str(), true);
1165 }
1166 
TEST_F(Dex2oatClassLoaderContextTest,ContextWithStrippedDexFiles)1167 TEST_F(Dex2oatClassLoaderContextTest, ContextWithStrippedDexFiles) {
1168   std::string stripped_classpath = GetScratchDir() + "/stripped_classpath.jar";
1169   Copy(GetStrippedDexSrc1(), stripped_classpath);
1170 
1171   std::string context = "PCL[" + stripped_classpath + "]";
1172   // Expect an empty context because stripped dex files cannot be open.
1173   RunTest(context.c_str(), kEmptyClassPathKey , /*expected_success*/ true);
1174 }
1175 
TEST_F(Dex2oatClassLoaderContextTest,ContextWithStrippedDexFilesBackedByOdex)1176 TEST_F(Dex2oatClassLoaderContextTest, ContextWithStrippedDexFilesBackedByOdex) {
1177   std::string stripped_classpath = GetScratchDir() + "/stripped_classpath.jar";
1178   std::string odex_for_classpath = GetOdexDir() + "/stripped_classpath.odex";
1179 
1180   Copy(GetDexSrc1(), stripped_classpath);
1181 
1182   ASSERT_TRUE(GenerateOdexForTest(stripped_classpath,
1183                                   odex_for_classpath,
1184                                   CompilerFilter::kQuicken,
1185                                   {},
1186                                   true));
1187 
1188   // Strip the dex file
1189   Copy(GetStrippedDexSrc1(), stripped_classpath);
1190 
1191   std::string context = "PCL[" + stripped_classpath + "]";
1192   std::string expected_classpath_key;
1193   {
1194     // Open the oat file to get the expected classpath.
1195     OatFileAssistant oat_file_assistant(stripped_classpath.c_str(), kRuntimeISA, false, false);
1196     std::unique_ptr<OatFile> oat_file(oat_file_assistant.GetBestOatFile());
1197     std::vector<std::unique_ptr<const DexFile>> oat_dex_files =
1198         OatFileAssistant::LoadDexFiles(*oat_file, stripped_classpath.c_str());
1199     expected_classpath_key = "PCL[";
1200     for (size_t i = 0; i < oat_dex_files.size(); i++) {
1201       if (i > 0) {
1202         expected_classpath_key + ":";
1203       }
1204       expected_classpath_key += oat_dex_files[i]->GetLocation() + "*" +
1205           std::to_string(oat_dex_files[i]->GetLocationChecksum());
1206     }
1207     expected_classpath_key += "]";
1208   }
1209 
1210   RunTest(context.c_str(),
1211           expected_classpath_key.c_str(),
1212           /*expected_success*/ true,
1213           /*use_second_source*/ true);
1214 }
1215 
TEST_F(Dex2oatClassLoaderContextTest,ContextWithNotExistentDexFiles)1216 TEST_F(Dex2oatClassLoaderContextTest, ContextWithNotExistentDexFiles) {
1217   std::string context = "PCL[does_not_exists.dex]";
1218   // Expect an empty context because stripped dex files cannot be open.
1219   RunTest(context.c_str(), kEmptyClassPathKey, /*expected_success*/ true);
1220 }
1221 
TEST_F(Dex2oatClassLoaderContextTest,ChainContext)1222 TEST_F(Dex2oatClassLoaderContextTest, ChainContext) {
1223   std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested");
1224   std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex");
1225 
1226   std::string context = "PCL[" + GetTestDexFileName("Nested") + "];" +
1227       "DLC[" + GetTestDexFileName("MultiDex") + "]";
1228   std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "];" +
1229       "DLC[" + CreateClassPathWithChecksums(dex_files2) + "]";
1230 
1231   RunTest(context.c_str(), expected_classpath_key.c_str(), true);
1232 }
1233 
TEST_F(Dex2oatClassLoaderContextTest,ContextWithSharedLibrary)1234 TEST_F(Dex2oatClassLoaderContextTest, ContextWithSharedLibrary) {
1235   std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested");
1236   std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex");
1237 
1238   std::string context = "PCL[" + GetTestDexFileName("Nested") + "]" +
1239       "{PCL[" + GetTestDexFileName("MultiDex") + "]}";
1240   std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "]" +
1241       "{PCL[" + CreateClassPathWithChecksums(dex_files2) + "]}";
1242   RunTest(context.c_str(), expected_classpath_key.c_str(), true);
1243 }
1244 
TEST_F(Dex2oatClassLoaderContextTest,ContextWithSharedLibraryAndImage)1245 TEST_F(Dex2oatClassLoaderContextTest, ContextWithSharedLibraryAndImage) {
1246   std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested");
1247   std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex");
1248 
1249   std::string context = "PCL[" + GetTestDexFileName("Nested") + "]" +
1250       "{PCL[" + GetTestDexFileName("MultiDex") + "]}";
1251   std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "]" +
1252       "{PCL[" + CreateClassPathWithChecksums(dex_files2) + "]}";
1253   RunTest(context.c_str(),
1254           expected_classpath_key.c_str(),
1255           /*expected_success=*/ true,
1256           /*use_second_source=*/ false,
1257           /*generate_image=*/ true);
1258 }
1259 
TEST_F(Dex2oatClassLoaderContextTest,ContextWithSameSharedLibrariesAndImage)1260 TEST_F(Dex2oatClassLoaderContextTest, ContextWithSameSharedLibrariesAndImage) {
1261   std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested");
1262   std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex");
1263 
1264   std::string context = "PCL[" + GetTestDexFileName("Nested") + "]" +
1265       "{PCL[" + GetTestDexFileName("MultiDex") + "]" +
1266       "#PCL[" + GetTestDexFileName("MultiDex") + "]}";
1267   std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "]" +
1268       "{PCL[" + CreateClassPathWithChecksums(dex_files2) + "]" +
1269       "#PCL[" + CreateClassPathWithChecksums(dex_files2) + "]}";
1270   RunTest(context.c_str(),
1271           expected_classpath_key.c_str(),
1272           /*expected_success=*/ true,
1273           /*use_second_source=*/ false,
1274           /*generate_image=*/ true);
1275 }
1276 
TEST_F(Dex2oatClassLoaderContextTest,ContextWithSharedLibrariesDependenciesAndImage)1277 TEST_F(Dex2oatClassLoaderContextTest, ContextWithSharedLibrariesDependenciesAndImage) {
1278   std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested");
1279   std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex");
1280 
1281   std::string context = "PCL[" + GetTestDexFileName("Nested") + "]" +
1282       "{PCL[" + GetTestDexFileName("MultiDex") + "]" +
1283       "{PCL[" + GetTestDexFileName("Nested") + "]}}";
1284   std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "]" +
1285       "{PCL[" + CreateClassPathWithChecksums(dex_files2) + "]" +
1286       "{PCL[" + CreateClassPathWithChecksums(dex_files1) + "]}}";
1287   RunTest(context.c_str(),
1288           expected_classpath_key.c_str(),
1289           /*expected_success=*/ true,
1290           /*use_second_source=*/ false,
1291           /*generate_image=*/ true);
1292 }
1293 
1294 class Dex2oatDeterminism : public Dex2oatTest {};
1295 
TEST_F(Dex2oatDeterminism,UnloadCompile)1296 TEST_F(Dex2oatDeterminism, UnloadCompile) {
1297   Runtime* const runtime = Runtime::Current();
1298   std::string out_dir = GetScratchDir();
1299   const std::string base_oat_name = out_dir + "/base.oat";
1300   const std::string base_vdex_name = out_dir + "/base.vdex";
1301   const std::string unload_oat_name = out_dir + "/unload.oat";
1302   const std::string unload_vdex_name = out_dir + "/unload.vdex";
1303   const std::string no_unload_oat_name = out_dir + "/nounload.oat";
1304   const std::string no_unload_vdex_name = out_dir + "/nounload.vdex";
1305   std::string error_msg;
1306   const std::vector<gc::space::ImageSpace*>& spaces = runtime->GetHeap()->GetBootImageSpaces();
1307   ASSERT_GT(spaces.size(), 0u);
1308   const std::string image_location = spaces[0]->GetImageLocation();
1309   // Without passing in an app image, it will unload in between compilations.
1310   const int res = GenerateOdexForTestWithStatus(
1311       GetLibCoreDexFileNames(),
1312       base_oat_name,
1313       CompilerFilter::Filter::kQuicken,
1314       &error_msg,
1315       {"--force-determinism", "--avoid-storing-invocation"});
1316   ASSERT_EQ(res, 0);
1317   Copy(base_oat_name, unload_oat_name);
1318   Copy(base_vdex_name, unload_vdex_name);
1319   std::unique_ptr<File> unload_oat(OS::OpenFileForReading(unload_oat_name.c_str()));
1320   std::unique_ptr<File> unload_vdex(OS::OpenFileForReading(unload_vdex_name.c_str()));
1321   ASSERT_TRUE(unload_oat != nullptr);
1322   ASSERT_TRUE(unload_vdex != nullptr);
1323   EXPECT_GT(unload_oat->GetLength(), 0u);
1324   EXPECT_GT(unload_vdex->GetLength(), 0u);
1325   // Regenerate with an app image to disable the dex2oat unloading and verify that the output is
1326   // the same.
1327   const int res2 = GenerateOdexForTestWithStatus(
1328       GetLibCoreDexFileNames(),
1329       base_oat_name,
1330       CompilerFilter::Filter::kQuicken,
1331       &error_msg,
1332       {"--force-determinism", "--avoid-storing-invocation", "--compile-individually"});
1333   ASSERT_EQ(res2, 0);
1334   Copy(base_oat_name, no_unload_oat_name);
1335   Copy(base_vdex_name, no_unload_vdex_name);
1336   std::unique_ptr<File> no_unload_oat(OS::OpenFileForReading(no_unload_oat_name.c_str()));
1337   std::unique_ptr<File> no_unload_vdex(OS::OpenFileForReading(no_unload_vdex_name.c_str()));
1338   ASSERT_TRUE(no_unload_oat != nullptr);
1339   ASSERT_TRUE(no_unload_vdex != nullptr);
1340   EXPECT_GT(no_unload_oat->GetLength(), 0u);
1341   EXPECT_GT(no_unload_vdex->GetLength(), 0u);
1342   // Verify that both of the files are the same (odex and vdex).
1343   EXPECT_EQ(unload_oat->GetLength(), no_unload_oat->GetLength());
1344   EXPECT_EQ(unload_vdex->GetLength(), no_unload_vdex->GetLength());
1345   EXPECT_EQ(unload_oat->Compare(no_unload_oat.get()), 0)
1346       << unload_oat_name << " " << no_unload_oat_name;
1347   EXPECT_EQ(unload_vdex->Compare(no_unload_vdex.get()), 0)
1348       << unload_vdex_name << " " << no_unload_vdex_name;
1349 }
1350 
1351 // Test that dexlayout section info is correctly written to the oat file for profile based
1352 // compilation.
TEST_F(Dex2oatTest,LayoutSections)1353 TEST_F(Dex2oatTest, LayoutSections) {
1354   using Hotness = ProfileCompilationInfo::MethodHotness;
1355   std::unique_ptr<const DexFile> dex(OpenTestDexFile("ManyMethods"));
1356   ScratchFile profile_file;
1357   // We can only layout method indices with code items, figure out which ones have this property
1358   // first.
1359   std::vector<uint16_t> methods;
1360   {
1361     const dex::TypeId* type_id = dex->FindTypeId("LManyMethods;");
1362     dex::TypeIndex type_idx = dex->GetIndexForTypeId(*type_id);
1363     ClassAccessor accessor(*dex, *dex->FindClassDef(type_idx));
1364     std::set<size_t> code_item_offsets;
1365     for (const ClassAccessor::Method& method : accessor.GetMethods()) {
1366       const uint16_t method_idx = method.GetIndex();
1367       const size_t code_item_offset = method.GetCodeItemOffset();
1368       if (code_item_offsets.insert(code_item_offset).second) {
1369         // Unique code item, add the method index.
1370         methods.push_back(method_idx);
1371       }
1372     }
1373   }
1374   ASSERT_GE(methods.size(), 8u);
1375   std::vector<uint16_t> hot_methods = {methods[1], methods[3], methods[5]};
1376   std::vector<uint16_t> startup_methods = {methods[1], methods[2], methods[7]};
1377   std::vector<uint16_t> post_methods = {methods[0], methods[2], methods[6]};
1378   // Here, we build the profile from the method lists.
1379   ProfileCompilationInfo info;
1380   info.AddMethodsForDex(
1381       static_cast<Hotness::Flag>(Hotness::kFlagHot | Hotness::kFlagStartup),
1382       dex.get(),
1383       hot_methods.begin(),
1384       hot_methods.end());
1385   info.AddMethodsForDex(
1386       Hotness::kFlagStartup,
1387       dex.get(),
1388       startup_methods.begin(),
1389       startup_methods.end());
1390   info.AddMethodsForDex(
1391       Hotness::kFlagPostStartup,
1392       dex.get(),
1393       post_methods.begin(),
1394       post_methods.end());
1395   for (uint16_t id : hot_methods) {
1396     EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsHot());
1397     EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsStartup());
1398   }
1399   for (uint16_t id : startup_methods) {
1400     EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsStartup());
1401   }
1402   for (uint16_t id : post_methods) {
1403     EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsPostStartup());
1404   }
1405   // Save the profile since we want to use it with dex2oat to produce an oat file.
1406   ASSERT_TRUE(info.Save(profile_file.GetFd()));
1407   // Generate a profile based odex.
1408   const std::string dir = GetScratchDir();
1409   const std::string oat_filename = dir + "/base.oat";
1410   const std::string vdex_filename = dir + "/base.vdex";
1411   std::string error_msg;
1412   const int res = GenerateOdexForTestWithStatus(
1413       {dex->GetLocation()},
1414       oat_filename,
1415       CompilerFilter::Filter::kQuicken,
1416       &error_msg,
1417       {"--profile-file=" + profile_file.GetFilename()});
1418   EXPECT_EQ(res, 0);
1419 
1420   // Open our generated oat file.
1421   std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
1422                                                    oat_filename.c_str(),
1423                                                    oat_filename.c_str(),
1424                                                    /*executable=*/ false,
1425                                                    /*low_4gb=*/ false,
1426                                                    dex->GetLocation(),
1427                                                    &error_msg));
1428   ASSERT_TRUE(odex_file != nullptr);
1429   std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
1430   ASSERT_EQ(oat_dex_files.size(), 1u);
1431   // Check that the code sections match what we expect.
1432   for (const OatDexFile* oat_dex : oat_dex_files) {
1433     const DexLayoutSections* const sections = oat_dex->GetDexLayoutSections();
1434     // Testing of logging the sections.
1435     ASSERT_TRUE(sections != nullptr);
1436     LOG(INFO) << *sections;
1437 
1438     // Load the sections into temporary variables for convenience.
1439     const DexLayoutSection& code_section =
1440         sections->sections_[static_cast<size_t>(DexLayoutSections::SectionType::kSectionTypeCode)];
1441     const DexLayoutSection::Subsection& section_hot_code =
1442         code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeHot)];
1443     const DexLayoutSection::Subsection& section_sometimes_used =
1444         code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeSometimesUsed)];
1445     const DexLayoutSection::Subsection& section_startup_only =
1446         code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeStartupOnly)];
1447     const DexLayoutSection::Subsection& section_unused =
1448         code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeUnused)];
1449 
1450     // All the sections should be non-empty.
1451     EXPECT_GT(section_hot_code.Size(), 0u);
1452     EXPECT_GT(section_sometimes_used.Size(), 0u);
1453     EXPECT_GT(section_startup_only.Size(), 0u);
1454     EXPECT_GT(section_unused.Size(), 0u);
1455 
1456     // Open the dex file since we need to peek at the code items to verify the layout matches what
1457     // we expect.
1458     std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1459     ASSERT_TRUE(dex_file != nullptr) << error_msg;
1460     const dex::TypeId* type_id = dex_file->FindTypeId("LManyMethods;");
1461     ASSERT_TRUE(type_id != nullptr);
1462     dex::TypeIndex type_idx = dex_file->GetIndexForTypeId(*type_id);
1463     const dex::ClassDef* class_def = dex_file->FindClassDef(type_idx);
1464     ASSERT_TRUE(class_def != nullptr);
1465 
1466     // Count how many code items are for each category, there should be at least one per category.
1467     size_t hot_count = 0;
1468     size_t post_startup_count = 0;
1469     size_t startup_count = 0;
1470     size_t unused_count = 0;
1471     // Visit all of the methdos of the main class and cross reference the method indices to their
1472     // corresponding code item offsets to verify the layout.
1473     ClassAccessor accessor(*dex_file, *class_def);
1474     for (const ClassAccessor::Method& method : accessor.GetMethods()) {
1475       const size_t method_idx = method.GetIndex();
1476       const size_t code_item_offset = method.GetCodeItemOffset();
1477       const bool is_hot = ContainsElement(hot_methods, method_idx);
1478       const bool is_startup = ContainsElement(startup_methods, method_idx);
1479       const bool is_post_startup = ContainsElement(post_methods, method_idx);
1480       if (is_hot) {
1481         // Hot is highest precedence, check that the hot methods are in the hot section.
1482         EXPECT_TRUE(section_hot_code.Contains(code_item_offset));
1483         ++hot_count;
1484       } else if (is_post_startup) {
1485         // Post startup is sometimes used section.
1486         EXPECT_TRUE(section_sometimes_used.Contains(code_item_offset));
1487         ++post_startup_count;
1488       } else if (is_startup) {
1489         // Startup at this point means not hot or post startup, these must be startup only then.
1490         EXPECT_TRUE(section_startup_only.Contains(code_item_offset));
1491         ++startup_count;
1492       } else {
1493         if (section_unused.Contains(code_item_offset)) {
1494           // If no flags are set, the method should be unused ...
1495           ++unused_count;
1496         } else {
1497           // or this method is part of the last code item and the end is 4 byte aligned.
1498           for (const ClassAccessor::Method& method2 : accessor.GetMethods()) {
1499             EXPECT_LE(method2.GetCodeItemOffset(), code_item_offset);
1500           }
1501           uint32_t code_item_size = dex_file->FindCodeItemOffset(*class_def, method_idx);
1502           EXPECT_EQ((code_item_offset + code_item_size) % 4, 0u);
1503         }
1504       }
1505     }
1506     EXPECT_GT(hot_count, 0u);
1507     EXPECT_GT(post_startup_count, 0u);
1508     EXPECT_GT(startup_count, 0u);
1509     EXPECT_GT(unused_count, 0u);
1510   }
1511 }
1512 
1513 // Test that generating compact dex works.
TEST_F(Dex2oatTest,GenerateCompactDex)1514 TEST_F(Dex2oatTest, GenerateCompactDex) {
1515   // Generate a compact dex based odex.
1516   const std::string dir = GetScratchDir();
1517   const std::string oat_filename = dir + "/base.oat";
1518   const std::string vdex_filename = dir + "/base.vdex";
1519   const std::string dex_location = GetTestDexFileName("MultiDex");
1520   std::string error_msg;
1521   const int res = GenerateOdexForTestWithStatus(
1522       { dex_location },
1523       oat_filename,
1524       CompilerFilter::Filter::kQuicken,
1525       &error_msg,
1526       {"--compact-dex-level=fast"});
1527   EXPECT_EQ(res, 0);
1528   // Open our generated oat file.
1529   std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
1530                                                    oat_filename.c_str(),
1531                                                    oat_filename.c_str(),
1532                                                    /*executable=*/ false,
1533                                                    /*low_4gb=*/ false,
1534                                                    dex_location,
1535                                                    &error_msg));
1536   ASSERT_TRUE(odex_file != nullptr);
1537   std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
1538   ASSERT_GT(oat_dex_files.size(), 1u);
1539   // Check that each dex is a compact dex file.
1540   std::vector<std::unique_ptr<const CompactDexFile>> compact_dex_files;
1541   for (const OatDexFile* oat_dex : oat_dex_files) {
1542     std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1543     ASSERT_TRUE(dex_file != nullptr) << error_msg;
1544     ASSERT_TRUE(dex_file->IsCompactDexFile());
1545     compact_dex_files.push_back(
1546         std::unique_ptr<const CompactDexFile>(dex_file.release()->AsCompactDexFile()));
1547   }
1548   for (const std::unique_ptr<const CompactDexFile>& dex_file : compact_dex_files) {
1549     // Test that every code item is in the owned section.
1550     const CompactDexFile::Header& header = dex_file->GetHeader();
1551     EXPECT_LE(header.OwnedDataBegin(), header.OwnedDataEnd());
1552     EXPECT_LE(header.OwnedDataBegin(), header.data_size_);
1553     EXPECT_LE(header.OwnedDataEnd(), header.data_size_);
1554     for (ClassAccessor accessor : dex_file->GetClasses()) {
1555       for (const ClassAccessor::Method& method : accessor.GetMethods()) {
1556         if (method.GetCodeItemOffset() != 0u) {
1557           ASSERT_GE(method.GetCodeItemOffset(), header.OwnedDataBegin());
1558           ASSERT_LT(method.GetCodeItemOffset(), header.OwnedDataEnd());
1559         }
1560       }
1561     }
1562     // Test that the owned sections don't overlap.
1563     for (const std::unique_ptr<const CompactDexFile>& other_dex : compact_dex_files) {
1564       if (dex_file != other_dex) {
1565         ASSERT_TRUE(
1566             (dex_file->GetHeader().OwnedDataBegin() >= other_dex->GetHeader().OwnedDataEnd()) ||
1567             (dex_file->GetHeader().OwnedDataEnd() <= other_dex->GetHeader().OwnedDataBegin()));
1568       }
1569     }
1570   }
1571 }
1572 
1573 class Dex2oatVerifierAbort : public Dex2oatTest {};
1574 
TEST_F(Dex2oatVerifierAbort,HardFail)1575 TEST_F(Dex2oatVerifierAbort, HardFail) {
1576   // Use VerifierDeps as it has hard-failing classes.
1577   std::unique_ptr<const DexFile> dex(OpenTestDexFile("VerifierDeps"));
1578   std::string out_dir = GetScratchDir();
1579   const std::string base_oat_name = out_dir + "/base.oat";
1580   std::string error_msg;
1581   const int res_fail = GenerateOdexForTestWithStatus(
1582         {dex->GetLocation()},
1583         base_oat_name,
1584         CompilerFilter::Filter::kQuicken,
1585         &error_msg,
1586         {"--abort-on-hard-verifier-error"});
1587   EXPECT_NE(0, res_fail);
1588 
1589   const int res_no_fail = GenerateOdexForTestWithStatus(
1590         {dex->GetLocation()},
1591         base_oat_name,
1592         CompilerFilter::Filter::kQuicken,
1593         &error_msg,
1594         {"--no-abort-on-hard-verifier-error"});
1595   EXPECT_EQ(0, res_no_fail);
1596 }
1597 
TEST_F(Dex2oatVerifierAbort,SoftFail)1598 TEST_F(Dex2oatVerifierAbort, SoftFail) {
1599   // Use VerifierDepsMulti as it has hard-failing classes.
1600   std::unique_ptr<const DexFile> dex(OpenTestDexFile("VerifierDepsMulti"));
1601   std::string out_dir = GetScratchDir();
1602   const std::string base_oat_name = out_dir + "/base.oat";
1603   std::string error_msg;
1604   const int res_fail = GenerateOdexForTestWithStatus(
1605         {dex->GetLocation()},
1606         base_oat_name,
1607         CompilerFilter::Filter::kQuicken,
1608         &error_msg,
1609         {"--abort-on-soft-verifier-error"});
1610   EXPECT_NE(0, res_fail);
1611 
1612   const int res_no_fail = GenerateOdexForTestWithStatus(
1613         {dex->GetLocation()},
1614         base_oat_name,
1615         CompilerFilter::Filter::kQuicken,
1616         &error_msg,
1617         {"--no-abort-on-soft-verifier-error"});
1618   EXPECT_EQ(0, res_no_fail);
1619 }
1620 
1621 class Dex2oatDedupeCode : public Dex2oatTest {};
1622 
TEST_F(Dex2oatDedupeCode,DedupeTest)1623 TEST_F(Dex2oatDedupeCode, DedupeTest) {
1624   // Use MyClassNatives. It has lots of native methods that will produce deduplicate-able code.
1625   std::unique_ptr<const DexFile> dex(OpenTestDexFile("MyClassNatives"));
1626   std::string out_dir = GetScratchDir();
1627   const std::string base_oat_name = out_dir + "/base.oat";
1628   size_t no_dedupe_size = 0;
1629   ASSERT_TRUE(GenerateOdexForTest(dex->GetLocation(),
1630                                   base_oat_name,
1631                                   CompilerFilter::Filter::kSpeed,
1632                                   { "--deduplicate-code=false" },
1633                                   /*expect_success=*/ true,
1634                                   /*use_fd=*/ false,
1635                                   /*use_zip_fd=*/ false,
1636                                   [&no_dedupe_size](const OatFile& o) {
1637                                     no_dedupe_size = o.Size();
1638                                   }));
1639 
1640   size_t dedupe_size = 0;
1641   ASSERT_TRUE(GenerateOdexForTest(dex->GetLocation(),
1642                                   base_oat_name,
1643                                   CompilerFilter::Filter::kSpeed,
1644                                   { "--deduplicate-code=true" },
1645                                   /*expect_success=*/ true,
1646                                   /*use_fd=*/ false,
1647                                   /*use_zip_fd=*/ false,
1648                                   [&dedupe_size](const OatFile& o) {
1649                                     dedupe_size = o.Size();
1650                                   }));
1651 
1652   EXPECT_LT(dedupe_size, no_dedupe_size);
1653 }
1654 
TEST_F(Dex2oatTest,UncompressedTest)1655 TEST_F(Dex2oatTest, UncompressedTest) {
1656   std::unique_ptr<const DexFile> dex(OpenTestDexFile("MainUncompressedAligned"));
1657   std::string out_dir = GetScratchDir();
1658   const std::string base_oat_name = out_dir + "/base.oat";
1659   ASSERT_TRUE(GenerateOdexForTest(dex->GetLocation(),
1660                                   base_oat_name,
1661                                   CompilerFilter::Filter::kQuicken,
1662                                   { },
1663                                   /*expect_success=*/ true,
1664                                   /*use_fd=*/ false,
1665                                   /*use_zip_fd=*/ false,
1666                                   [](const OatFile& o) {
1667                                     CHECK(!o.ContainsDexCode());
1668                                   }));
1669 }
1670 
TEST_F(Dex2oatTest,EmptyUncompressedDexTest)1671 TEST_F(Dex2oatTest, EmptyUncompressedDexTest) {
1672   std::string out_dir = GetScratchDir();
1673   const std::string base_oat_name = out_dir + "/base.oat";
1674   std::string error_msg;
1675   int status = GenerateOdexForTestWithStatus(
1676       { GetTestDexFileName("MainEmptyUncompressed") },
1677       base_oat_name,
1678       CompilerFilter::Filter::kQuicken,
1679       &error_msg,
1680       { },
1681       /*use_fd*/ false);
1682   // Expect to fail with code 1 and not SIGSEGV or SIGABRT.
1683   ASSERT_TRUE(WIFEXITED(status));
1684   ASSERT_EQ(WEXITSTATUS(status), 1) << error_msg;
1685 }
1686 
TEST_F(Dex2oatTest,EmptyUncompressedAlignedDexTest)1687 TEST_F(Dex2oatTest, EmptyUncompressedAlignedDexTest) {
1688   std::string out_dir = GetScratchDir();
1689   const std::string base_oat_name = out_dir + "/base.oat";
1690   std::string error_msg;
1691   int status = GenerateOdexForTestWithStatus(
1692       { GetTestDexFileName("MainEmptyUncompressedAligned") },
1693       base_oat_name,
1694       CompilerFilter::Filter::kQuicken,
1695       &error_msg,
1696       { },
1697       /*use_fd*/ false);
1698   // Expect to fail with code 1 and not SIGSEGV or SIGABRT.
1699   ASSERT_TRUE(WIFEXITED(status));
1700   ASSERT_EQ(WEXITSTATUS(status), 1) << error_msg;
1701 }
1702 
1703 // Dex file that has duplicate methods have different code items and debug info.
1704 static const char kDuplicateMethodInputDex[] =
1705     "ZGV4CjAzOQDEy8VPdj4qHpgPYFWtLCtOykfFP4kB8tGYDAAAcAAAAHhWNBIAAAAAAAAAANALAABI"
1706     "AAAAcAAAAA4AAACQAQAABQAAAMgBAAANAAAABAIAABkAAABsAgAABAAAADQDAADgCAAAuAMAADgI"
1707     "AABCCAAASggAAE8IAABcCAAAaggAAHkIAACICAAAlggAAKQIAACyCAAAwAgAAM4IAADcCAAA6ggA"
1708     "APgIAAD7CAAA/wgAABcJAAAuCQAARQkAAFQJAAB4CQAAmAkAALsJAADSCQAA5gkAAPoJAAAVCgAA"
1709     "KQoAADsKAABCCgAASgoAAFIKAABbCgAAZAoAAGwKAAB0CgAAfAoAAIQKAACMCgAAlAoAAJwKAACk"
1710     "CgAArQoAALcKAADACgAAwwoAAMcKAADcCgAA6QoAAPEKAAD3CgAA/QoAAAMLAAAJCwAAEAsAABcL"
1711     "AAAdCwAAIwsAACkLAAAvCwAANQsAADsLAABBCwAARwsAAE0LAABSCwAAWwsAAF4LAABoCwAAbwsA"
1712     "ABEAAAASAAAAEwAAABQAAAAVAAAAFgAAABcAAAAYAAAAGQAAABoAAAAbAAAAHAAAAC4AAAAwAAAA"
1713     "DwAAAAkAAAAAAAAAEAAAAAoAAACoBwAALgAAAAwAAAAAAAAALwAAAAwAAACoBwAALwAAAAwAAACw"
1714     "BwAAAgAJADUAAAACAAkANgAAAAIACQA3AAAAAgAJADgAAAACAAkAOQAAAAIACQA6AAAAAgAJADsA"
1715     "AAACAAkAPAAAAAIACQA9AAAAAgAJAD4AAAACAAkAPwAAAAIACQBAAAAACwAHAEIAAAAAAAIAAQAA"
1716     "AAAAAwAeAAAAAQACAAEAAAABAAMAHgAAAAIAAgAAAAAAAgACAAEAAAADAAIAAQAAAAMAAgAfAAAA"
1717     "AwACACAAAAADAAIAIQAAAAMAAgAiAAAAAwACACMAAAADAAIAJAAAAAMAAgAlAAAAAwACACYAAAAD"
1718     "AAIAJwAAAAMAAgAoAAAAAwACACkAAAADAAIAKgAAAAMABAA0AAAABwADAEMAAAAIAAIAAQAAAAoA"
1719     "AgABAAAACgABADIAAAAKAAAARQAAAAAAAAAAAAAACAAAAAAAAAAdAAAAaAcAALYHAAAAAAAAAQAA"
1720     "AAAAAAAIAAAAAAAAAB0AAAB4BwAAxAcAAAAAAAACAAAAAAAAAAgAAAAAAAAAHQAAAIgHAADSBwAA"
1721     "AAAAAAMAAAAAAAAACAAAAAAAAAAdAAAAmAcAAPoHAAAAAAAAAAAAAAEAAAAAAAAArAYAADEAAAAa"
1722     "AAMAaQAAABoABABpAAEAGgAHAGkABAAaAAgAaQAFABoACQBpAAYAGgAKAGkABwAaAAsAaQAIABoA"
1723     "DABpAAkAGgANAGkACgAaAA4AaQALABoABQBpAAIAGgAGAGkAAwAOAAAAAQABAAEAAACSBgAABAAA"
1724     "AHAQFQAAAA4ABAABAAIAAACWBgAAFwAAAGIADAAiAQoAcBAWAAEAGgICAG4gFwAhAG4gFwAxAG4Q"
1725     "GAABAAwBbiAUABAADgAAAAEAAQABAAAAngYAAAQAAABwEBUAAAAOAAIAAQACAAAAogYAAAYAAABi"
1726     "AAwAbiAUABAADgABAAEAAQAAAKgGAAAEAAAAcBAVAAAADgABAAEAAQAAALsGAAAEAAAAcBAVAAAA"
1727     "DgABAAAAAQAAAL8GAAAGAAAAYgAAAHEQAwAAAA4AAQAAAAEAAADEBgAABgAAAGIAAQBxEAMAAAAO"
1728     "AAEAAAABAAAA8QYAAAYAAABiAAIAcRABAAAADgABAAAAAQAAAPYGAAAGAAAAYgADAHEQAwAAAA4A"
1729     "AQAAAAEAAADJBgAABgAAAGIABABxEAMAAAAOAAEAAAABAAAAzgYAAAYAAABiAAEAcRADAAAADgAB"
1730     "AAAAAQAAANMGAAAGAAAAYgAGAHEQAwAAAA4AAQAAAAEAAADYBgAABgAAAGIABwBxEAMAAAAOAAEA"
1731     "AAABAAAA3QYAAAYAAABiAAgAcRABAAAADgABAAAAAQAAAOIGAAAGAAAAYgAJAHEQAwAAAA4AAQAA"
1732     "AAEAAADnBgAABgAAAGIACgBxEAMAAAAOAAEAAAABAAAA7AYAAAYAAABiAAsAcRABAAAADgABAAEA"
1733     "AAAAAPsGAAAlAAAAcQAHAAAAcQAIAAAAcQALAAAAcQAMAAAAcQANAAAAcQAOAAAAcQAPAAAAcQAQ"
1734     "AAAAcQARAAAAcQASAAAAcQAJAAAAcQAKAAAADgAnAA4AKQFFDgEWDwAhAA4AIwFFDloAEgAOABMA"
1735     "DktLS0tLS0tLS0tLABEADgAuAA5aADIADloANgAOWgA6AA5aAD4ADloAQgAOWgBGAA5aAEoADloA"
1736     "TgAOWgBSAA5aAFYADloAWgAOWgBeATQOPDw8PDw8PDw8PDw8AAIEAUYYAwIFAjEECEEXLAIFAjEE"
1737     "CEEXKwIFAjEECEEXLQIGAUYcAxgAGAEYAgAAAAIAAAAMBwAAEgcAAAIAAAAMBwAAGwcAAAIAAAAM"
1738     "BwAAJAcAAAEAAAAtBwAAPAcAAAAAAAAAAAAAAAAAAEgHAAAAAAAAAAAAAAAAAABUBwAAAAAAAAAA"
1739     "AAAAAAAAYAcAAAAAAAAAAAAAAAAAAAEAAAAJAAAAAQAAAA0AAAACAACAgASsCAEIxAgAAAIAAoCA"
1740     "BIQJAQicCQwAAgAACQEJAQkBCQEJAQkBCQEJAQkBCQEJAQkEiIAEuAcBgIAEuAkAAA4ABoCABNAJ"
1741     "AQnoCQAJhAoACaAKAAm8CgAJ2AoACfQKAAmQCwAJrAsACcgLAAnkCwAJgAwACZwMAAm4DAg8Y2xp"
1742     "bml0PgAGPGluaXQ+AANBQUEAC0hlbGxvIFdvcmxkAAxIZWxsbyBXb3JsZDEADUhlbGxvIFdvcmxk"
1743     "MTAADUhlbGxvIFdvcmxkMTEADEhlbGxvIFdvcmxkMgAMSGVsbG8gV29ybGQzAAxIZWxsbyBXb3Js"
1744     "ZDQADEhlbGxvIFdvcmxkNQAMSGVsbG8gV29ybGQ2AAxIZWxsbyBXb3JsZDcADEhlbGxvIFdvcmxk"
1745     "OAAMSGVsbG8gV29ybGQ5AAFMAAJMTAAWTE1hbnlNZXRob2RzJFByaW50ZXIyOwAVTE1hbnlNZXRo"
1746     "b2RzJFByaW50ZXI7ABVMTWFueU1ldGhvZHMkU3RyaW5nczsADUxNYW55TWV0aG9kczsAIkxkYWx2"
1747     "aWsvYW5ub3RhdGlvbi9FbmNsb3NpbmdDbGFzczsAHkxkYWx2aWsvYW5ub3RhdGlvbi9Jbm5lckNs"
1748     "YXNzOwAhTGRhbHZpay9hbm5vdGF0aW9uL01lbWJlckNsYXNzZXM7ABVMamF2YS9pby9QcmludFN0"
1749     "cmVhbTsAEkxqYXZhL2xhbmcvT2JqZWN0OwASTGphdmEvbGFuZy9TdHJpbmc7ABlMamF2YS9sYW5n"
1750     "L1N0cmluZ0J1aWxkZXI7ABJMamF2YS9sYW5nL1N5c3RlbTsAEE1hbnlNZXRob2RzLmphdmEABVBy"
1751     "aW50AAZQcmludDAABlByaW50MQAHUHJpbnQxMAAHUHJpbnQxMQAGUHJpbnQyAAZQcmludDMABlBy"
1752     "aW50NAAGUHJpbnQ1AAZQcmludDYABlByaW50NwAGUHJpbnQ4AAZQcmludDkAB1ByaW50ZXIACFBy"
1753     "aW50ZXIyAAdTdHJpbmdzAAFWAAJWTAATW0xqYXZhL2xhbmcvU3RyaW5nOwALYWNjZXNzRmxhZ3MA"
1754     "BmFwcGVuZAAEYXJncwAEbWFpbgAEbXNnMAAEbXNnMQAFbXNnMTAABW1zZzExAARtc2cyAARtc2cz"
1755     "AARtc2c0AARtc2c1AARtc2c2AARtc2c3AARtc2c4AARtc2c5AARuYW1lAANvdXQAB3ByaW50bG4A"
1756     "AXMACHRvU3RyaW5nAAV2YWx1ZQBffn5EOHsibWluLWFwaSI6MTAwMDAsInNoYS0xIjoiZmViODZj"
1757     "MDA2ZWZhY2YxZDc5ODRiODVlMTc5MGZlZjdhNzY3YWViYyIsInZlcnNpb24iOiJ2MS4xLjUtZGV2"
1758     "In0AEAAAAAAAAAABAAAAAAAAAAEAAABIAAAAcAAAAAIAAAAOAAAAkAEAAAMAAAAFAAAAyAEAAAQA"
1759     "AAANAAAABAIAAAUAAAAZAAAAbAIAAAYAAAAEAAAANAMAAAEgAAAUAAAAuAMAAAMgAAAUAAAAkgYA"
1760     "AAQgAAAFAAAADAcAAAMQAAAEAAAAOQcAAAYgAAAEAAAAaAcAAAEQAAACAAAAqAcAAAAgAAAEAAAA"
1761     "tgcAAAIgAABIAAAAOAgAAAAQAAABAAAA0AsAAAAAAAA=";
1762 
WriteBase64ToFile(const char * base64,File * file)1763 static void WriteBase64ToFile(const char* base64, File* file) {
1764   // Decode base64.
1765   CHECK(base64 != nullptr);
1766   size_t length;
1767   std::unique_ptr<uint8_t[]> bytes(DecodeBase64(base64, &length));
1768   CHECK(bytes != nullptr);
1769   if (!file->WriteFully(bytes.get(), length)) {
1770     PLOG(FATAL) << "Failed to write base64 as file";
1771   }
1772 }
1773 
TEST_F(Dex2oatTest,CompactDexGenerationFailure)1774 TEST_F(Dex2oatTest, CompactDexGenerationFailure) {
1775   ScratchFile temp_dex;
1776   WriteBase64ToFile(kDuplicateMethodInputDex, temp_dex.GetFile());
1777   std::string out_dir = GetScratchDir();
1778   const std::string oat_filename = out_dir + "/base.oat";
1779   // The dex won't pass the method verifier, only use the verify filter.
1780   ASSERT_TRUE(GenerateOdexForTest(temp_dex.GetFilename(),
1781                                   oat_filename,
1782                                   CompilerFilter::Filter::kVerify,
1783                                   { },
1784                                   /*expect_success=*/ true,
1785                                   /*use_fd=*/ false,
1786                                   /*use_zip_fd=*/ false,
1787                                   [](const OatFile& o) {
1788                                     CHECK(o.ContainsDexCode());
1789                                   }));
1790   // Open our generated oat file.
1791   std::string error_msg;
1792   std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
1793                                                    oat_filename.c_str(),
1794                                                    oat_filename.c_str(),
1795                                                    /*executable=*/ false,
1796                                                    /*low_4gb=*/ false,
1797                                                    temp_dex.GetFilename(),
1798                                                    &error_msg));
1799   ASSERT_TRUE(odex_file != nullptr);
1800   std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
1801   ASSERT_EQ(oat_dex_files.size(), 1u);
1802   // The dexes should have failed to convert to compact dex.
1803   for (const OatDexFile* oat_dex : oat_dex_files) {
1804     std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1805     ASSERT_TRUE(dex_file != nullptr) << error_msg;
1806     ASSERT_TRUE(!dex_file->IsCompactDexFile());
1807   }
1808 }
1809 
TEST_F(Dex2oatTest,CompactDexGenerationFailureMultiDex)1810 TEST_F(Dex2oatTest, CompactDexGenerationFailureMultiDex) {
1811   // Create a multidex file with only one dex that gets rejected for cdex conversion.
1812   ScratchFile apk_file;
1813   {
1814     FILE* file = fdopen(DupCloexec(apk_file.GetFd()), "w+b");
1815     ZipWriter writer(file);
1816     // Add vdex to zip.
1817     writer.StartEntry("classes.dex", ZipWriter::kCompress);
1818     size_t length = 0u;
1819     std::unique_ptr<uint8_t[]> bytes(DecodeBase64(kDuplicateMethodInputDex, &length));
1820     ASSERT_GE(writer.WriteBytes(&bytes[0], length), 0);
1821     writer.FinishEntry();
1822     writer.StartEntry("classes2.dex", ZipWriter::kCompress);
1823     std::unique_ptr<const DexFile> dex(OpenTestDexFile("ManyMethods"));
1824     ASSERT_GE(writer.WriteBytes(dex->Begin(), dex->Size()), 0);
1825     writer.FinishEntry();
1826     writer.Finish();
1827     ASSERT_EQ(apk_file.GetFile()->Flush(), 0);
1828   }
1829   const std::string& dex_location = apk_file.GetFilename();
1830   const std::string odex_location = GetOdexDir() + "/output.odex";
1831   ASSERT_TRUE(GenerateOdexForTest(dex_location,
1832                                   odex_location,
1833                                   CompilerFilter::kQuicken,
1834                                   { "--compact-dex-level=fast" },
1835                                   true));
1836 }
1837 
TEST_F(Dex2oatTest,StderrLoggerOutput)1838 TEST_F(Dex2oatTest, StderrLoggerOutput) {
1839   std::string dex_location = GetScratchDir() + "/Dex2OatStderrLoggerTest.jar";
1840   std::string odex_location = GetOdexDir() + "/Dex2OatStderrLoggerTest.odex";
1841 
1842   // Test file doesn't matter.
1843   Copy(GetDexSrc1(), dex_location);
1844 
1845   ASSERT_TRUE(GenerateOdexForTest(dex_location,
1846                                   odex_location,
1847                                   CompilerFilter::kQuicken,
1848                                   { "--runtime-arg", "-Xuse-stderr-logger" },
1849                                   true));
1850   // Look for some random part of dex2oat logging. With the stderr logger this should be captured,
1851   // even on device.
1852   EXPECT_NE(std::string::npos, output_.find("dex2oat took"));
1853 }
1854 
TEST_F(Dex2oatTest,VerifyCompilationReason)1855 TEST_F(Dex2oatTest, VerifyCompilationReason) {
1856   std::string dex_location = GetScratchDir() + "/Dex2OatCompilationReason.jar";
1857   std::string odex_location = GetOdexDir() + "/Dex2OatCompilationReason.odex";
1858 
1859   // Test file doesn't matter.
1860   Copy(GetDexSrc1(), dex_location);
1861 
1862   ASSERT_TRUE(GenerateOdexForTest(dex_location,
1863                                   odex_location,
1864                                   CompilerFilter::kVerify,
1865                                   { "--compilation-reason=install" },
1866                                   true));
1867   std::string error_msg;
1868   std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
1869                                                    odex_location.c_str(),
1870                                                    odex_location.c_str(),
1871                                                    /*executable=*/ false,
1872                                                    /*low_4gb=*/ false,
1873                                                    dex_location,
1874                                                    &error_msg));
1875   ASSERT_TRUE(odex_file != nullptr);
1876   ASSERT_STREQ("install", odex_file->GetCompilationReason());
1877 }
1878 
TEST_F(Dex2oatTest,VerifyNoCompilationReason)1879 TEST_F(Dex2oatTest, VerifyNoCompilationReason) {
1880   std::string dex_location = GetScratchDir() + "/Dex2OatNoCompilationReason.jar";
1881   std::string odex_location = GetOdexDir() + "/Dex2OatNoCompilationReason.odex";
1882 
1883   // Test file doesn't matter.
1884   Copy(GetDexSrc1(), dex_location);
1885 
1886   ASSERT_TRUE(GenerateOdexForTest(dex_location,
1887                                   odex_location,
1888                                   CompilerFilter::kVerify,
1889                                   {},
1890                                   true));
1891   std::string error_msg;
1892   std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
1893                                                    odex_location.c_str(),
1894                                                    odex_location.c_str(),
1895                                                    /*executable=*/ false,
1896                                                    /*low_4gb=*/ false,
1897                                                    dex_location,
1898                                                    &error_msg));
1899   ASSERT_TRUE(odex_file != nullptr);
1900   ASSERT_EQ(nullptr, odex_file->GetCompilationReason());
1901 }
1902 
TEST_F(Dex2oatTest,DontExtract)1903 TEST_F(Dex2oatTest, DontExtract) {
1904   std::unique_ptr<const DexFile> dex(OpenTestDexFile("ManyMethods"));
1905   std::string error_msg;
1906   const std::string out_dir = GetScratchDir();
1907   const std::string dex_location = dex->GetLocation();
1908   const std::string odex_location = out_dir + "/base.oat";
1909   const std::string vdex_location = out_dir + "/base.vdex";
1910   ASSERT_TRUE(GenerateOdexForTest(dex_location,
1911                                   odex_location,
1912                                   CompilerFilter::Filter::kVerify,
1913                                   { "--copy-dex-files=false" },
1914                                   /*expect_success=*/ true,
1915                                   /*use_fd=*/ false,
1916                                   /*use_zip_fd=*/ false,
1917                                   [](const OatFile&) {}));
1918   {
1919     // Check the vdex doesn't have dex.
1920     std::unique_ptr<VdexFile> vdex(VdexFile::Open(vdex_location.c_str(),
1921                                                   /*writable=*/ false,
1922                                                   /*low_4gb=*/ false,
1923                                                   /*unquicken=*/ false,
1924                                                   &error_msg));
1925     ASSERT_TRUE(vdex != nullptr);
1926     EXPECT_FALSE(vdex->HasDexSection()) << output_;
1927   }
1928   std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
1929                                                    odex_location.c_str(),
1930                                                    odex_location.c_str(),
1931                                                    /*executable=*/ false,
1932                                                    /*low_4gb=*/ false,
1933                                                    dex_location,
1934                                                    &error_msg));
1935   ASSERT_TRUE(odex_file != nullptr) << dex_location;
1936   std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
1937   ASSERT_EQ(oat_dex_files.size(), 1u);
1938   // Verify that the oat file can still open the dex files.
1939   for (const OatDexFile* oat_dex : oat_dex_files) {
1940     std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1941     ASSERT_TRUE(dex_file != nullptr) << error_msg;
1942   }
1943   // Create a dm file and use it to verify.
1944   // Add produced artifacts to a zip file that doesn't contain the classes.dex.
1945   ScratchFile dm_file;
1946   {
1947     std::unique_ptr<File> vdex_file(OS::OpenFileForReading(vdex_location.c_str()));
1948     ASSERT_TRUE(vdex_file != nullptr);
1949     ASSERT_GT(vdex_file->GetLength(), 0u);
1950     FILE* file = fdopen(DupCloexec(dm_file.GetFd()), "w+b");
1951     ZipWriter writer(file);
1952     auto write_all_bytes = [&](File* file) {
1953       std::unique_ptr<uint8_t[]> bytes(new uint8_t[file->GetLength()]);
1954       ASSERT_TRUE(file->ReadFully(&bytes[0], file->GetLength()));
1955       ASSERT_GE(writer.WriteBytes(&bytes[0], file->GetLength()), 0);
1956     };
1957     // Add vdex to zip.
1958     writer.StartEntry(VdexFile::kVdexNameInDmFile, ZipWriter::kCompress);
1959     write_all_bytes(vdex_file.get());
1960     writer.FinishEntry();
1961     writer.Finish();
1962     ASSERT_EQ(dm_file.GetFile()->Flush(), 0);
1963   }
1964 
1965   auto generate_and_check = [&](CompilerFilter::Filter filter) {
1966     output_.clear();
1967     ASSERT_TRUE(GenerateOdexForTest(dex_location,
1968                                     odex_location,
1969                                     filter,
1970                                     { "--dump-timings",
1971                                       "--dm-file=" + dm_file.GetFilename(),
1972                                       // Pass -Xuse-stderr-logger have dex2oat output in output_ on
1973                                       // target.
1974                                       "--runtime-arg",
1975                                       "-Xuse-stderr-logger" },
1976                                     /*expect_success=*/ true,
1977                                     /*use_fd=*/ false,
1978                                     /*use_zip_fd=*/ false,
1979                                     [](const OatFile& o) {
1980                                       CHECK(o.ContainsDexCode());
1981                                     }));
1982     // Check the output for "Fast verify", this is printed from --dump-timings.
1983     std::istringstream iss(output_);
1984     std::string line;
1985     bool found_fast_verify = false;
1986     const std::string kFastVerifyString = "Fast Verify";
1987     while (std::getline(iss, line) && !found_fast_verify) {
1988       found_fast_verify = found_fast_verify || line.find(kFastVerifyString) != std::string::npos;
1989     }
1990     EXPECT_TRUE(found_fast_verify) << "Expected to find " << kFastVerifyString << "\n" << output_;
1991   };
1992 
1993   // Generate a quickened dex by using the input dm file to verify.
1994   generate_and_check(CompilerFilter::Filter::kQuicken);
1995   // Use verify compiler filter to check that FastVerify works for that filter too.
1996   generate_and_check(CompilerFilter::Filter::kVerify);
1997 }
1998 
1999 // Test that dex files with quickened opcodes aren't dequickened.
TEST_F(Dex2oatTest,QuickenedInput)2000 TEST_F(Dex2oatTest, QuickenedInput) {
2001   std::string error_msg;
2002   ScratchFile temp_dex;
2003   MutateDexFile(temp_dex.GetFile(), GetTestDexFileName("ManyMethods"), [] (DexFile* dex) {
2004     bool mutated_successfully = false;
2005     // Change the dex instructions to make an opcode that spans past the end of the code item.
2006     for (ClassAccessor accessor : dex->GetClasses()) {
2007       for (const ClassAccessor::Method& method : accessor.GetMethods()) {
2008         CodeItemInstructionAccessor instructions = method.GetInstructions();
2009         // Make a quickened instruction that doesn't run past the end of the code item.
2010         if (instructions.InsnsSizeInCodeUnits() > 2) {
2011           const_cast<Instruction&>(instructions.InstructionAt(0)).SetOpcode(
2012               Instruction::IGET_BYTE_QUICK);
2013           mutated_successfully = true;
2014         }
2015       }
2016     }
2017     CHECK(mutated_successfully)
2018         << "Failed to find candidate code item with only one code unit in last instruction.";
2019   });
2020 
2021   const std::string& dex_location = temp_dex.GetFilename();
2022   std::string odex_location = GetOdexDir() + "/quickened.odex";
2023   std::string vdex_location = GetOdexDir() + "/quickened.vdex";
2024   std::unique_ptr<File> vdex_output(OS::CreateEmptyFile(vdex_location.c_str()));
2025   // Quicken the dex
2026   {
2027     std::string input_vdex = "--input-vdex-fd=-1";
2028     std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_output->Fd());
2029     ASSERT_TRUE(GenerateOdexForTest(dex_location,
2030                                     odex_location,
2031                                     CompilerFilter::kQuicken,
2032                                     // Disable cdex since we want to compare against the original
2033                                     // dex file after unquickening.
2034                                     { input_vdex, output_vdex, kDisableCompactDex },
2035                                     /* expect_success= */ true,
2036                                     /* use_fd= */ true));
2037   }
2038   // Unquicken by running the verify compiler filter on the vdex file and verify it matches.
2039   std::string odex_location2 = GetOdexDir() + "/unquickened.odex";
2040   std::string vdex_location2 = GetOdexDir() + "/unquickened.vdex";
2041   std::unique_ptr<File> vdex_unquickened(OS::CreateEmptyFile(vdex_location2.c_str()));
2042   {
2043     std::string input_vdex = StringPrintf("--input-vdex-fd=%d", vdex_output->Fd());
2044     std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_unquickened->Fd());
2045     ASSERT_TRUE(GenerateOdexForTest(dex_location,
2046                                     odex_location2,
2047                                     CompilerFilter::kVerify,
2048                                     // Disable cdex to avoid needing to write out the shared
2049                                     // section.
2050                                     { input_vdex, output_vdex, kDisableCompactDex },
2051                                     /* expect_success= */ true,
2052                                     /* use_fd= */ true));
2053   }
2054   ASSERT_EQ(vdex_unquickened->Flush(), 0) << "Could not flush and close vdex file";
2055   ASSERT_TRUE(success_);
2056   {
2057     // Check that hte vdex has one dex and compare it to the original one.
2058     std::unique_ptr<VdexFile> vdex(VdexFile::Open(vdex_location2.c_str(),
2059                                                   /*writable*/ false,
2060                                                   /*low_4gb*/ false,
2061                                                   /*unquicken*/ false,
2062                                                   &error_msg));
2063     std::vector<std::unique_ptr<const DexFile>> dex_files;
2064     bool result = vdex->OpenAllDexFiles(&dex_files, &error_msg);
2065     ASSERT_TRUE(result) << error_msg;
2066     ASSERT_EQ(dex_files.size(), 1u) << error_msg;
2067     ScratchFile temp;
2068     ASSERT_TRUE(temp.GetFile()->WriteFully(dex_files[0]->Begin(), dex_files[0]->Size()));
2069     ASSERT_EQ(temp.GetFile()->Flush(), 0) << "Could not flush extracted dex";
2070     EXPECT_EQ(temp.GetFile()->Compare(temp_dex.GetFile()), 0);
2071   }
2072   ASSERT_EQ(vdex_output->FlushCloseOrErase(), 0) << "Could not flush and close";
2073   ASSERT_EQ(vdex_unquickened->FlushCloseOrErase(), 0) << "Could not flush and close";
2074 }
2075 
2076 // Test that compact dex generation with invalid dex files doesn't crash dex2oat. b/75970654
TEST_F(Dex2oatTest,CompactDexInvalidSource)2077 TEST_F(Dex2oatTest, CompactDexInvalidSource) {
2078   ScratchFile invalid_dex;
2079   {
2080     FILE* file = fdopen(DupCloexec(invalid_dex.GetFd()), "w+b");
2081     ZipWriter writer(file);
2082     writer.StartEntry("classes.dex", ZipWriter::kAlign32);
2083     DexFile::Header header = {};
2084     StandardDexFile::WriteMagic(header.magic_);
2085     StandardDexFile::WriteCurrentVersion(header.magic_);
2086     header.file_size_ = 4 * KB;
2087     header.data_size_ = 4 * KB;
2088     header.data_off_ = 10 * MB;
2089     header.map_off_ = 10 * MB;
2090     header.class_defs_off_ = 10 * MB;
2091     header.class_defs_size_ = 10000;
2092     ASSERT_GE(writer.WriteBytes(&header, sizeof(header)), 0);
2093     writer.FinishEntry();
2094     writer.Finish();
2095     ASSERT_EQ(invalid_dex.GetFile()->Flush(), 0);
2096   }
2097   const std::string& dex_location = invalid_dex.GetFilename();
2098   const std::string odex_location = GetOdexDir() + "/output.odex";
2099   std::string error_msg;
2100   int status = GenerateOdexForTestWithStatus(
2101       {dex_location},
2102       odex_location,
2103       CompilerFilter::kQuicken,
2104       &error_msg,
2105       { "--compact-dex-level=fast" });
2106   ASSERT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) != 0) << status << " " << output_;
2107 }
2108 
2109 // Test that dex2oat with a CompactDex file in the APK fails.
TEST_F(Dex2oatTest,CompactDexInZip)2110 TEST_F(Dex2oatTest, CompactDexInZip) {
2111   CompactDexFile::Header header = {};
2112   CompactDexFile::WriteMagic(header.magic_);
2113   CompactDexFile::WriteCurrentVersion(header.magic_);
2114   header.file_size_ = sizeof(CompactDexFile::Header);
2115   header.data_off_ = 10 * MB;
2116   header.map_off_ = 10 * MB;
2117   header.class_defs_off_ = 10 * MB;
2118   header.class_defs_size_ = 10000;
2119   // Create a zip containing the invalid dex.
2120   ScratchFile invalid_dex_zip;
2121   {
2122     FILE* file = fdopen(DupCloexec(invalid_dex_zip.GetFd()), "w+b");
2123     ZipWriter writer(file);
2124     writer.StartEntry("classes.dex", ZipWriter::kCompress);
2125     ASSERT_GE(writer.WriteBytes(&header, sizeof(header)), 0);
2126     writer.FinishEntry();
2127     writer.Finish();
2128     ASSERT_EQ(invalid_dex_zip.GetFile()->Flush(), 0);
2129   }
2130   // Create the dex file directly.
2131   ScratchFile invalid_dex;
2132   {
2133     ASSERT_GE(invalid_dex.GetFile()->WriteFully(&header, sizeof(header)), 0);
2134     ASSERT_EQ(invalid_dex.GetFile()->Flush(), 0);
2135   }
2136   std::string error_msg;
2137   int status = 0u;
2138 
2139   status = GenerateOdexForTestWithStatus(
2140       { invalid_dex_zip.GetFilename() },
2141       GetOdexDir() + "/output_apk.odex",
2142       CompilerFilter::kQuicken,
2143       &error_msg,
2144       { "--compact-dex-level=fast" });
2145   ASSERT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) != 0) << status << " " << output_;
2146 
2147   status = GenerateOdexForTestWithStatus(
2148       { invalid_dex.GetFilename() },
2149       GetOdexDir() + "/output.odex",
2150       CompilerFilter::kQuicken,
2151       &error_msg,
2152       { "--compact-dex-level=fast" });
2153   ASSERT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) != 0) << status << " " << output_;
2154 }
2155 
TEST_F(Dex2oatTest,AppImageNoProfile)2156 TEST_F(Dex2oatTest, AppImageNoProfile) {
2157   ScratchFile app_image_file;
2158   const std::string out_dir = GetScratchDir();
2159   const std::string odex_location = out_dir + "/base.odex";
2160   ASSERT_TRUE(GenerateOdexForTest(GetTestDexFileName("ManyMethods"),
2161                                   odex_location,
2162                                   CompilerFilter::Filter::kSpeedProfile,
2163                                   { "--app-image-fd=" + std::to_string(app_image_file.GetFd()) },
2164                                   /*expect_success=*/ true,
2165                                   /*use_fd=*/ false,
2166                                   /*use_zip_fd=*/ false,
2167                                   [](const OatFile&) {}));
2168   // Open our generated oat file.
2169   std::string error_msg;
2170   std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
2171                                                    odex_location.c_str(),
2172                                                    odex_location.c_str(),
2173                                                    /*executable=*/ false,
2174                                                    /*low_4gb=*/ false,
2175                                                    &error_msg));
2176   ASSERT_TRUE(odex_file != nullptr);
2177   ImageHeader header = {};
2178   ASSERT_TRUE(app_image_file.GetFile()->PreadFully(
2179       reinterpret_cast<void*>(&header),
2180       sizeof(header),
2181       /*offset*/ 0u)) << app_image_file.GetFile()->GetLength();
2182   EXPECT_GT(header.GetImageSection(ImageHeader::kSectionObjects).Size(), 0u);
2183   EXPECT_EQ(header.GetImageSection(ImageHeader::kSectionArtMethods).Size(), 0u);
2184   EXPECT_EQ(header.GetImageSection(ImageHeader::kSectionArtFields).Size(), 0u);
2185 }
2186 
TEST_F(Dex2oatTest,ZipFd)2187 TEST_F(Dex2oatTest, ZipFd) {
2188   std::string zip_location = GetTestDexFileName("MainUncompressedAligned");
2189   std::unique_ptr<File> dex_file(OS::OpenFileForReading(zip_location.c_str()));
2190   std::vector<std::string> extra_args{
2191       StringPrintf("--zip-fd=%d", dex_file->Fd()),
2192       "--zip-location=" + zip_location,
2193   };
2194   std::string out_dir = GetScratchDir();
2195   const std::string base_oat_name = out_dir + "/base.oat";
2196   ASSERT_TRUE(GenerateOdexForTest(zip_location,
2197                                   base_oat_name,
2198                                   CompilerFilter::Filter::kQuicken,
2199                                   extra_args,
2200                                   /*expect_success=*/ true,
2201                                   /*use_fd=*/ false,
2202                                   /*use_zip_fd=*/ true));
2203 }
2204 
TEST_F(Dex2oatTest,AppImageEmptyDex)2205 TEST_F(Dex2oatTest, AppImageEmptyDex) {
2206   // Create a profile with the startup method marked.
2207   ScratchFile profile_file;
2208   ScratchFile temp_dex;
2209   const std::string& dex_location = temp_dex.GetFilename();
2210   std::vector<uint16_t> methods;
2211   std::vector<dex::TypeIndex> classes;
2212   {
2213     MutateDexFile(temp_dex.GetFile(), GetTestDexFileName("StringLiterals"), [&] (DexFile* dex) {
2214       // Modify the header to make the dex file valid but empty.
2215       DexFile::Header* header = const_cast<DexFile::Header*>(&dex->GetHeader());
2216       header->string_ids_size_ = 0;
2217       header->string_ids_off_ = 0;
2218       header->type_ids_size_ = 0;
2219       header->type_ids_off_ = 0;
2220       header->proto_ids_size_ = 0;
2221       header->proto_ids_off_ = 0;
2222       header->field_ids_size_ = 0;
2223       header->field_ids_off_ = 0;
2224       header->method_ids_size_ = 0;
2225       header->method_ids_off_ = 0;
2226       header->class_defs_size_ = 0;
2227       header->class_defs_off_ = 0;
2228       ASSERT_GT(header->file_size_,
2229                 sizeof(*header) + sizeof(dex::MapList) + sizeof(dex::MapItem) * 2);
2230       // Move map list to be right after the header.
2231       header->map_off_ = sizeof(DexFile::Header);
2232       dex::MapList* map_list = const_cast<dex::MapList*>(dex->GetMapList());
2233       map_list->list_[0].type_ = DexFile::kDexTypeHeaderItem;
2234       map_list->list_[0].size_ = 1u;
2235       map_list->list_[0].offset_ = 0u;
2236       map_list->list_[1].type_ = DexFile::kDexTypeMapList;
2237       map_list->list_[1].size_ = 1u;
2238       map_list->list_[1].offset_ = header->map_off_;
2239       map_list->size_ = 2;
2240       header->data_off_ = header->map_off_;
2241       header->data_size_ = map_list->Size();
2242     });
2243   }
2244   std::unique_ptr<const DexFile> dex_file(OpenDexFile(temp_dex.GetFilename().c_str()));
2245   const std::string out_dir = GetScratchDir();
2246   const std::string odex_location = out_dir + "/base.odex";
2247   const std::string app_image_location = out_dir + "/base.art";
2248   ASSERT_TRUE(GenerateOdexForTest(dex_location,
2249                                   odex_location,
2250                                   CompilerFilter::Filter::kSpeedProfile,
2251                                   { "--app-image-file=" + app_image_location,
2252                                     "--resolve-startup-const-strings=true",
2253                                     "--profile-file=" + profile_file.GetFilename()},
2254                                   /*expect_success=*/ true,
2255                                   /*use_fd=*/ false,
2256                                   /*use_zip_fd=*/ false,
2257                                   [](const OatFile&) {}));
2258   // Open our generated oat file.
2259   std::string error_msg;
2260   std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
2261                                                    odex_location.c_str(),
2262                                                    odex_location.c_str(),
2263                                                    /*executable=*/ false,
2264                                                    /*low_4gb=*/ false,
2265                                                    &error_msg));
2266   ASSERT_TRUE(odex_file != nullptr);
2267 }
2268 
TEST_F(Dex2oatTest,DexFileFd)2269 TEST_F(Dex2oatTest, DexFileFd) {
2270   std::string error_msg;
2271   std::string zip_location = GetTestDexFileName("Main");
2272   std::unique_ptr<File> zip_file(OS::OpenFileForReading(zip_location.c_str()));
2273   ASSERT_NE(-1, zip_file->Fd());
2274 
2275   std::unique_ptr<ZipArchive> zip_archive(
2276       ZipArchive::OpenFromFd(zip_file->Release(), zip_location.c_str(), &error_msg));
2277   ASSERT_TRUE(zip_archive != nullptr);
2278 
2279   std::string entry_name = DexFileLoader::GetMultiDexClassesDexName(0);
2280   std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
2281   ASSERT_TRUE(entry != nullptr);
2282 
2283   ScratchFile dex_file;
2284   const std::string& dex_location = dex_file.GetFilename();
2285   const std::string base_oat_name = GetScratchDir() + "/base.oat";
2286 
2287   bool success = entry->ExtractToFile(*(dex_file.GetFile()), &error_msg);
2288   ASSERT_TRUE(success);
2289   ASSERT_EQ(0, lseek(dex_file.GetFd(), 0, SEEK_SET));
2290 
2291   std::vector<std::string> extra_args{
2292       StringPrintf("--zip-fd=%d", dex_file.GetFd()),
2293       "--zip-location=" + dex_location,
2294   };
2295   ASSERT_TRUE(GenerateOdexForTest(dex_location,
2296                                   base_oat_name,
2297                                   CompilerFilter::Filter::kQuicken,
2298                                   extra_args,
2299                                   /*expect_success=*/ true,
2300                                   /*use_fd=*/ false,
2301                                   /*use_zip_fd=*/ true));
2302 }
2303 
TEST_F(Dex2oatTest,AppImageResolveStrings)2304 TEST_F(Dex2oatTest, AppImageResolveStrings) {
2305   using Hotness = ProfileCompilationInfo::MethodHotness;
2306   // Create a profile with the startup method marked.
2307   ScratchFile profile_file;
2308   ScratchFile temp_dex;
2309   const std::string& dex_location = temp_dex.GetFilename();
2310   std::vector<uint16_t> methods;
2311   std::vector<dex::TypeIndex> classes;
2312   {
2313     MutateDexFile(temp_dex.GetFile(), GetTestDexFileName("StringLiterals"), [&] (DexFile* dex) {
2314       bool mutated_successfully = false;
2315       // Change the dex instructions to make an opcode that spans past the end of the code item.
2316       for (ClassAccessor accessor : dex->GetClasses()) {
2317         if (accessor.GetDescriptor() == std::string("LStringLiterals$StartupClass;")) {
2318           classes.push_back(accessor.GetClassIdx());
2319         }
2320         for (const ClassAccessor::Method& method : accessor.GetMethods()) {
2321           std::string method_name(dex->GetMethodName(dex->GetMethodId(method.GetIndex())));
2322           CodeItemInstructionAccessor instructions = method.GetInstructions();
2323           if (method_name == "startUpMethod2") {
2324             // Make an instruction that runs past the end of the code item and verify that it
2325             // doesn't cause dex2oat to crash.
2326             ASSERT_TRUE(instructions.begin() != instructions.end());
2327             DexInstructionIterator last_instruction = instructions.begin();
2328             for (auto dex_it = instructions.begin(); dex_it != instructions.end(); ++dex_it) {
2329               last_instruction = dex_it;
2330             }
2331             ASSERT_EQ(last_instruction->SizeInCodeUnits(), 1u);
2332             // Set the opcode to something that will go past the end of the code item.
2333             const_cast<Instruction&>(last_instruction.Inst()).SetOpcode(
2334                 Instruction::CONST_STRING_JUMBO);
2335             mutated_successfully = true;
2336             // Test that the safe iterator doesn't go past the end.
2337             SafeDexInstructionIterator it2(instructions.begin(), instructions.end());
2338             while (!it2.IsErrorState()) {
2339               ++it2;
2340             }
2341             EXPECT_TRUE(it2 == last_instruction);
2342             EXPECT_TRUE(it2 < instructions.end());
2343             methods.push_back(method.GetIndex());
2344             mutated_successfully = true;
2345           } else if (method_name == "startUpMethod") {
2346             methods.push_back(method.GetIndex());
2347           }
2348         }
2349       }
2350       CHECK(mutated_successfully)
2351           << "Failed to find candidate code item with only one code unit in last instruction.";
2352     });
2353   }
2354   std::unique_ptr<const DexFile> dex_file(OpenDexFile(temp_dex.GetFilename().c_str()));
2355   {
2356     ASSERT_GT(classes.size(), 0u);
2357     ASSERT_GT(methods.size(), 0u);
2358     // Here, we build the profile from the method lists.
2359     ProfileCompilationInfo info;
2360     info.AddClassesForDex(dex_file.get(), classes.begin(), classes.end());
2361     info.AddMethodsForDex(Hotness::kFlagStartup, dex_file.get(), methods.begin(), methods.end());
2362     // Save the profile since we want to use it with dex2oat to produce an oat file.
2363     ASSERT_TRUE(info.Save(profile_file.GetFd()));
2364   }
2365   const std::string out_dir = GetScratchDir();
2366   const std::string odex_location = out_dir + "/base.odex";
2367   const std::string app_image_location = out_dir + "/base.art";
2368   ASSERT_TRUE(GenerateOdexForTest(dex_location,
2369                                   odex_location,
2370                                   CompilerFilter::Filter::kSpeedProfile,
2371                                   { "--app-image-file=" + app_image_location,
2372                                     "--resolve-startup-const-strings=true",
2373                                     "--profile-file=" + profile_file.GetFilename()},
2374                                   /*expect_success=*/ true,
2375                                   /*use_fd=*/ false,
2376                                   /*use_zip_fd=*/ false,
2377                                   [](const OatFile&) {}));
2378   // Open our generated oat file.
2379   std::string error_msg;
2380   std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
2381                                                    odex_location.c_str(),
2382                                                    odex_location.c_str(),
2383                                                    /*executable=*/ false,
2384                                                    /*low_4gb=*/ false,
2385                                                    &error_msg));
2386   ASSERT_TRUE(odex_file != nullptr);
2387   // Check the strings in the app image intern table only contain the "startup" strigs.
2388   {
2389     ScopedObjectAccess soa(Thread::Current());
2390     std::unique_ptr<gc::space::ImageSpace> space =
2391         gc::space::ImageSpace::CreateFromAppImage(app_image_location.c_str(),
2392                                                   odex_file.get(),
2393                                                   &error_msg);
2394     ASSERT_TRUE(space != nullptr) << error_msg;
2395     std::set<std::string> seen;
2396     InternTable intern_table;
2397     intern_table.AddImageStringsToTable(space.get(), [&](InternTable::UnorderedSet& interns)
2398         REQUIRES_SHARED(Locks::mutator_lock_) {
2399       for (const GcRoot<mirror::String>& str : interns) {
2400         seen.insert(str.Read()->ToModifiedUtf8());
2401       }
2402     });
2403     // Ensure that the dex cache has a preresolved string array.
2404     std::set<std::string> preresolved_seen;
2405     bool saw_dexcache = false;
2406     space->GetLiveBitmap()->VisitAllMarked(
2407         [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
2408       if (obj->IsDexCache<kVerifyNone>()) {
2409         ObjPtr<mirror::DexCache> dex_cache = obj->AsDexCache();
2410         GcRoot<mirror::String>* preresolved_strings = dex_cache->GetPreResolvedStrings();
2411         ASSERT_EQ(dex_file->NumStringIds(), dex_cache->NumPreResolvedStrings());
2412         for (size_t i = 0; i < dex_cache->NumPreResolvedStrings(); ++i) {
2413           ObjPtr<mirror::String> string = preresolved_strings[i].Read<kWithoutReadBarrier>();
2414           if (string != nullptr) {
2415             preresolved_seen.insert(string->ToModifiedUtf8());
2416           }
2417         }
2418         saw_dexcache = true;
2419       }
2420     });
2421     ASSERT_TRUE(saw_dexcache);
2422     // Everything in the preresolved array should also be in the intern table.
2423     for (const std::string& str : preresolved_seen) {
2424       EXPECT_TRUE(seen.find(str) != seen.end());
2425     }
2426     // Normal methods
2427     EXPECT_TRUE(preresolved_seen.find("Loading ") != preresolved_seen.end());
2428     EXPECT_TRUE(preresolved_seen.find("Starting up") != preresolved_seen.end());
2429     EXPECT_TRUE(preresolved_seen.find("abcd.apk") != preresolved_seen.end());
2430     EXPECT_TRUE(seen.find("Unexpected error") == seen.end());
2431     EXPECT_TRUE(seen.find("Shutting down!") == seen.end());
2432     EXPECT_TRUE(preresolved_seen.find("Unexpected error") == preresolved_seen.end());
2433     EXPECT_TRUE(preresolved_seen.find("Shutting down!") == preresolved_seen.end());
2434     // Classes initializers
2435     EXPECT_TRUE(preresolved_seen.find("Startup init") != preresolved_seen.end());
2436     EXPECT_TRUE(seen.find("Other class init") == seen.end());
2437     EXPECT_TRUE(preresolved_seen.find("Other class init") == preresolved_seen.end());
2438     // Expect the sets match.
2439     EXPECT_GE(seen.size(), preresolved_seen.size());
2440 
2441     // Verify what strings are marked as boot image.
2442     std::set<std::string> boot_image_strings;
2443     std::set<std::string> app_image_strings;
2444 
2445     MutexLock mu(Thread::Current(), *Locks::intern_table_lock_);
2446     intern_table.VisitInterns([&](const GcRoot<mirror::String>& root)
2447         REQUIRES_SHARED(Locks::mutator_lock_) {
2448       boot_image_strings.insert(root.Read()->ToModifiedUtf8());
2449     }, /*visit_boot_images=*/true, /*visit_non_boot_images=*/false);
2450     intern_table.VisitInterns([&](const GcRoot<mirror::String>& root)
2451         REQUIRES_SHARED(Locks::mutator_lock_) {
2452       app_image_strings.insert(root.Read()->ToModifiedUtf8());
2453     }, /*visit_boot_images=*/false, /*visit_non_boot_images=*/true);
2454     EXPECT_EQ(boot_image_strings.size(), 0u);
2455     EXPECT_TRUE(app_image_strings == seen);
2456   }
2457 }
2458 
2459 
TEST_F(Dex2oatClassLoaderContextTest,StoredClassLoaderContext)2460 TEST_F(Dex2oatClassLoaderContextTest, StoredClassLoaderContext) {
2461   std::vector<std::unique_ptr<const DexFile>> dex_files = OpenTestDexFiles("MultiDex");
2462   const std::string out_dir = GetScratchDir();
2463   const std::string odex_location = out_dir + "/base.odex";
2464   const std::string valid_context = "PCL[" + dex_files[0]->GetLocation() + "]";
2465   const std::string stored_context = "PCL[/system/not_real_lib.jar]";
2466   std::string expected_stored_context = "PCL[";
2467   size_t index = 1;
2468   for (const std::unique_ptr<const DexFile>& dex_file : dex_files) {
2469     const bool is_first = index == 1u;
2470     if (!is_first) {
2471       expected_stored_context += ":";
2472     }
2473     expected_stored_context += "/system/not_real_lib.jar";
2474     if (!is_first) {
2475       expected_stored_context += "!classes" + std::to_string(index) + ".dex";
2476     }
2477     expected_stored_context += "*" + std::to_string(dex_file->GetLocationChecksum());
2478     ++index;
2479   }
2480   expected_stored_context +=    + "]";
2481   // The class path should not be valid and should fail being stored.
2482   EXPECT_TRUE(GenerateOdexForTest(GetTestDexFileName("ManyMethods"),
2483                                   odex_location,
2484                                   CompilerFilter::Filter::kQuicken,
2485                                   { "--class-loader-context=" + stored_context },
2486                                   /*expect_success=*/ true,
2487                                   /*use_fd=*/ false,
2488                                   /*use_zip_fd=*/ false,
2489                                   [&](const OatFile& oat_file) {
2490     EXPECT_NE(oat_file.GetClassLoaderContext(), stored_context) << output_;
2491     EXPECT_NE(oat_file.GetClassLoaderContext(), valid_context) << output_;
2492   }));
2493   // The stored context should match what we expect even though it's invalid.
2494   EXPECT_TRUE(GenerateOdexForTest(GetTestDexFileName("ManyMethods"),
2495                                   odex_location,
2496                                   CompilerFilter::Filter::kQuicken,
2497                                   { "--class-loader-context=" + valid_context,
2498                                     "--stored-class-loader-context=" + stored_context },
2499                                   /*expect_success=*/ true,
2500                                   /*use_fd=*/ false,
2501                                   /*use_zip_fd=*/ false,
2502                                   [&](const OatFile& oat_file) {
2503     EXPECT_EQ(oat_file.GetClassLoaderContext(), expected_stored_context) << output_;
2504   }));
2505 }
2506 
2507 class Dex2oatISAFeaturesRuntimeDetectionTest : public Dex2oatTest {
2508  protected:
RunTest(const std::vector<std::string> & extra_args={})2509   void RunTest(const std::vector<std::string>& extra_args = {}) {
2510     std::string dex_location = GetScratchDir() + "/Dex2OatSwapTest.jar";
2511     std::string odex_location = GetOdexDir() + "/Dex2OatSwapTest.odex";
2512 
2513     Copy(GetTestDexFileName(), dex_location);
2514 
2515     ASSERT_TRUE(GenerateOdexForTest(dex_location,
2516                                     odex_location,
2517                                     CompilerFilter::kSpeed,
2518                                     extra_args));
2519   }
2520 
GetTestDexFileName()2521   std::string GetTestDexFileName() {
2522     return GetDexSrc1();
2523   }
2524 };
2525 
TEST_F(Dex2oatISAFeaturesRuntimeDetectionTest,TestCurrentRuntimeFeaturesAsDex2OatArguments)2526 TEST_F(Dex2oatISAFeaturesRuntimeDetectionTest, TestCurrentRuntimeFeaturesAsDex2OatArguments) {
2527   std::vector<std::string> argv;
2528   Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv);
2529   auto option_pos =
2530       std::find(std::begin(argv), std::end(argv), "--instruction-set-features=runtime");
2531   if (InstructionSetFeatures::IsRuntimeDetectionSupported()) {
2532     EXPECT_TRUE(kIsTargetBuild);
2533     EXPECT_NE(option_pos, std::end(argv));
2534   } else {
2535     EXPECT_EQ(option_pos, std::end(argv));
2536   }
2537 
2538   RunTest();
2539 }
2540 
2541 class LinkageTest : public Dex2oatTest {};
2542 
TEST_F(LinkageTest,LinkageEnabled)2543 TEST_F(LinkageTest, LinkageEnabled) {
2544   TEST_DISABLED_FOR_TARGET();
2545   std::unique_ptr<const DexFile> dex(OpenTestDexFile("LinkageTest"));
2546   std::string out_dir = GetScratchDir();
2547   const std::string base_oat_name = out_dir + "/base.oat";
2548   std::string error_msg;
2549   const int res_fail = GenerateOdexForTestWithStatus(
2550         {dex->GetLocation()},
2551         base_oat_name,
2552         CompilerFilter::Filter::kQuicken,
2553         &error_msg,
2554         {"--check-linkage-conditions", "--crash-on-linkage-violation"});
2555   EXPECT_NE(0, res_fail);
2556 
2557   const int res_no_fail = GenerateOdexForTestWithStatus(
2558         {dex->GetLocation()},
2559         base_oat_name,
2560         CompilerFilter::Filter::kQuicken,
2561         &error_msg,
2562         {"--check-linkage-conditions"});
2563   EXPECT_EQ(0, res_no_fail);
2564 }
2565 
2566 }  // namespace art
2567