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