blob: 9ee532a4e399c325dee7e3ff1509f89e54d66daa [file] [log] [blame]
Andreas Gampee1459ae2016-06-29 09:36:30 -07001/*
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
Jiakai Zhang19f95682021-12-06 16:19:39 +000017#include <sys/wait.h>
18#include <unistd.h>
19
xueliang.zhong7f88c1a2018-11-06 11:42:41 +000020#include <algorithm>
Jiakai Zhang19f95682021-12-06 16:19:39 +000021#include <iterator>
Igor Murashkin5573c372017-11-16 13:34:30 -080022#include <regex>
Andreas Gampe7adeda82016-07-25 08:27:35 -070023#include <sstream>
Andreas Gampee1459ae2016-06-29 09:36:30 -070024#include <string>
25#include <vector>
Andreas Gampee1459ae2016-06-29 09:36:30 -070026
Jiakai Zhang19f95682021-12-06 16:19:39 +000027#include "android-base/logging.h"
28#include "android-base/macros.h"
29#include "android-base/stringprintf.h"
xueliang.zhong7f88c1a2018-11-06 11:42:41 +000030#include "arch/instruction_set_features.h"
Andreas Gampee1459ae2016-06-29 09:36:30 -070031#include "base/macros.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070032#include "base/mutex-inl.h"
Vladimir Marko21910692019-11-06 13:27:03 +000033#include "base/string_view_cpp20.h"
David Sehrc431b9d2018-03-02 12:01:51 -080034#include "base/utils.h"
wangshumin3949e5e2019-11-08 19:25:50 +080035#include "base/zip_archive.h"
Jiakai Zhang19f95682021-12-06 16:19:39 +000036#include "common_runtime_test.h"
David Sehr013fd802018-01-11 22:55:24 -080037#include "dex/art_dex_file_loader.h"
Mathieu Chartier05f90d12018-02-07 13:47:17 -080038#include "dex/base64_test_util.h"
David Sehr312f3b22018-03-19 08:39:26 -070039#include "dex/bytecode_utils.h"
Mathieu Chartier2242ef12018-07-23 18:14:13 -070040#include "dex/class_accessor-inl.h"
David Sehr9e734c72018-01-04 17:56:19 -080041#include "dex/code_item_accessors-inl.h"
42#include "dex/dex_file-inl.h"
43#include "dex/dex_file_loader.h"
Andreas Gampee1459ae2016-06-29 09:36:30 -070044#include "dex2oat_environment_test.h"
Vladimir Markoef8c3372021-03-17 15:01:42 +000045#include "elf_file.h"
46#include "elf_file_impl.h"
Andreas Gampee15b9b12018-10-29 12:54:27 -070047#include "gc_root-inl.h"
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -070048#include "intern_table-inl.h"
Andreas Gampe67f02822016-06-24 21:05:23 -070049#include "oat.h"
50#include "oat_file.h"
David Sehr82d046e2018-04-23 08:14:19 -070051#include "profile/profile_compilation_info.h"
Mathieu Chartier792111c2018-02-15 13:02:15 -080052#include "vdex_file.h"
53#include "ziparchive/zip_writer.h"
Andreas Gampee1459ae2016-06-29 09:36:30 -070054
Andreas Gampee1459ae2016-06-29 09:36:30 -070055namespace art {
56
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080057using android::base::StringPrintf;
58
Andreas Gampee1459ae2016-06-29 09:36:30 -070059class Dex2oatTest : public Dex2oatEnvironmentTest {
60 public:
Roland Levillainf73caca2018-08-24 17:19:07 +010061 void TearDown() override {
Andreas Gampee1459ae2016-06-29 09:36:30 -070062 Dex2oatEnvironmentTest::TearDown();
63
64 output_ = "";
65 error_msg_ = "";
Andreas Gampee1459ae2016-06-29 09:36:30 -070066 }
67
68 protected:
Mathieu Chartier9e050df2017-08-09 10:05:47 -070069 int GenerateOdexForTestWithStatus(const std::vector<std::string>& dex_locations,
Andreas Gampef7882972017-03-20 16:35:24 -070070 const std::string& odex_location,
71 CompilerFilter::Filter filter,
72 std::string* error_msg,
73 const std::vector<std::string>& extra_args = {},
74 bool use_fd = false) {
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080075 std::unique_ptr<File> oat_file;
Andreas Gampee1459ae2016-06-29 09:36:30 -070076 std::vector<std::string> args;
Mathieu Chartier9e050df2017-08-09 10:05:47 -070077 // Add dex file args.
78 for (const std::string& dex_location : dex_locations) {
79 args.push_back("--dex-file=" + dex_location);
80 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080081 if (use_fd) {
82 oat_file.reset(OS::CreateEmptyFile(odex_location.c_str()));
83 CHECK(oat_file != nullptr) << odex_location;
84 args.push_back("--oat-fd=" + std::to_string(oat_file->Fd()));
Mathieu Chartier046854b2017-03-01 17:16:22 -080085 args.push_back("--oat-location=" + odex_location);
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080086 } else {
87 args.push_back("--oat-file=" + odex_location);
88 }
Andreas Gampee1459ae2016-06-29 09:36:30 -070089 args.push_back("--compiler-filter=" + CompilerFilter::NameOfFilter(filter));
90 args.push_back("--runtime-arg");
91 args.push_back("-Xnorelocate");
92
Andreas Gampe50f9dc22018-11-05 10:29:43 -080093 // Unless otherwise stated, use a small amount of threads, so that potential aborts are
94 // shorter. This can be overridden with extra_args.
95 args.push_back("-j4");
96
Andreas Gampee1459ae2016-06-29 09:36:30 -070097 args.insert(args.end(), extra_args.begin(), extra_args.end());
98
Calin Juravle858cfd82020-11-23 19:21:09 -080099 int status = Dex2Oat(args, &output_, error_msg);
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800100 if (oat_file != nullptr) {
Andreas Gampef7882972017-03-20 16:35:24 -0700101 CHECK_EQ(oat_file->FlushClose(), 0) << "Could not flush and close oat file";
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800102 }
Andreas Gampef7882972017-03-20 16:35:24 -0700103 return status;
104 }
Andreas Gampee1459ae2016-06-29 09:36:30 -0700105
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800106 ::testing::AssertionResult GenerateOdexForTest(
Andreas Gampe641a4732017-08-24 13:21:35 -0700107 const std::string& dex_location,
108 const std::string& odex_location,
109 CompilerFilter::Filter filter,
110 const std::vector<std::string>& extra_args = {},
111 bool expect_success = true,
Vladimir Marko21910692019-11-06 13:27:03 +0000112 bool use_fd = false,
113 bool use_zip_fd = false) WARN_UNUSED {
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800114 return GenerateOdexForTest(dex_location,
115 odex_location,
116 filter,
117 extra_args,
118 expect_success,
119 use_fd,
Vladimir Marko21910692019-11-06 13:27:03 +0000120 use_zip_fd,
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800121 [](const OatFile&) {});
Andreas Gampe641a4732017-08-24 13:21:35 -0700122 }
123
Andreas Gampe80ddf272018-01-11 09:41:00 -0800124 bool test_accepts_odex_file_on_failure = false;
125
Andreas Gampe641a4732017-08-24 13:21:35 -0700126 template <typename T>
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800127 ::testing::AssertionResult GenerateOdexForTest(
Andreas Gampe641a4732017-08-24 13:21:35 -0700128 const std::string& dex_location,
129 const std::string& odex_location,
130 CompilerFilter::Filter filter,
131 const std::vector<std::string>& extra_args,
132 bool expect_success,
133 bool use_fd,
Vladimir Marko21910692019-11-06 13:27:03 +0000134 bool use_zip_fd,
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800135 T check_oat) WARN_UNUSED {
Vladimir Marko21910692019-11-06 13:27:03 +0000136 std::vector<std::string> dex_locations;
137 if (use_zip_fd) {
138 std::string loc_arg = "--zip-location=" + dex_location;
139 CHECK(std::any_of(extra_args.begin(),
140 extra_args.end(),
141 [&](const std::string& s) { return s == loc_arg; }));
142 CHECK(std::any_of(extra_args.begin(),
143 extra_args.end(),
144 [](const std::string& s) { return StartsWith(s, "--zip-fd="); }));
145 } else {
146 dex_locations.push_back(dex_location);
147 }
Andreas Gampef7882972017-03-20 16:35:24 -0700148 std::string error_msg;
Vladimir Marko21910692019-11-06 13:27:03 +0000149 int status = GenerateOdexForTestWithStatus(dex_locations,
Andreas Gampef7882972017-03-20 16:35:24 -0700150 odex_location,
151 filter,
152 &error_msg,
153 extra_args,
154 use_fd);
Andreas Gampe80ddf272018-01-11 09:41:00 -0800155 bool success = (WIFEXITED(status) && WEXITSTATUS(status) == 0);
Andreas Gampee1459ae2016-06-29 09:36:30 -0700156 if (expect_success) {
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800157 if (!success) {
158 return ::testing::AssertionFailure()
159 << "Failed to compile odex: " << error_msg << std::endl << output_;
160 }
Andreas Gampee1459ae2016-06-29 09:36:30 -0700161
162 // Verify the odex file was generated as expected.
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100163 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +0100164 odex_location.c_str(),
Andreas Gampee1459ae2016-06-29 09:36:30 -0700165 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100166 /*executable=*/ false,
167 /*low_4gb=*/ false,
Vladimir Markob7bf8432019-12-03 13:18:50 +0000168 dex_location,
Andreas Gampee1459ae2016-06-29 09:36:30 -0700169 &error_msg));
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800170 if (odex_file == nullptr) {
171 return ::testing::AssertionFailure() << "Could not open odex file: " << error_msg;
172 }
Andreas Gampee1459ae2016-06-29 09:36:30 -0700173
174 CheckFilter(filter, odex_file->GetCompilerFilter());
Calin Juravle1ce70852017-06-28 10:59:03 -0700175 check_oat(*(odex_file.get()));
Andreas Gampee1459ae2016-06-29 09:36:30 -0700176 } else {
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800177 if (success) {
178 return ::testing::AssertionFailure() << "Succeeded to compile odex: " << output_;
179 }
Andreas Gampee1459ae2016-06-29 09:36:30 -0700180
181 error_msg_ = error_msg;
182
Andreas Gampe80ddf272018-01-11 09:41:00 -0800183 if (!test_accepts_odex_file_on_failure) {
184 // Verify there's no loadable odex file.
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100185 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +0100186 odex_location.c_str(),
Andreas Gampe80ddf272018-01-11 09:41:00 -0800187 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100188 /*executable=*/ false,
189 /*low_4gb=*/ false,
Vladimir Markob7bf8432019-12-03 13:18:50 +0000190 dex_location,
Andreas Gampe80ddf272018-01-11 09:41:00 -0800191 &error_msg));
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800192 if (odex_file != nullptr) {
193 return ::testing::AssertionFailure() << "Could open odex file: " << error_msg;
194 }
Andreas Gampe80ddf272018-01-11 09:41:00 -0800195 }
Andreas Gampee1459ae2016-06-29 09:36:30 -0700196 }
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800197 return ::testing::AssertionSuccess();
Andreas Gampee1459ae2016-06-29 09:36:30 -0700198 }
199
Calin Juravle1ccf6132017-08-02 17:46:53 -0700200 // Check the input compiler filter against the generated oat file's filter. May be overridden
Andreas Gampee1459ae2016-06-29 09:36:30 -0700201 // in subclasses when equality is not expected.
202 virtual void CheckFilter(CompilerFilter::Filter expected, CompilerFilter::Filter actual) {
203 EXPECT_EQ(expected, actual);
204 }
205
Andreas Gampee1459ae2016-06-29 09:36:30 -0700206 std::string output_ = "";
207 std::string error_msg_ = "";
Andreas Gampee1459ae2016-06-29 09:36:30 -0700208};
209
Calin Juravle028c7ef2021-05-26 15:37:00 -0700210// This test class provides an easy way to validate an expected filter which is different
211// then the one pass to generate the odex file (compared to adding yet another argument
212// to what's already huge test methods).
213class Dex2oatWithExpectedFilterTest : public Dex2oatTest {
214 protected:
215 void CheckFilter(
216 CompilerFilter::Filter expected ATTRIBUTE_UNUSED,
217 CompilerFilter::Filter actual) override {
218 EXPECT_EQ(expected_filter_, actual);
219 }
220
221 CompilerFilter::Filter expected_filter_;
222};
223
Andreas Gampee1459ae2016-06-29 09:36:30 -0700224class Dex2oatSwapTest : public Dex2oatTest {
225 protected:
226 void RunTest(bool use_fd, bool expect_use, const std::vector<std::string>& extra_args = {}) {
227 std::string dex_location = GetScratchDir() + "/Dex2OatSwapTest.jar";
228 std::string odex_location = GetOdexDir() + "/Dex2OatSwapTest.odex";
229
Andreas Gampe7adeda82016-07-25 08:27:35 -0700230 Copy(GetTestDexFileName(), dex_location);
Andreas Gampee1459ae2016-06-29 09:36:30 -0700231
232 std::vector<std::string> copy(extra_args);
233
234 std::unique_ptr<ScratchFile> sf;
235 if (use_fd) {
236 sf.reset(new ScratchFile());
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800237 copy.push_back(android::base::StringPrintf("--swap-fd=%d", sf->GetFd()));
Andreas Gampee1459ae2016-06-29 09:36:30 -0700238 } else {
239 std::string swap_location = GetOdexDir() + "/Dex2OatSwapTest.odex.swap";
240 copy.push_back("--swap-file=" + swap_location);
241 }
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800242 ASSERT_TRUE(GenerateOdexForTest(dex_location, odex_location, CompilerFilter::kSpeed, copy));
Andreas Gampee1459ae2016-06-29 09:36:30 -0700243
244 CheckValidity();
Andreas Gampee1459ae2016-06-29 09:36:30 -0700245 CheckResult(expect_use);
246 }
247
Andreas Gampe7adeda82016-07-25 08:27:35 -0700248 virtual std::string GetTestDexFileName() {
Vladimir Marko15357702017-02-09 10:37:31 +0000249 return Dex2oatEnvironmentTest::GetTestDexFileName("VerifierDeps");
Andreas Gampe7adeda82016-07-25 08:27:35 -0700250 }
251
252 virtual void CheckResult(bool expect_use) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700253 if (kIsTargetBuild) {
254 CheckTargetResult(expect_use);
255 } else {
256 CheckHostResult(expect_use);
257 }
258 }
259
Andreas Gampe7adeda82016-07-25 08:27:35 -0700260 virtual void CheckTargetResult(bool expect_use ATTRIBUTE_UNUSED) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700261 // TODO: Ignore for now, as we won't capture any output (it goes to the logcat). We may do
262 // something for variants with file descriptor where we can control the lifetime of
263 // the swap file and thus take a look at it.
264 }
265
Andreas Gampe7adeda82016-07-25 08:27:35 -0700266 virtual void CheckHostResult(bool expect_use) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700267 if (!kIsTargetBuild) {
268 if (expect_use) {
269 EXPECT_NE(output_.find("Large app, accepted running with swap."), std::string::npos)
270 << output_;
271 } else {
272 EXPECT_EQ(output_.find("Large app, accepted running with swap."), std::string::npos)
273 << output_;
274 }
275 }
276 }
277
278 // Check whether the dex2oat run was really successful.
Andreas Gampe7adeda82016-07-25 08:27:35 -0700279 virtual void CheckValidity() {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700280 if (kIsTargetBuild) {
281 CheckTargetValidity();
282 } else {
283 CheckHostValidity();
284 }
285 }
286
Andreas Gampe7adeda82016-07-25 08:27:35 -0700287 virtual void CheckTargetValidity() {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700288 // TODO: Ignore for now, as we won't capture any output (it goes to the logcat). We may do
289 // something for variants with file descriptor where we can control the lifetime of
290 // the swap file and thus take a look at it.
291 }
292
293 // On the host, we can get the dex2oat output. Here, look for "dex2oat took."
Andreas Gampe7adeda82016-07-25 08:27:35 -0700294 virtual void CheckHostValidity() {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700295 EXPECT_NE(output_.find("dex2oat took"), std::string::npos) << output_;
296 }
297};
298
299TEST_F(Dex2oatSwapTest, DoNotUseSwapDefaultSingleSmall) {
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100300 RunTest(/*use_fd=*/ false, /*expect_use=*/ false);
301 RunTest(/*use_fd=*/ true, /*expect_use=*/ false);
Andreas Gampee1459ae2016-06-29 09:36:30 -0700302}
303
304TEST_F(Dex2oatSwapTest, DoNotUseSwapSingle) {
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100305 RunTest(/*use_fd=*/ false, /*expect_use=*/ false, { "--swap-dex-size-threshold=0" });
306 RunTest(/*use_fd=*/ true, /*expect_use=*/ false, { "--swap-dex-size-threshold=0" });
Andreas Gampee1459ae2016-06-29 09:36:30 -0700307}
308
309TEST_F(Dex2oatSwapTest, DoNotUseSwapSmall) {
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100310 RunTest(/*use_fd=*/ false, /*expect_use=*/ false, { "--swap-dex-count-threshold=0" });
311 RunTest(/*use_fd=*/ true, /*expect_use=*/ false, { "--swap-dex-count-threshold=0" });
Andreas Gampee1459ae2016-06-29 09:36:30 -0700312}
313
314TEST_F(Dex2oatSwapTest, DoUseSwapSingleSmall) {
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100315 RunTest(/*use_fd=*/ false,
316 /*expect_use=*/ true,
Andreas Gampee1459ae2016-06-29 09:36:30 -0700317 { "--swap-dex-size-threshold=0", "--swap-dex-count-threshold=0" });
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100318 RunTest(/*use_fd=*/ true,
319 /*expect_use=*/ true,
Andreas Gampee1459ae2016-06-29 09:36:30 -0700320 { "--swap-dex-size-threshold=0", "--swap-dex-count-threshold=0" });
321}
322
Andreas Gampe7adeda82016-07-25 08:27:35 -0700323class Dex2oatSwapUseTest : public Dex2oatSwapTest {
324 protected:
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100325 void CheckHostResult(bool expect_use) override {
Andreas Gampe7adeda82016-07-25 08:27:35 -0700326 if (!kIsTargetBuild) {
327 if (expect_use) {
328 EXPECT_NE(output_.find("Large app, accepted running with swap."), std::string::npos)
329 << output_;
330 } else {
331 EXPECT_EQ(output_.find("Large app, accepted running with swap."), std::string::npos)
332 << output_;
333 }
334 }
335 }
336
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100337 std::string GetTestDexFileName() override {
Andreas Gampe7adeda82016-07-25 08:27:35 -0700338 // Use Statics as it has a handful of functions.
339 return CommonRuntimeTest::GetTestDexFileName("Statics");
340 }
341
342 void GrabResult1() {
343 if (!kIsTargetBuild) {
344 native_alloc_1_ = ParseNativeAlloc();
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100345 swap_1_ = ParseSwap(/*expected=*/ false);
Andreas Gampe7adeda82016-07-25 08:27:35 -0700346 } else {
347 native_alloc_1_ = std::numeric_limits<size_t>::max();
348 swap_1_ = 0;
349 }
350 }
351
352 void GrabResult2() {
353 if (!kIsTargetBuild) {
354 native_alloc_2_ = ParseNativeAlloc();
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100355 swap_2_ = ParseSwap(/*expected=*/ true);
Andreas Gampe7adeda82016-07-25 08:27:35 -0700356 } else {
357 native_alloc_2_ = 0;
358 swap_2_ = std::numeric_limits<size_t>::max();
359 }
360 }
361
362 private:
363 size_t ParseNativeAlloc() {
364 std::regex native_alloc_regex("dex2oat took.*native alloc=[^ ]+ \\(([0-9]+)B\\)");
365 std::smatch native_alloc_match;
366 bool found = std::regex_search(output_, native_alloc_match, native_alloc_regex);
367 if (!found) {
368 EXPECT_TRUE(found);
369 return 0;
370 }
371 if (native_alloc_match.size() != 2U) {
372 EXPECT_EQ(native_alloc_match.size(), 2U);
373 return 0;
374 }
375
376 std::istringstream stream(native_alloc_match[1].str());
377 size_t value;
378 stream >> value;
379
380 return value;
381 }
382
383 size_t ParseSwap(bool expected) {
384 std::regex swap_regex("dex2oat took[^\\n]+swap=[^ ]+ \\(([0-9]+)B\\)");
385 std::smatch swap_match;
386 bool found = std::regex_search(output_, swap_match, swap_regex);
387 if (found != expected) {
388 EXPECT_EQ(expected, found);
389 return 0;
390 }
391
392 if (!found) {
393 return 0;
394 }
395
396 if (swap_match.size() != 2U) {
397 EXPECT_EQ(swap_match.size(), 2U);
398 return 0;
399 }
400
401 std::istringstream stream(swap_match[1].str());
402 size_t value;
403 stream >> value;
404
405 return value;
406 }
407
408 protected:
409 size_t native_alloc_1_;
410 size_t native_alloc_2_;
411
412 size_t swap_1_;
413 size_t swap_2_;
414};
415
416TEST_F(Dex2oatSwapUseTest, CheckSwapUsage) {
Roland Levillain05e34f42018-05-24 13:19:05 +0000417 // Native memory usage isn't correctly tracked when running under ASan.
418 TEST_DISABLED_FOR_MEMORY_TOOL();
Andreas Gampef4a67fd2017-05-04 09:55:36 -0700419
Vladimir Marko57070da2017-02-14 16:16:30 +0000420 // The `native_alloc_2_ >= native_alloc_1_` assertion below may not
Evgeny Astigeevichd2ac3072020-01-29 11:51:40 +0000421 // hold true on some x86 or x86_64 systems; disable this test while we
Roland Levillain19772bf2017-02-16 11:28:10 +0000422 // investigate (b/29259363).
Alex Lighte0c6d432020-01-22 22:04:20 +0000423 TEST_DISABLED_FOR_X86();
Evgeny Astigeevichd2ac3072020-01-29 11:51:40 +0000424 TEST_DISABLED_FOR_X86_64();
Vladimir Marko57070da2017-02-14 16:16:30 +0000425
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100426 RunTest(/*use_fd=*/ false,
427 /*expect_use=*/ false);
Andreas Gampe7adeda82016-07-25 08:27:35 -0700428 GrabResult1();
429 std::string output_1 = output_;
430
431 output_ = "";
432
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100433 RunTest(/*use_fd=*/ false,
434 /*expect_use=*/ true,
Andreas Gampe7adeda82016-07-25 08:27:35 -0700435 { "--swap-dex-size-threshold=0", "--swap-dex-count-threshold=0" });
436 GrabResult2();
437 std::string output_2 = output_;
438
439 if (native_alloc_2_ >= native_alloc_1_ || swap_1_ >= swap_2_) {
440 EXPECT_LT(native_alloc_2_, native_alloc_1_);
441 EXPECT_LT(swap_1_, swap_2_);
442
443 LOG(ERROR) << output_1;
444 LOG(ERROR) << output_2;
445 }
446}
447
Andreas Gampe67f02822016-06-24 21:05:23 -0700448class Dex2oatVeryLargeTest : public Dex2oatTest {
449 protected:
450 void CheckFilter(CompilerFilter::Filter input ATTRIBUTE_UNUSED,
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100451 CompilerFilter::Filter result ATTRIBUTE_UNUSED) override {
Andreas Gampe67f02822016-06-24 21:05:23 -0700452 // Ignore, we'll do our own checks.
453 }
454
455 void RunTest(CompilerFilter::Filter filter,
456 bool expect_large,
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700457 bool expect_downgrade,
Andreas Gampe67f02822016-06-24 21:05:23 -0700458 const std::vector<std::string>& extra_args = {}) {
Calin Juravle028c7ef2021-05-26 15:37:00 -0700459 RunTest(filter, filter, expect_large, expect_downgrade, extra_args);
460 }
461
462 void RunTest(CompilerFilter::Filter filter,
463 CompilerFilter::Filter expected_filter,
464 bool expect_large,
465 bool expect_downgrade,
466 const std::vector<std::string>& extra_args = {}) {
Andreas Gampe67f02822016-06-24 21:05:23 -0700467 std::string dex_location = GetScratchDir() + "/DexNoOat.jar";
468 std::string odex_location = GetOdexDir() + "/DexOdexNoOat.odex";
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700469 std::string app_image_file = GetScratchDir() + "/Test.art";
Andreas Gampe67f02822016-06-24 21:05:23 -0700470
471 Copy(GetDexSrc1(), dex_location);
472
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700473 std::vector<std::string> new_args(extra_args);
474 new_args.push_back("--app-image-file=" + app_image_file);
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800475 ASSERT_TRUE(GenerateOdexForTest(dex_location, odex_location, filter, new_args));
Andreas Gampe67f02822016-06-24 21:05:23 -0700476
477 CheckValidity();
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700478 CheckResult(dex_location,
479 odex_location,
480 app_image_file,
481 filter,
Calin Juravle028c7ef2021-05-26 15:37:00 -0700482 expected_filter,
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700483 expect_large,
484 expect_downgrade);
Andreas Gampe67f02822016-06-24 21:05:23 -0700485 }
486
487 void CheckResult(const std::string& dex_location,
488 const std::string& odex_location,
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700489 const std::string& app_image_file,
Andreas Gampe67f02822016-06-24 21:05:23 -0700490 CompilerFilter::Filter filter,
Calin Juravle028c7ef2021-05-26 15:37:00 -0700491 CompilerFilter::Filter expected_filter,
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700492 bool expect_large,
493 bool expect_downgrade) {
494 if (expect_downgrade) {
495 EXPECT_TRUE(expect_large);
496 }
Andreas Gampe67f02822016-06-24 21:05:23 -0700497 // Host/target independent checks.
498 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100499 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +0100500 odex_location.c_str(),
Andreas Gampe67f02822016-06-24 21:05:23 -0700501 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100502 /*executable=*/ false,
503 /*low_4gb=*/ false,
Vladimir Markob7bf8432019-12-03 13:18:50 +0000504 dex_location,
Andreas Gampe67f02822016-06-24 21:05:23 -0700505 &error_msg));
506 ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700507 EXPECT_GT(app_image_file.length(), 0u);
508 std::unique_ptr<File> file(OS::OpenFileForReading(app_image_file.c_str()));
Andreas Gampe67f02822016-06-24 21:05:23 -0700509 if (expect_large) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700510 // Note: we cannot check the following
511 // EXPECT_FALSE(CompilerFilter::IsAotCompilationEnabled(odex_file->GetCompilerFilter()));
Andreas Gampe67f02822016-06-24 21:05:23 -0700512 // The reason is that the filter override currently happens when the dex files are
513 // loaded in dex2oat, which is after the oat file has been started. Thus, the header
514 // store cannot be changed, and the original filter is set in stone.
515
516 for (const OatDexFile* oat_dex_file : odex_file->GetOatDexFiles()) {
517 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
518 ASSERT_TRUE(dex_file != nullptr);
519 uint32_t class_def_count = dex_file->NumClassDefs();
520 ASSERT_LT(class_def_count, std::numeric_limits<uint16_t>::max());
521 for (uint16_t class_def_index = 0; class_def_index < class_def_count; ++class_def_index) {
522 OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
Vladimir Marko3d76ebe2021-04-19 15:07:50 +0000523 EXPECT_EQ(oat_class.GetType(), OatClassType::kNoneCompiled);
Andreas Gampe67f02822016-06-24 21:05:23 -0700524 }
525 }
526
527 // If the input filter was "below," it should have been used.
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100528 if (!CompilerFilter::IsAsGoodAs(CompilerFilter::kExtract, filter)) {
Calin Juravle028c7ef2021-05-26 15:37:00 -0700529 EXPECT_EQ(odex_file->GetCompilerFilter(), expected_filter);
Andreas Gampe67f02822016-06-24 21:05:23 -0700530 }
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700531
532 // If expect large, make sure the app image isn't generated or is empty.
533 if (file != nullptr) {
534 EXPECT_EQ(file->GetLength(), 0u);
535 }
Andreas Gampe67f02822016-06-24 21:05:23 -0700536 } else {
Calin Juravle028c7ef2021-05-26 15:37:00 -0700537 EXPECT_EQ(odex_file->GetCompilerFilter(), expected_filter);
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700538 ASSERT_TRUE(file != nullptr) << app_image_file;
539 EXPECT_GT(file->GetLength(), 0u);
Andreas Gampe67f02822016-06-24 21:05:23 -0700540 }
541
542 // Host/target dependent checks.
543 if (kIsTargetBuild) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700544 CheckTargetResult(expect_downgrade);
Andreas Gampe67f02822016-06-24 21:05:23 -0700545 } else {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700546 CheckHostResult(expect_downgrade);
Andreas Gampe67f02822016-06-24 21:05:23 -0700547 }
548 }
549
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700550 void CheckTargetResult(bool expect_downgrade ATTRIBUTE_UNUSED) {
Andreas Gampe67f02822016-06-24 21:05:23 -0700551 // TODO: Ignore for now. May do something for fd things.
552 }
553
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700554 void CheckHostResult(bool expect_downgrade) {
Andreas Gampe67f02822016-06-24 21:05:23 -0700555 if (!kIsTargetBuild) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700556 if (expect_downgrade) {
557 EXPECT_NE(output_.find("Very large app, downgrading to"), std::string::npos) << output_;
Andreas Gampe67f02822016-06-24 21:05:23 -0700558 } else {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700559 EXPECT_EQ(output_.find("Very large app, downgrading to"), std::string::npos) << output_;
Andreas Gampe67f02822016-06-24 21:05:23 -0700560 }
561 }
562 }
563
564 // Check whether the dex2oat run was really successful.
565 void CheckValidity() {
566 if (kIsTargetBuild) {
567 CheckTargetValidity();
568 } else {
569 CheckHostValidity();
570 }
571 }
572
573 void CheckTargetValidity() {
574 // TODO: Ignore for now.
575 }
576
577 // On the host, we can get the dex2oat output. Here, look for "dex2oat took."
578 void CheckHostValidity() {
579 EXPECT_NE(output_.find("dex2oat took"), std::string::npos) << output_;
580 }
581};
582
583TEST_F(Dex2oatVeryLargeTest, DontUseVeryLarge) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700584 RunTest(CompilerFilter::kAssumeVerified, false, false);
585 RunTest(CompilerFilter::kExtract, false, false);
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700586 RunTest(CompilerFilter::kSpeed, false, false);
Andreas Gampe67f02822016-06-24 21:05:23 -0700587
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700588 RunTest(CompilerFilter::kAssumeVerified, false, false, { "--very-large-app-threshold=10000000" });
589 RunTest(CompilerFilter::kExtract, false, false, { "--very-large-app-threshold=10000000" });
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700590 RunTest(CompilerFilter::kSpeed, false, false, { "--very-large-app-threshold=10000000" });
Andreas Gampe67f02822016-06-24 21:05:23 -0700591}
592
593TEST_F(Dex2oatVeryLargeTest, UseVeryLarge) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700594 RunTest(CompilerFilter::kAssumeVerified, true, false, { "--very-large-app-threshold=100" });
595 RunTest(CompilerFilter::kExtract, true, false, { "--very-large-app-threshold=100" });
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700596 RunTest(CompilerFilter::kSpeed, true, true, { "--very-large-app-threshold=100" });
Andreas Gampe67f02822016-06-24 21:05:23 -0700597}
598
Mathieu Chartier97ab5e32017-02-22 13:35:44 -0800599// Regressin test for b/35665292.
600TEST_F(Dex2oatVeryLargeTest, SpeedProfileNoProfile) {
601 // Test that dex2oat doesn't crash with speed-profile but no input profile.
Calin Juravle028c7ef2021-05-26 15:37:00 -0700602 RunTest(CompilerFilter::kSpeedProfile, CompilerFilter::kVerify, false, false);
Mathieu Chartier97ab5e32017-02-22 13:35:44 -0800603}
604
Jeff Hao608f2ce2016-10-19 11:17:11 -0700605class Dex2oatLayoutTest : public Dex2oatTest {
606 protected:
607 void CheckFilter(CompilerFilter::Filter input ATTRIBUTE_UNUSED,
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100608 CompilerFilter::Filter result ATTRIBUTE_UNUSED) override {
Jeff Hao608f2ce2016-10-19 11:17:11 -0700609 // Ignore, we'll do our own checks.
610 }
611
Calin Juravle45cdd052019-09-23 23:03:18 -0400612 // Emits a profile with a single dex file with the given location and classes ranging
Jiakai Zhang19f95682021-12-06 16:19:39 +0000613 // from `class_offset` to `class_offset + num_classes`.
Jeff Hao41fba6a2016-11-28 11:53:33 -0800614 void GenerateProfile(const std::string& test_profile,
Jiakai Zhang19f95682021-12-06 16:19:39 +0000615 const std::string& dex_location,
616 size_t num_classes,
617 size_t class_offset = 0) {
618 const char* location = dex_location.c_str();
619 std::string error_msg;
620 std::vector<std::unique_ptr<const DexFile>> dex_files;
621 const ArtDexFileLoader dex_file_loader;
622 ASSERT_TRUE(dex_file_loader.Open(
623 location, location, /*verify=*/true, /*verify_checksum=*/true, &error_msg, &dex_files));
624 EXPECT_EQ(dex_files.size(), 1U);
625 std::unique_ptr<const DexFile>& dex_file = dex_files[0];
626
Andreas Gampedfcd82c2018-10-16 20:22:37 -0700627 int profile_test_fd = open(test_profile.c_str(),
628 O_CREAT | O_TRUNC | O_WRONLY | O_CLOEXEC,
629 0644);
Jeff Hao41fba6a2016-11-28 11:53:33 -0800630 CHECK_GE(profile_test_fd, 0);
631
632 ProfileCompilationInfo info;
Calin Juravle45cdd052019-09-23 23:03:18 -0400633 std::vector<dex::TypeIndex> classes;;
Mathieu Chartier046854b2017-03-01 17:16:22 -0800634 for (size_t i = 0; i < num_classes; ++i) {
Jiakai Zhang19f95682021-12-06 16:19:39 +0000635 classes.push_back(dex::TypeIndex(class_offset + 1 + i));
Mathieu Chartier046854b2017-03-01 17:16:22 -0800636 }
Jiakai Zhang19f95682021-12-06 16:19:39 +0000637 info.AddClassesForDex(dex_file.get(), classes.begin(), classes.end());
Jeff Hao41fba6a2016-11-28 11:53:33 -0800638 bool result = info.Save(profile_test_fd);
639 close(profile_test_fd);
640 ASSERT_TRUE(result);
641 }
642
Jiakai Zhang19f95682021-12-06 16:19:39 +0000643 // Compiles a dex file with profiles.
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800644 void CompileProfileOdex(const std::string& dex_location,
645 const std::string& odex_location,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800646 const std::string& app_image_file_name,
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800647 bool use_fd,
Jiakai Zhang19f95682021-12-06 16:19:39 +0000648 const std::vector<std::string>& profile_locations,
Nicolas Geoffray97fa9922017-03-09 13:13:25 +0000649 const std::vector<std::string>& extra_args = {},
650 bool expect_success = true) {
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800651 std::vector<std::string> copy(extra_args);
Jiakai Zhang19f95682021-12-06 16:19:39 +0000652 for (const std::string& profile_location : profile_locations) {
653 copy.push_back("--profile-file=" + profile_location);
654 }
Mathieu Chartier046854b2017-03-01 17:16:22 -0800655 std::unique_ptr<File> app_image_file;
656 if (!app_image_file_name.empty()) {
657 if (use_fd) {
658 app_image_file.reset(OS::CreateEmptyFile(app_image_file_name.c_str()));
659 copy.push_back("--app-image-fd=" + std::to_string(app_image_file->Fd()));
660 } else {
661 copy.push_back("--app-image-file=" + app_image_file_name);
662 }
663 }
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800664 ASSERT_TRUE(GenerateOdexForTest(dex_location,
665 odex_location,
666 CompilerFilter::kSpeedProfile,
667 copy,
668 expect_success,
669 use_fd));
Mathieu Chartier046854b2017-03-01 17:16:22 -0800670 if (app_image_file != nullptr) {
671 ASSERT_EQ(app_image_file->FlushCloseOrErase(), 0) << "Could not flush and close art file";
672 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800673 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700674
Jiakai Zhang19f95682021-12-06 16:19:39 +0000675 // Same as above, but generates the profile internally with classes ranging from 0 to
676 // `num_profile_classes`.
677 void CompileProfileOdex(const std::string& dex_location,
678 const std::string& odex_location,
679 const std::string& app_image_file_name,
680 bool use_fd,
681 size_t num_profile_classes,
682 const std::vector<std::string>& extra_args = {},
683 bool expect_success = true) {
684 const std::string profile_location = GetScratchDir() + "/primary.prof";
685 GenerateProfile(profile_location, dex_location, num_profile_classes);
686 CompileProfileOdex(dex_location,
687 odex_location,
688 app_image_file_name,
689 use_fd,
690 {profile_location},
691 extra_args,
692 expect_success);
693 }
694
Jiakai Zhang890beb02022-01-06 14:05:44 +0000695 uint32_t GetImageObjectSectionSize(const std::string& image_file_name) {
Mathieu Chartier046854b2017-03-01 17:16:22 -0800696 EXPECT_FALSE(image_file_name.empty());
697 std::unique_ptr<File> file(OS::OpenFileForReading(image_file_name.c_str()));
698 CHECK(file != nullptr);
699 ImageHeader image_header;
700 const bool success = file->ReadFully(&image_header, sizeof(image_header));
701 CHECK(success);
702 CHECK(image_header.IsValid());
703 ReaderMutexLock mu(Thread::Current(), *Locks::mutator_lock_);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100704 return image_header.GetObjectsSection().Size();
Mathieu Chartier046854b2017-03-01 17:16:22 -0800705 }
706
707 void RunTest(bool app_image) {
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800708 std::string dex_location = GetScratchDir() + "/DexNoOat.jar";
709 std::string odex_location = GetOdexDir() + "/DexOdexNoOat.odex";
Mathieu Chartier046854b2017-03-01 17:16:22 -0800710 std::string app_image_file = app_image ? (GetOdexDir() + "/DexOdexNoOat.art"): "";
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800711 Copy(GetDexSrc2(), dex_location);
712
Jiakai Zhang890beb02022-01-06 14:05:44 +0000713 uint32_t image_file_empty_profile = 0;
Mathieu Chartier046854b2017-03-01 17:16:22 -0800714 if (app_image) {
715 CompileProfileOdex(dex_location,
716 odex_location,
717 app_image_file,
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100718 /*use_fd=*/ false,
719 /*num_profile_classes=*/ 0);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800720 CheckValidity();
Mathieu Chartier046854b2017-03-01 17:16:22 -0800721 // Don't check the result since CheckResult relies on the class being in the profile.
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100722 image_file_empty_profile = GetImageObjectSectionSize(app_image_file);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800723 EXPECT_GT(image_file_empty_profile, 0u);
Calin Juravle028c7ef2021-05-26 15:37:00 -0700724 CheckCompilerFilter(dex_location, odex_location, CompilerFilter::Filter::kVerify);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800725 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700726
Mathieu Chartier046854b2017-03-01 17:16:22 -0800727 // Small profile.
728 CompileProfileOdex(dex_location,
729 odex_location,
730 app_image_file,
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100731 /*use_fd=*/ false,
732 /*num_profile_classes=*/ 1);
Jeff Hao608f2ce2016-10-19 11:17:11 -0700733 CheckValidity();
Mathieu Chartier046854b2017-03-01 17:16:22 -0800734 CheckResult(dex_location, odex_location, app_image_file);
Calin Juravle028c7ef2021-05-26 15:37:00 -0700735 CheckCompilerFilter(dex_location, odex_location, CompilerFilter::Filter::kSpeedProfile);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800736
737 if (app_image) {
738 // Test that the profile made a difference by adding more classes.
Jiakai Zhang890beb02022-01-06 14:05:44 +0000739 const uint32_t image_file_small_profile = GetImageObjectSectionSize(app_image_file);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100740 ASSERT_LT(image_file_empty_profile, image_file_small_profile);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800741 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700742 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800743
Calin Juravle028c7ef2021-05-26 15:37:00 -0700744 void CheckCompilerFilter(
745 const std::string& dex_location,
746 const std::string& odex_location,
747 CompilerFilter::Filter expected_filter) {
748 std::string error_msg;
749 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
750 odex_location.c_str(),
751 odex_location.c_str(),
752 /*executable=*/ false,
753 /*low_4gb=*/ false,
754 dex_location,
755 &error_msg));
756 EXPECT_EQ(odex_file->GetCompilerFilter(), expected_filter);
757 }
758
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800759 void RunTestVDex() {
760 std::string dex_location = GetScratchDir() + "/DexNoOat.jar";
761 std::string odex_location = GetOdexDir() + "/DexOdexNoOat.odex";
762 std::string vdex_location = GetOdexDir() + "/DexOdexNoOat.vdex";
Mathieu Chartier046854b2017-03-01 17:16:22 -0800763 std::string app_image_file_name = GetOdexDir() + "/DexOdexNoOat.art";
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800764 Copy(GetDexSrc2(), dex_location);
765
766 std::unique_ptr<File> vdex_file1(OS::CreateEmptyFile(vdex_location.c_str()));
767 CHECK(vdex_file1 != nullptr) << vdex_location;
768 ScratchFile vdex_file2;
769 {
770 std::string input_vdex = "--input-vdex-fd=-1";
771 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file1->Fd());
772 CompileProfileOdex(dex_location,
773 odex_location,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800774 app_image_file_name,
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100775 /*use_fd=*/ true,
776 /*num_profile_classes=*/ 1,
Mathieu Chartierf1609832018-01-31 03:09:56 -0800777 { input_vdex, output_vdex });
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800778 EXPECT_GT(vdex_file1->GetLength(), 0u);
779 }
780 {
Nicolas Geoffray97fa9922017-03-09 13:13:25 +0000781 // Test that vdex and dexlayout fail gracefully.
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800782 std::string input_vdex = StringPrintf("--input-vdex-fd=%d", vdex_file1->Fd());
783 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file2.GetFd());
784 CompileProfileOdex(dex_location,
785 odex_location,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800786 app_image_file_name,
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100787 /*use_fd=*/ true,
788 /*num_profile_classes=*/ 1,
Mathieu Chartierd27923c2018-02-08 21:00:03 -0800789 { input_vdex, output_vdex },
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100790 /*expect_success=*/ true);
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +0100791 EXPECT_GT(vdex_file2.GetFile()->GetLength(), 0u);
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800792 }
793 ASSERT_EQ(vdex_file1->FlushCloseOrErase(), 0) << "Could not flush and close vdex file";
794 CheckValidity();
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800795 }
796
Mathieu Chartier046854b2017-03-01 17:16:22 -0800797 void CheckResult(const std::string& dex_location,
798 const std::string& odex_location,
799 const std::string& app_image_file_name) {
Jeff Hao608f2ce2016-10-19 11:17:11 -0700800 // Host/target independent checks.
801 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100802 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +0100803 odex_location.c_str(),
Jeff Hao608f2ce2016-10-19 11:17:11 -0700804 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100805 /*executable=*/ false,
806 /*low_4gb=*/ false,
Vladimir Markob7bf8432019-12-03 13:18:50 +0000807 dex_location,
Jeff Hao608f2ce2016-10-19 11:17:11 -0700808 &error_msg));
809 ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
810
Jeff Hao042e8982016-10-19 11:17:11 -0700811 const char* location = dex_location.c_str();
812 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Sehr013fd802018-01-11 22:55:24 -0800813 const ArtDexFileLoader dex_file_loader;
814 ASSERT_TRUE(dex_file_loader.Open(
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100815 location, location, /*verify=*/ true, /*verify_checksum=*/ true, &error_msg, &dex_files));
Jeff Hao042e8982016-10-19 11:17:11 -0700816 EXPECT_EQ(dex_files.size(), 1U);
817 std::unique_ptr<const DexFile>& old_dex_file = dex_files[0];
818
Jeff Hao608f2ce2016-10-19 11:17:11 -0700819 for (const OatDexFile* oat_dex_file : odex_file->GetOatDexFiles()) {
Jeff Hao042e8982016-10-19 11:17:11 -0700820 std::unique_ptr<const DexFile> new_dex_file = oat_dex_file->OpenDexFile(&error_msg);
821 ASSERT_TRUE(new_dex_file != nullptr);
822 uint32_t class_def_count = new_dex_file->NumClassDefs();
Jeff Hao608f2ce2016-10-19 11:17:11 -0700823 ASSERT_LT(class_def_count, std::numeric_limits<uint16_t>::max());
Jeff Hao042e8982016-10-19 11:17:11 -0700824 ASSERT_GE(class_def_count, 2U);
825
Mathieu Chartier24066ec2017-10-21 16:01:08 -0700826 // Make sure the indexes stay the same.
Jeff Hao042e8982016-10-19 11:17:11 -0700827 std::string old_class0 = old_dex_file->PrettyType(old_dex_file->GetClassDef(0).class_idx_);
828 std::string old_class1 = old_dex_file->PrettyType(old_dex_file->GetClassDef(1).class_idx_);
829 std::string new_class0 = new_dex_file->PrettyType(new_dex_file->GetClassDef(0).class_idx_);
830 std::string new_class1 = new_dex_file->PrettyType(new_dex_file->GetClassDef(1).class_idx_);
Mathieu Chartier24066ec2017-10-21 16:01:08 -0700831 EXPECT_EQ(old_class0, new_class0);
832 EXPECT_EQ(old_class1, new_class1);
Jeff Hao608f2ce2016-10-19 11:17:11 -0700833 }
834
Jeff Haoc155b052017-01-17 17:43:29 -0800835 EXPECT_EQ(odex_file->GetCompilerFilter(), CompilerFilter::kSpeedProfile);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800836
837 if (!app_image_file_name.empty()) {
838 // Go peek at the image header to make sure it was large enough to contain the class.
839 std::unique_ptr<File> file(OS::OpenFileForReading(app_image_file_name.c_str()));
840 ImageHeader image_header;
841 bool success = file->ReadFully(&image_header, sizeof(image_header));
842 ASSERT_TRUE(success);
843 ASSERT_TRUE(image_header.IsValid());
Vladimir Markocd87c3e2017-09-05 13:11:57 +0100844 EXPECT_GT(image_header.GetObjectsSection().Size(), 0u);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800845 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700846 }
847
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800848 // Check whether the dex2oat run was really successful.
849 void CheckValidity() {
850 if (kIsTargetBuild) {
851 CheckTargetValidity();
852 } else {
853 CheckHostValidity();
Jeff Hao608f2ce2016-10-19 11:17:11 -0700854 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800855 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700856
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800857 void CheckTargetValidity() {
858 // TODO: Ignore for now.
859 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700860
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800861 // On the host, we can get the dex2oat output. Here, look for "dex2oat took."
862 void CheckHostValidity() {
863 EXPECT_NE(output_.find("dex2oat took"), std::string::npos) << output_;
864 }
865};
Jeff Hao608f2ce2016-10-19 11:17:11 -0700866
867TEST_F(Dex2oatLayoutTest, TestLayout) {
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100868 RunTest(/*app_image=*/ false);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800869}
870
871TEST_F(Dex2oatLayoutTest, TestLayoutAppImage) {
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100872 RunTest(/*app_image=*/ true);
Jeff Hao608f2ce2016-10-19 11:17:11 -0700873}
874
Jiakai Zhanged0dcad2022-01-21 15:52:32 +0000875TEST_F(Dex2oatLayoutTest, TestLayoutAppImageMissingBootImage) {
876 std::string dex_location = GetScratchDir() + "/DexNoOat.jar";
877 std::string odex_location = GetOdexDir() + "/DexOdexNoOat.odex";
878 std::string app_image_file = GetOdexDir() + "/DexOdexNoOat.art";
879 Copy(GetDexSrc2(), dex_location);
880
881 CompileProfileOdex(dex_location,
882 odex_location,
883 app_image_file,
884 /*use_fd=*/ false,
885 /*num_profile_classes=*/ 1,
886 /*extra_args=*/ {"--boot-image=/nonx/boot.art"},
Nicolas Geoffrayfc1ba6d2022-03-23 14:18:23 +0000887 /*expect_success=*/ true);
888
889 // Verify the odex file does not require an image.
890 std::string error_msg;
891 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
892 odex_location.c_str(),
893 odex_location.c_str(),
894 /*executable=*/ false,
895 /*low_4gb=*/ false,
896 dex_location,
897 &error_msg));
898 ASSERT_TRUE(odex_file != nullptr) << "Could not open odex file: " << error_msg;
899
900 CheckFilter(CompilerFilter::kSpeedProfile, odex_file->GetCompilerFilter());
901 ASSERT_FALSE(odex_file->GetOatHeader().RequiresImage());
Jiakai Zhanged0dcad2022-01-21 15:52:32 +0000902}
903
Jiakai Zhang19f95682021-12-06 16:19:39 +0000904TEST_F(Dex2oatLayoutTest, TestLayoutMultipleProfiles) {
Jiakai Zhang890beb02022-01-06 14:05:44 +0000905 std::string dex_location = GetScratchDir() + "/Dex.jar";
906 std::string odex_location = GetOdexDir() + "/Dex.odex";
907 std::string app_image_file = GetOdexDir() + "/Dex.art";
Jiakai Zhang19f95682021-12-06 16:19:39 +0000908 Copy(GetDexSrc2(), dex_location);
909
910 const std::string profile1_location = GetScratchDir() + "/primary.prof";
911 GenerateProfile(profile1_location, dex_location, /*num_classes=*/1, /*class_offset=*/0);
912 CompileProfileOdex(dex_location,
913 odex_location,
914 app_image_file,
915 /*use_fd=*/false,
916 {profile1_location});
Jiakai Zhang890beb02022-01-06 14:05:44 +0000917 uint32_t image_file_size_profile1 = GetImageObjectSectionSize(app_image_file);
Jiakai Zhang19f95682021-12-06 16:19:39 +0000918
919 const std::string profile2_location = GetScratchDir() + "/secondary.prof";
920 GenerateProfile(profile2_location, dex_location, /*num_classes=*/1, /*class_offset=*/1);
921 CompileProfileOdex(dex_location,
922 odex_location,
923 app_image_file,
924 /*use_fd=*/false,
925 {profile2_location});
Jiakai Zhang890beb02022-01-06 14:05:44 +0000926 uint32_t image_file_size_profile2 = GetImageObjectSectionSize(app_image_file);
Jiakai Zhang19f95682021-12-06 16:19:39 +0000927
928 CompileProfileOdex(dex_location,
929 odex_location,
930 app_image_file,
931 /*use_fd=*/false,
932 {profile1_location, profile2_location});
Jiakai Zhang890beb02022-01-06 14:05:44 +0000933 uint32_t image_file_size_multiple_profiles = GetImageObjectSectionSize(app_image_file);
Jiakai Zhang19f95682021-12-06 16:19:39 +0000934
935 CheckCompilerFilter(dex_location, odex_location, CompilerFilter::Filter::kSpeedProfile);
936
937 // The image file generated with multiple profiles should be larger than any image file generated
938 // with each profile.
939 ASSERT_GT(image_file_size_multiple_profiles, image_file_size_profile1);
940 ASSERT_GT(image_file_size_multiple_profiles, image_file_size_profile2);
941}
942
Jiakai Zhang890beb02022-01-06 14:05:44 +0000943TEST_F(Dex2oatLayoutTest, TestLayoutMultipleProfilesChecksumMismatch) {
944 std::string dex_location = GetScratchDir() + "/Dex.jar";
945
946 // Create two profiles whose dex locations are the same but checksums are different.
947 Copy(GetDexSrc1(), dex_location);
948 const std::string profile_old = GetScratchDir() + "/profile_old.prof";
949 GenerateProfile(profile_old, dex_location, /*num_classes=*/1, /*class_offset=*/0);
950
951 Copy(GetDexSrc2(), dex_location);
952 const std::string profile_new = GetScratchDir() + "/profile_new.prof";
953 GenerateProfile(profile_new, dex_location, /*num_classes=*/1, /*class_offset=*/0);
954
955 // Create an empty profile for reference.
956 const std::string profile_empty = GetScratchDir() + "/profile_empty.prof";
957 GenerateProfile(profile_empty, dex_location, /*num_classes=*/0, /*class_offset=*/0);
958
959 std::string odex_location = GetOdexDir() + "/Dex.odex";
960 std::string app_image_file = GetOdexDir() + "/Dex.art";
961
962 // This should produce a normal image because only `profile_new` is used and it has the right
963 // checksum.
964 CompileProfileOdex(dex_location,
965 odex_location,
966 app_image_file,
967 /*use_fd=*/false,
968 {profile_new, profile_old});
969 uint32_t image_size_right_checksum = GetImageObjectSectionSize(app_image_file);
970
971 // This should produce an empty image because only `profile_old` is used and it has the wrong
972 // checksum. Note that dex2oat does not abort compilation when the profile verification fails
973 // (b/62602192, b/65260586).
974 CompileProfileOdex(dex_location,
975 odex_location,
976 app_image_file,
977 /*use_fd=*/false,
978 {profile_old, profile_new});
979 uint32_t image_size_wrong_checksum = GetImageObjectSectionSize(app_image_file);
980
981 // Create an empty image using an empty profile for reference.
982 CompileProfileOdex(dex_location,
983 odex_location,
984 app_image_file,
985 /*use_fd=*/false,
986 {profile_empty});
987 uint32_t image_size_empty = GetImageObjectSectionSize(app_image_file);
988
989 EXPECT_GT(image_size_right_checksum, image_size_empty);
990 EXPECT_EQ(image_size_wrong_checksum, image_size_empty);
991}
992
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800993TEST_F(Dex2oatLayoutTest, TestVdexLayout) {
994 RunTestVDex();
995}
996
Andreas Gampe2e8a2562017-01-18 20:39:02 -0800997class Dex2oatWatchdogTest : public Dex2oatTest {
998 protected:
999 void RunTest(bool expect_success, const std::vector<std::string>& extra_args = {}) {
1000 std::string dex_location = GetScratchDir() + "/Dex2OatSwapTest.jar";
1001 std::string odex_location = GetOdexDir() + "/Dex2OatSwapTest.odex";
1002
1003 Copy(GetTestDexFileName(), dex_location);
1004
1005 std::vector<std::string> copy(extra_args);
1006
1007 std::string swap_location = GetOdexDir() + "/Dex2OatSwapTest.odex.swap";
1008 copy.push_back("--swap-file=" + swap_location);
Andreas Gampe22fa3762017-10-23 20:58:12 -07001009 copy.push_back("-j512"); // Excessive idle threads just slow down dex2oat.
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001010 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1011 odex_location,
1012 CompilerFilter::kSpeed,
1013 copy,
1014 expect_success));
Andreas Gampe2e8a2562017-01-18 20:39:02 -08001015 }
1016
1017 std::string GetTestDexFileName() {
1018 return GetDexSrc1();
1019 }
1020};
1021
1022TEST_F(Dex2oatWatchdogTest, TestWatchdogOK) {
1023 // Check with default.
1024 RunTest(true);
1025
1026 // Check with ten minutes.
1027 RunTest(true, { "--watchdog-timeout=600000" });
1028}
1029
1030TEST_F(Dex2oatWatchdogTest, TestWatchdogTrigger) {
Andreas Gampe148c1602019-06-10 16:47:46 -07001031 // This test is frequently interrupted by signal_dumper on host (x86);
Roland Levillain1fb24e22019-01-09 13:33:37 +00001032 // disable it while we investigate (b/121352534).
1033 TEST_DISABLED_FOR_X86();
1034
Andreas Gampe80ddf272018-01-11 09:41:00 -08001035 // The watchdog is independent of dex2oat and will not delete intermediates. It is possible
1036 // that the compilation succeeds and the file is completely written by the time the watchdog
1037 // kills dex2oat (but the dex2oat threads must have been scheduled pretty badly).
1038 test_accepts_odex_file_on_failure = true;
1039
Andreas Gampe2e8a2562017-01-18 20:39:02 -08001040 // Check with ten milliseconds.
1041 RunTest(false, { "--watchdog-timeout=10" });
1042}
1043
Andreas Gampef7882972017-03-20 16:35:24 -07001044class Dex2oatReturnCodeTest : public Dex2oatTest {
1045 protected:
1046 int RunTest(const std::vector<std::string>& extra_args = {}) {
1047 std::string dex_location = GetScratchDir() + "/Dex2OatSwapTest.jar";
1048 std::string odex_location = GetOdexDir() + "/Dex2OatSwapTest.odex";
1049
1050 Copy(GetTestDexFileName(), dex_location);
1051
1052 std::string error_msg;
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001053 return GenerateOdexForTestWithStatus({dex_location},
Andreas Gampef7882972017-03-20 16:35:24 -07001054 odex_location,
1055 CompilerFilter::kSpeed,
1056 &error_msg,
1057 extra_args);
1058 }
1059
1060 std::string GetTestDexFileName() {
1061 return GetDexSrc1();
1062 }
1063};
1064
Calin Juravle1ce70852017-06-28 10:59:03 -07001065class Dex2oatClassLoaderContextTest : public Dex2oatTest {
1066 protected:
1067 void RunTest(const char* class_loader_context,
1068 const char* expected_classpath_key,
1069 bool expected_success,
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001070 bool use_second_source = false,
1071 bool generate_image = false) {
Calin Juravle1ce70852017-06-28 10:59:03 -07001072 std::string dex_location = GetUsedDexLocation();
1073 std::string odex_location = GetUsedOatLocation();
1074
1075 Copy(use_second_source ? GetDexSrc2() : GetDexSrc1(), dex_location);
1076
1077 std::string error_msg;
1078 std::vector<std::string> extra_args;
1079 if (class_loader_context != nullptr) {
1080 extra_args.push_back(std::string("--class-loader-context=") + class_loader_context);
1081 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001082 if (generate_image) {
1083 extra_args.push_back(std::string("--app-image-file=") + GetUsedImageLocation());
1084 }
Calin Juravle1ce70852017-06-28 10:59:03 -07001085 auto check_oat = [expected_classpath_key](const OatFile& oat_file) {
1086 ASSERT_TRUE(expected_classpath_key != nullptr);
1087 const char* classpath = oat_file.GetOatHeader().GetStoreValueByKey(OatHeader::kClassPathKey);
1088 ASSERT_TRUE(classpath != nullptr);
1089 ASSERT_STREQ(expected_classpath_key, classpath);
1090 };
1091
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001092 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1093 odex_location,
Nicolas Geoffrayf50975a2020-10-15 13:34:55 +00001094 CompilerFilter::kVerify,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001095 extra_args,
1096 expected_success,
Vladimir Marko21910692019-11-06 13:27:03 +00001097 /*use_fd=*/ false,
1098 /*use_zip_fd=*/ false,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001099 check_oat));
Calin Juravle1ce70852017-06-28 10:59:03 -07001100 }
1101
1102 std::string GetUsedDexLocation() {
1103 return GetScratchDir() + "/Context.jar";
1104 }
1105
1106 std::string GetUsedOatLocation() {
1107 return GetOdexDir() + "/Context.odex";
1108 }
1109
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001110 std::string GetUsedImageLocation() {
1111 return GetOdexDir() + "/Context.art";
1112 }
1113
Calin Juravle7b0648a2017-07-07 18:40:50 -07001114 const char* kEmptyClassPathKey = "PCL[]";
Calin Juravle1ce70852017-06-28 10:59:03 -07001115};
1116
1117TEST_F(Dex2oatClassLoaderContextTest, InvalidContext) {
1118 RunTest("Invalid[]", /*expected_classpath_key*/ nullptr, /*expected_success*/ false);
1119}
1120
1121TEST_F(Dex2oatClassLoaderContextTest, EmptyContext) {
1122 RunTest("PCL[]", kEmptyClassPathKey, /*expected_success*/ true);
1123}
1124
Calin Juravle1ce70852017-06-28 10:59:03 -07001125TEST_F(Dex2oatClassLoaderContextTest, ContextWithTheSourceDexFiles) {
1126 std::string context = "PCL[" + GetUsedDexLocation() + "]";
1127 RunTest(context.c_str(), kEmptyClassPathKey, /*expected_success*/ true);
1128}
1129
1130TEST_F(Dex2oatClassLoaderContextTest, ContextWithOtherDexFiles) {
1131 std::vector<std::unique_ptr<const DexFile>> dex_files = OpenTestDexFiles("Nested");
Calin Juravle1ce70852017-06-28 10:59:03 -07001132
1133 std::string context = "PCL[" + dex_files[0]->GetLocation() + "]";
Calin Juravle7b0648a2017-07-07 18:40:50 -07001134 std::string expected_classpath_key = "PCL[" +
1135 dex_files[0]->GetLocation() + "*" + std::to_string(dex_files[0]->GetLocationChecksum()) + "]";
Calin Juravle1ce70852017-06-28 10:59:03 -07001136 RunTest(context.c_str(), expected_classpath_key.c_str(), true);
1137}
1138
Calin Juravle5ff23932020-12-11 18:26:14 -08001139TEST_F(Dex2oatClassLoaderContextTest, ContextWithResourceOnlyDexFiles) {
1140 std::string resource_only_classpath = GetScratchDir() + "/resource_only_classpath.jar";
1141 Copy(GetResourceOnlySrc1(), resource_only_classpath);
Calin Juravle1ce70852017-06-28 10:59:03 -07001142
Calin Juravle5ff23932020-12-11 18:26:14 -08001143 std::string context = "PCL[" + resource_only_classpath + "]";
1144 // Expect an empty context because resource only dex files cannot be open.
Calin Juravle7b0648a2017-07-07 18:40:50 -07001145 RunTest(context.c_str(), kEmptyClassPathKey , /*expected_success*/ true);
Calin Juravle1ce70852017-06-28 10:59:03 -07001146}
1147
Calin Juravle1ce70852017-06-28 10:59:03 -07001148TEST_F(Dex2oatClassLoaderContextTest, ContextWithNotExistentDexFiles) {
1149 std::string context = "PCL[does_not_exists.dex]";
1150 // Expect an empty context because stripped dex files cannot be open.
1151 RunTest(context.c_str(), kEmptyClassPathKey, /*expected_success*/ true);
1152}
1153
Calin Juravlec79470d2017-07-12 17:37:42 -07001154TEST_F(Dex2oatClassLoaderContextTest, ChainContext) {
1155 std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested");
1156 std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex");
1157
1158 std::string context = "PCL[" + GetTestDexFileName("Nested") + "];" +
1159 "DLC[" + GetTestDexFileName("MultiDex") + "]";
1160 std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "];" +
1161 "DLC[" + CreateClassPathWithChecksums(dex_files2) + "]";
1162
1163 RunTest(context.c_str(), expected_classpath_key.c_str(), true);
1164}
1165
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00001166TEST_F(Dex2oatClassLoaderContextTest, ContextWithSharedLibrary) {
1167 std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested");
1168 std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex");
1169
1170 std::string context = "PCL[" + GetTestDexFileName("Nested") + "]" +
1171 "{PCL[" + GetTestDexFileName("MultiDex") + "]}";
1172 std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "]" +
1173 "{PCL[" + CreateClassPathWithChecksums(dex_files2) + "]}";
1174 RunTest(context.c_str(), expected_classpath_key.c_str(), true);
1175}
1176
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001177TEST_F(Dex2oatClassLoaderContextTest, ContextWithSharedLibraryAndImage) {
1178 std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested");
1179 std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex");
1180
1181 std::string context = "PCL[" + GetTestDexFileName("Nested") + "]" +
1182 "{PCL[" + GetTestDexFileName("MultiDex") + "]}";
1183 std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "]" +
1184 "{PCL[" + CreateClassPathWithChecksums(dex_files2) + "]}";
1185 RunTest(context.c_str(),
1186 expected_classpath_key.c_str(),
1187 /*expected_success=*/ true,
1188 /*use_second_source=*/ false,
1189 /*generate_image=*/ true);
1190}
1191
1192TEST_F(Dex2oatClassLoaderContextTest, ContextWithSameSharedLibrariesAndImage) {
1193 std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested");
1194 std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex");
1195
1196 std::string context = "PCL[" + GetTestDexFileName("Nested") + "]" +
1197 "{PCL[" + GetTestDexFileName("MultiDex") + "]" +
1198 "#PCL[" + GetTestDexFileName("MultiDex") + "]}";
1199 std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "]" +
1200 "{PCL[" + CreateClassPathWithChecksums(dex_files2) + "]" +
1201 "#PCL[" + CreateClassPathWithChecksums(dex_files2) + "]}";
1202 RunTest(context.c_str(),
1203 expected_classpath_key.c_str(),
1204 /*expected_success=*/ true,
1205 /*use_second_source=*/ false,
1206 /*generate_image=*/ true);
1207}
1208
1209TEST_F(Dex2oatClassLoaderContextTest, ContextWithSharedLibrariesDependenciesAndImage) {
1210 std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested");
1211 std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex");
1212
1213 std::string context = "PCL[" + GetTestDexFileName("Nested") + "]" +
1214 "{PCL[" + GetTestDexFileName("MultiDex") + "]" +
1215 "{PCL[" + GetTestDexFileName("Nested") + "]}}";
1216 std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "]" +
1217 "{PCL[" + CreateClassPathWithChecksums(dex_files2) + "]" +
1218 "{PCL[" + CreateClassPathWithChecksums(dex_files1) + "]}}";
1219 RunTest(context.c_str(),
1220 expected_classpath_key.c_str(),
1221 /*expected_success=*/ true,
1222 /*use_second_source=*/ false,
1223 /*generate_image=*/ true);
1224}
1225
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001226class Dex2oatDeterminism : public Dex2oatTest {};
1227
1228TEST_F(Dex2oatDeterminism, UnloadCompile) {
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001229 Runtime* const runtime = Runtime::Current();
1230 std::string out_dir = GetScratchDir();
1231 const std::string base_oat_name = out_dir + "/base.oat";
1232 const std::string base_vdex_name = out_dir + "/base.vdex";
1233 const std::string unload_oat_name = out_dir + "/unload.oat";
1234 const std::string unload_vdex_name = out_dir + "/unload.vdex";
1235 const std::string no_unload_oat_name = out_dir + "/nounload.oat";
1236 const std::string no_unload_vdex_name = out_dir + "/nounload.vdex";
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001237 std::string error_msg;
1238 const std::vector<gc::space::ImageSpace*>& spaces = runtime->GetHeap()->GetBootImageSpaces();
1239 ASSERT_GT(spaces.size(), 0u);
1240 const std::string image_location = spaces[0]->GetImageLocation();
1241 // Without passing in an app image, it will unload in between compilations.
1242 const int res = GenerateOdexForTestWithStatus(
1243 GetLibCoreDexFileNames(),
1244 base_oat_name,
Nicolas Geoffrayf50975a2020-10-15 13:34:55 +00001245 CompilerFilter::Filter::kVerify,
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001246 &error_msg,
1247 {"--force-determinism", "--avoid-storing-invocation"});
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001248 ASSERT_EQ(res, 0);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001249 Copy(base_oat_name, unload_oat_name);
1250 Copy(base_vdex_name, unload_vdex_name);
1251 std::unique_ptr<File> unload_oat(OS::OpenFileForReading(unload_oat_name.c_str()));
1252 std::unique_ptr<File> unload_vdex(OS::OpenFileForReading(unload_vdex_name.c_str()));
1253 ASSERT_TRUE(unload_oat != nullptr);
1254 ASSERT_TRUE(unload_vdex != nullptr);
1255 EXPECT_GT(unload_oat->GetLength(), 0u);
1256 EXPECT_GT(unload_vdex->GetLength(), 0u);
1257 // Regenerate with an app image to disable the dex2oat unloading and verify that the output is
1258 // the same.
1259 const int res2 = GenerateOdexForTestWithStatus(
1260 GetLibCoreDexFileNames(),
1261 base_oat_name,
Nicolas Geoffrayf50975a2020-10-15 13:34:55 +00001262 CompilerFilter::Filter::kVerify,
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001263 &error_msg,
Eric Holkbc89ed42020-04-29 19:59:24 +00001264 {"--force-determinism", "--avoid-storing-invocation", "--compile-individually"});
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001265 ASSERT_EQ(res2, 0);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001266 Copy(base_oat_name, no_unload_oat_name);
1267 Copy(base_vdex_name, no_unload_vdex_name);
1268 std::unique_ptr<File> no_unload_oat(OS::OpenFileForReading(no_unload_oat_name.c_str()));
1269 std::unique_ptr<File> no_unload_vdex(OS::OpenFileForReading(no_unload_vdex_name.c_str()));
1270 ASSERT_TRUE(no_unload_oat != nullptr);
1271 ASSERT_TRUE(no_unload_vdex != nullptr);
1272 EXPECT_GT(no_unload_oat->GetLength(), 0u);
1273 EXPECT_GT(no_unload_vdex->GetLength(), 0u);
1274 // Verify that both of the files are the same (odex and vdex).
1275 EXPECT_EQ(unload_oat->GetLength(), no_unload_oat->GetLength());
1276 EXPECT_EQ(unload_vdex->GetLength(), no_unload_vdex->GetLength());
1277 EXPECT_EQ(unload_oat->Compare(no_unload_oat.get()), 0)
1278 << unload_oat_name << " " << no_unload_oat_name;
1279 EXPECT_EQ(unload_vdex->Compare(no_unload_vdex.get()), 0)
1280 << unload_vdex_name << " " << no_unload_vdex_name;
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001281}
1282
Mathieu Chartier120aa282017-08-05 16:03:03 -07001283// Test that dexlayout section info is correctly written to the oat file for profile based
1284// compilation.
1285TEST_F(Dex2oatTest, LayoutSections) {
1286 using Hotness = ProfileCompilationInfo::MethodHotness;
1287 std::unique_ptr<const DexFile> dex(OpenTestDexFile("ManyMethods"));
1288 ScratchFile profile_file;
1289 // We can only layout method indices with code items, figure out which ones have this property
1290 // first.
1291 std::vector<uint16_t> methods;
1292 {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001293 const dex::TypeId* type_id = dex->FindTypeId("LManyMethods;");
Mathieu Chartier120aa282017-08-05 16:03:03 -07001294 dex::TypeIndex type_idx = dex->GetIndexForTypeId(*type_id);
Mathieu Chartier2242ef12018-07-23 18:14:13 -07001295 ClassAccessor accessor(*dex, *dex->FindClassDef(type_idx));
Mathieu Chartier120aa282017-08-05 16:03:03 -07001296 std::set<size_t> code_item_offsets;
Mathieu Chartier2242ef12018-07-23 18:14:13 -07001297 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
1298 const uint16_t method_idx = method.GetIndex();
1299 const size_t code_item_offset = method.GetCodeItemOffset();
Mathieu Chartier120aa282017-08-05 16:03:03 -07001300 if (code_item_offsets.insert(code_item_offset).second) {
1301 // Unique code item, add the method index.
1302 methods.push_back(method_idx);
1303 }
1304 }
Mathieu Chartier120aa282017-08-05 16:03:03 -07001305 }
1306 ASSERT_GE(methods.size(), 8u);
1307 std::vector<uint16_t> hot_methods = {methods[1], methods[3], methods[5]};
1308 std::vector<uint16_t> startup_methods = {methods[1], methods[2], methods[7]};
1309 std::vector<uint16_t> post_methods = {methods[0], methods[2], methods[6]};
1310 // Here, we build the profile from the method lists.
1311 ProfileCompilationInfo info;
1312 info.AddMethodsForDex(
1313 static_cast<Hotness::Flag>(Hotness::kFlagHot | Hotness::kFlagStartup),
1314 dex.get(),
1315 hot_methods.begin(),
1316 hot_methods.end());
1317 info.AddMethodsForDex(
1318 Hotness::kFlagStartup,
1319 dex.get(),
1320 startup_methods.begin(),
1321 startup_methods.end());
1322 info.AddMethodsForDex(
1323 Hotness::kFlagPostStartup,
1324 dex.get(),
1325 post_methods.begin(),
1326 post_methods.end());
1327 for (uint16_t id : hot_methods) {
1328 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsHot());
1329 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsStartup());
1330 }
1331 for (uint16_t id : startup_methods) {
1332 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsStartup());
1333 }
1334 for (uint16_t id : post_methods) {
1335 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsPostStartup());
1336 }
1337 // Save the profile since we want to use it with dex2oat to produce an oat file.
1338 ASSERT_TRUE(info.Save(profile_file.GetFd()));
1339 // Generate a profile based odex.
1340 const std::string dir = GetScratchDir();
1341 const std::string oat_filename = dir + "/base.oat";
1342 const std::string vdex_filename = dir + "/base.vdex";
1343 std::string error_msg;
1344 const int res = GenerateOdexForTestWithStatus(
1345 {dex->GetLocation()},
1346 oat_filename,
Nicolas Geoffrayf50975a2020-10-15 13:34:55 +00001347 CompilerFilter::Filter::kVerify,
Mathieu Chartier120aa282017-08-05 16:03:03 -07001348 &error_msg,
Nicolas Geoffraydb7c76b2022-03-21 16:23:30 +00001349 {"--profile-file=" + profile_file.GetFilename(),
1350 "--compact-dex-level=fast"});
Mathieu Chartier120aa282017-08-05 16:03:03 -07001351 EXPECT_EQ(res, 0);
1352
1353 // Open our generated oat file.
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001354 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01001355 oat_filename.c_str(),
Mathieu Chartier120aa282017-08-05 16:03:03 -07001356 oat_filename.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001357 /*executable=*/ false,
1358 /*low_4gb=*/ false,
Vladimir Markob7bf8432019-12-03 13:18:50 +00001359 dex->GetLocation(),
Mathieu Chartier120aa282017-08-05 16:03:03 -07001360 &error_msg));
1361 ASSERT_TRUE(odex_file != nullptr);
1362 std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
1363 ASSERT_EQ(oat_dex_files.size(), 1u);
1364 // Check that the code sections match what we expect.
1365 for (const OatDexFile* oat_dex : oat_dex_files) {
1366 const DexLayoutSections* const sections = oat_dex->GetDexLayoutSections();
1367 // Testing of logging the sections.
1368 ASSERT_TRUE(sections != nullptr);
1369 LOG(INFO) << *sections;
1370
1371 // Load the sections into temporary variables for convenience.
1372 const DexLayoutSection& code_section =
1373 sections->sections_[static_cast<size_t>(DexLayoutSections::SectionType::kSectionTypeCode)];
1374 const DexLayoutSection::Subsection& section_hot_code =
1375 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeHot)];
1376 const DexLayoutSection::Subsection& section_sometimes_used =
1377 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeSometimesUsed)];
1378 const DexLayoutSection::Subsection& section_startup_only =
1379 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeStartupOnly)];
1380 const DexLayoutSection::Subsection& section_unused =
1381 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeUnused)];
1382
1383 // All the sections should be non-empty.
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001384 EXPECT_GT(section_hot_code.Size(), 0u);
1385 EXPECT_GT(section_sometimes_used.Size(), 0u);
1386 EXPECT_GT(section_startup_only.Size(), 0u);
1387 EXPECT_GT(section_unused.Size(), 0u);
Mathieu Chartier120aa282017-08-05 16:03:03 -07001388
1389 // Open the dex file since we need to peek at the code items to verify the layout matches what
1390 // we expect.
1391 std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1392 ASSERT_TRUE(dex_file != nullptr) << error_msg;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001393 const dex::TypeId* type_id = dex_file->FindTypeId("LManyMethods;");
Mathieu Chartier120aa282017-08-05 16:03:03 -07001394 ASSERT_TRUE(type_id != nullptr);
1395 dex::TypeIndex type_idx = dex_file->GetIndexForTypeId(*type_id);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001396 const dex::ClassDef* class_def = dex_file->FindClassDef(type_idx);
Mathieu Chartier120aa282017-08-05 16:03:03 -07001397 ASSERT_TRUE(class_def != nullptr);
1398
1399 // Count how many code items are for each category, there should be at least one per category.
1400 size_t hot_count = 0;
1401 size_t post_startup_count = 0;
1402 size_t startup_count = 0;
1403 size_t unused_count = 0;
1404 // Visit all of the methdos of the main class and cross reference the method indices to their
1405 // corresponding code item offsets to verify the layout.
Mathieu Chartier2242ef12018-07-23 18:14:13 -07001406 ClassAccessor accessor(*dex_file, *class_def);
1407 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
1408 const size_t method_idx = method.GetIndex();
1409 const size_t code_item_offset = method.GetCodeItemOffset();
Mathieu Chartier120aa282017-08-05 16:03:03 -07001410 const bool is_hot = ContainsElement(hot_methods, method_idx);
1411 const bool is_startup = ContainsElement(startup_methods, method_idx);
1412 const bool is_post_startup = ContainsElement(post_methods, method_idx);
1413 if (is_hot) {
1414 // Hot is highest precedence, check that the hot methods are in the hot section.
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001415 EXPECT_TRUE(section_hot_code.Contains(code_item_offset));
Mathieu Chartier120aa282017-08-05 16:03:03 -07001416 ++hot_count;
1417 } else if (is_post_startup) {
1418 // Post startup is sometimes used section.
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001419 EXPECT_TRUE(section_sometimes_used.Contains(code_item_offset));
Mathieu Chartier120aa282017-08-05 16:03:03 -07001420 ++post_startup_count;
1421 } else if (is_startup) {
1422 // Startup at this point means not hot or post startup, these must be startup only then.
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001423 EXPECT_TRUE(section_startup_only.Contains(code_item_offset));
Mathieu Chartier120aa282017-08-05 16:03:03 -07001424 ++startup_count;
1425 } else {
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001426 if (section_unused.Contains(code_item_offset)) {
Alan Leung9595fd32017-10-17 17:08:19 -07001427 // If no flags are set, the method should be unused ...
1428 ++unused_count;
1429 } else {
1430 // or this method is part of the last code item and the end is 4 byte aligned.
Mathieu Chartier2242ef12018-07-23 18:14:13 -07001431 for (const ClassAccessor::Method& method2 : accessor.GetMethods()) {
1432 EXPECT_LE(method2.GetCodeItemOffset(), code_item_offset);
Alan Leung9595fd32017-10-17 17:08:19 -07001433 }
1434 uint32_t code_item_size = dex_file->FindCodeItemOffset(*class_def, method_idx);
1435 EXPECT_EQ((code_item_offset + code_item_size) % 4, 0u);
1436 }
Mathieu Chartier120aa282017-08-05 16:03:03 -07001437 }
1438 }
Mathieu Chartier120aa282017-08-05 16:03:03 -07001439 EXPECT_GT(hot_count, 0u);
1440 EXPECT_GT(post_startup_count, 0u);
1441 EXPECT_GT(startup_count, 0u);
1442 EXPECT_GT(unused_count, 0u);
1443 }
1444}
1445
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001446// Test that generating compact dex works.
1447TEST_F(Dex2oatTest, GenerateCompactDex) {
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001448 // Generate a compact dex based odex.
1449 const std::string dir = GetScratchDir();
1450 const std::string oat_filename = dir + "/base.oat";
1451 const std::string vdex_filename = dir + "/base.vdex";
Mathieu Chartierc17b7d82018-03-14 14:00:04 -07001452 const std::string dex_location = GetTestDexFileName("MultiDex");
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001453 std::string error_msg;
1454 const int res = GenerateOdexForTestWithStatus(
Mathieu Chartierc17b7d82018-03-14 14:00:04 -07001455 { dex_location },
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001456 oat_filename,
Nicolas Geoffrayf50975a2020-10-15 13:34:55 +00001457 CompilerFilter::Filter::kVerify,
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001458 &error_msg,
1459 {"--compact-dex-level=fast"});
1460 EXPECT_EQ(res, 0);
1461 // Open our generated oat file.
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001462 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01001463 oat_filename.c_str(),
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001464 oat_filename.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001465 /*executable=*/ false,
1466 /*low_4gb=*/ false,
Vladimir Markob7bf8432019-12-03 13:18:50 +00001467 dex_location,
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001468 &error_msg));
1469 ASSERT_TRUE(odex_file != nullptr);
1470 std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
Mathieu Chartierc17b7d82018-03-14 14:00:04 -07001471 ASSERT_GT(oat_dex_files.size(), 1u);
1472 // Check that each dex is a compact dex file.
1473 std::vector<std::unique_ptr<const CompactDexFile>> compact_dex_files;
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001474 for (const OatDexFile* oat_dex : oat_dex_files) {
1475 std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1476 ASSERT_TRUE(dex_file != nullptr) << error_msg;
1477 ASSERT_TRUE(dex_file->IsCompactDexFile());
Mathieu Chartierc17b7d82018-03-14 14:00:04 -07001478 compact_dex_files.push_back(
1479 std::unique_ptr<const CompactDexFile>(dex_file.release()->AsCompactDexFile()));
1480 }
1481 for (const std::unique_ptr<const CompactDexFile>& dex_file : compact_dex_files) {
1482 // Test that every code item is in the owned section.
1483 const CompactDexFile::Header& header = dex_file->GetHeader();
1484 EXPECT_LE(header.OwnedDataBegin(), header.OwnedDataEnd());
1485 EXPECT_LE(header.OwnedDataBegin(), header.data_size_);
1486 EXPECT_LE(header.OwnedDataEnd(), header.data_size_);
Mathieu Chartier2242ef12018-07-23 18:14:13 -07001487 for (ClassAccessor accessor : dex_file->GetClasses()) {
1488 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
1489 if (method.GetCodeItemOffset() != 0u) {
1490 ASSERT_GE(method.GetCodeItemOffset(), header.OwnedDataBegin());
1491 ASSERT_LT(method.GetCodeItemOffset(), header.OwnedDataEnd());
Mathieu Chartierc17b7d82018-03-14 14:00:04 -07001492 }
Mathieu Chartier2242ef12018-07-23 18:14:13 -07001493 }
Mathieu Chartierc17b7d82018-03-14 14:00:04 -07001494 }
1495 // Test that the owned sections don't overlap.
1496 for (const std::unique_ptr<const CompactDexFile>& other_dex : compact_dex_files) {
1497 if (dex_file != other_dex) {
1498 ASSERT_TRUE(
1499 (dex_file->GetHeader().OwnedDataBegin() >= other_dex->GetHeader().OwnedDataEnd()) ||
1500 (dex_file->GetHeader().OwnedDataEnd() <= other_dex->GetHeader().OwnedDataBegin()));
1501 }
1502 }
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001503 }
1504}
1505
Andreas Gampef39208f2017-10-19 15:06:59 -07001506class Dex2oatVerifierAbort : public Dex2oatTest {};
1507
1508TEST_F(Dex2oatVerifierAbort, HardFail) {
1509 // Use VerifierDeps as it has hard-failing classes.
1510 std::unique_ptr<const DexFile> dex(OpenTestDexFile("VerifierDeps"));
1511 std::string out_dir = GetScratchDir();
1512 const std::string base_oat_name = out_dir + "/base.oat";
1513 std::string error_msg;
1514 const int res_fail = GenerateOdexForTestWithStatus(
1515 {dex->GetLocation()},
1516 base_oat_name,
Nicolas Geoffrayf50975a2020-10-15 13:34:55 +00001517 CompilerFilter::Filter::kVerify,
Andreas Gampef39208f2017-10-19 15:06:59 -07001518 &error_msg,
1519 {"--abort-on-hard-verifier-error"});
1520 EXPECT_NE(0, res_fail);
1521
1522 const int res_no_fail = GenerateOdexForTestWithStatus(
1523 {dex->GetLocation()},
1524 base_oat_name,
Nicolas Geoffrayf50975a2020-10-15 13:34:55 +00001525 CompilerFilter::Filter::kVerify,
Andreas Gampef39208f2017-10-19 15:06:59 -07001526 &error_msg,
1527 {"--no-abort-on-hard-verifier-error"});
1528 EXPECT_EQ(0, res_no_fail);
1529}
1530
Andreas Gampecac31ad2017-11-06 20:01:17 -08001531class Dex2oatDedupeCode : public Dex2oatTest {};
1532
1533TEST_F(Dex2oatDedupeCode, DedupeTest) {
1534 // Use MyClassNatives. It has lots of native methods that will produce deduplicate-able code.
1535 std::unique_ptr<const DexFile> dex(OpenTestDexFile("MyClassNatives"));
1536 std::string out_dir = GetScratchDir();
1537 const std::string base_oat_name = out_dir + "/base.oat";
1538 size_t no_dedupe_size = 0;
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001539 ASSERT_TRUE(GenerateOdexForTest(dex->GetLocation(),
1540 base_oat_name,
1541 CompilerFilter::Filter::kSpeed,
1542 { "--deduplicate-code=false" },
Vladimir Marko21910692019-11-06 13:27:03 +00001543 /*expect_success=*/ true,
1544 /*use_fd=*/ false,
1545 /*use_zip_fd=*/ false,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001546 [&no_dedupe_size](const OatFile& o) {
1547 no_dedupe_size = o.Size();
1548 }));
Andreas Gampecac31ad2017-11-06 20:01:17 -08001549
1550 size_t dedupe_size = 0;
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001551 ASSERT_TRUE(GenerateOdexForTest(dex->GetLocation(),
1552 base_oat_name,
1553 CompilerFilter::Filter::kSpeed,
1554 { "--deduplicate-code=true" },
Vladimir Marko21910692019-11-06 13:27:03 +00001555 /*expect_success=*/ true,
1556 /*use_fd=*/ false,
1557 /*use_zip_fd=*/ false,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001558 [&dedupe_size](const OatFile& o) {
1559 dedupe_size = o.Size();
1560 }));
Andreas Gampecac31ad2017-11-06 20:01:17 -08001561
1562 EXPECT_LT(dedupe_size, no_dedupe_size);
1563}
1564
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00001565TEST_F(Dex2oatTest, UncompressedTest) {
David Srbecky8c8f1482020-02-05 20:17:10 +00001566 std::unique_ptr<const DexFile> dex(OpenTestDexFile("MainUncompressedAligned"));
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00001567 std::string out_dir = GetScratchDir();
1568 const std::string base_oat_name = out_dir + "/base.oat";
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001569 ASSERT_TRUE(GenerateOdexForTest(dex->GetLocation(),
1570 base_oat_name,
Nicolas Geoffrayf50975a2020-10-15 13:34:55 +00001571 CompilerFilter::Filter::kVerify,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001572 { },
Vladimir Marko21910692019-11-06 13:27:03 +00001573 /*expect_success=*/ true,
1574 /*use_fd=*/ false,
1575 /*use_zip_fd=*/ false,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001576 [](const OatFile& o) {
1577 CHECK(!o.ContainsDexCode());
1578 }));
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00001579}
1580
Vladimir Markod4290262021-05-21 16:36:23 +01001581TEST_F(Dex2oatTest, MissingBootImageTest) {
1582 std::string out_dir = GetScratchDir();
1583 const std::string base_oat_name = out_dir + "/base.oat";
Jiakai Zhange7815b82021-12-23 14:39:58 +00001584 // The compilation should succeed even without the boot image.
1585 ASSERT_TRUE(GenerateOdexForTest(
1586 {GetTestDexFileName("MainUncompressedAligned")},
Vladimir Markod4290262021-05-21 16:36:23 +01001587 base_oat_name,
1588 CompilerFilter::Filter::kVerify,
Vladimir Markod4290262021-05-21 16:36:23 +01001589 // Note: Extra options go last and the second `--boot-image` option overrides the first.
Jiakai Zhange7815b82021-12-23 14:39:58 +00001590 {"--boot-image=/nonx/boot.art"}));
Vladimir Markod4290262021-05-21 16:36:23 +01001591}
1592
Mathieu Chartier700a9852018-02-06 18:27:38 -08001593TEST_F(Dex2oatTest, EmptyUncompressedDexTest) {
1594 std::string out_dir = GetScratchDir();
1595 const std::string base_oat_name = out_dir + "/base.oat";
1596 std::string error_msg;
1597 int status = GenerateOdexForTestWithStatus(
1598 { GetTestDexFileName("MainEmptyUncompressed") },
1599 base_oat_name,
Nicolas Geoffrayf50975a2020-10-15 13:34:55 +00001600 CompilerFilter::Filter::kVerify,
Mathieu Chartier700a9852018-02-06 18:27:38 -08001601 &error_msg,
1602 { },
1603 /*use_fd*/ false);
1604 // Expect to fail with code 1 and not SIGSEGV or SIGABRT.
1605 ASSERT_TRUE(WIFEXITED(status));
1606 ASSERT_EQ(WEXITSTATUS(status), 1) << error_msg;
1607}
1608
Nicolas Geoffrayc36a8cc2019-04-29 13:37:42 +01001609TEST_F(Dex2oatTest, EmptyUncompressedAlignedDexTest) {
1610 std::string out_dir = GetScratchDir();
1611 const std::string base_oat_name = out_dir + "/base.oat";
1612 std::string error_msg;
1613 int status = GenerateOdexForTestWithStatus(
1614 { GetTestDexFileName("MainEmptyUncompressedAligned") },
1615 base_oat_name,
Nicolas Geoffrayf50975a2020-10-15 13:34:55 +00001616 CompilerFilter::Filter::kVerify,
Nicolas Geoffrayc36a8cc2019-04-29 13:37:42 +01001617 &error_msg,
1618 { },
1619 /*use_fd*/ false);
1620 // Expect to fail with code 1 and not SIGSEGV or SIGABRT.
1621 ASSERT_TRUE(WIFEXITED(status));
1622 ASSERT_EQ(WEXITSTATUS(status), 1) << error_msg;
1623}
1624
Mathieu Chartier05f90d12018-02-07 13:47:17 -08001625// Dex file that has duplicate methods have different code items and debug info.
1626static const char kDuplicateMethodInputDex[] =
1627 "ZGV4CjAzOQDEy8VPdj4qHpgPYFWtLCtOykfFP4kB8tGYDAAAcAAAAHhWNBIAAAAAAAAAANALAABI"
1628 "AAAAcAAAAA4AAACQAQAABQAAAMgBAAANAAAABAIAABkAAABsAgAABAAAADQDAADgCAAAuAMAADgI"
1629 "AABCCAAASggAAE8IAABcCAAAaggAAHkIAACICAAAlggAAKQIAACyCAAAwAgAAM4IAADcCAAA6ggA"
1630 "APgIAAD7CAAA/wgAABcJAAAuCQAARQkAAFQJAAB4CQAAmAkAALsJAADSCQAA5gkAAPoJAAAVCgAA"
1631 "KQoAADsKAABCCgAASgoAAFIKAABbCgAAZAoAAGwKAAB0CgAAfAoAAIQKAACMCgAAlAoAAJwKAACk"
1632 "CgAArQoAALcKAADACgAAwwoAAMcKAADcCgAA6QoAAPEKAAD3CgAA/QoAAAMLAAAJCwAAEAsAABcL"
1633 "AAAdCwAAIwsAACkLAAAvCwAANQsAADsLAABBCwAARwsAAE0LAABSCwAAWwsAAF4LAABoCwAAbwsA"
1634 "ABEAAAASAAAAEwAAABQAAAAVAAAAFgAAABcAAAAYAAAAGQAAABoAAAAbAAAAHAAAAC4AAAAwAAAA"
1635 "DwAAAAkAAAAAAAAAEAAAAAoAAACoBwAALgAAAAwAAAAAAAAALwAAAAwAAACoBwAALwAAAAwAAACw"
1636 "BwAAAgAJADUAAAACAAkANgAAAAIACQA3AAAAAgAJADgAAAACAAkAOQAAAAIACQA6AAAAAgAJADsA"
1637 "AAACAAkAPAAAAAIACQA9AAAAAgAJAD4AAAACAAkAPwAAAAIACQBAAAAACwAHAEIAAAAAAAIAAQAA"
1638 "AAAAAwAeAAAAAQACAAEAAAABAAMAHgAAAAIAAgAAAAAAAgACAAEAAAADAAIAAQAAAAMAAgAfAAAA"
1639 "AwACACAAAAADAAIAIQAAAAMAAgAiAAAAAwACACMAAAADAAIAJAAAAAMAAgAlAAAAAwACACYAAAAD"
1640 "AAIAJwAAAAMAAgAoAAAAAwACACkAAAADAAIAKgAAAAMABAA0AAAABwADAEMAAAAIAAIAAQAAAAoA"
1641 "AgABAAAACgABADIAAAAKAAAARQAAAAAAAAAAAAAACAAAAAAAAAAdAAAAaAcAALYHAAAAAAAAAQAA"
1642 "AAAAAAAIAAAAAAAAAB0AAAB4BwAAxAcAAAAAAAACAAAAAAAAAAgAAAAAAAAAHQAAAIgHAADSBwAA"
1643 "AAAAAAMAAAAAAAAACAAAAAAAAAAdAAAAmAcAAPoHAAAAAAAAAAAAAAEAAAAAAAAArAYAADEAAAAa"
1644 "AAMAaQAAABoABABpAAEAGgAHAGkABAAaAAgAaQAFABoACQBpAAYAGgAKAGkABwAaAAsAaQAIABoA"
1645 "DABpAAkAGgANAGkACgAaAA4AaQALABoABQBpAAIAGgAGAGkAAwAOAAAAAQABAAEAAACSBgAABAAA"
1646 "AHAQFQAAAA4ABAABAAIAAACWBgAAFwAAAGIADAAiAQoAcBAWAAEAGgICAG4gFwAhAG4gFwAxAG4Q"
1647 "GAABAAwBbiAUABAADgAAAAEAAQABAAAAngYAAAQAAABwEBUAAAAOAAIAAQACAAAAogYAAAYAAABi"
1648 "AAwAbiAUABAADgABAAEAAQAAAKgGAAAEAAAAcBAVAAAADgABAAEAAQAAALsGAAAEAAAAcBAVAAAA"
1649 "DgABAAAAAQAAAL8GAAAGAAAAYgAAAHEQAwAAAA4AAQAAAAEAAADEBgAABgAAAGIAAQBxEAMAAAAO"
1650 "AAEAAAABAAAA8QYAAAYAAABiAAIAcRABAAAADgABAAAAAQAAAPYGAAAGAAAAYgADAHEQAwAAAA4A"
1651 "AQAAAAEAAADJBgAABgAAAGIABABxEAMAAAAOAAEAAAABAAAAzgYAAAYAAABiAAEAcRADAAAADgAB"
1652 "AAAAAQAAANMGAAAGAAAAYgAGAHEQAwAAAA4AAQAAAAEAAADYBgAABgAAAGIABwBxEAMAAAAOAAEA"
1653 "AAABAAAA3QYAAAYAAABiAAgAcRABAAAADgABAAAAAQAAAOIGAAAGAAAAYgAJAHEQAwAAAA4AAQAA"
1654 "AAEAAADnBgAABgAAAGIACgBxEAMAAAAOAAEAAAABAAAA7AYAAAYAAABiAAsAcRABAAAADgABAAEA"
1655 "AAAAAPsGAAAlAAAAcQAHAAAAcQAIAAAAcQALAAAAcQAMAAAAcQANAAAAcQAOAAAAcQAPAAAAcQAQ"
1656 "AAAAcQARAAAAcQASAAAAcQAJAAAAcQAKAAAADgAnAA4AKQFFDgEWDwAhAA4AIwFFDloAEgAOABMA"
1657 "DktLS0tLS0tLS0tLABEADgAuAA5aADIADloANgAOWgA6AA5aAD4ADloAQgAOWgBGAA5aAEoADloA"
1658 "TgAOWgBSAA5aAFYADloAWgAOWgBeATQOPDw8PDw8PDw8PDw8AAIEAUYYAwIFAjEECEEXLAIFAjEE"
1659 "CEEXKwIFAjEECEEXLQIGAUYcAxgAGAEYAgAAAAIAAAAMBwAAEgcAAAIAAAAMBwAAGwcAAAIAAAAM"
1660 "BwAAJAcAAAEAAAAtBwAAPAcAAAAAAAAAAAAAAAAAAEgHAAAAAAAAAAAAAAAAAABUBwAAAAAAAAAA"
1661 "AAAAAAAAYAcAAAAAAAAAAAAAAAAAAAEAAAAJAAAAAQAAAA0AAAACAACAgASsCAEIxAgAAAIAAoCA"
1662 "BIQJAQicCQwAAgAACQEJAQkBCQEJAQkBCQEJAQkBCQEJAQkEiIAEuAcBgIAEuAkAAA4ABoCABNAJ"
1663 "AQnoCQAJhAoACaAKAAm8CgAJ2AoACfQKAAmQCwAJrAsACcgLAAnkCwAJgAwACZwMAAm4DAg8Y2xp"
1664 "bml0PgAGPGluaXQ+AANBQUEAC0hlbGxvIFdvcmxkAAxIZWxsbyBXb3JsZDEADUhlbGxvIFdvcmxk"
1665 "MTAADUhlbGxvIFdvcmxkMTEADEhlbGxvIFdvcmxkMgAMSGVsbG8gV29ybGQzAAxIZWxsbyBXb3Js"
1666 "ZDQADEhlbGxvIFdvcmxkNQAMSGVsbG8gV29ybGQ2AAxIZWxsbyBXb3JsZDcADEhlbGxvIFdvcmxk"
1667 "OAAMSGVsbG8gV29ybGQ5AAFMAAJMTAAWTE1hbnlNZXRob2RzJFByaW50ZXIyOwAVTE1hbnlNZXRo"
1668 "b2RzJFByaW50ZXI7ABVMTWFueU1ldGhvZHMkU3RyaW5nczsADUxNYW55TWV0aG9kczsAIkxkYWx2"
1669 "aWsvYW5ub3RhdGlvbi9FbmNsb3NpbmdDbGFzczsAHkxkYWx2aWsvYW5ub3RhdGlvbi9Jbm5lckNs"
1670 "YXNzOwAhTGRhbHZpay9hbm5vdGF0aW9uL01lbWJlckNsYXNzZXM7ABVMamF2YS9pby9QcmludFN0"
1671 "cmVhbTsAEkxqYXZhL2xhbmcvT2JqZWN0OwASTGphdmEvbGFuZy9TdHJpbmc7ABlMamF2YS9sYW5n"
1672 "L1N0cmluZ0J1aWxkZXI7ABJMamF2YS9sYW5nL1N5c3RlbTsAEE1hbnlNZXRob2RzLmphdmEABVBy"
1673 "aW50AAZQcmludDAABlByaW50MQAHUHJpbnQxMAAHUHJpbnQxMQAGUHJpbnQyAAZQcmludDMABlBy"
1674 "aW50NAAGUHJpbnQ1AAZQcmludDYABlByaW50NwAGUHJpbnQ4AAZQcmludDkAB1ByaW50ZXIACFBy"
1675 "aW50ZXIyAAdTdHJpbmdzAAFWAAJWTAATW0xqYXZhL2xhbmcvU3RyaW5nOwALYWNjZXNzRmxhZ3MA"
1676 "BmFwcGVuZAAEYXJncwAEbWFpbgAEbXNnMAAEbXNnMQAFbXNnMTAABW1zZzExAARtc2cyAARtc2cz"
1677 "AARtc2c0AARtc2c1AARtc2c2AARtc2c3AARtc2c4AARtc2c5AARuYW1lAANvdXQAB3ByaW50bG4A"
1678 "AXMACHRvU3RyaW5nAAV2YWx1ZQBffn5EOHsibWluLWFwaSI6MTAwMDAsInNoYS0xIjoiZmViODZj"
1679 "MDA2ZWZhY2YxZDc5ODRiODVlMTc5MGZlZjdhNzY3YWViYyIsInZlcnNpb24iOiJ2MS4xLjUtZGV2"
1680 "In0AEAAAAAAAAAABAAAAAAAAAAEAAABIAAAAcAAAAAIAAAAOAAAAkAEAAAMAAAAFAAAAyAEAAAQA"
1681 "AAANAAAABAIAAAUAAAAZAAAAbAIAAAYAAAAEAAAANAMAAAEgAAAUAAAAuAMAAAMgAAAUAAAAkgYA"
1682 "AAQgAAAFAAAADAcAAAMQAAAEAAAAOQcAAAYgAAAEAAAAaAcAAAEQAAACAAAAqAcAAAAgAAAEAAAA"
1683 "tgcAAAIgAABIAAAAOAgAAAAQAAABAAAA0AsAAAAAAAA=";
1684
1685static void WriteBase64ToFile(const char* base64, File* file) {
1686 // Decode base64.
1687 CHECK(base64 != nullptr);
1688 size_t length;
1689 std::unique_ptr<uint8_t[]> bytes(DecodeBase64(base64, &length));
1690 CHECK(bytes != nullptr);
1691 if (!file->WriteFully(bytes.get(), length)) {
1692 PLOG(FATAL) << "Failed to write base64 as file";
1693 }
1694}
1695
1696TEST_F(Dex2oatTest, CompactDexGenerationFailure) {
1697 ScratchFile temp_dex;
1698 WriteBase64ToFile(kDuplicateMethodInputDex, temp_dex.GetFile());
1699 std::string out_dir = GetScratchDir();
1700 const std::string oat_filename = out_dir + "/base.oat";
1701 // The dex won't pass the method verifier, only use the verify filter.
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001702 ASSERT_TRUE(GenerateOdexForTest(temp_dex.GetFilename(),
1703 oat_filename,
1704 CompilerFilter::Filter::kVerify,
1705 { },
Vladimir Marko21910692019-11-06 13:27:03 +00001706 /*expect_success=*/ true,
1707 /*use_fd=*/ false,
1708 /*use_zip_fd=*/ false,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001709 [](const OatFile& o) {
1710 CHECK(o.ContainsDexCode());
1711 }));
Mathieu Chartier05f90d12018-02-07 13:47:17 -08001712 // Open our generated oat file.
1713 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001714 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01001715 oat_filename.c_str(),
Mathieu Chartier05f90d12018-02-07 13:47:17 -08001716 oat_filename.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001717 /*executable=*/ false,
1718 /*low_4gb=*/ false,
Vladimir Markob7bf8432019-12-03 13:18:50 +00001719 temp_dex.GetFilename(),
Mathieu Chartier05f90d12018-02-07 13:47:17 -08001720 &error_msg));
1721 ASSERT_TRUE(odex_file != nullptr);
1722 std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
1723 ASSERT_EQ(oat_dex_files.size(), 1u);
1724 // The dexes should have failed to convert to compact dex.
1725 for (const OatDexFile* oat_dex : oat_dex_files) {
1726 std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1727 ASSERT_TRUE(dex_file != nullptr) << error_msg;
1728 ASSERT_TRUE(!dex_file->IsCompactDexFile());
1729 }
1730}
1731
Mathieu Chartiercda83be2018-03-01 23:55:55 -08001732TEST_F(Dex2oatTest, CompactDexGenerationFailureMultiDex) {
1733 // Create a multidex file with only one dex that gets rejected for cdex conversion.
1734 ScratchFile apk_file;
1735 {
Andreas Gampedfcd82c2018-10-16 20:22:37 -07001736 FILE* file = fdopen(DupCloexec(apk_file.GetFd()), "w+b");
Mathieu Chartiercda83be2018-03-01 23:55:55 -08001737 ZipWriter writer(file);
1738 // Add vdex to zip.
1739 writer.StartEntry("classes.dex", ZipWriter::kCompress);
1740 size_t length = 0u;
1741 std::unique_ptr<uint8_t[]> bytes(DecodeBase64(kDuplicateMethodInputDex, &length));
1742 ASSERT_GE(writer.WriteBytes(&bytes[0], length), 0);
1743 writer.FinishEntry();
1744 writer.StartEntry("classes2.dex", ZipWriter::kCompress);
1745 std::unique_ptr<const DexFile> dex(OpenTestDexFile("ManyMethods"));
1746 ASSERT_GE(writer.WriteBytes(dex->Begin(), dex->Size()), 0);
1747 writer.FinishEntry();
1748 writer.Finish();
1749 ASSERT_EQ(apk_file.GetFile()->Flush(), 0);
1750 }
Andreas Gampebc802de2018-06-20 17:24:11 -07001751 const std::string& dex_location = apk_file.GetFilename();
Mathieu Chartiercda83be2018-03-01 23:55:55 -08001752 const std::string odex_location = GetOdexDir() + "/output.odex";
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001753 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1754 odex_location,
Nicolas Geoffrayf50975a2020-10-15 13:34:55 +00001755 CompilerFilter::kVerify,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001756 { "--compact-dex-level=fast" },
1757 true));
Mathieu Chartiercda83be2018-03-01 23:55:55 -08001758}
1759
Andreas Gampe25419b52018-02-08 21:30:26 -08001760TEST_F(Dex2oatTest, StderrLoggerOutput) {
1761 std::string dex_location = GetScratchDir() + "/Dex2OatStderrLoggerTest.jar";
1762 std::string odex_location = GetOdexDir() + "/Dex2OatStderrLoggerTest.odex";
1763
1764 // Test file doesn't matter.
1765 Copy(GetDexSrc1(), dex_location);
1766
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001767 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1768 odex_location,
Nicolas Geoffrayf50975a2020-10-15 13:34:55 +00001769 CompilerFilter::kVerify,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001770 { "--runtime-arg", "-Xuse-stderr-logger" },
1771 true));
Andreas Gampe25419b52018-02-08 21:30:26 -08001772 // Look for some random part of dex2oat logging. With the stderr logger this should be captured,
1773 // even on device.
1774 EXPECT_NE(std::string::npos, output_.find("dex2oat took"));
1775}
1776
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001777TEST_F(Dex2oatTest, VerifyCompilationReason) {
1778 std::string dex_location = GetScratchDir() + "/Dex2OatCompilationReason.jar";
1779 std::string odex_location = GetOdexDir() + "/Dex2OatCompilationReason.odex";
1780
1781 // Test file doesn't matter.
1782 Copy(GetDexSrc1(), dex_location);
1783
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001784 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1785 odex_location,
1786 CompilerFilter::kVerify,
1787 { "--compilation-reason=install" },
1788 true));
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001789 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001790 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01001791 odex_location.c_str(),
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001792 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001793 /*executable=*/ false,
1794 /*low_4gb=*/ false,
Vladimir Markob7bf8432019-12-03 13:18:50 +00001795 dex_location,
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001796 &error_msg));
1797 ASSERT_TRUE(odex_file != nullptr);
1798 ASSERT_STREQ("install", odex_file->GetCompilationReason());
1799}
1800
1801TEST_F(Dex2oatTest, VerifyNoCompilationReason) {
1802 std::string dex_location = GetScratchDir() + "/Dex2OatNoCompilationReason.jar";
1803 std::string odex_location = GetOdexDir() + "/Dex2OatNoCompilationReason.odex";
1804
1805 // Test file doesn't matter.
1806 Copy(GetDexSrc1(), dex_location);
1807
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001808 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1809 odex_location,
1810 CompilerFilter::kVerify,
1811 {},
1812 true));
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001813 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001814 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01001815 odex_location.c_str(),
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001816 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001817 /*executable=*/ false,
1818 /*low_4gb=*/ false,
Vladimir Markob7bf8432019-12-03 13:18:50 +00001819 dex_location,
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001820 &error_msg));
1821 ASSERT_TRUE(odex_file != nullptr);
1822 ASSERT_EQ(nullptr, odex_file->GetCompilationReason());
1823}
1824
Mathieu Chartier792111c2018-02-15 13:02:15 -08001825TEST_F(Dex2oatTest, DontExtract) {
1826 std::unique_ptr<const DexFile> dex(OpenTestDexFile("ManyMethods"));
1827 std::string error_msg;
1828 const std::string out_dir = GetScratchDir();
1829 const std::string dex_location = dex->GetLocation();
1830 const std::string odex_location = out_dir + "/base.oat";
1831 const std::string vdex_location = out_dir + "/base.vdex";
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001832 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1833 odex_location,
1834 CompilerFilter::Filter::kVerify,
1835 { "--copy-dex-files=false" },
Vladimir Marko21910692019-11-06 13:27:03 +00001836 /*expect_success=*/ true,
1837 /*use_fd=*/ false,
1838 /*use_zip_fd=*/ false,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001839 [](const OatFile&) {}));
Mathieu Chartier792111c2018-02-15 13:02:15 -08001840 {
1841 // Check the vdex doesn't have dex.
1842 std::unique_ptr<VdexFile> vdex(VdexFile::Open(vdex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001843 /*writable=*/ false,
1844 /*low_4gb=*/ false,
Mathieu Chartier792111c2018-02-15 13:02:15 -08001845 &error_msg));
1846 ASSERT_TRUE(vdex != nullptr);
Nicolas Geoffray3a293552018-03-02 10:52:16 +00001847 EXPECT_FALSE(vdex->HasDexSection()) << output_;
Mathieu Chartier792111c2018-02-15 13:02:15 -08001848 }
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001849 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01001850 odex_location.c_str(),
Mathieu Chartier792111c2018-02-15 13:02:15 -08001851 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001852 /*executable=*/ false,
1853 /*low_4gb=*/ false,
Vladimir Markob7bf8432019-12-03 13:18:50 +00001854 dex_location,
Mathieu Chartier792111c2018-02-15 13:02:15 -08001855 &error_msg));
1856 ASSERT_TRUE(odex_file != nullptr) << dex_location;
1857 std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
1858 ASSERT_EQ(oat_dex_files.size(), 1u);
1859 // Verify that the oat file can still open the dex files.
1860 for (const OatDexFile* oat_dex : oat_dex_files) {
1861 std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1862 ASSERT_TRUE(dex_file != nullptr) << error_msg;
1863 }
1864 // Create a dm file and use it to verify.
1865 // Add produced artifacts to a zip file that doesn't contain the classes.dex.
1866 ScratchFile dm_file;
1867 {
1868 std::unique_ptr<File> vdex_file(OS::OpenFileForReading(vdex_location.c_str()));
1869 ASSERT_TRUE(vdex_file != nullptr);
1870 ASSERT_GT(vdex_file->GetLength(), 0u);
Andreas Gampedfcd82c2018-10-16 20:22:37 -07001871 FILE* file = fdopen(DupCloexec(dm_file.GetFd()), "w+b");
Mathieu Chartier792111c2018-02-15 13:02:15 -08001872 ZipWriter writer(file);
1873 auto write_all_bytes = [&](File* file) {
1874 std::unique_ptr<uint8_t[]> bytes(new uint8_t[file->GetLength()]);
1875 ASSERT_TRUE(file->ReadFully(&bytes[0], file->GetLength()));
1876 ASSERT_GE(writer.WriteBytes(&bytes[0], file->GetLength()), 0);
1877 };
1878 // Add vdex to zip.
1879 writer.StartEntry(VdexFile::kVdexNameInDmFile, ZipWriter::kCompress);
1880 write_all_bytes(vdex_file.get());
1881 writer.FinishEntry();
1882 writer.Finish();
1883 ASSERT_EQ(dm_file.GetFile()->Flush(), 0);
1884 }
1885
Mathieu Chartier2eabc612018-05-25 14:31:16 -07001886 auto generate_and_check = [&](CompilerFilter::Filter filter) {
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001887 output_.clear();
1888 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1889 odex_location,
1890 filter,
1891 { "--dump-timings",
1892 "--dm-file=" + dm_file.GetFilename(),
1893 // Pass -Xuse-stderr-logger have dex2oat output in output_ on
1894 // target.
1895 "--runtime-arg",
1896 "-Xuse-stderr-logger" },
Vladimir Marko21910692019-11-06 13:27:03 +00001897 /*expect_success=*/ true,
1898 /*use_fd=*/ false,
1899 /*use_zip_fd=*/ false,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001900 [](const OatFile& o) {
1901 CHECK(o.ContainsDexCode());
1902 }));
Mathieu Chartier2eabc612018-05-25 14:31:16 -07001903 // Check the output for "Fast verify", this is printed from --dump-timings.
1904 std::istringstream iss(output_);
1905 std::string line;
1906 bool found_fast_verify = false;
1907 const std::string kFastVerifyString = "Fast Verify";
1908 while (std::getline(iss, line) && !found_fast_verify) {
1909 found_fast_verify = found_fast_verify || line.find(kFastVerifyString) != std::string::npos;
1910 }
1911 EXPECT_TRUE(found_fast_verify) << "Expected to find " << kFastVerifyString << "\n" << output_;
1912 };
1913
Ian Pedowitz14464672020-07-24 09:40:26 -07001914 // Use verify compiler filter to check that FastVerify works for that filter too.
Mathieu Chartier2eabc612018-05-25 14:31:16 -07001915 generate_and_check(CompilerFilter::Filter::kVerify);
Mathieu Chartier792111c2018-02-15 13:02:15 -08001916}
1917
Mathieu Chartierd45863a2018-03-21 18:16:36 -07001918// Test that compact dex generation with invalid dex files doesn't crash dex2oat. b/75970654
1919TEST_F(Dex2oatTest, CompactDexInvalidSource) {
1920 ScratchFile invalid_dex;
1921 {
Andreas Gampedfcd82c2018-10-16 20:22:37 -07001922 FILE* file = fdopen(DupCloexec(invalid_dex.GetFd()), "w+b");
Mathieu Chartierd45863a2018-03-21 18:16:36 -07001923 ZipWriter writer(file);
1924 writer.StartEntry("classes.dex", ZipWriter::kAlign32);
1925 DexFile::Header header = {};
1926 StandardDexFile::WriteMagic(header.magic_);
1927 StandardDexFile::WriteCurrentVersion(header.magic_);
1928 header.file_size_ = 4 * KB;
1929 header.data_size_ = 4 * KB;
1930 header.data_off_ = 10 * MB;
1931 header.map_off_ = 10 * MB;
1932 header.class_defs_off_ = 10 * MB;
1933 header.class_defs_size_ = 10000;
1934 ASSERT_GE(writer.WriteBytes(&header, sizeof(header)), 0);
1935 writer.FinishEntry();
1936 writer.Finish();
1937 ASSERT_EQ(invalid_dex.GetFile()->Flush(), 0);
1938 }
Andreas Gampebc802de2018-06-20 17:24:11 -07001939 const std::string& dex_location = invalid_dex.GetFilename();
Mathieu Chartierd45863a2018-03-21 18:16:36 -07001940 const std::string odex_location = GetOdexDir() + "/output.odex";
1941 std::string error_msg;
1942 int status = GenerateOdexForTestWithStatus(
1943 {dex_location},
1944 odex_location,
Nicolas Geoffrayf50975a2020-10-15 13:34:55 +00001945 CompilerFilter::kVerify,
Mathieu Chartierd45863a2018-03-21 18:16:36 -07001946 &error_msg,
1947 { "--compact-dex-level=fast" });
1948 ASSERT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) != 0) << status << " " << output_;
1949}
1950
Mathieu Chartier14e7bad2018-03-22 14:33:20 -07001951// Test that dex2oat with a CompactDex file in the APK fails.
1952TEST_F(Dex2oatTest, CompactDexInZip) {
1953 CompactDexFile::Header header = {};
1954 CompactDexFile::WriteMagic(header.magic_);
1955 CompactDexFile::WriteCurrentVersion(header.magic_);
1956 header.file_size_ = sizeof(CompactDexFile::Header);
1957 header.data_off_ = 10 * MB;
1958 header.map_off_ = 10 * MB;
1959 header.class_defs_off_ = 10 * MB;
1960 header.class_defs_size_ = 10000;
1961 // Create a zip containing the invalid dex.
1962 ScratchFile invalid_dex_zip;
1963 {
Andreas Gampedfcd82c2018-10-16 20:22:37 -07001964 FILE* file = fdopen(DupCloexec(invalid_dex_zip.GetFd()), "w+b");
Mathieu Chartier14e7bad2018-03-22 14:33:20 -07001965 ZipWriter writer(file);
1966 writer.StartEntry("classes.dex", ZipWriter::kCompress);
1967 ASSERT_GE(writer.WriteBytes(&header, sizeof(header)), 0);
1968 writer.FinishEntry();
1969 writer.Finish();
1970 ASSERT_EQ(invalid_dex_zip.GetFile()->Flush(), 0);
1971 }
1972 // Create the dex file directly.
1973 ScratchFile invalid_dex;
1974 {
1975 ASSERT_GE(invalid_dex.GetFile()->WriteFully(&header, sizeof(header)), 0);
1976 ASSERT_EQ(invalid_dex.GetFile()->Flush(), 0);
1977 }
1978 std::string error_msg;
1979 int status = 0u;
1980
1981 status = GenerateOdexForTestWithStatus(
1982 { invalid_dex_zip.GetFilename() },
1983 GetOdexDir() + "/output_apk.odex",
Nicolas Geoffrayf50975a2020-10-15 13:34:55 +00001984 CompilerFilter::kVerify,
Mathieu Chartier14e7bad2018-03-22 14:33:20 -07001985 &error_msg,
1986 { "--compact-dex-level=fast" });
1987 ASSERT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) != 0) << status << " " << output_;
1988
1989 status = GenerateOdexForTestWithStatus(
1990 { invalid_dex.GetFilename() },
1991 GetOdexDir() + "/output.odex",
Nicolas Geoffrayf50975a2020-10-15 13:34:55 +00001992 CompilerFilter::kVerify,
Mathieu Chartier14e7bad2018-03-22 14:33:20 -07001993 &error_msg,
1994 { "--compact-dex-level=fast" });
1995 ASSERT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) != 0) << status << " " << output_;
1996}
1997
Calin Juravle028c7ef2021-05-26 15:37:00 -07001998TEST_F(Dex2oatWithExpectedFilterTest, AppImageNoProfile) {
1999 // Set the expected filter.
2000 expected_filter_ = CompilerFilter::Filter::kVerify;
2001
Mathieu Chartierf85b3db2018-04-02 18:16:21 -07002002 ScratchFile app_image_file;
2003 const std::string out_dir = GetScratchDir();
2004 const std::string odex_location = out_dir + "/base.odex";
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002005 ASSERT_TRUE(GenerateOdexForTest(GetTestDexFileName("ManyMethods"),
2006 odex_location,
2007 CompilerFilter::Filter::kSpeedProfile,
2008 { "--app-image-fd=" + std::to_string(app_image_file.GetFd()) },
Vladimir Marko21910692019-11-06 13:27:03 +00002009 /*expect_success=*/ true,
2010 /*use_fd=*/ false,
2011 /*use_zip_fd=*/ false,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002012 [](const OatFile&) {}));
Mathieu Chartierf85b3db2018-04-02 18:16:21 -07002013 // Open our generated oat file.
2014 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002015 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01002016 odex_location.c_str(),
Mathieu Chartierf85b3db2018-04-02 18:16:21 -07002017 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002018 /*executable=*/ false,
2019 /*low_4gb=*/ false,
Mathieu Chartierf85b3db2018-04-02 18:16:21 -07002020 &error_msg));
2021 ASSERT_TRUE(odex_file != nullptr);
2022 ImageHeader header = {};
2023 ASSERT_TRUE(app_image_file.GetFile()->PreadFully(
2024 reinterpret_cast<void*>(&header),
2025 sizeof(header),
2026 /*offset*/ 0u)) << app_image_file.GetFile()->GetLength();
2027 EXPECT_GT(header.GetImageSection(ImageHeader::kSectionObjects).Size(), 0u);
2028 EXPECT_EQ(header.GetImageSection(ImageHeader::kSectionArtMethods).Size(), 0u);
2029 EXPECT_EQ(header.GetImageSection(ImageHeader::kSectionArtFields).Size(), 0u);
2030}
2031
Vladimir Marko21910692019-11-06 13:27:03 +00002032TEST_F(Dex2oatTest, ZipFd) {
David Srbecky8c8f1482020-02-05 20:17:10 +00002033 std::string zip_location = GetTestDexFileName("MainUncompressedAligned");
Vladimir Marko21910692019-11-06 13:27:03 +00002034 std::unique_ptr<File> dex_file(OS::OpenFileForReading(zip_location.c_str()));
2035 std::vector<std::string> extra_args{
2036 StringPrintf("--zip-fd=%d", dex_file->Fd()),
2037 "--zip-location=" + zip_location,
2038 };
2039 std::string out_dir = GetScratchDir();
2040 const std::string base_oat_name = out_dir + "/base.oat";
2041 ASSERT_TRUE(GenerateOdexForTest(zip_location,
2042 base_oat_name,
Nicolas Geoffrayf50975a2020-10-15 13:34:55 +00002043 CompilerFilter::Filter::kVerify,
Vladimir Marko21910692019-11-06 13:27:03 +00002044 extra_args,
2045 /*expect_success=*/ true,
2046 /*use_fd=*/ false,
2047 /*use_zip_fd=*/ true));
2048}
2049
Calin Juravle028c7ef2021-05-26 15:37:00 -07002050TEST_F(Dex2oatWithExpectedFilterTest, AppImageEmptyDex) {
2051 // Set the expected filter.
2052 expected_filter_ = CompilerFilter::Filter::kVerify;
2053
Mathieu Chartier9c06d442020-04-01 14:11:05 -07002054 // Create a profile with the startup method marked.
2055 ScratchFile profile_file;
2056 ScratchFile temp_dex;
2057 const std::string& dex_location = temp_dex.GetFilename();
2058 std::vector<uint16_t> methods;
2059 std::vector<dex::TypeIndex> classes;
2060 {
2061 MutateDexFile(temp_dex.GetFile(), GetTestDexFileName("StringLiterals"), [&] (DexFile* dex) {
2062 // Modify the header to make the dex file valid but empty.
2063 DexFile::Header* header = const_cast<DexFile::Header*>(&dex->GetHeader());
2064 header->string_ids_size_ = 0;
2065 header->string_ids_off_ = 0;
2066 header->type_ids_size_ = 0;
2067 header->type_ids_off_ = 0;
2068 header->proto_ids_size_ = 0;
2069 header->proto_ids_off_ = 0;
2070 header->field_ids_size_ = 0;
2071 header->field_ids_off_ = 0;
2072 header->method_ids_size_ = 0;
2073 header->method_ids_off_ = 0;
2074 header->class_defs_size_ = 0;
2075 header->class_defs_off_ = 0;
2076 ASSERT_GT(header->file_size_,
2077 sizeof(*header) + sizeof(dex::MapList) + sizeof(dex::MapItem) * 2);
2078 // Move map list to be right after the header.
2079 header->map_off_ = sizeof(DexFile::Header);
2080 dex::MapList* map_list = const_cast<dex::MapList*>(dex->GetMapList());
2081 map_list->list_[0].type_ = DexFile::kDexTypeHeaderItem;
2082 map_list->list_[0].size_ = 1u;
2083 map_list->list_[0].offset_ = 0u;
2084 map_list->list_[1].type_ = DexFile::kDexTypeMapList;
2085 map_list->list_[1].size_ = 1u;
2086 map_list->list_[1].offset_ = header->map_off_;
2087 map_list->size_ = 2;
2088 header->data_off_ = header->map_off_;
2089 header->data_size_ = map_list->Size();
2090 });
2091 }
2092 std::unique_ptr<const DexFile> dex_file(OpenDexFile(temp_dex.GetFilename().c_str()));
2093 const std::string out_dir = GetScratchDir();
2094 const std::string odex_location = out_dir + "/base.odex";
2095 const std::string app_image_location = out_dir + "/base.art";
2096 ASSERT_TRUE(GenerateOdexForTest(dex_location,
2097 odex_location,
2098 CompilerFilter::Filter::kSpeedProfile,
2099 { "--app-image-file=" + app_image_location,
2100 "--resolve-startup-const-strings=true",
2101 "--profile-file=" + profile_file.GetFilename()},
2102 /*expect_success=*/ true,
2103 /*use_fd=*/ false,
2104 /*use_zip_fd=*/ false,
2105 [](const OatFile&) {}));
2106 // Open our generated oat file.
2107 std::string error_msg;
2108 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
2109 odex_location.c_str(),
2110 odex_location.c_str(),
2111 /*executable=*/ false,
2112 /*low_4gb=*/ false,
2113 &error_msg));
2114 ASSERT_TRUE(odex_file != nullptr);
2115}
2116
wangshumin3949e5e2019-11-08 19:25:50 +08002117TEST_F(Dex2oatTest, DexFileFd) {
2118 std::string error_msg;
2119 std::string zip_location = GetTestDexFileName("Main");
2120 std::unique_ptr<File> zip_file(OS::OpenFileForReading(zip_location.c_str()));
2121 ASSERT_NE(-1, zip_file->Fd());
2122
2123 std::unique_ptr<ZipArchive> zip_archive(
2124 ZipArchive::OpenFromFd(zip_file->Release(), zip_location.c_str(), &error_msg));
2125 ASSERT_TRUE(zip_archive != nullptr);
2126
2127 std::string entry_name = DexFileLoader::GetMultiDexClassesDexName(0);
2128 std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
2129 ASSERT_TRUE(entry != nullptr);
2130
2131 ScratchFile dex_file;
2132 const std::string& dex_location = dex_file.GetFilename();
2133 const std::string base_oat_name = GetScratchDir() + "/base.oat";
2134
2135 bool success = entry->ExtractToFile(*(dex_file.GetFile()), &error_msg);
2136 ASSERT_TRUE(success);
2137 ASSERT_EQ(0, lseek(dex_file.GetFd(), 0, SEEK_SET));
2138
2139 std::vector<std::string> extra_args{
2140 StringPrintf("--zip-fd=%d", dex_file.GetFd()),
2141 "--zip-location=" + dex_location,
2142 };
2143 ASSERT_TRUE(GenerateOdexForTest(dex_location,
2144 base_oat_name,
Nicolas Geoffrayf50975a2020-10-15 13:34:55 +00002145 CompilerFilter::Filter::kVerify,
wangshumin3949e5e2019-11-08 19:25:50 +08002146 extra_args,
2147 /*expect_success=*/ true,
2148 /*use_fd=*/ false,
2149 /*use_zip_fd=*/ true));
2150}
Mathieu Chartier9c06d442020-04-01 14:11:05 -07002151
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002152TEST_F(Dex2oatTest, AppImageResolveStrings) {
2153 using Hotness = ProfileCompilationInfo::MethodHotness;
2154 // Create a profile with the startup method marked.
2155 ScratchFile profile_file;
Mathieu Chartierc2109c62019-03-20 13:34:39 -07002156 ScratchFile temp_dex;
2157 const std::string& dex_location = temp_dex.GetFilename();
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002158 std::vector<uint16_t> methods;
Mathieu Chartier22752772018-10-18 14:18:59 -07002159 std::vector<dex::TypeIndex> classes;
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002160 {
Mathieu Chartierc2109c62019-03-20 13:34:39 -07002161 MutateDexFile(temp_dex.GetFile(), GetTestDexFileName("StringLiterals"), [&] (DexFile* dex) {
2162 bool mutated_successfully = false;
2163 // Change the dex instructions to make an opcode that spans past the end of the code item.
2164 for (ClassAccessor accessor : dex->GetClasses()) {
2165 if (accessor.GetDescriptor() == std::string("LStringLiterals$StartupClass;")) {
2166 classes.push_back(accessor.GetClassIdx());
2167 }
2168 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
2169 std::string method_name(dex->GetMethodName(dex->GetMethodId(method.GetIndex())));
2170 CodeItemInstructionAccessor instructions = method.GetInstructions();
2171 if (method_name == "startUpMethod2") {
2172 // Make an instruction that runs past the end of the code item and verify that it
2173 // doesn't cause dex2oat to crash.
2174 ASSERT_TRUE(instructions.begin() != instructions.end());
2175 DexInstructionIterator last_instruction = instructions.begin();
2176 for (auto dex_it = instructions.begin(); dex_it != instructions.end(); ++dex_it) {
2177 last_instruction = dex_it;
2178 }
2179 ASSERT_EQ(last_instruction->SizeInCodeUnits(), 1u);
2180 // Set the opcode to something that will go past the end of the code item.
2181 const_cast<Instruction&>(last_instruction.Inst()).SetOpcode(
2182 Instruction::CONST_STRING_JUMBO);
2183 mutated_successfully = true;
2184 // Test that the safe iterator doesn't go past the end.
2185 SafeDexInstructionIterator it2(instructions.begin(), instructions.end());
2186 while (!it2.IsErrorState()) {
2187 ++it2;
2188 }
2189 EXPECT_TRUE(it2 == last_instruction);
2190 EXPECT_TRUE(it2 < instructions.end());
2191 methods.push_back(method.GetIndex());
2192 mutated_successfully = true;
2193 } else if (method_name == "startUpMethod") {
2194 methods.push_back(method.GetIndex());
2195 }
Mathieu Chartier22752772018-10-18 14:18:59 -07002196 }
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002197 }
Mathieu Chartierc2109c62019-03-20 13:34:39 -07002198 CHECK(mutated_successfully)
2199 << "Failed to find candidate code item with only one code unit in last instruction.";
2200 });
2201 }
2202 std::unique_ptr<const DexFile> dex_file(OpenDexFile(temp_dex.GetFilename().c_str()));
2203 {
Mathieu Chartier22752772018-10-18 14:18:59 -07002204 ASSERT_GT(classes.size(), 0u);
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002205 ASSERT_GT(methods.size(), 0u);
2206 // Here, we build the profile from the method lists.
2207 ProfileCompilationInfo info;
Mathieu Chartierc2109c62019-03-20 13:34:39 -07002208 info.AddClassesForDex(dex_file.get(), classes.begin(), classes.end());
2209 info.AddMethodsForDex(Hotness::kFlagStartup, dex_file.get(), methods.begin(), methods.end());
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002210 // Save the profile since we want to use it with dex2oat to produce an oat file.
2211 ASSERT_TRUE(info.Save(profile_file.GetFd()));
2212 }
2213 const std::string out_dir = GetScratchDir();
2214 const std::string odex_location = out_dir + "/base.odex";
2215 const std::string app_image_location = out_dir + "/base.art";
Mathieu Chartierc2109c62019-03-20 13:34:39 -07002216 ASSERT_TRUE(GenerateOdexForTest(dex_location,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002217 odex_location,
2218 CompilerFilter::Filter::kSpeedProfile,
2219 { "--app-image-file=" + app_image_location,
2220 "--resolve-startup-const-strings=true",
2221 "--profile-file=" + profile_file.GetFilename()},
Vladimir Marko21910692019-11-06 13:27:03 +00002222 /*expect_success=*/ true,
2223 /*use_fd=*/ false,
2224 /*use_zip_fd=*/ false,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002225 [](const OatFile&) {}));
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002226 // Open our generated oat file.
2227 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002228 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002229 odex_location.c_str(),
2230 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002231 /*executable=*/ false,
2232 /*low_4gb=*/ false,
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002233 &error_msg));
2234 ASSERT_TRUE(odex_file != nullptr);
2235 // Check the strings in the app image intern table only contain the "startup" strigs.
2236 {
2237 ScopedObjectAccess soa(Thread::Current());
2238 std::unique_ptr<gc::space::ImageSpace> space =
2239 gc::space::ImageSpace::CreateFromAppImage(app_image_location.c_str(),
2240 odex_file.get(),
2241 &error_msg);
2242 ASSERT_TRUE(space != nullptr) << error_msg;
2243 std::set<std::string> seen;
2244 InternTable intern_table;
2245 intern_table.AddImageStringsToTable(space.get(), [&](InternTable::UnorderedSet& interns)
2246 REQUIRES_SHARED(Locks::mutator_lock_) {
2247 for (const GcRoot<mirror::String>& str : interns) {
2248 seen.insert(str.Read()->ToModifiedUtf8());
2249 }
2250 });
Mathieu Chartier22752772018-10-18 14:18:59 -07002251 // Normal methods
David Srbecky86d6cd52020-12-02 18:13:10 +00002252 EXPECT_TRUE(seen.find("Loading ") != seen.end());
2253 EXPECT_TRUE(seen.find("Starting up") != seen.end());
2254 EXPECT_TRUE(seen.find("abcd.apk") != seen.end());
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002255 EXPECT_TRUE(seen.find("Unexpected error") == seen.end());
2256 EXPECT_TRUE(seen.find("Shutting down!") == seen.end());
Mathieu Chartier22752772018-10-18 14:18:59 -07002257 // Classes initializers
David Srbecky86d6cd52020-12-02 18:13:10 +00002258 EXPECT_TRUE(seen.find("Startup init") != seen.end());
Mathieu Chartier22752772018-10-18 14:18:59 -07002259 EXPECT_TRUE(seen.find("Other class init") == seen.end());
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07002260 // Expect the sets match.
David Srbecky86d6cd52020-12-02 18:13:10 +00002261 EXPECT_GE(seen.size(), seen.size());
Mathieu Chartier8cc418e2018-10-31 10:54:30 -07002262
2263 // Verify what strings are marked as boot image.
2264 std::set<std::string> boot_image_strings;
2265 std::set<std::string> app_image_strings;
2266
2267 MutexLock mu(Thread::Current(), *Locks::intern_table_lock_);
2268 intern_table.VisitInterns([&](const GcRoot<mirror::String>& root)
2269 REQUIRES_SHARED(Locks::mutator_lock_) {
2270 boot_image_strings.insert(root.Read()->ToModifiedUtf8());
2271 }, /*visit_boot_images=*/true, /*visit_non_boot_images=*/false);
2272 intern_table.VisitInterns([&](const GcRoot<mirror::String>& root)
2273 REQUIRES_SHARED(Locks::mutator_lock_) {
2274 app_image_strings.insert(root.Read()->ToModifiedUtf8());
2275 }, /*visit_boot_images=*/false, /*visit_non_boot_images=*/true);
2276 EXPECT_EQ(boot_image_strings.size(), 0u);
2277 EXPECT_TRUE(app_image_strings == seen);
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002278 }
2279}
2280
2281
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002282TEST_F(Dex2oatClassLoaderContextTest, StoredClassLoaderContext) {
Mathieu Chartierc4440772018-04-16 14:40:56 -07002283 std::vector<std::unique_ptr<const DexFile>> dex_files = OpenTestDexFiles("MultiDex");
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002284 const std::string out_dir = GetScratchDir();
2285 const std::string odex_location = out_dir + "/base.odex";
Mathieu Chartierc4440772018-04-16 14:40:56 -07002286 const std::string valid_context = "PCL[" + dex_files[0]->GetLocation() + "]";
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002287 const std::string stored_context = "PCL[/system/not_real_lib.jar]";
Mathieu Chartierc4440772018-04-16 14:40:56 -07002288 std::string expected_stored_context = "PCL[";
2289 size_t index = 1;
2290 for (const std::unique_ptr<const DexFile>& dex_file : dex_files) {
2291 const bool is_first = index == 1u;
2292 if (!is_first) {
2293 expected_stored_context += ":";
2294 }
2295 expected_stored_context += "/system/not_real_lib.jar";
2296 if (!is_first) {
2297 expected_stored_context += "!classes" + std::to_string(index) + ".dex";
2298 }
2299 expected_stored_context += "*" + std::to_string(dex_file->GetLocationChecksum());
2300 ++index;
2301 }
2302 expected_stored_context += + "]";
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002303 // The class path should not be valid and should fail being stored.
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002304 EXPECT_TRUE(GenerateOdexForTest(GetTestDexFileName("ManyMethods"),
2305 odex_location,
Nicolas Geoffrayf50975a2020-10-15 13:34:55 +00002306 CompilerFilter::Filter::kVerify,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002307 { "--class-loader-context=" + stored_context },
Vladimir Marko21910692019-11-06 13:27:03 +00002308 /*expect_success=*/ true,
2309 /*use_fd=*/ false,
2310 /*use_zip_fd=*/ false,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002311 [&](const OatFile& oat_file) {
Mathieu Chartierc4440772018-04-16 14:40:56 -07002312 EXPECT_NE(oat_file.GetClassLoaderContext(), stored_context) << output_;
2313 EXPECT_NE(oat_file.GetClassLoaderContext(), valid_context) << output_;
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002314 }));
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002315 // The stored context should match what we expect even though it's invalid.
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002316 EXPECT_TRUE(GenerateOdexForTest(GetTestDexFileName("ManyMethods"),
2317 odex_location,
Nicolas Geoffrayf50975a2020-10-15 13:34:55 +00002318 CompilerFilter::Filter::kVerify,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002319 { "--class-loader-context=" + valid_context,
2320 "--stored-class-loader-context=" + stored_context },
Vladimir Marko21910692019-11-06 13:27:03 +00002321 /*expect_success=*/ true,
2322 /*use_fd=*/ false,
2323 /*use_zip_fd=*/ false,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002324 [&](const OatFile& oat_file) {
Mathieu Chartierc4440772018-04-16 14:40:56 -07002325 EXPECT_EQ(oat_file.GetClassLoaderContext(), expected_stored_context) << output_;
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002326 }));
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002327}
2328
xueliang.zhong7f88c1a2018-11-06 11:42:41 +00002329class Dex2oatISAFeaturesRuntimeDetectionTest : public Dex2oatTest {
2330 protected:
2331 void RunTest(const std::vector<std::string>& extra_args = {}) {
2332 std::string dex_location = GetScratchDir() + "/Dex2OatSwapTest.jar";
2333 std::string odex_location = GetOdexDir() + "/Dex2OatSwapTest.odex";
2334
2335 Copy(GetTestDexFileName(), dex_location);
2336
2337 ASSERT_TRUE(GenerateOdexForTest(dex_location,
2338 odex_location,
2339 CompilerFilter::kSpeed,
2340 extra_args));
2341 }
2342
2343 std::string GetTestDexFileName() {
2344 return GetDexSrc1();
2345 }
2346};
2347
2348TEST_F(Dex2oatISAFeaturesRuntimeDetectionTest, TestCurrentRuntimeFeaturesAsDex2OatArguments) {
2349 std::vector<std::string> argv;
2350 Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv);
2351 auto option_pos =
2352 std::find(std::begin(argv), std::end(argv), "--instruction-set-features=runtime");
2353 if (InstructionSetFeatures::IsRuntimeDetectionSupported()) {
2354 EXPECT_TRUE(kIsTargetBuild);
2355 EXPECT_NE(option_pos, std::end(argv));
2356 } else {
2357 EXPECT_EQ(option_pos, std::end(argv));
2358 }
2359
2360 RunTest();
2361}
2362
David Sehrfe57c2b2020-03-27 14:58:54 +00002363class LinkageTest : public Dex2oatTest {};
2364
2365TEST_F(LinkageTest, LinkageEnabled) {
2366 TEST_DISABLED_FOR_TARGET();
2367 std::unique_ptr<const DexFile> dex(OpenTestDexFile("LinkageTest"));
2368 std::string out_dir = GetScratchDir();
2369 const std::string base_oat_name = out_dir + "/base.oat";
2370 std::string error_msg;
2371 const int res_fail = GenerateOdexForTestWithStatus(
2372 {dex->GetLocation()},
2373 base_oat_name,
Nicolas Geoffrayf50975a2020-10-15 13:34:55 +00002374 CompilerFilter::Filter::kSpeed,
David Sehrfe57c2b2020-03-27 14:58:54 +00002375 &error_msg,
2376 {"--check-linkage-conditions", "--crash-on-linkage-violation"});
2377 EXPECT_NE(0, res_fail);
2378
2379 const int res_no_fail = GenerateOdexForTestWithStatus(
2380 {dex->GetLocation()},
2381 base_oat_name,
Nicolas Geoffrayf50975a2020-10-15 13:34:55 +00002382 CompilerFilter::Filter::kSpeed,
David Sehrfe57c2b2020-03-27 14:58:54 +00002383 &error_msg,
2384 {"--check-linkage-conditions"});
2385 EXPECT_EQ(0, res_no_fail);
2386}
2387
Vladimir Markoef8c3372021-03-17 15:01:42 +00002388// Regression test for bug 179221298.
2389TEST_F(Dex2oatTest, LoadOutOfDateOatFile) {
2390 std::unique_ptr<const DexFile> dex(OpenTestDexFile("ManyMethods"));
2391 std::string out_dir = GetScratchDir();
2392 const std::string base_oat_name = out_dir + "/base.oat";
2393 ASSERT_TRUE(GenerateOdexForTest(dex->GetLocation(),
2394 base_oat_name,
2395 CompilerFilter::Filter::kSpeed,
2396 { "--deduplicate-code=false" },
2397 /*expect_success=*/ true,
2398 /*use_fd=*/ false,
2399 /*use_zip_fd=*/ false));
2400
2401 // Check that we can open the oat file as executable.
2402 {
2403 std::string error_msg;
2404 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
2405 base_oat_name.c_str(),
2406 base_oat_name.c_str(),
2407 /*executable=*/ true,
2408 /*low_4gb=*/ false,
2409 dex->GetLocation(),
2410 &error_msg));
2411 ASSERT_TRUE(odex_file != nullptr) << error_msg;
2412 }
2413
2414 // Rewrite the oat file with wrong version and bogus contents.
2415 {
2416 std::unique_ptr<File> file(OS::OpenFileReadWrite(base_oat_name.c_str()));
2417 ASSERT_TRUE(file != nullptr);
2418 // Retrieve the offset and size of the embedded oat file.
2419 size_t oatdata_offset;
2420 size_t oatdata_size;
2421 {
2422 std::string error_msg;
2423 std::unique_ptr<ElfFile> elf_file(ElfFile::Open(file.get(),
2424 /*writable=*/ false,
2425 /*program_header_only=*/ true,
2426 /*low_4gb=*/ false,
2427 &error_msg));
2428 ASSERT_TRUE(elf_file != nullptr) << error_msg;
2429 ASSERT_TRUE(elf_file->Load(file.get(),
2430 /*executable=*/ false,
2431 /*low_4gb=*/ false,
2432 /*reservation=*/ nullptr,
2433 &error_msg)) << error_msg;
2434 const uint8_t* base_address = elf_file->Is64Bit()
2435 ? elf_file->GetImpl64()->GetBaseAddress()
2436 : elf_file->GetImpl32()->GetBaseAddress();
2437 const uint8_t* oatdata = elf_file->FindDynamicSymbolAddress("oatdata");
2438 ASSERT_TRUE(oatdata != nullptr);
2439 ASSERT_TRUE(oatdata > base_address);
2440 // Note: We're assuming here that the virtual address offset is the same
2441 // as file offset. This is currently true for all oat files we generate.
2442 oatdata_offset = static_cast<size_t>(oatdata - base_address);
2443 const uint8_t* oatlastword = elf_file->FindDynamicSymbolAddress("oatlastword");
2444 ASSERT_TRUE(oatlastword != nullptr);
2445 ASSERT_TRUE(oatlastword > oatdata);
2446 oatdata_size = oatlastword - oatdata;
2447 }
2448
2449 // Check that we have the right `oatdata_offset`.
2450 int64_t length = file->GetLength();
2451 ASSERT_GE(length, static_cast<ssize_t>(oatdata_offset + sizeof(OatHeader)));
2452 alignas(OatHeader) uint8_t header_data[sizeof(OatHeader)];
2453 ASSERT_TRUE(file->PreadFully(header_data, sizeof(header_data), oatdata_offset));
2454 const OatHeader& header = reinterpret_cast<const OatHeader&>(header_data);
2455 ASSERT_TRUE(header.IsValid()) << header.GetValidationErrorMessage();
2456
2457 // Overwrite all oat data from version onwards with bytes with value 4.
2458 // (0x04040404 is not a valid version, we're using three decimal digits and '\0'.)
2459 //
2460 // We previously tried to find the value for key "debuggable" (bug 179221298)
2461 // in the key-value store before checking the oat header. This test tries to
2462 // ensure that such early processing of the key-value store shall crash.
2463 // Reading 0x04040404 as the size of the key-value store yields a bit over
2464 // 64MiB which should hopefully include some unmapped memory beyond the end
2465 // of the loaded oat file. Overwriting the whole embedded oat file ensures
2466 // that we do not match the key within the oat file but we could still
2467 // accidentally match it in the additional sections of the elf file, so this
2468 // approach could fail to catch similar issues. At the time of writing, this
2469 // test crashed when run without the fix on 64-bit host (but not 32-bit).
2470 static constexpr size_t kVersionOffset = sizeof(OatHeader::kOatMagic);
2471 static_assert(kVersionOffset < sizeof(OatHeader));
2472 std::vector<uint8_t> data(oatdata_size - kVersionOffset, 4u);
2473 ASSERT_TRUE(file->PwriteFully(data.data(), data.size(), oatdata_offset + kVersionOffset));
2474 UNUSED(oatdata_size);
2475 CHECK_EQ(file->FlushClose(), 0) << "Could not flush and close oat file";
2476 }
2477
2478 // Check that we reject the oat file without crashing.
2479 {
2480 std::string error_msg;
2481 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
2482 base_oat_name.c_str(),
2483 base_oat_name.c_str(),
2484 /*executable=*/ true,
2485 /*low_4gb=*/ false,
2486 dex->GetLocation(),
2487 &error_msg));
2488 ASSERT_FALSE(odex_file != nullptr);
2489 }
2490}
2491
Andreas Gampee1459ae2016-06-29 09:36:30 -07002492} // namespace art