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
TEST_F(Dex2oatReturnCodeTest,TestCreateRuntime)1087 TEST_F(Dex2oatReturnCodeTest, TestCreateRuntime) {
1088 TEST_DISABLED_FOR_MEMORY_TOOL(); // b/19100793
1089 int status = RunTest({ "--boot-image=/this/does/not/exist/yolo.oat" });
1090 EXPECT_EQ(static_cast<int>(dex2oat::ReturnCode::kCreateRuntime), WEXITSTATUS(status)) << output_;
1091 }
1092
1093 class Dex2oatClassLoaderContextTest : public Dex2oatTest {
1094 protected:
RunTest(const char * class_loader_context,const char * expected_classpath_key,bool expected_success,bool use_second_source=false,bool generate_image=false)1095 void RunTest(const char* class_loader_context,
1096 const char* expected_classpath_key,
1097 bool expected_success,
1098 bool use_second_source = false,
1099 bool generate_image = false) {
1100 std::string dex_location = GetUsedDexLocation();
1101 std::string odex_location = GetUsedOatLocation();
1102
1103 Copy(use_second_source ? GetDexSrc2() : GetDexSrc1(), dex_location);
1104
1105 std::string error_msg;
1106 std::vector<std::string> extra_args;
1107 if (class_loader_context != nullptr) {
1108 extra_args.push_back(std::string("--class-loader-context=") + class_loader_context);
1109 }
1110 if (generate_image) {
1111 extra_args.push_back(std::string("--app-image-file=") + GetUsedImageLocation());
1112 }
1113 auto check_oat = [expected_classpath_key](const OatFile& oat_file) {
1114 ASSERT_TRUE(expected_classpath_key != nullptr);
1115 const char* classpath = oat_file.GetOatHeader().GetStoreValueByKey(OatHeader::kClassPathKey);
1116 ASSERT_TRUE(classpath != nullptr);
1117 ASSERT_STREQ(expected_classpath_key, classpath);
1118 };
1119
1120 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1121 odex_location,
1122 CompilerFilter::kQuicken,
1123 extra_args,
1124 expected_success,
1125 /*use_fd=*/ false,
1126 /*use_zip_fd=*/ false,
1127 check_oat));
1128 }
1129
GetUsedDexLocation()1130 std::string GetUsedDexLocation() {
1131 return GetScratchDir() + "/Context.jar";
1132 }
1133
GetUsedOatLocation()1134 std::string GetUsedOatLocation() {
1135 return GetOdexDir() + "/Context.odex";
1136 }
1137
GetUsedImageLocation()1138 std::string GetUsedImageLocation() {
1139 return GetOdexDir() + "/Context.art";
1140 }
1141
1142 const char* kEmptyClassPathKey = "PCL[]";
1143 };
1144
TEST_F(Dex2oatClassLoaderContextTest,InvalidContext)1145 TEST_F(Dex2oatClassLoaderContextTest, InvalidContext) {
1146 RunTest("Invalid[]", /*expected_classpath_key*/ nullptr, /*expected_success*/ false);
1147 }
1148
TEST_F(Dex2oatClassLoaderContextTest,EmptyContext)1149 TEST_F(Dex2oatClassLoaderContextTest, EmptyContext) {
1150 RunTest("PCL[]", kEmptyClassPathKey, /*expected_success*/ true);
1151 }
1152
TEST_F(Dex2oatClassLoaderContextTest,SpecialContext)1153 TEST_F(Dex2oatClassLoaderContextTest, SpecialContext) {
1154 RunTest(OatFile::kSpecialSharedLibrary,
1155 OatFile::kSpecialSharedLibrary,
1156 /*expected_success*/ true);
1157 }
1158
TEST_F(Dex2oatClassLoaderContextTest,ContextWithTheSourceDexFiles)1159 TEST_F(Dex2oatClassLoaderContextTest, ContextWithTheSourceDexFiles) {
1160 std::string context = "PCL[" + GetUsedDexLocation() + "]";
1161 RunTest(context.c_str(), kEmptyClassPathKey, /*expected_success*/ true);
1162 }
1163
TEST_F(Dex2oatClassLoaderContextTest,ContextWithOtherDexFiles)1164 TEST_F(Dex2oatClassLoaderContextTest, ContextWithOtherDexFiles) {
1165 std::vector<std::unique_ptr<const DexFile>> dex_files = OpenTestDexFiles("Nested");
1166
1167 std::string context = "PCL[" + dex_files[0]->GetLocation() + "]";
1168 std::string expected_classpath_key = "PCL[" +
1169 dex_files[0]->GetLocation() + "*" + std::to_string(dex_files[0]->GetLocationChecksum()) + "]";
1170 RunTest(context.c_str(), expected_classpath_key.c_str(), true);
1171 }
1172
TEST_F(Dex2oatClassLoaderContextTest,ContextWithStrippedDexFiles)1173 TEST_F(Dex2oatClassLoaderContextTest, ContextWithStrippedDexFiles) {
1174 std::string stripped_classpath = GetScratchDir() + "/stripped_classpath.jar";
1175 Copy(GetStrippedDexSrc1(), stripped_classpath);
1176
1177 std::string context = "PCL[" + stripped_classpath + "]";
1178 // Expect an empty context because stripped dex files cannot be open.
1179 RunTest(context.c_str(), kEmptyClassPathKey , /*expected_success*/ true);
1180 }
1181
TEST_F(Dex2oatClassLoaderContextTest,ContextWithStrippedDexFilesBackedByOdex)1182 TEST_F(Dex2oatClassLoaderContextTest, ContextWithStrippedDexFilesBackedByOdex) {
1183 std::string stripped_classpath = GetScratchDir() + "/stripped_classpath.jar";
1184 std::string odex_for_classpath = GetOdexDir() + "/stripped_classpath.odex";
1185
1186 Copy(GetDexSrc1(), stripped_classpath);
1187
1188 ASSERT_TRUE(GenerateOdexForTest(stripped_classpath,
1189 odex_for_classpath,
1190 CompilerFilter::kQuicken,
1191 {},
1192 true));
1193
1194 // Strip the dex file
1195 Copy(GetStrippedDexSrc1(), stripped_classpath);
1196
1197 std::string context = "PCL[" + stripped_classpath + "]";
1198 std::string expected_classpath_key;
1199 {
1200 // Open the oat file to get the expected classpath.
1201 OatFileAssistant oat_file_assistant(stripped_classpath.c_str(), kRuntimeISA, false, false);
1202 std::unique_ptr<OatFile> oat_file(oat_file_assistant.GetBestOatFile());
1203 std::vector<std::unique_ptr<const DexFile>> oat_dex_files =
1204 OatFileAssistant::LoadDexFiles(*oat_file, stripped_classpath.c_str());
1205 expected_classpath_key = "PCL[";
1206 for (size_t i = 0; i < oat_dex_files.size(); i++) {
1207 if (i > 0) {
1208 expected_classpath_key + ":";
1209 }
1210 expected_classpath_key += oat_dex_files[i]->GetLocation() + "*" +
1211 std::to_string(oat_dex_files[i]->GetLocationChecksum());
1212 }
1213 expected_classpath_key += "]";
1214 }
1215
1216 RunTest(context.c_str(),
1217 expected_classpath_key.c_str(),
1218 /*expected_success*/ true,
1219 /*use_second_source*/ true);
1220 }
1221
TEST_F(Dex2oatClassLoaderContextTest,ContextWithNotExistentDexFiles)1222 TEST_F(Dex2oatClassLoaderContextTest, ContextWithNotExistentDexFiles) {
1223 std::string context = "PCL[does_not_exists.dex]";
1224 // Expect an empty context because stripped dex files cannot be open.
1225 RunTest(context.c_str(), kEmptyClassPathKey, /*expected_success*/ true);
1226 }
1227
TEST_F(Dex2oatClassLoaderContextTest,ChainContext)1228 TEST_F(Dex2oatClassLoaderContextTest, ChainContext) {
1229 std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested");
1230 std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex");
1231
1232 std::string context = "PCL[" + GetTestDexFileName("Nested") + "];" +
1233 "DLC[" + GetTestDexFileName("MultiDex") + "]";
1234 std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "];" +
1235 "DLC[" + CreateClassPathWithChecksums(dex_files2) + "]";
1236
1237 RunTest(context.c_str(), expected_classpath_key.c_str(), true);
1238 }
1239
TEST_F(Dex2oatClassLoaderContextTest,ContextWithSharedLibrary)1240 TEST_F(Dex2oatClassLoaderContextTest, ContextWithSharedLibrary) {
1241 std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested");
1242 std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex");
1243
1244 std::string context = "PCL[" + GetTestDexFileName("Nested") + "]" +
1245 "{PCL[" + GetTestDexFileName("MultiDex") + "]}";
1246 std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "]" +
1247 "{PCL[" + CreateClassPathWithChecksums(dex_files2) + "]}";
1248 RunTest(context.c_str(), expected_classpath_key.c_str(), true);
1249 }
1250
TEST_F(Dex2oatClassLoaderContextTest,ContextWithSharedLibraryAndImage)1251 TEST_F(Dex2oatClassLoaderContextTest, ContextWithSharedLibraryAndImage) {
1252 std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested");
1253 std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex");
1254
1255 std::string context = "PCL[" + GetTestDexFileName("Nested") + "]" +
1256 "{PCL[" + GetTestDexFileName("MultiDex") + "]}";
1257 std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "]" +
1258 "{PCL[" + CreateClassPathWithChecksums(dex_files2) + "]}";
1259 RunTest(context.c_str(),
1260 expected_classpath_key.c_str(),
1261 /*expected_success=*/ true,
1262 /*use_second_source=*/ false,
1263 /*generate_image=*/ true);
1264 }
1265
TEST_F(Dex2oatClassLoaderContextTest,ContextWithSameSharedLibrariesAndImage)1266 TEST_F(Dex2oatClassLoaderContextTest, ContextWithSameSharedLibrariesAndImage) {
1267 std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested");
1268 std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex");
1269
1270 std::string context = "PCL[" + GetTestDexFileName("Nested") + "]" +
1271 "{PCL[" + GetTestDexFileName("MultiDex") + "]" +
1272 "#PCL[" + GetTestDexFileName("MultiDex") + "]}";
1273 std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "]" +
1274 "{PCL[" + CreateClassPathWithChecksums(dex_files2) + "]" +
1275 "#PCL[" + CreateClassPathWithChecksums(dex_files2) + "]}";
1276 RunTest(context.c_str(),
1277 expected_classpath_key.c_str(),
1278 /*expected_success=*/ true,
1279 /*use_second_source=*/ false,
1280 /*generate_image=*/ true);
1281 }
1282
TEST_F(Dex2oatClassLoaderContextTest,ContextWithSharedLibrariesDependenciesAndImage)1283 TEST_F(Dex2oatClassLoaderContextTest, ContextWithSharedLibrariesDependenciesAndImage) {
1284 std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested");
1285 std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex");
1286
1287 std::string context = "PCL[" + GetTestDexFileName("Nested") + "]" +
1288 "{PCL[" + GetTestDexFileName("MultiDex") + "]" +
1289 "{PCL[" + GetTestDexFileName("Nested") + "]}}";
1290 std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "]" +
1291 "{PCL[" + CreateClassPathWithChecksums(dex_files2) + "]" +
1292 "{PCL[" + CreateClassPathWithChecksums(dex_files1) + "]}}";
1293 RunTest(context.c_str(),
1294 expected_classpath_key.c_str(),
1295 /*expected_success=*/ true,
1296 /*use_second_source=*/ false,
1297 /*generate_image=*/ true);
1298 }
1299
1300 class Dex2oatDeterminism : public Dex2oatTest {};
1301
TEST_F(Dex2oatDeterminism,UnloadCompile)1302 TEST_F(Dex2oatDeterminism, UnloadCompile) {
1303 Runtime* const runtime = Runtime::Current();
1304 std::string out_dir = GetScratchDir();
1305 const std::string base_oat_name = out_dir + "/base.oat";
1306 const std::string base_vdex_name = out_dir + "/base.vdex";
1307 const std::string unload_oat_name = out_dir + "/unload.oat";
1308 const std::string unload_vdex_name = out_dir + "/unload.vdex";
1309 const std::string no_unload_oat_name = out_dir + "/nounload.oat";
1310 const std::string no_unload_vdex_name = out_dir + "/nounload.vdex";
1311 const std::string app_image_name = out_dir + "/unload.art";
1312 std::string error_msg;
1313 const std::vector<gc::space::ImageSpace*>& spaces = runtime->GetHeap()->GetBootImageSpaces();
1314 ASSERT_GT(spaces.size(), 0u);
1315 const std::string image_location = spaces[0]->GetImageLocation();
1316 // Without passing in an app image, it will unload in between compilations.
1317 const int res = GenerateOdexForTestWithStatus(
1318 GetLibCoreDexFileNames(),
1319 base_oat_name,
1320 CompilerFilter::Filter::kQuicken,
1321 &error_msg,
1322 {"--force-determinism", "--avoid-storing-invocation"});
1323 ASSERT_EQ(res, 0);
1324 Copy(base_oat_name, unload_oat_name);
1325 Copy(base_vdex_name, unload_vdex_name);
1326 std::unique_ptr<File> unload_oat(OS::OpenFileForReading(unload_oat_name.c_str()));
1327 std::unique_ptr<File> unload_vdex(OS::OpenFileForReading(unload_vdex_name.c_str()));
1328 ASSERT_TRUE(unload_oat != nullptr);
1329 ASSERT_TRUE(unload_vdex != nullptr);
1330 EXPECT_GT(unload_oat->GetLength(), 0u);
1331 EXPECT_GT(unload_vdex->GetLength(), 0u);
1332 // Regenerate with an app image to disable the dex2oat unloading and verify that the output is
1333 // the same.
1334 const int res2 = GenerateOdexForTestWithStatus(
1335 GetLibCoreDexFileNames(),
1336 base_oat_name,
1337 CompilerFilter::Filter::kQuicken,
1338 &error_msg,
1339 {"--force-determinism", "--avoid-storing-invocation", "--app-image-file=" + app_image_name});
1340 ASSERT_EQ(res2, 0);
1341 Copy(base_oat_name, no_unload_oat_name);
1342 Copy(base_vdex_name, no_unload_vdex_name);
1343 std::unique_ptr<File> no_unload_oat(OS::OpenFileForReading(no_unload_oat_name.c_str()));
1344 std::unique_ptr<File> no_unload_vdex(OS::OpenFileForReading(no_unload_vdex_name.c_str()));
1345 ASSERT_TRUE(no_unload_oat != nullptr);
1346 ASSERT_TRUE(no_unload_vdex != nullptr);
1347 EXPECT_GT(no_unload_oat->GetLength(), 0u);
1348 EXPECT_GT(no_unload_vdex->GetLength(), 0u);
1349 // Verify that both of the files are the same (odex and vdex).
1350 EXPECT_EQ(unload_oat->GetLength(), no_unload_oat->GetLength());
1351 EXPECT_EQ(unload_vdex->GetLength(), no_unload_vdex->GetLength());
1352 EXPECT_EQ(unload_oat->Compare(no_unload_oat.get()), 0)
1353 << unload_oat_name << " " << no_unload_oat_name;
1354 EXPECT_EQ(unload_vdex->Compare(no_unload_vdex.get()), 0)
1355 << unload_vdex_name << " " << no_unload_vdex_name;
1356 // App image file.
1357 std::unique_ptr<File> app_image_file(OS::OpenFileForReading(app_image_name.c_str()));
1358 ASSERT_TRUE(app_image_file != nullptr);
1359 EXPECT_GT(app_image_file->GetLength(), 0u);
1360 }
1361
1362 // Test that dexlayout section info is correctly written to the oat file for profile based
1363 // compilation.
TEST_F(Dex2oatTest,LayoutSections)1364 TEST_F(Dex2oatTest, LayoutSections) {
1365 using Hotness = ProfileCompilationInfo::MethodHotness;
1366 std::unique_ptr<const DexFile> dex(OpenTestDexFile("ManyMethods"));
1367 ScratchFile profile_file;
1368 // We can only layout method indices with code items, figure out which ones have this property
1369 // first.
1370 std::vector<uint16_t> methods;
1371 {
1372 const dex::TypeId* type_id = dex->FindTypeId("LManyMethods;");
1373 dex::TypeIndex type_idx = dex->GetIndexForTypeId(*type_id);
1374 ClassAccessor accessor(*dex, *dex->FindClassDef(type_idx));
1375 std::set<size_t> code_item_offsets;
1376 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
1377 const uint16_t method_idx = method.GetIndex();
1378 const size_t code_item_offset = method.GetCodeItemOffset();
1379 if (code_item_offsets.insert(code_item_offset).second) {
1380 // Unique code item, add the method index.
1381 methods.push_back(method_idx);
1382 }
1383 }
1384 }
1385 ASSERT_GE(methods.size(), 8u);
1386 std::vector<uint16_t> hot_methods = {methods[1], methods[3], methods[5]};
1387 std::vector<uint16_t> startup_methods = {methods[1], methods[2], methods[7]};
1388 std::vector<uint16_t> post_methods = {methods[0], methods[2], methods[6]};
1389 // Here, we build the profile from the method lists.
1390 ProfileCompilationInfo info;
1391 info.AddMethodsForDex(
1392 static_cast<Hotness::Flag>(Hotness::kFlagHot | Hotness::kFlagStartup),
1393 dex.get(),
1394 hot_methods.begin(),
1395 hot_methods.end());
1396 info.AddMethodsForDex(
1397 Hotness::kFlagStartup,
1398 dex.get(),
1399 startup_methods.begin(),
1400 startup_methods.end());
1401 info.AddMethodsForDex(
1402 Hotness::kFlagPostStartup,
1403 dex.get(),
1404 post_methods.begin(),
1405 post_methods.end());
1406 for (uint16_t id : hot_methods) {
1407 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsHot());
1408 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsStartup());
1409 }
1410 for (uint16_t id : startup_methods) {
1411 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsStartup());
1412 }
1413 for (uint16_t id : post_methods) {
1414 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsPostStartup());
1415 }
1416 // Save the profile since we want to use it with dex2oat to produce an oat file.
1417 ASSERT_TRUE(info.Save(profile_file.GetFd()));
1418 // Generate a profile based odex.
1419 const std::string dir = GetScratchDir();
1420 const std::string oat_filename = dir + "/base.oat";
1421 const std::string vdex_filename = dir + "/base.vdex";
1422 std::string error_msg;
1423 const int res = GenerateOdexForTestWithStatus(
1424 {dex->GetLocation()},
1425 oat_filename,
1426 CompilerFilter::Filter::kQuicken,
1427 &error_msg,
1428 {"--profile-file=" + profile_file.GetFilename()});
1429 EXPECT_EQ(res, 0);
1430
1431 // Open our generated oat file.
1432 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
1433 oat_filename.c_str(),
1434 oat_filename.c_str(),
1435 /*executable=*/ false,
1436 /*low_4gb=*/ false,
1437 dex->GetLocation(),
1438 &error_msg));
1439 ASSERT_TRUE(odex_file != nullptr);
1440 std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
1441 ASSERT_EQ(oat_dex_files.size(), 1u);
1442 // Check that the code sections match what we expect.
1443 for (const OatDexFile* oat_dex : oat_dex_files) {
1444 const DexLayoutSections* const sections = oat_dex->GetDexLayoutSections();
1445 // Testing of logging the sections.
1446 ASSERT_TRUE(sections != nullptr);
1447 LOG(INFO) << *sections;
1448
1449 // Load the sections into temporary variables for convenience.
1450 const DexLayoutSection& code_section =
1451 sections->sections_[static_cast<size_t>(DexLayoutSections::SectionType::kSectionTypeCode)];
1452 const DexLayoutSection::Subsection& section_hot_code =
1453 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeHot)];
1454 const DexLayoutSection::Subsection& section_sometimes_used =
1455 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeSometimesUsed)];
1456 const DexLayoutSection::Subsection& section_startup_only =
1457 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeStartupOnly)];
1458 const DexLayoutSection::Subsection& section_unused =
1459 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeUnused)];
1460
1461 // All the sections should be non-empty.
1462 EXPECT_GT(section_hot_code.Size(), 0u);
1463 EXPECT_GT(section_sometimes_used.Size(), 0u);
1464 EXPECT_GT(section_startup_only.Size(), 0u);
1465 EXPECT_GT(section_unused.Size(), 0u);
1466
1467 // Open the dex file since we need to peek at the code items to verify the layout matches what
1468 // we expect.
1469 std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1470 ASSERT_TRUE(dex_file != nullptr) << error_msg;
1471 const dex::TypeId* type_id = dex_file->FindTypeId("LManyMethods;");
1472 ASSERT_TRUE(type_id != nullptr);
1473 dex::TypeIndex type_idx = dex_file->GetIndexForTypeId(*type_id);
1474 const dex::ClassDef* class_def = dex_file->FindClassDef(type_idx);
1475 ASSERT_TRUE(class_def != nullptr);
1476
1477 // Count how many code items are for each category, there should be at least one per category.
1478 size_t hot_count = 0;
1479 size_t post_startup_count = 0;
1480 size_t startup_count = 0;
1481 size_t unused_count = 0;
1482 // Visit all of the methdos of the main class and cross reference the method indices to their
1483 // corresponding code item offsets to verify the layout.
1484 ClassAccessor accessor(*dex_file, *class_def);
1485 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
1486 const size_t method_idx = method.GetIndex();
1487 const size_t code_item_offset = method.GetCodeItemOffset();
1488 const bool is_hot = ContainsElement(hot_methods, method_idx);
1489 const bool is_startup = ContainsElement(startup_methods, method_idx);
1490 const bool is_post_startup = ContainsElement(post_methods, method_idx);
1491 if (is_hot) {
1492 // Hot is highest precedence, check that the hot methods are in the hot section.
1493 EXPECT_TRUE(section_hot_code.Contains(code_item_offset));
1494 ++hot_count;
1495 } else if (is_post_startup) {
1496 // Post startup is sometimes used section.
1497 EXPECT_TRUE(section_sometimes_used.Contains(code_item_offset));
1498 ++post_startup_count;
1499 } else if (is_startup) {
1500 // Startup at this point means not hot or post startup, these must be startup only then.
1501 EXPECT_TRUE(section_startup_only.Contains(code_item_offset));
1502 ++startup_count;
1503 } else {
1504 if (section_unused.Contains(code_item_offset)) {
1505 // If no flags are set, the method should be unused ...
1506 ++unused_count;
1507 } else {
1508 // or this method is part of the last code item and the end is 4 byte aligned.
1509 for (const ClassAccessor::Method& method2 : accessor.GetMethods()) {
1510 EXPECT_LE(method2.GetCodeItemOffset(), code_item_offset);
1511 }
1512 uint32_t code_item_size = dex_file->FindCodeItemOffset(*class_def, method_idx);
1513 EXPECT_EQ((code_item_offset + code_item_size) % 4, 0u);
1514 }
1515 }
1516 }
1517 EXPECT_GT(hot_count, 0u);
1518 EXPECT_GT(post_startup_count, 0u);
1519 EXPECT_GT(startup_count, 0u);
1520 EXPECT_GT(unused_count, 0u);
1521 }
1522 }
1523
1524 // Test that generating compact dex works.
TEST_F(Dex2oatTest,GenerateCompactDex)1525 TEST_F(Dex2oatTest, GenerateCompactDex) {
1526 // Generate a compact dex based odex.
1527 const std::string dir = GetScratchDir();
1528 const std::string oat_filename = dir + "/base.oat";
1529 const std::string vdex_filename = dir + "/base.vdex";
1530 const std::string dex_location = GetTestDexFileName("MultiDex");
1531 std::string error_msg;
1532 const int res = GenerateOdexForTestWithStatus(
1533 { dex_location },
1534 oat_filename,
1535 CompilerFilter::Filter::kQuicken,
1536 &error_msg,
1537 {"--compact-dex-level=fast"});
1538 EXPECT_EQ(res, 0);
1539 // Open our generated oat file.
1540 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
1541 oat_filename.c_str(),
1542 oat_filename.c_str(),
1543 /*executable=*/ false,
1544 /*low_4gb=*/ false,
1545 dex_location,
1546 &error_msg));
1547 ASSERT_TRUE(odex_file != nullptr);
1548 std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
1549 ASSERT_GT(oat_dex_files.size(), 1u);
1550 // Check that each dex is a compact dex file.
1551 std::vector<std::unique_ptr<const CompactDexFile>> compact_dex_files;
1552 for (const OatDexFile* oat_dex : oat_dex_files) {
1553 std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1554 ASSERT_TRUE(dex_file != nullptr) << error_msg;
1555 ASSERT_TRUE(dex_file->IsCompactDexFile());
1556 compact_dex_files.push_back(
1557 std::unique_ptr<const CompactDexFile>(dex_file.release()->AsCompactDexFile()));
1558 }
1559 for (const std::unique_ptr<const CompactDexFile>& dex_file : compact_dex_files) {
1560 // Test that every code item is in the owned section.
1561 const CompactDexFile::Header& header = dex_file->GetHeader();
1562 EXPECT_LE(header.OwnedDataBegin(), header.OwnedDataEnd());
1563 EXPECT_LE(header.OwnedDataBegin(), header.data_size_);
1564 EXPECT_LE(header.OwnedDataEnd(), header.data_size_);
1565 for (ClassAccessor accessor : dex_file->GetClasses()) {
1566 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
1567 if (method.GetCodeItemOffset() != 0u) {
1568 ASSERT_GE(method.GetCodeItemOffset(), header.OwnedDataBegin());
1569 ASSERT_LT(method.GetCodeItemOffset(), header.OwnedDataEnd());
1570 }
1571 }
1572 }
1573 // Test that the owned sections don't overlap.
1574 for (const std::unique_ptr<const CompactDexFile>& other_dex : compact_dex_files) {
1575 if (dex_file != other_dex) {
1576 ASSERT_TRUE(
1577 (dex_file->GetHeader().OwnedDataBegin() >= other_dex->GetHeader().OwnedDataEnd()) ||
1578 (dex_file->GetHeader().OwnedDataEnd() <= other_dex->GetHeader().OwnedDataBegin()));
1579 }
1580 }
1581 }
1582 }
1583
1584 class Dex2oatVerifierAbort : public Dex2oatTest {};
1585
TEST_F(Dex2oatVerifierAbort,HardFail)1586 TEST_F(Dex2oatVerifierAbort, HardFail) {
1587 // Use VerifierDeps as it has hard-failing classes.
1588 std::unique_ptr<const DexFile> dex(OpenTestDexFile("VerifierDeps"));
1589 std::string out_dir = GetScratchDir();
1590 const std::string base_oat_name = out_dir + "/base.oat";
1591 std::string error_msg;
1592 const int res_fail = GenerateOdexForTestWithStatus(
1593 {dex->GetLocation()},
1594 base_oat_name,
1595 CompilerFilter::Filter::kQuicken,
1596 &error_msg,
1597 {"--abort-on-hard-verifier-error"});
1598 EXPECT_NE(0, res_fail);
1599
1600 const int res_no_fail = GenerateOdexForTestWithStatus(
1601 {dex->GetLocation()},
1602 base_oat_name,
1603 CompilerFilter::Filter::kQuicken,
1604 &error_msg,
1605 {"--no-abort-on-hard-verifier-error"});
1606 EXPECT_EQ(0, res_no_fail);
1607 }
1608
TEST_F(Dex2oatVerifierAbort,SoftFail)1609 TEST_F(Dex2oatVerifierAbort, SoftFail) {
1610 // Use VerifierDepsMulti as it has hard-failing classes.
1611 std::unique_ptr<const DexFile> dex(OpenTestDexFile("VerifierDepsMulti"));
1612 std::string out_dir = GetScratchDir();
1613 const std::string base_oat_name = out_dir + "/base.oat";
1614 std::string error_msg;
1615 const int res_fail = GenerateOdexForTestWithStatus(
1616 {dex->GetLocation()},
1617 base_oat_name,
1618 CompilerFilter::Filter::kQuicken,
1619 &error_msg,
1620 {"--abort-on-soft-verifier-error"});
1621 EXPECT_NE(0, res_fail);
1622
1623 const int res_no_fail = GenerateOdexForTestWithStatus(
1624 {dex->GetLocation()},
1625 base_oat_name,
1626 CompilerFilter::Filter::kQuicken,
1627 &error_msg,
1628 {"--no-abort-on-soft-verifier-error"});
1629 EXPECT_EQ(0, res_no_fail);
1630 }
1631
1632 class Dex2oatDedupeCode : public Dex2oatTest {};
1633
TEST_F(Dex2oatDedupeCode,DedupeTest)1634 TEST_F(Dex2oatDedupeCode, DedupeTest) {
1635 // Use MyClassNatives. It has lots of native methods that will produce deduplicate-able code.
1636 std::unique_ptr<const DexFile> dex(OpenTestDexFile("MyClassNatives"));
1637 std::string out_dir = GetScratchDir();
1638 const std::string base_oat_name = out_dir + "/base.oat";
1639 size_t no_dedupe_size = 0;
1640 ASSERT_TRUE(GenerateOdexForTest(dex->GetLocation(),
1641 base_oat_name,
1642 CompilerFilter::Filter::kSpeed,
1643 { "--deduplicate-code=false" },
1644 /*expect_success=*/ true,
1645 /*use_fd=*/ false,
1646 /*use_zip_fd=*/ false,
1647 [&no_dedupe_size](const OatFile& o) {
1648 no_dedupe_size = o.Size();
1649 }));
1650
1651 size_t dedupe_size = 0;
1652 ASSERT_TRUE(GenerateOdexForTest(dex->GetLocation(),
1653 base_oat_name,
1654 CompilerFilter::Filter::kSpeed,
1655 { "--deduplicate-code=true" },
1656 /*expect_success=*/ true,
1657 /*use_fd=*/ false,
1658 /*use_zip_fd=*/ false,
1659 [&dedupe_size](const OatFile& o) {
1660 dedupe_size = o.Size();
1661 }));
1662
1663 EXPECT_LT(dedupe_size, no_dedupe_size);
1664 }
1665
TEST_F(Dex2oatTest,UncompressedTest)1666 TEST_F(Dex2oatTest, UncompressedTest) {
1667 std::unique_ptr<const DexFile> dex(OpenTestDexFile("MainUncompressedAligned"));
1668 std::string out_dir = GetScratchDir();
1669 const std::string base_oat_name = out_dir + "/base.oat";
1670 ASSERT_TRUE(GenerateOdexForTest(dex->GetLocation(),
1671 base_oat_name,
1672 CompilerFilter::Filter::kQuicken,
1673 { },
1674 /*expect_success=*/ true,
1675 /*use_fd=*/ false,
1676 /*use_zip_fd=*/ false,
1677 [](const OatFile& o) {
1678 CHECK(!o.ContainsDexCode());
1679 }));
1680 }
1681
TEST_F(Dex2oatTest,EmptyUncompressedDexTest)1682 TEST_F(Dex2oatTest, EmptyUncompressedDexTest) {
1683 std::string out_dir = GetScratchDir();
1684 const std::string base_oat_name = out_dir + "/base.oat";
1685 std::string error_msg;
1686 int status = GenerateOdexForTestWithStatus(
1687 { GetTestDexFileName("MainEmptyUncompressed") },
1688 base_oat_name,
1689 CompilerFilter::Filter::kQuicken,
1690 &error_msg,
1691 { },
1692 /*use_fd*/ false);
1693 // Expect to fail with code 1 and not SIGSEGV or SIGABRT.
1694 ASSERT_TRUE(WIFEXITED(status));
1695 ASSERT_EQ(WEXITSTATUS(status), 1) << error_msg;
1696 }
1697
TEST_F(Dex2oatTest,EmptyUncompressedAlignedDexTest)1698 TEST_F(Dex2oatTest, EmptyUncompressedAlignedDexTest) {
1699 std::string out_dir = GetScratchDir();
1700 const std::string base_oat_name = out_dir + "/base.oat";
1701 std::string error_msg;
1702 int status = GenerateOdexForTestWithStatus(
1703 { GetTestDexFileName("MainEmptyUncompressedAligned") },
1704 base_oat_name,
1705 CompilerFilter::Filter::kQuicken,
1706 &error_msg,
1707 { },
1708 /*use_fd*/ false);
1709 // Expect to fail with code 1 and not SIGSEGV or SIGABRT.
1710 ASSERT_TRUE(WIFEXITED(status));
1711 ASSERT_EQ(WEXITSTATUS(status), 1) << error_msg;
1712 }
1713
1714 // Dex file that has duplicate methods have different code items and debug info.
1715 static const char kDuplicateMethodInputDex[] =
1716 "ZGV4CjAzOQDEy8VPdj4qHpgPYFWtLCtOykfFP4kB8tGYDAAAcAAAAHhWNBIAAAAAAAAAANALAABI"
1717 "AAAAcAAAAA4AAACQAQAABQAAAMgBAAANAAAABAIAABkAAABsAgAABAAAADQDAADgCAAAuAMAADgI"
1718 "AABCCAAASggAAE8IAABcCAAAaggAAHkIAACICAAAlggAAKQIAACyCAAAwAgAAM4IAADcCAAA6ggA"
1719 "APgIAAD7CAAA/wgAABcJAAAuCQAARQkAAFQJAAB4CQAAmAkAALsJAADSCQAA5gkAAPoJAAAVCgAA"
1720 "KQoAADsKAABCCgAASgoAAFIKAABbCgAAZAoAAGwKAAB0CgAAfAoAAIQKAACMCgAAlAoAAJwKAACk"
1721 "CgAArQoAALcKAADACgAAwwoAAMcKAADcCgAA6QoAAPEKAAD3CgAA/QoAAAMLAAAJCwAAEAsAABcL"
1722 "AAAdCwAAIwsAACkLAAAvCwAANQsAADsLAABBCwAARwsAAE0LAABSCwAAWwsAAF4LAABoCwAAbwsA"
1723 "ABEAAAASAAAAEwAAABQAAAAVAAAAFgAAABcAAAAYAAAAGQAAABoAAAAbAAAAHAAAAC4AAAAwAAAA"
1724 "DwAAAAkAAAAAAAAAEAAAAAoAAACoBwAALgAAAAwAAAAAAAAALwAAAAwAAACoBwAALwAAAAwAAACw"
1725 "BwAAAgAJADUAAAACAAkANgAAAAIACQA3AAAAAgAJADgAAAACAAkAOQAAAAIACQA6AAAAAgAJADsA"
1726 "AAACAAkAPAAAAAIACQA9AAAAAgAJAD4AAAACAAkAPwAAAAIACQBAAAAACwAHAEIAAAAAAAIAAQAA"
1727 "AAAAAwAeAAAAAQACAAEAAAABAAMAHgAAAAIAAgAAAAAAAgACAAEAAAADAAIAAQAAAAMAAgAfAAAA"
1728 "AwACACAAAAADAAIAIQAAAAMAAgAiAAAAAwACACMAAAADAAIAJAAAAAMAAgAlAAAAAwACACYAAAAD"
1729 "AAIAJwAAAAMAAgAoAAAAAwACACkAAAADAAIAKgAAAAMABAA0AAAABwADAEMAAAAIAAIAAQAAAAoA"
1730 "AgABAAAACgABADIAAAAKAAAARQAAAAAAAAAAAAAACAAAAAAAAAAdAAAAaAcAALYHAAAAAAAAAQAA"
1731 "AAAAAAAIAAAAAAAAAB0AAAB4BwAAxAcAAAAAAAACAAAAAAAAAAgAAAAAAAAAHQAAAIgHAADSBwAA"
1732 "AAAAAAMAAAAAAAAACAAAAAAAAAAdAAAAmAcAAPoHAAAAAAAAAAAAAAEAAAAAAAAArAYAADEAAAAa"
1733 "AAMAaQAAABoABABpAAEAGgAHAGkABAAaAAgAaQAFABoACQBpAAYAGgAKAGkABwAaAAsAaQAIABoA"
1734 "DABpAAkAGgANAGkACgAaAA4AaQALABoABQBpAAIAGgAGAGkAAwAOAAAAAQABAAEAAACSBgAABAAA"
1735 "AHAQFQAAAA4ABAABAAIAAACWBgAAFwAAAGIADAAiAQoAcBAWAAEAGgICAG4gFwAhAG4gFwAxAG4Q"
1736 "GAABAAwBbiAUABAADgAAAAEAAQABAAAAngYAAAQAAABwEBUAAAAOAAIAAQACAAAAogYAAAYAAABi"
1737 "AAwAbiAUABAADgABAAEAAQAAAKgGAAAEAAAAcBAVAAAADgABAAEAAQAAALsGAAAEAAAAcBAVAAAA"
1738 "DgABAAAAAQAAAL8GAAAGAAAAYgAAAHEQAwAAAA4AAQAAAAEAAADEBgAABgAAAGIAAQBxEAMAAAAO"
1739 "AAEAAAABAAAA8QYAAAYAAABiAAIAcRABAAAADgABAAAAAQAAAPYGAAAGAAAAYgADAHEQAwAAAA4A"
1740 "AQAAAAEAAADJBgAABgAAAGIABABxEAMAAAAOAAEAAAABAAAAzgYAAAYAAABiAAEAcRADAAAADgAB"
1741 "AAAAAQAAANMGAAAGAAAAYgAGAHEQAwAAAA4AAQAAAAEAAADYBgAABgAAAGIABwBxEAMAAAAOAAEA"
1742 "AAABAAAA3QYAAAYAAABiAAgAcRABAAAADgABAAAAAQAAAOIGAAAGAAAAYgAJAHEQAwAAAA4AAQAA"
1743 "AAEAAADnBgAABgAAAGIACgBxEAMAAAAOAAEAAAABAAAA7AYAAAYAAABiAAsAcRABAAAADgABAAEA"
1744 "AAAAAPsGAAAlAAAAcQAHAAAAcQAIAAAAcQALAAAAcQAMAAAAcQANAAAAcQAOAAAAcQAPAAAAcQAQ"
1745 "AAAAcQARAAAAcQASAAAAcQAJAAAAcQAKAAAADgAnAA4AKQFFDgEWDwAhAA4AIwFFDloAEgAOABMA"
1746 "DktLS0tLS0tLS0tLABEADgAuAA5aADIADloANgAOWgA6AA5aAD4ADloAQgAOWgBGAA5aAEoADloA"
1747 "TgAOWgBSAA5aAFYADloAWgAOWgBeATQOPDw8PDw8PDw8PDw8AAIEAUYYAwIFAjEECEEXLAIFAjEE"
1748 "CEEXKwIFAjEECEEXLQIGAUYcAxgAGAEYAgAAAAIAAAAMBwAAEgcAAAIAAAAMBwAAGwcAAAIAAAAM"
1749 "BwAAJAcAAAEAAAAtBwAAPAcAAAAAAAAAAAAAAAAAAEgHAAAAAAAAAAAAAAAAAABUBwAAAAAAAAAA"
1750 "AAAAAAAAYAcAAAAAAAAAAAAAAAAAAAEAAAAJAAAAAQAAAA0AAAACAACAgASsCAEIxAgAAAIAAoCA"
1751 "BIQJAQicCQwAAgAACQEJAQkBCQEJAQkBCQEJAQkBCQEJAQkEiIAEuAcBgIAEuAkAAA4ABoCABNAJ"
1752 "AQnoCQAJhAoACaAKAAm8CgAJ2AoACfQKAAmQCwAJrAsACcgLAAnkCwAJgAwACZwMAAm4DAg8Y2xp"
1753 "bml0PgAGPGluaXQ+AANBQUEAC0hlbGxvIFdvcmxkAAxIZWxsbyBXb3JsZDEADUhlbGxvIFdvcmxk"
1754 "MTAADUhlbGxvIFdvcmxkMTEADEhlbGxvIFdvcmxkMgAMSGVsbG8gV29ybGQzAAxIZWxsbyBXb3Js"
1755 "ZDQADEhlbGxvIFdvcmxkNQAMSGVsbG8gV29ybGQ2AAxIZWxsbyBXb3JsZDcADEhlbGxvIFdvcmxk"
1756 "OAAMSGVsbG8gV29ybGQ5AAFMAAJMTAAWTE1hbnlNZXRob2RzJFByaW50ZXIyOwAVTE1hbnlNZXRo"
1757 "b2RzJFByaW50ZXI7ABVMTWFueU1ldGhvZHMkU3RyaW5nczsADUxNYW55TWV0aG9kczsAIkxkYWx2"
1758 "aWsvYW5ub3RhdGlvbi9FbmNsb3NpbmdDbGFzczsAHkxkYWx2aWsvYW5ub3RhdGlvbi9Jbm5lckNs"
1759 "YXNzOwAhTGRhbHZpay9hbm5vdGF0aW9uL01lbWJlckNsYXNzZXM7ABVMamF2YS9pby9QcmludFN0"
1760 "cmVhbTsAEkxqYXZhL2xhbmcvT2JqZWN0OwASTGphdmEvbGFuZy9TdHJpbmc7ABlMamF2YS9sYW5n"
1761 "L1N0cmluZ0J1aWxkZXI7ABJMamF2YS9sYW5nL1N5c3RlbTsAEE1hbnlNZXRob2RzLmphdmEABVBy"
1762 "aW50AAZQcmludDAABlByaW50MQAHUHJpbnQxMAAHUHJpbnQxMQAGUHJpbnQyAAZQcmludDMABlBy"
1763 "aW50NAAGUHJpbnQ1AAZQcmludDYABlByaW50NwAGUHJpbnQ4AAZQcmludDkAB1ByaW50ZXIACFBy"
1764 "aW50ZXIyAAdTdHJpbmdzAAFWAAJWTAATW0xqYXZhL2xhbmcvU3RyaW5nOwALYWNjZXNzRmxhZ3MA"
1765 "BmFwcGVuZAAEYXJncwAEbWFpbgAEbXNnMAAEbXNnMQAFbXNnMTAABW1zZzExAARtc2cyAARtc2cz"
1766 "AARtc2c0AARtc2c1AARtc2c2AARtc2c3AARtc2c4AARtc2c5AARuYW1lAANvdXQAB3ByaW50bG4A"
1767 "AXMACHRvU3RyaW5nAAV2YWx1ZQBffn5EOHsibWluLWFwaSI6MTAwMDAsInNoYS0xIjoiZmViODZj"
1768 "MDA2ZWZhY2YxZDc5ODRiODVlMTc5MGZlZjdhNzY3YWViYyIsInZlcnNpb24iOiJ2MS4xLjUtZGV2"
1769 "In0AEAAAAAAAAAABAAAAAAAAAAEAAABIAAAAcAAAAAIAAAAOAAAAkAEAAAMAAAAFAAAAyAEAAAQA"
1770 "AAANAAAABAIAAAUAAAAZAAAAbAIAAAYAAAAEAAAANAMAAAEgAAAUAAAAuAMAAAMgAAAUAAAAkgYA"
1771 "AAQgAAAFAAAADAcAAAMQAAAEAAAAOQcAAAYgAAAEAAAAaAcAAAEQAAACAAAAqAcAAAAgAAAEAAAA"
1772 "tgcAAAIgAABIAAAAOAgAAAAQAAABAAAA0AsAAAAAAAA=";
1773
WriteBase64ToFile(const char * base64,File * file)1774 static void WriteBase64ToFile(const char* base64, File* file) {
1775 // Decode base64.
1776 CHECK(base64 != nullptr);
1777 size_t length;
1778 std::unique_ptr<uint8_t[]> bytes(DecodeBase64(base64, &length));
1779 CHECK(bytes != nullptr);
1780 if (!file->WriteFully(bytes.get(), length)) {
1781 PLOG(FATAL) << "Failed to write base64 as file";
1782 }
1783 }
1784
TEST_F(Dex2oatTest,CompactDexGenerationFailure)1785 TEST_F(Dex2oatTest, CompactDexGenerationFailure) {
1786 ScratchFile temp_dex;
1787 WriteBase64ToFile(kDuplicateMethodInputDex, temp_dex.GetFile());
1788 std::string out_dir = GetScratchDir();
1789 const std::string oat_filename = out_dir + "/base.oat";
1790 // The dex won't pass the method verifier, only use the verify filter.
1791 ASSERT_TRUE(GenerateOdexForTest(temp_dex.GetFilename(),
1792 oat_filename,
1793 CompilerFilter::Filter::kVerify,
1794 { },
1795 /*expect_success=*/ true,
1796 /*use_fd=*/ false,
1797 /*use_zip_fd=*/ false,
1798 [](const OatFile& o) {
1799 CHECK(o.ContainsDexCode());
1800 }));
1801 // Open our generated oat file.
1802 std::string error_msg;
1803 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
1804 oat_filename.c_str(),
1805 oat_filename.c_str(),
1806 /*executable=*/ false,
1807 /*low_4gb=*/ false,
1808 temp_dex.GetFilename(),
1809 &error_msg));
1810 ASSERT_TRUE(odex_file != nullptr);
1811 std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
1812 ASSERT_EQ(oat_dex_files.size(), 1u);
1813 // The dexes should have failed to convert to compact dex.
1814 for (const OatDexFile* oat_dex : oat_dex_files) {
1815 std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1816 ASSERT_TRUE(dex_file != nullptr) << error_msg;
1817 ASSERT_TRUE(!dex_file->IsCompactDexFile());
1818 }
1819 }
1820
TEST_F(Dex2oatTest,CompactDexGenerationFailureMultiDex)1821 TEST_F(Dex2oatTest, CompactDexGenerationFailureMultiDex) {
1822 // Create a multidex file with only one dex that gets rejected for cdex conversion.
1823 ScratchFile apk_file;
1824 {
1825 FILE* file = fdopen(DupCloexec(apk_file.GetFd()), "w+b");
1826 ZipWriter writer(file);
1827 // Add vdex to zip.
1828 writer.StartEntry("classes.dex", ZipWriter::kCompress);
1829 size_t length = 0u;
1830 std::unique_ptr<uint8_t[]> bytes(DecodeBase64(kDuplicateMethodInputDex, &length));
1831 ASSERT_GE(writer.WriteBytes(&bytes[0], length), 0);
1832 writer.FinishEntry();
1833 writer.StartEntry("classes2.dex", ZipWriter::kCompress);
1834 std::unique_ptr<const DexFile> dex(OpenTestDexFile("ManyMethods"));
1835 ASSERT_GE(writer.WriteBytes(dex->Begin(), dex->Size()), 0);
1836 writer.FinishEntry();
1837 writer.Finish();
1838 ASSERT_EQ(apk_file.GetFile()->Flush(), 0);
1839 }
1840 const std::string& dex_location = apk_file.GetFilename();
1841 const std::string odex_location = GetOdexDir() + "/output.odex";
1842 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1843 odex_location,
1844 CompilerFilter::kQuicken,
1845 { "--compact-dex-level=fast" },
1846 true));
1847 }
1848
TEST_F(Dex2oatTest,StderrLoggerOutput)1849 TEST_F(Dex2oatTest, StderrLoggerOutput) {
1850 std::string dex_location = GetScratchDir() + "/Dex2OatStderrLoggerTest.jar";
1851 std::string odex_location = GetOdexDir() + "/Dex2OatStderrLoggerTest.odex";
1852
1853 // Test file doesn't matter.
1854 Copy(GetDexSrc1(), dex_location);
1855
1856 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1857 odex_location,
1858 CompilerFilter::kQuicken,
1859 { "--runtime-arg", "-Xuse-stderr-logger" },
1860 true));
1861 // Look for some random part of dex2oat logging. With the stderr logger this should be captured,
1862 // even on device.
1863 EXPECT_NE(std::string::npos, output_.find("dex2oat took"));
1864 }
1865
TEST_F(Dex2oatTest,VerifyCompilationReason)1866 TEST_F(Dex2oatTest, VerifyCompilationReason) {
1867 std::string dex_location = GetScratchDir() + "/Dex2OatCompilationReason.jar";
1868 std::string odex_location = GetOdexDir() + "/Dex2OatCompilationReason.odex";
1869
1870 // Test file doesn't matter.
1871 Copy(GetDexSrc1(), dex_location);
1872
1873 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1874 odex_location,
1875 CompilerFilter::kVerify,
1876 { "--compilation-reason=install" },
1877 true));
1878 std::string error_msg;
1879 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
1880 odex_location.c_str(),
1881 odex_location.c_str(),
1882 /*executable=*/ false,
1883 /*low_4gb=*/ false,
1884 dex_location,
1885 &error_msg));
1886 ASSERT_TRUE(odex_file != nullptr);
1887 ASSERT_STREQ("install", odex_file->GetCompilationReason());
1888 }
1889
TEST_F(Dex2oatTest,VerifyNoCompilationReason)1890 TEST_F(Dex2oatTest, VerifyNoCompilationReason) {
1891 std::string dex_location = GetScratchDir() + "/Dex2OatNoCompilationReason.jar";
1892 std::string odex_location = GetOdexDir() + "/Dex2OatNoCompilationReason.odex";
1893
1894 // Test file doesn't matter.
1895 Copy(GetDexSrc1(), dex_location);
1896
1897 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1898 odex_location,
1899 CompilerFilter::kVerify,
1900 {},
1901 true));
1902 std::string error_msg;
1903 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
1904 odex_location.c_str(),
1905 odex_location.c_str(),
1906 /*executable=*/ false,
1907 /*low_4gb=*/ false,
1908 dex_location,
1909 &error_msg));
1910 ASSERT_TRUE(odex_file != nullptr);
1911 ASSERT_EQ(nullptr, odex_file->GetCompilationReason());
1912 }
1913
TEST_F(Dex2oatTest,DontExtract)1914 TEST_F(Dex2oatTest, DontExtract) {
1915 std::unique_ptr<const DexFile> dex(OpenTestDexFile("ManyMethods"));
1916 std::string error_msg;
1917 const std::string out_dir = GetScratchDir();
1918 const std::string dex_location = dex->GetLocation();
1919 const std::string odex_location = out_dir + "/base.oat";
1920 const std::string vdex_location = out_dir + "/base.vdex";
1921 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1922 odex_location,
1923 CompilerFilter::Filter::kVerify,
1924 { "--copy-dex-files=false" },
1925 /*expect_success=*/ true,
1926 /*use_fd=*/ false,
1927 /*use_zip_fd=*/ false,
1928 [](const OatFile&) {}));
1929 {
1930 // Check the vdex doesn't have dex.
1931 std::unique_ptr<VdexFile> vdex(VdexFile::Open(vdex_location.c_str(),
1932 /*writable=*/ false,
1933 /*low_4gb=*/ false,
1934 /*unquicken=*/ false,
1935 &error_msg));
1936 ASSERT_TRUE(vdex != nullptr);
1937 EXPECT_FALSE(vdex->HasDexSection()) << output_;
1938 }
1939 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
1940 odex_location.c_str(),
1941 odex_location.c_str(),
1942 /*executable=*/ false,
1943 /*low_4gb=*/ false,
1944 dex_location,
1945 &error_msg));
1946 ASSERT_TRUE(odex_file != nullptr) << dex_location;
1947 std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
1948 ASSERT_EQ(oat_dex_files.size(), 1u);
1949 // Verify that the oat file can still open the dex files.
1950 for (const OatDexFile* oat_dex : oat_dex_files) {
1951 std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1952 ASSERT_TRUE(dex_file != nullptr) << error_msg;
1953 }
1954 // Create a dm file and use it to verify.
1955 // Add produced artifacts to a zip file that doesn't contain the classes.dex.
1956 ScratchFile dm_file;
1957 {
1958 std::unique_ptr<File> vdex_file(OS::OpenFileForReading(vdex_location.c_str()));
1959 ASSERT_TRUE(vdex_file != nullptr);
1960 ASSERT_GT(vdex_file->GetLength(), 0u);
1961 FILE* file = fdopen(DupCloexec(dm_file.GetFd()), "w+b");
1962 ZipWriter writer(file);
1963 auto write_all_bytes = [&](File* file) {
1964 std::unique_ptr<uint8_t[]> bytes(new uint8_t[file->GetLength()]);
1965 ASSERT_TRUE(file->ReadFully(&bytes[0], file->GetLength()));
1966 ASSERT_GE(writer.WriteBytes(&bytes[0], file->GetLength()), 0);
1967 };
1968 // Add vdex to zip.
1969 writer.StartEntry(VdexFile::kVdexNameInDmFile, ZipWriter::kCompress);
1970 write_all_bytes(vdex_file.get());
1971 writer.FinishEntry();
1972 writer.Finish();
1973 ASSERT_EQ(dm_file.GetFile()->Flush(), 0);
1974 }
1975
1976 auto generate_and_check = [&](CompilerFilter::Filter filter) {
1977 output_.clear();
1978 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1979 odex_location,
1980 filter,
1981 { "--dump-timings",
1982 "--dm-file=" + dm_file.GetFilename(),
1983 // Pass -Xuse-stderr-logger have dex2oat output in output_ on
1984 // target.
1985 "--runtime-arg",
1986 "-Xuse-stderr-logger" },
1987 /*expect_success=*/ true,
1988 /*use_fd=*/ false,
1989 /*use_zip_fd=*/ false,
1990 [](const OatFile& o) {
1991 CHECK(o.ContainsDexCode());
1992 }));
1993 // Check the output for "Fast verify", this is printed from --dump-timings.
1994 std::istringstream iss(output_);
1995 std::string line;
1996 bool found_fast_verify = false;
1997 const std::string kFastVerifyString = "Fast Verify";
1998 while (std::getline(iss, line) && !found_fast_verify) {
1999 found_fast_verify = found_fast_verify || line.find(kFastVerifyString) != std::string::npos;
2000 }
2001 EXPECT_TRUE(found_fast_verify) << "Expected to find " << kFastVerifyString << "\n" << output_;
2002 };
2003
2004 // Generate a quickened dex by using the input dm file to verify.
2005 generate_and_check(CompilerFilter::Filter::kQuicken);
2006 // Use verify compiler filter to sanity check that FastVerify works for that filter too.
2007 generate_and_check(CompilerFilter::Filter::kVerify);
2008 }
2009
2010 // Test that dex files with quickened opcodes aren't dequickened.
TEST_F(Dex2oatTest,QuickenedInput)2011 TEST_F(Dex2oatTest, QuickenedInput) {
2012 std::string error_msg;
2013 ScratchFile temp_dex;
2014 MutateDexFile(temp_dex.GetFile(), GetTestDexFileName("ManyMethods"), [] (DexFile* dex) {
2015 bool mutated_successfully = false;
2016 // Change the dex instructions to make an opcode that spans past the end of the code item.
2017 for (ClassAccessor accessor : dex->GetClasses()) {
2018 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
2019 CodeItemInstructionAccessor instructions = method.GetInstructions();
2020 // Make a quickened instruction that doesn't run past the end of the code item.
2021 if (instructions.InsnsSizeInCodeUnits() > 2) {
2022 const_cast<Instruction&>(instructions.InstructionAt(0)).SetOpcode(
2023 Instruction::IGET_BYTE_QUICK);
2024 mutated_successfully = true;
2025 }
2026 }
2027 }
2028 CHECK(mutated_successfully)
2029 << "Failed to find candidate code item with only one code unit in last instruction.";
2030 });
2031
2032 const std::string& dex_location = temp_dex.GetFilename();
2033 std::string odex_location = GetOdexDir() + "/quickened.odex";
2034 std::string vdex_location = GetOdexDir() + "/quickened.vdex";
2035 std::unique_ptr<File> vdex_output(OS::CreateEmptyFile(vdex_location.c_str()));
2036 // Quicken the dex
2037 {
2038 std::string input_vdex = "--input-vdex-fd=-1";
2039 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_output->Fd());
2040 ASSERT_TRUE(GenerateOdexForTest(dex_location,
2041 odex_location,
2042 CompilerFilter::kQuicken,
2043 // Disable cdex since we want to compare against the original
2044 // dex file after unquickening.
2045 { input_vdex, output_vdex, kDisableCompactDex },
2046 /* expect_success= */ true,
2047 /* use_fd= */ true));
2048 }
2049 // Unquicken by running the verify compiler filter on the vdex file and verify it matches.
2050 std::string odex_location2 = GetOdexDir() + "/unquickened.odex";
2051 std::string vdex_location2 = GetOdexDir() + "/unquickened.vdex";
2052 std::unique_ptr<File> vdex_unquickened(OS::CreateEmptyFile(vdex_location2.c_str()));
2053 {
2054 std::string input_vdex = StringPrintf("--input-vdex-fd=%d", vdex_output->Fd());
2055 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_unquickened->Fd());
2056 ASSERT_TRUE(GenerateOdexForTest(dex_location,
2057 odex_location2,
2058 CompilerFilter::kVerify,
2059 // Disable cdex to avoid needing to write out the shared
2060 // section.
2061 { input_vdex, output_vdex, kDisableCompactDex },
2062 /* expect_success= */ true,
2063 /* use_fd= */ true));
2064 }
2065 ASSERT_EQ(vdex_unquickened->Flush(), 0) << "Could not flush and close vdex file";
2066 ASSERT_TRUE(success_);
2067 {
2068 // Check that hte vdex has one dex and compare it to the original one.
2069 std::unique_ptr<VdexFile> vdex(VdexFile::Open(vdex_location2.c_str(),
2070 /*writable*/ false,
2071 /*low_4gb*/ false,
2072 /*unquicken*/ false,
2073 &error_msg));
2074 std::vector<std::unique_ptr<const DexFile>> dex_files;
2075 bool result = vdex->OpenAllDexFiles(&dex_files, &error_msg);
2076 ASSERT_TRUE(result) << error_msg;
2077 ASSERT_EQ(dex_files.size(), 1u) << error_msg;
2078 ScratchFile temp;
2079 ASSERT_TRUE(temp.GetFile()->WriteFully(dex_files[0]->Begin(), dex_files[0]->Size()));
2080 ASSERT_EQ(temp.GetFile()->Flush(), 0) << "Could not flush extracted dex";
2081 EXPECT_EQ(temp.GetFile()->Compare(temp_dex.GetFile()), 0);
2082 }
2083 ASSERT_EQ(vdex_output->FlushCloseOrErase(), 0) << "Could not flush and close";
2084 ASSERT_EQ(vdex_unquickened->FlushCloseOrErase(), 0) << "Could not flush and close";
2085 }
2086
2087 // Test that compact dex generation with invalid dex files doesn't crash dex2oat. b/75970654
TEST_F(Dex2oatTest,CompactDexInvalidSource)2088 TEST_F(Dex2oatTest, CompactDexInvalidSource) {
2089 ScratchFile invalid_dex;
2090 {
2091 FILE* file = fdopen(DupCloexec(invalid_dex.GetFd()), "w+b");
2092 ZipWriter writer(file);
2093 writer.StartEntry("classes.dex", ZipWriter::kAlign32);
2094 DexFile::Header header = {};
2095 StandardDexFile::WriteMagic(header.magic_);
2096 StandardDexFile::WriteCurrentVersion(header.magic_);
2097 header.file_size_ = 4 * KB;
2098 header.data_size_ = 4 * KB;
2099 header.data_off_ = 10 * MB;
2100 header.map_off_ = 10 * MB;
2101 header.class_defs_off_ = 10 * MB;
2102 header.class_defs_size_ = 10000;
2103 ASSERT_GE(writer.WriteBytes(&header, sizeof(header)), 0);
2104 writer.FinishEntry();
2105 writer.Finish();
2106 ASSERT_EQ(invalid_dex.GetFile()->Flush(), 0);
2107 }
2108 const std::string& dex_location = invalid_dex.GetFilename();
2109 const std::string odex_location = GetOdexDir() + "/output.odex";
2110 std::string error_msg;
2111 int status = GenerateOdexForTestWithStatus(
2112 {dex_location},
2113 odex_location,
2114 CompilerFilter::kQuicken,
2115 &error_msg,
2116 { "--compact-dex-level=fast" });
2117 ASSERT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) != 0) << status << " " << output_;
2118 }
2119
2120 // Test that dex2oat with a CompactDex file in the APK fails.
TEST_F(Dex2oatTest,CompactDexInZip)2121 TEST_F(Dex2oatTest, CompactDexInZip) {
2122 CompactDexFile::Header header = {};
2123 CompactDexFile::WriteMagic(header.magic_);
2124 CompactDexFile::WriteCurrentVersion(header.magic_);
2125 header.file_size_ = sizeof(CompactDexFile::Header);
2126 header.data_off_ = 10 * MB;
2127 header.map_off_ = 10 * MB;
2128 header.class_defs_off_ = 10 * MB;
2129 header.class_defs_size_ = 10000;
2130 // Create a zip containing the invalid dex.
2131 ScratchFile invalid_dex_zip;
2132 {
2133 FILE* file = fdopen(DupCloexec(invalid_dex_zip.GetFd()), "w+b");
2134 ZipWriter writer(file);
2135 writer.StartEntry("classes.dex", ZipWriter::kCompress);
2136 ASSERT_GE(writer.WriteBytes(&header, sizeof(header)), 0);
2137 writer.FinishEntry();
2138 writer.Finish();
2139 ASSERT_EQ(invalid_dex_zip.GetFile()->Flush(), 0);
2140 }
2141 // Create the dex file directly.
2142 ScratchFile invalid_dex;
2143 {
2144 ASSERT_GE(invalid_dex.GetFile()->WriteFully(&header, sizeof(header)), 0);
2145 ASSERT_EQ(invalid_dex.GetFile()->Flush(), 0);
2146 }
2147 std::string error_msg;
2148 int status = 0u;
2149
2150 status = GenerateOdexForTestWithStatus(
2151 { invalid_dex_zip.GetFilename() },
2152 GetOdexDir() + "/output_apk.odex",
2153 CompilerFilter::kQuicken,
2154 &error_msg,
2155 { "--compact-dex-level=fast" });
2156 ASSERT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) != 0) << status << " " << output_;
2157
2158 status = GenerateOdexForTestWithStatus(
2159 { invalid_dex.GetFilename() },
2160 GetOdexDir() + "/output.odex",
2161 CompilerFilter::kQuicken,
2162 &error_msg,
2163 { "--compact-dex-level=fast" });
2164 ASSERT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) != 0) << status << " " << output_;
2165 }
2166
TEST_F(Dex2oatTest,AppImageNoProfile)2167 TEST_F(Dex2oatTest, AppImageNoProfile) {
2168 ScratchFile app_image_file;
2169 const std::string out_dir = GetScratchDir();
2170 const std::string odex_location = out_dir + "/base.odex";
2171 ASSERT_TRUE(GenerateOdexForTest(GetTestDexFileName("ManyMethods"),
2172 odex_location,
2173 CompilerFilter::Filter::kSpeedProfile,
2174 { "--app-image-fd=" + std::to_string(app_image_file.GetFd()) },
2175 /*expect_success=*/ true,
2176 /*use_fd=*/ false,
2177 /*use_zip_fd=*/ false,
2178 [](const OatFile&) {}));
2179 // Open our generated oat file.
2180 std::string error_msg;
2181 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
2182 odex_location.c_str(),
2183 odex_location.c_str(),
2184 /*executable=*/ false,
2185 /*low_4gb=*/ false,
2186 &error_msg));
2187 ASSERT_TRUE(odex_file != nullptr);
2188 ImageHeader header = {};
2189 ASSERT_TRUE(app_image_file.GetFile()->PreadFully(
2190 reinterpret_cast<void*>(&header),
2191 sizeof(header),
2192 /*offset*/ 0u)) << app_image_file.GetFile()->GetLength();
2193 EXPECT_GT(header.GetImageSection(ImageHeader::kSectionObjects).Size(), 0u);
2194 EXPECT_EQ(header.GetImageSection(ImageHeader::kSectionArtMethods).Size(), 0u);
2195 EXPECT_EQ(header.GetImageSection(ImageHeader::kSectionArtFields).Size(), 0u);
2196 }
2197
TEST_F(Dex2oatTest,ZipFd)2198 TEST_F(Dex2oatTest, ZipFd) {
2199 std::string zip_location = GetTestDexFileName("MainUncompressedAligned");
2200 std::unique_ptr<File> dex_file(OS::OpenFileForReading(zip_location.c_str()));
2201 std::vector<std::string> extra_args{
2202 StringPrintf("--zip-fd=%d", dex_file->Fd()),
2203 "--zip-location=" + zip_location,
2204 };
2205 std::string out_dir = GetScratchDir();
2206 const std::string base_oat_name = out_dir + "/base.oat";
2207 ASSERT_TRUE(GenerateOdexForTest(zip_location,
2208 base_oat_name,
2209 CompilerFilter::Filter::kQuicken,
2210 extra_args,
2211 /*expect_success=*/ true,
2212 /*use_fd=*/ false,
2213 /*use_zip_fd=*/ true));
2214 }
2215
TEST_F(Dex2oatTest,AppImageEmptyDex)2216 TEST_F(Dex2oatTest, AppImageEmptyDex) {
2217 // Create a profile with the startup method marked.
2218 ScratchFile profile_file;
2219 ScratchFile temp_dex;
2220 const std::string& dex_location = temp_dex.GetFilename();
2221 std::vector<uint16_t> methods;
2222 std::vector<dex::TypeIndex> classes;
2223 {
2224 MutateDexFile(temp_dex.GetFile(), GetTestDexFileName("StringLiterals"), [&] (DexFile* dex) {
2225 // Modify the header to make the dex file valid but empty.
2226 DexFile::Header* header = const_cast<DexFile::Header*>(&dex->GetHeader());
2227 header->string_ids_size_ = 0;
2228 header->string_ids_off_ = 0;
2229 header->type_ids_size_ = 0;
2230 header->type_ids_off_ = 0;
2231 header->proto_ids_size_ = 0;
2232 header->proto_ids_off_ = 0;
2233 header->field_ids_size_ = 0;
2234 header->field_ids_off_ = 0;
2235 header->method_ids_size_ = 0;
2236 header->method_ids_off_ = 0;
2237 header->class_defs_size_ = 0;
2238 header->class_defs_off_ = 0;
2239 ASSERT_GT(header->file_size_,
2240 sizeof(*header) + sizeof(dex::MapList) + sizeof(dex::MapItem) * 2);
2241 // Move map list to be right after the header.
2242 header->map_off_ = sizeof(DexFile::Header);
2243 dex::MapList* map_list = const_cast<dex::MapList*>(dex->GetMapList());
2244 map_list->list_[0].type_ = DexFile::kDexTypeHeaderItem;
2245 map_list->list_[0].size_ = 1u;
2246 map_list->list_[0].offset_ = 0u;
2247 map_list->list_[1].type_ = DexFile::kDexTypeMapList;
2248 map_list->list_[1].size_ = 1u;
2249 map_list->list_[1].offset_ = header->map_off_;
2250 map_list->size_ = 2;
2251 header->data_off_ = header->map_off_;
2252 header->data_size_ = map_list->Size();
2253 });
2254 }
2255 std::unique_ptr<const DexFile> dex_file(OpenDexFile(temp_dex.GetFilename().c_str()));
2256 const std::string out_dir = GetScratchDir();
2257 const std::string odex_location = out_dir + "/base.odex";
2258 const std::string app_image_location = out_dir + "/base.art";
2259 ASSERT_TRUE(GenerateOdexForTest(dex_location,
2260 odex_location,
2261 CompilerFilter::Filter::kSpeedProfile,
2262 { "--app-image-file=" + app_image_location,
2263 "--resolve-startup-const-strings=true",
2264 "--profile-file=" + profile_file.GetFilename()},
2265 /*expect_success=*/ true,
2266 /*use_fd=*/ false,
2267 /*use_zip_fd=*/ false,
2268 [](const OatFile&) {}));
2269 // Open our generated oat file.
2270 std::string error_msg;
2271 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
2272 odex_location.c_str(),
2273 odex_location.c_str(),
2274 /*executable=*/ false,
2275 /*low_4gb=*/ false,
2276 &error_msg));
2277 ASSERT_TRUE(odex_file != nullptr);
2278 }
2279
TEST_F(Dex2oatTest,DexFileFd)2280 TEST_F(Dex2oatTest, DexFileFd) {
2281 std::string error_msg;
2282 std::string zip_location = GetTestDexFileName("Main");
2283 std::unique_ptr<File> zip_file(OS::OpenFileForReading(zip_location.c_str()));
2284 ASSERT_NE(-1, zip_file->Fd());
2285
2286 std::unique_ptr<ZipArchive> zip_archive(
2287 ZipArchive::OpenFromFd(zip_file->Release(), zip_location.c_str(), &error_msg));
2288 ASSERT_TRUE(zip_archive != nullptr);
2289
2290 std::string entry_name = DexFileLoader::GetMultiDexClassesDexName(0);
2291 std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
2292 ASSERT_TRUE(entry != nullptr);
2293
2294 ScratchFile dex_file;
2295 const std::string& dex_location = dex_file.GetFilename();
2296 const std::string base_oat_name = GetScratchDir() + "/base.oat";
2297
2298 bool success = entry->ExtractToFile(*(dex_file.GetFile()), &error_msg);
2299 ASSERT_TRUE(success);
2300 ASSERT_EQ(0, lseek(dex_file.GetFd(), 0, SEEK_SET));
2301
2302 std::vector<std::string> extra_args{
2303 StringPrintf("--zip-fd=%d", dex_file.GetFd()),
2304 "--zip-location=" + dex_location,
2305 };
2306 ASSERT_TRUE(GenerateOdexForTest(dex_location,
2307 base_oat_name,
2308 CompilerFilter::Filter::kQuicken,
2309 extra_args,
2310 /*expect_success=*/ true,
2311 /*use_fd=*/ false,
2312 /*use_zip_fd=*/ true));
2313 }
2314
TEST_F(Dex2oatTest,AppImageResolveStrings)2315 TEST_F(Dex2oatTest, AppImageResolveStrings) {
2316 using Hotness = ProfileCompilationInfo::MethodHotness;
2317 // Create a profile with the startup method marked.
2318 ScratchFile profile_file;
2319 ScratchFile temp_dex;
2320 const std::string& dex_location = temp_dex.GetFilename();
2321 std::vector<uint16_t> methods;
2322 std::vector<dex::TypeIndex> classes;
2323 {
2324 MutateDexFile(temp_dex.GetFile(), GetTestDexFileName("StringLiterals"), [&] (DexFile* dex) {
2325 bool mutated_successfully = false;
2326 // Change the dex instructions to make an opcode that spans past the end of the code item.
2327 for (ClassAccessor accessor : dex->GetClasses()) {
2328 if (accessor.GetDescriptor() == std::string("LStringLiterals$StartupClass;")) {
2329 classes.push_back(accessor.GetClassIdx());
2330 }
2331 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
2332 std::string method_name(dex->GetMethodName(dex->GetMethodId(method.GetIndex())));
2333 CodeItemInstructionAccessor instructions = method.GetInstructions();
2334 if (method_name == "startUpMethod2") {
2335 // Make an instruction that runs past the end of the code item and verify that it
2336 // doesn't cause dex2oat to crash.
2337 ASSERT_TRUE(instructions.begin() != instructions.end());
2338 DexInstructionIterator last_instruction = instructions.begin();
2339 for (auto dex_it = instructions.begin(); dex_it != instructions.end(); ++dex_it) {
2340 last_instruction = dex_it;
2341 }
2342 ASSERT_EQ(last_instruction->SizeInCodeUnits(), 1u);
2343 // Set the opcode to something that will go past the end of the code item.
2344 const_cast<Instruction&>(last_instruction.Inst()).SetOpcode(
2345 Instruction::CONST_STRING_JUMBO);
2346 mutated_successfully = true;
2347 // Test that the safe iterator doesn't go past the end.
2348 SafeDexInstructionIterator it2(instructions.begin(), instructions.end());
2349 while (!it2.IsErrorState()) {
2350 ++it2;
2351 }
2352 EXPECT_TRUE(it2 == last_instruction);
2353 EXPECT_TRUE(it2 < instructions.end());
2354 methods.push_back(method.GetIndex());
2355 mutated_successfully = true;
2356 } else if (method_name == "startUpMethod") {
2357 methods.push_back(method.GetIndex());
2358 }
2359 }
2360 }
2361 CHECK(mutated_successfully)
2362 << "Failed to find candidate code item with only one code unit in last instruction.";
2363 });
2364 }
2365 std::unique_ptr<const DexFile> dex_file(OpenDexFile(temp_dex.GetFilename().c_str()));
2366 {
2367 ASSERT_GT(classes.size(), 0u);
2368 ASSERT_GT(methods.size(), 0u);
2369 // Here, we build the profile from the method lists.
2370 ProfileCompilationInfo info;
2371 info.AddClassesForDex(dex_file.get(), classes.begin(), classes.end());
2372 info.AddMethodsForDex(Hotness::kFlagStartup, dex_file.get(), methods.begin(), methods.end());
2373 // Save the profile since we want to use it with dex2oat to produce an oat file.
2374 ASSERT_TRUE(info.Save(profile_file.GetFd()));
2375 }
2376 const std::string out_dir = GetScratchDir();
2377 const std::string odex_location = out_dir + "/base.odex";
2378 const std::string app_image_location = out_dir + "/base.art";
2379 ASSERT_TRUE(GenerateOdexForTest(dex_location,
2380 odex_location,
2381 CompilerFilter::Filter::kSpeedProfile,
2382 { "--app-image-file=" + app_image_location,
2383 "--resolve-startup-const-strings=true",
2384 "--profile-file=" + profile_file.GetFilename()},
2385 /*expect_success=*/ true,
2386 /*use_fd=*/ false,
2387 /*use_zip_fd=*/ false,
2388 [](const OatFile&) {}));
2389 // Open our generated oat file.
2390 std::string error_msg;
2391 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
2392 odex_location.c_str(),
2393 odex_location.c_str(),
2394 /*executable=*/ false,
2395 /*low_4gb=*/ false,
2396 &error_msg));
2397 ASSERT_TRUE(odex_file != nullptr);
2398 // Check the strings in the app image intern table only contain the "startup" strigs.
2399 {
2400 ScopedObjectAccess soa(Thread::Current());
2401 std::unique_ptr<gc::space::ImageSpace> space =
2402 gc::space::ImageSpace::CreateFromAppImage(app_image_location.c_str(),
2403 odex_file.get(),
2404 &error_msg);
2405 ASSERT_TRUE(space != nullptr) << error_msg;
2406 std::set<std::string> seen;
2407 InternTable intern_table;
2408 intern_table.AddImageStringsToTable(space.get(), [&](InternTable::UnorderedSet& interns)
2409 REQUIRES_SHARED(Locks::mutator_lock_) {
2410 for (const GcRoot<mirror::String>& str : interns) {
2411 seen.insert(str.Read()->ToModifiedUtf8());
2412 }
2413 });
2414 // Ensure that the dex cache has a preresolved string array.
2415 std::set<std::string> preresolved_seen;
2416 bool saw_dexcache = false;
2417 space->GetLiveBitmap()->VisitAllMarked(
2418 [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
2419 if (obj->IsDexCache<kVerifyNone>()) {
2420 ObjPtr<mirror::DexCache> dex_cache = obj->AsDexCache();
2421 GcRoot<mirror::String>* preresolved_strings = dex_cache->GetPreResolvedStrings();
2422 ASSERT_EQ(dex_file->NumStringIds(), dex_cache->NumPreResolvedStrings());
2423 for (size_t i = 0; i < dex_cache->NumPreResolvedStrings(); ++i) {
2424 ObjPtr<mirror::String> string = preresolved_strings[i].Read<kWithoutReadBarrier>();
2425 if (string != nullptr) {
2426 preresolved_seen.insert(string->ToModifiedUtf8());
2427 }
2428 }
2429 saw_dexcache = true;
2430 }
2431 });
2432 ASSERT_TRUE(saw_dexcache);
2433 // Everything in the preresolved array should also be in the intern table.
2434 for (const std::string& str : preresolved_seen) {
2435 EXPECT_TRUE(seen.find(str) != seen.end());
2436 }
2437 // Normal methods
2438 EXPECT_TRUE(preresolved_seen.find("Loading ") != preresolved_seen.end());
2439 EXPECT_TRUE(preresolved_seen.find("Starting up") != preresolved_seen.end());
2440 EXPECT_TRUE(preresolved_seen.find("abcd.apk") != preresolved_seen.end());
2441 EXPECT_TRUE(seen.find("Unexpected error") == seen.end());
2442 EXPECT_TRUE(seen.find("Shutting down!") == seen.end());
2443 EXPECT_TRUE(preresolved_seen.find("Unexpected error") == preresolved_seen.end());
2444 EXPECT_TRUE(preresolved_seen.find("Shutting down!") == preresolved_seen.end());
2445 // Classes initializers
2446 EXPECT_TRUE(preresolved_seen.find("Startup init") != preresolved_seen.end());
2447 EXPECT_TRUE(seen.find("Other class init") == seen.end());
2448 EXPECT_TRUE(preresolved_seen.find("Other class init") == preresolved_seen.end());
2449 // Expect the sets match.
2450 EXPECT_GE(seen.size(), preresolved_seen.size());
2451
2452 // Verify what strings are marked as boot image.
2453 std::set<std::string> boot_image_strings;
2454 std::set<std::string> app_image_strings;
2455
2456 MutexLock mu(Thread::Current(), *Locks::intern_table_lock_);
2457 intern_table.VisitInterns([&](const GcRoot<mirror::String>& root)
2458 REQUIRES_SHARED(Locks::mutator_lock_) {
2459 boot_image_strings.insert(root.Read()->ToModifiedUtf8());
2460 }, /*visit_boot_images=*/true, /*visit_non_boot_images=*/false);
2461 intern_table.VisitInterns([&](const GcRoot<mirror::String>& root)
2462 REQUIRES_SHARED(Locks::mutator_lock_) {
2463 app_image_strings.insert(root.Read()->ToModifiedUtf8());
2464 }, /*visit_boot_images=*/false, /*visit_non_boot_images=*/true);
2465 EXPECT_EQ(boot_image_strings.size(), 0u);
2466 EXPECT_TRUE(app_image_strings == seen);
2467 }
2468 }
2469
2470
TEST_F(Dex2oatClassLoaderContextTest,StoredClassLoaderContext)2471 TEST_F(Dex2oatClassLoaderContextTest, StoredClassLoaderContext) {
2472 std::vector<std::unique_ptr<const DexFile>> dex_files = OpenTestDexFiles("MultiDex");
2473 const std::string out_dir = GetScratchDir();
2474 const std::string odex_location = out_dir + "/base.odex";
2475 const std::string valid_context = "PCL[" + dex_files[0]->GetLocation() + "]";
2476 const std::string stored_context = "PCL[/system/not_real_lib.jar]";
2477 std::string expected_stored_context = "PCL[";
2478 size_t index = 1;
2479 for (const std::unique_ptr<const DexFile>& dex_file : dex_files) {
2480 const bool is_first = index == 1u;
2481 if (!is_first) {
2482 expected_stored_context += ":";
2483 }
2484 expected_stored_context += "/system/not_real_lib.jar";
2485 if (!is_first) {
2486 expected_stored_context += "!classes" + std::to_string(index) + ".dex";
2487 }
2488 expected_stored_context += "*" + std::to_string(dex_file->GetLocationChecksum());
2489 ++index;
2490 }
2491 expected_stored_context += + "]";
2492 // The class path should not be valid and should fail being stored.
2493 EXPECT_TRUE(GenerateOdexForTest(GetTestDexFileName("ManyMethods"),
2494 odex_location,
2495 CompilerFilter::Filter::kQuicken,
2496 { "--class-loader-context=" + stored_context },
2497 /*expect_success=*/ true,
2498 /*use_fd=*/ false,
2499 /*use_zip_fd=*/ false,
2500 [&](const OatFile& oat_file) {
2501 EXPECT_NE(oat_file.GetClassLoaderContext(), stored_context) << output_;
2502 EXPECT_NE(oat_file.GetClassLoaderContext(), valid_context) << output_;
2503 }));
2504 // The stored context should match what we expect even though it's invalid.
2505 EXPECT_TRUE(GenerateOdexForTest(GetTestDexFileName("ManyMethods"),
2506 odex_location,
2507 CompilerFilter::Filter::kQuicken,
2508 { "--class-loader-context=" + valid_context,
2509 "--stored-class-loader-context=" + stored_context },
2510 /*expect_success=*/ true,
2511 /*use_fd=*/ false,
2512 /*use_zip_fd=*/ false,
2513 [&](const OatFile& oat_file) {
2514 EXPECT_EQ(oat_file.GetClassLoaderContext(), expected_stored_context) << output_;
2515 }));
2516 }
2517
2518 class Dex2oatISAFeaturesRuntimeDetectionTest : public Dex2oatTest {
2519 protected:
RunTest(const std::vector<std::string> & extra_args={})2520 void RunTest(const std::vector<std::string>& extra_args = {}) {
2521 std::string dex_location = GetScratchDir() + "/Dex2OatSwapTest.jar";
2522 std::string odex_location = GetOdexDir() + "/Dex2OatSwapTest.odex";
2523
2524 Copy(GetTestDexFileName(), dex_location);
2525
2526 ASSERT_TRUE(GenerateOdexForTest(dex_location,
2527 odex_location,
2528 CompilerFilter::kSpeed,
2529 extra_args));
2530 }
2531
GetTestDexFileName()2532 std::string GetTestDexFileName() {
2533 return GetDexSrc1();
2534 }
2535 };
2536
TEST_F(Dex2oatISAFeaturesRuntimeDetectionTest,TestCurrentRuntimeFeaturesAsDex2OatArguments)2537 TEST_F(Dex2oatISAFeaturesRuntimeDetectionTest, TestCurrentRuntimeFeaturesAsDex2OatArguments) {
2538 std::vector<std::string> argv;
2539 Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv);
2540 auto option_pos =
2541 std::find(std::begin(argv), std::end(argv), "--instruction-set-features=runtime");
2542 if (InstructionSetFeatures::IsRuntimeDetectionSupported()) {
2543 EXPECT_TRUE(kIsTargetBuild);
2544 EXPECT_NE(option_pos, std::end(argv));
2545 } else {
2546 EXPECT_EQ(option_pos, std::end(argv));
2547 }
2548
2549 RunTest();
2550 }
2551
2552 } // namespace art
2553