blob: e131e066ce3ac494607b020b420bb3162b225d78 [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
xueliang.zhong7f88c1a2018-11-06 11:42:41 +000017#include <algorithm>
Igor Murashkin5573c372017-11-16 13:34:30 -080018#include <regex>
Andreas Gampe7adeda82016-07-25 08:27:35 -070019#include <sstream>
Andreas Gampee1459ae2016-06-29 09:36:30 -070020#include <string>
21#include <vector>
Andreas Gampee1459ae2016-06-29 09:36:30 -070022
Andreas Gampe46ee31b2016-12-14 10:11:49 -080023#include <sys/wait.h>
24#include <unistd.h>
25
Andreas Gampe57943812017-12-06 21:39:13 -080026#include <android-base/logging.h>
Andreas Gampe50f9dc22018-11-05 10:29:43 -080027#include <android-base/macros.h>
Andreas Gampe57943812017-12-06 21:39:13 -080028#include <android-base/stringprintf.h>
Andreas Gampe46ee31b2016-12-14 10:11:49 -080029
Andreas Gampee1459ae2016-06-29 09:36:30 -070030#include "common_runtime_test.h"
31
xueliang.zhong7f88c1a2018-11-06 11:42:41 +000032#include "arch/instruction_set_features.h"
Andreas Gampee1459ae2016-06-29 09:36:30 -070033#include "base/macros.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070034#include "base/mutex-inl.h"
Vladimir Marko21910692019-11-06 13:27:03 +000035#include "base/string_view_cpp20.h"
David Sehrc431b9d2018-03-02 12:01:51 -080036#include "base/utils.h"
wangshumin3949e5e2019-11-08 19:25:50 +080037#include "base/zip_archive.h"
David Sehr013fd802018-01-11 22:55:24 -080038#include "dex/art_dex_file_loader.h"
Mathieu Chartier05f90d12018-02-07 13:47:17 -080039#include "dex/base64_test_util.h"
David Sehr312f3b22018-03-19 08:39:26 -070040#include "dex/bytecode_utils.h"
Mathieu Chartier2242ef12018-07-23 18:14:13 -070041#include "dex/class_accessor-inl.h"
David Sehr9e734c72018-01-04 17:56:19 -080042#include "dex/code_item_accessors-inl.h"
43#include "dex/dex_file-inl.h"
44#include "dex/dex_file_loader.h"
Andreas Gampee1459ae2016-06-29 09:36:30 -070045#include "dex2oat_environment_test.h"
Andreas Gampee15b9b12018-10-29 12:54:27 -070046#include "gc_root-inl.h"
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -070047#include "intern_table-inl.h"
Andreas Gampe67f02822016-06-24 21:05:23 -070048#include "oat.h"
49#include "oat_file.h"
David Sehr82d046e2018-04-23 08:14:19 -070050#include "profile/profile_compilation_info.h"
Mathieu Chartier792111c2018-02-15 13:02:15 -080051#include "vdex_file.h"
52#include "ziparchive/zip_writer.h"
Andreas Gampee1459ae2016-06-29 09:36:30 -070053
Andreas Gampee1459ae2016-06-29 09:36:30 -070054namespace art {
55
Mathieu Chartier9e050df2017-08-09 10:05:47 -070056static constexpr bool kDebugArgs = false;
Ming-Shin Lu7e9fc9d2020-10-12 03:36:52 +000057static const char* kDisableCompactDex = "--compact-dex-level=none";
Mathieu Chartierea650f32017-05-24 12:04:13 -070058
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080059using android::base::StringPrintf;
60
Andreas Gampee1459ae2016-06-29 09:36:30 -070061class Dex2oatTest : public Dex2oatEnvironmentTest {
62 public:
Roland Levillainf73caca2018-08-24 17:19:07 +010063 void TearDown() override {
Andreas Gampee1459ae2016-06-29 09:36:30 -070064 Dex2oatEnvironmentTest::TearDown();
65
66 output_ = "";
67 error_msg_ = "";
68 success_ = false;
69 }
70
71 protected:
Mathieu Chartier9e050df2017-08-09 10:05:47 -070072 int GenerateOdexForTestWithStatus(const std::vector<std::string>& dex_locations,
Andreas Gampef7882972017-03-20 16:35:24 -070073 const std::string& odex_location,
74 CompilerFilter::Filter filter,
75 std::string* error_msg,
76 const std::vector<std::string>& extra_args = {},
77 bool use_fd = false) {
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080078 std::unique_ptr<File> oat_file;
Andreas Gampee1459ae2016-06-29 09:36:30 -070079 std::vector<std::string> args;
Mathieu Chartier9e050df2017-08-09 10:05:47 -070080 // Add dex file args.
81 for (const std::string& dex_location : dex_locations) {
82 args.push_back("--dex-file=" + dex_location);
83 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080084 if (use_fd) {
85 oat_file.reset(OS::CreateEmptyFile(odex_location.c_str()));
86 CHECK(oat_file != nullptr) << odex_location;
87 args.push_back("--oat-fd=" + std::to_string(oat_file->Fd()));
Mathieu Chartier046854b2017-03-01 17:16:22 -080088 args.push_back("--oat-location=" + odex_location);
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080089 } else {
90 args.push_back("--oat-file=" + odex_location);
91 }
Andreas Gampee1459ae2016-06-29 09:36:30 -070092 args.push_back("--compiler-filter=" + CompilerFilter::NameOfFilter(filter));
93 args.push_back("--runtime-arg");
94 args.push_back("-Xnorelocate");
95
Andreas Gampe50f9dc22018-11-05 10:29:43 -080096 // Unless otherwise stated, use a small amount of threads, so that potential aborts are
97 // shorter. This can be overridden with extra_args.
98 args.push_back("-j4");
99
Andreas Gampee1459ae2016-06-29 09:36:30 -0700100 args.insert(args.end(), extra_args.begin(), extra_args.end());
101
Andreas Gampef7882972017-03-20 16:35:24 -0700102 int status = Dex2Oat(args, error_msg);
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800103 if (oat_file != nullptr) {
Andreas Gampef7882972017-03-20 16:35:24 -0700104 CHECK_EQ(oat_file->FlushClose(), 0) << "Could not flush and close oat file";
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800105 }
Andreas Gampef7882972017-03-20 16:35:24 -0700106 return status;
107 }
Andreas Gampee1459ae2016-06-29 09:36:30 -0700108
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800109 ::testing::AssertionResult GenerateOdexForTest(
Andreas Gampe641a4732017-08-24 13:21:35 -0700110 const std::string& dex_location,
111 const std::string& odex_location,
112 CompilerFilter::Filter filter,
113 const std::vector<std::string>& extra_args = {},
114 bool expect_success = true,
Vladimir Marko21910692019-11-06 13:27:03 +0000115 bool use_fd = false,
116 bool use_zip_fd = false) WARN_UNUSED {
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800117 return GenerateOdexForTest(dex_location,
118 odex_location,
119 filter,
120 extra_args,
121 expect_success,
122 use_fd,
Vladimir Marko21910692019-11-06 13:27:03 +0000123 use_zip_fd,
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800124 [](const OatFile&) {});
Andreas Gampe641a4732017-08-24 13:21:35 -0700125 }
126
Andreas Gampe80ddf272018-01-11 09:41:00 -0800127 bool test_accepts_odex_file_on_failure = false;
128
Andreas Gampe641a4732017-08-24 13:21:35 -0700129 template <typename T>
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800130 ::testing::AssertionResult GenerateOdexForTest(
Andreas Gampe641a4732017-08-24 13:21:35 -0700131 const std::string& dex_location,
132 const std::string& odex_location,
133 CompilerFilter::Filter filter,
134 const std::vector<std::string>& extra_args,
135 bool expect_success,
136 bool use_fd,
Vladimir Marko21910692019-11-06 13:27:03 +0000137 bool use_zip_fd,
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800138 T check_oat) WARN_UNUSED {
Vladimir Marko21910692019-11-06 13:27:03 +0000139 std::vector<std::string> dex_locations;
140 if (use_zip_fd) {
141 std::string loc_arg = "--zip-location=" + dex_location;
142 CHECK(std::any_of(extra_args.begin(),
143 extra_args.end(),
144 [&](const std::string& s) { return s == loc_arg; }));
145 CHECK(std::any_of(extra_args.begin(),
146 extra_args.end(),
147 [](const std::string& s) { return StartsWith(s, "--zip-fd="); }));
148 } else {
149 dex_locations.push_back(dex_location);
150 }
Andreas Gampef7882972017-03-20 16:35:24 -0700151 std::string error_msg;
Vladimir Marko21910692019-11-06 13:27:03 +0000152 int status = GenerateOdexForTestWithStatus(dex_locations,
Andreas Gampef7882972017-03-20 16:35:24 -0700153 odex_location,
154 filter,
155 &error_msg,
156 extra_args,
157 use_fd);
Andreas Gampe80ddf272018-01-11 09:41:00 -0800158 bool success = (WIFEXITED(status) && WEXITSTATUS(status) == 0);
Andreas Gampee1459ae2016-06-29 09:36:30 -0700159 if (expect_success) {
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800160 if (!success) {
161 return ::testing::AssertionFailure()
162 << "Failed to compile odex: " << error_msg << std::endl << output_;
163 }
Andreas Gampee1459ae2016-06-29 09:36:30 -0700164
165 // Verify the odex file was generated as expected.
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100166 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +0100167 odex_location.c_str(),
Andreas Gampee1459ae2016-06-29 09:36:30 -0700168 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100169 /*executable=*/ false,
170 /*low_4gb=*/ false,
Vladimir Markob7bf8432019-12-03 13:18:50 +0000171 dex_location,
Andreas Gampee1459ae2016-06-29 09:36:30 -0700172 &error_msg));
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800173 if (odex_file == nullptr) {
174 return ::testing::AssertionFailure() << "Could not open odex file: " << error_msg;
175 }
Andreas Gampee1459ae2016-06-29 09:36:30 -0700176
177 CheckFilter(filter, odex_file->GetCompilerFilter());
Calin Juravle1ce70852017-06-28 10:59:03 -0700178 check_oat(*(odex_file.get()));
Andreas Gampee1459ae2016-06-29 09:36:30 -0700179 } else {
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800180 if (success) {
181 return ::testing::AssertionFailure() << "Succeeded to compile odex: " << output_;
182 }
Andreas Gampee1459ae2016-06-29 09:36:30 -0700183
184 error_msg_ = error_msg;
185
Andreas Gampe80ddf272018-01-11 09:41:00 -0800186 if (!test_accepts_odex_file_on_failure) {
187 // Verify there's no loadable odex file.
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100188 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +0100189 odex_location.c_str(),
Andreas Gampe80ddf272018-01-11 09:41:00 -0800190 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100191 /*executable=*/ false,
192 /*low_4gb=*/ false,
Vladimir Markob7bf8432019-12-03 13:18:50 +0000193 dex_location,
Andreas Gampe80ddf272018-01-11 09:41:00 -0800194 &error_msg));
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800195 if (odex_file != nullptr) {
196 return ::testing::AssertionFailure() << "Could open odex file: " << error_msg;
197 }
Andreas Gampe80ddf272018-01-11 09:41:00 -0800198 }
Andreas Gampee1459ae2016-06-29 09:36:30 -0700199 }
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800200 return ::testing::AssertionSuccess();
Andreas Gampee1459ae2016-06-29 09:36:30 -0700201 }
202
Calin Juravle1ccf6132017-08-02 17:46:53 -0700203 // Check the input compiler filter against the generated oat file's filter. May be overridden
Andreas Gampee1459ae2016-06-29 09:36:30 -0700204 // in subclasses when equality is not expected.
205 virtual void CheckFilter(CompilerFilter::Filter expected, CompilerFilter::Filter actual) {
206 EXPECT_EQ(expected, actual);
207 }
208
Andreas Gampef7882972017-03-20 16:35:24 -0700209 int Dex2Oat(const std::vector<std::string>& dex2oat_args, std::string* error_msg) {
Vladimir Marko7a85e702018-12-03 18:47:23 +0000210 std::vector<std::string> argv;
211 if (!CommonRuntimeTest::StartDex2OatCommandLine(&argv, error_msg)) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700212 return false;
213 }
Andreas Gampee1459ae2016-06-29 09:36:30 -0700214
Vladimir Marko7a85e702018-12-03 18:47:23 +0000215 Runtime* runtime = Runtime::Current();
Andreas Gampee1459ae2016-06-29 09:36:30 -0700216 if (!runtime->IsVerificationEnabled()) {
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100217 argv.push_back("--compiler-filter=assume-verified");
Andreas Gampee1459ae2016-06-29 09:36:30 -0700218 }
219
220 if (runtime->MustRelocateIfPossible()) {
221 argv.push_back("--runtime-arg");
222 argv.push_back("-Xrelocate");
223 } else {
224 argv.push_back("--runtime-arg");
225 argv.push_back("-Xnorelocate");
226 }
227
228 if (!kIsTargetBuild) {
229 argv.push_back("--host");
230 }
231
Andreas Gampee1459ae2016-06-29 09:36:30 -0700232 argv.insert(argv.end(), dex2oat_args.begin(), dex2oat_args.end());
233
234 // We must set --android-root.
235 const char* android_root = getenv("ANDROID_ROOT");
236 CHECK(android_root != nullptr);
237 argv.push_back("--android-root=" + std::string(android_root));
238
Mathieu Chartier9e050df2017-08-09 10:05:47 -0700239 if (kDebugArgs) {
240 std::string all_args;
241 for (const std::string& arg : argv) {
242 all_args += arg + " ";
243 }
244 LOG(ERROR) << all_args;
245 }
246
Andreas Gampe38aa0b52018-07-10 23:26:55 -0700247 // We need dex2oat to actually log things.
248 auto post_fork_fn = []() { return setenv("ANDROID_LOG_TAGS", "*:d", 1) == 0; };
249 ForkAndExecResult res = ForkAndExec(argv, post_fork_fn, &output_);
250 if (res.stage != ForkAndExecResult::kFinished) {
251 *error_msg = strerror(errno);
252 return -1;
Nicolas Geoffray56fe0f02016-06-30 15:07:46 +0100253 }
Andreas Gampe38aa0b52018-07-10 23:26:55 -0700254 success_ = res.StandardSuccess();
255 return res.status_code;
Andreas Gampee1459ae2016-06-29 09:36:30 -0700256 }
257
258 std::string output_ = "";
259 std::string error_msg_ = "";
260 bool success_ = false;
261};
262
263class Dex2oatSwapTest : public Dex2oatTest {
264 protected:
265 void RunTest(bool use_fd, bool expect_use, const std::vector<std::string>& extra_args = {}) {
266 std::string dex_location = GetScratchDir() + "/Dex2OatSwapTest.jar";
267 std::string odex_location = GetOdexDir() + "/Dex2OatSwapTest.odex";
268
Andreas Gampe7adeda82016-07-25 08:27:35 -0700269 Copy(GetTestDexFileName(), dex_location);
Andreas Gampee1459ae2016-06-29 09:36:30 -0700270
271 std::vector<std::string> copy(extra_args);
272
273 std::unique_ptr<ScratchFile> sf;
274 if (use_fd) {
275 sf.reset(new ScratchFile());
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800276 copy.push_back(android::base::StringPrintf("--swap-fd=%d", sf->GetFd()));
Andreas Gampee1459ae2016-06-29 09:36:30 -0700277 } else {
278 std::string swap_location = GetOdexDir() + "/Dex2OatSwapTest.odex.swap";
279 copy.push_back("--swap-file=" + swap_location);
280 }
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800281 ASSERT_TRUE(GenerateOdexForTest(dex_location, odex_location, CompilerFilter::kSpeed, copy));
Andreas Gampee1459ae2016-06-29 09:36:30 -0700282
283 CheckValidity();
284 ASSERT_TRUE(success_);
285 CheckResult(expect_use);
286 }
287
Andreas Gampe7adeda82016-07-25 08:27:35 -0700288 virtual std::string GetTestDexFileName() {
Vladimir Marko15357702017-02-09 10:37:31 +0000289 return Dex2oatEnvironmentTest::GetTestDexFileName("VerifierDeps");
Andreas Gampe7adeda82016-07-25 08:27:35 -0700290 }
291
292 virtual void CheckResult(bool expect_use) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700293 if (kIsTargetBuild) {
294 CheckTargetResult(expect_use);
295 } else {
296 CheckHostResult(expect_use);
297 }
298 }
299
Andreas Gampe7adeda82016-07-25 08:27:35 -0700300 virtual void CheckTargetResult(bool expect_use ATTRIBUTE_UNUSED) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700301 // TODO: Ignore for now, as we won't capture any output (it goes to the logcat). We may do
302 // something for variants with file descriptor where we can control the lifetime of
303 // the swap file and thus take a look at it.
304 }
305
Andreas Gampe7adeda82016-07-25 08:27:35 -0700306 virtual void CheckHostResult(bool expect_use) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700307 if (!kIsTargetBuild) {
308 if (expect_use) {
309 EXPECT_NE(output_.find("Large app, accepted running with swap."), std::string::npos)
310 << output_;
311 } else {
312 EXPECT_EQ(output_.find("Large app, accepted running with swap."), std::string::npos)
313 << output_;
314 }
315 }
316 }
317
318 // Check whether the dex2oat run was really successful.
Andreas Gampe7adeda82016-07-25 08:27:35 -0700319 virtual void CheckValidity() {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700320 if (kIsTargetBuild) {
321 CheckTargetValidity();
322 } else {
323 CheckHostValidity();
324 }
325 }
326
Andreas Gampe7adeda82016-07-25 08:27:35 -0700327 virtual void CheckTargetValidity() {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700328 // TODO: Ignore for now, as we won't capture any output (it goes to the logcat). We may do
329 // something for variants with file descriptor where we can control the lifetime of
330 // the swap file and thus take a look at it.
331 }
332
333 // On the host, we can get the dex2oat output. Here, look for "dex2oat took."
Andreas Gampe7adeda82016-07-25 08:27:35 -0700334 virtual void CheckHostValidity() {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700335 EXPECT_NE(output_.find("dex2oat took"), std::string::npos) << output_;
336 }
337};
338
339TEST_F(Dex2oatSwapTest, DoNotUseSwapDefaultSingleSmall) {
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100340 RunTest(/*use_fd=*/ false, /*expect_use=*/ false);
341 RunTest(/*use_fd=*/ true, /*expect_use=*/ false);
Andreas Gampee1459ae2016-06-29 09:36:30 -0700342}
343
344TEST_F(Dex2oatSwapTest, DoNotUseSwapSingle) {
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100345 RunTest(/*use_fd=*/ false, /*expect_use=*/ false, { "--swap-dex-size-threshold=0" });
346 RunTest(/*use_fd=*/ true, /*expect_use=*/ false, { "--swap-dex-size-threshold=0" });
Andreas Gampee1459ae2016-06-29 09:36:30 -0700347}
348
349TEST_F(Dex2oatSwapTest, DoNotUseSwapSmall) {
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100350 RunTest(/*use_fd=*/ false, /*expect_use=*/ false, { "--swap-dex-count-threshold=0" });
351 RunTest(/*use_fd=*/ true, /*expect_use=*/ false, { "--swap-dex-count-threshold=0" });
Andreas Gampee1459ae2016-06-29 09:36:30 -0700352}
353
354TEST_F(Dex2oatSwapTest, DoUseSwapSingleSmall) {
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100355 RunTest(/*use_fd=*/ false,
356 /*expect_use=*/ true,
Andreas Gampee1459ae2016-06-29 09:36:30 -0700357 { "--swap-dex-size-threshold=0", "--swap-dex-count-threshold=0" });
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100358 RunTest(/*use_fd=*/ true,
359 /*expect_use=*/ true,
Andreas Gampee1459ae2016-06-29 09:36:30 -0700360 { "--swap-dex-size-threshold=0", "--swap-dex-count-threshold=0" });
361}
362
Andreas Gampe7adeda82016-07-25 08:27:35 -0700363class Dex2oatSwapUseTest : public Dex2oatSwapTest {
364 protected:
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100365 void CheckHostResult(bool expect_use) override {
Andreas Gampe7adeda82016-07-25 08:27:35 -0700366 if (!kIsTargetBuild) {
367 if (expect_use) {
368 EXPECT_NE(output_.find("Large app, accepted running with swap."), std::string::npos)
369 << output_;
370 } else {
371 EXPECT_EQ(output_.find("Large app, accepted running with swap."), std::string::npos)
372 << output_;
373 }
374 }
375 }
376
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100377 std::string GetTestDexFileName() override {
Andreas Gampe7adeda82016-07-25 08:27:35 -0700378 // Use Statics as it has a handful of functions.
379 return CommonRuntimeTest::GetTestDexFileName("Statics");
380 }
381
382 void GrabResult1() {
383 if (!kIsTargetBuild) {
384 native_alloc_1_ = ParseNativeAlloc();
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100385 swap_1_ = ParseSwap(/*expected=*/ false);
Andreas Gampe7adeda82016-07-25 08:27:35 -0700386 } else {
387 native_alloc_1_ = std::numeric_limits<size_t>::max();
388 swap_1_ = 0;
389 }
390 }
391
392 void GrabResult2() {
393 if (!kIsTargetBuild) {
394 native_alloc_2_ = ParseNativeAlloc();
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100395 swap_2_ = ParseSwap(/*expected=*/ true);
Andreas Gampe7adeda82016-07-25 08:27:35 -0700396 } else {
397 native_alloc_2_ = 0;
398 swap_2_ = std::numeric_limits<size_t>::max();
399 }
400 }
401
402 private:
403 size_t ParseNativeAlloc() {
404 std::regex native_alloc_regex("dex2oat took.*native alloc=[^ ]+ \\(([0-9]+)B\\)");
405 std::smatch native_alloc_match;
406 bool found = std::regex_search(output_, native_alloc_match, native_alloc_regex);
407 if (!found) {
408 EXPECT_TRUE(found);
409 return 0;
410 }
411 if (native_alloc_match.size() != 2U) {
412 EXPECT_EQ(native_alloc_match.size(), 2U);
413 return 0;
414 }
415
416 std::istringstream stream(native_alloc_match[1].str());
417 size_t value;
418 stream >> value;
419
420 return value;
421 }
422
423 size_t ParseSwap(bool expected) {
424 std::regex swap_regex("dex2oat took[^\\n]+swap=[^ ]+ \\(([0-9]+)B\\)");
425 std::smatch swap_match;
426 bool found = std::regex_search(output_, swap_match, swap_regex);
427 if (found != expected) {
428 EXPECT_EQ(expected, found);
429 return 0;
430 }
431
432 if (!found) {
433 return 0;
434 }
435
436 if (swap_match.size() != 2U) {
437 EXPECT_EQ(swap_match.size(), 2U);
438 return 0;
439 }
440
441 std::istringstream stream(swap_match[1].str());
442 size_t value;
443 stream >> value;
444
445 return value;
446 }
447
448 protected:
449 size_t native_alloc_1_;
450 size_t native_alloc_2_;
451
452 size_t swap_1_;
453 size_t swap_2_;
454};
455
456TEST_F(Dex2oatSwapUseTest, CheckSwapUsage) {
Roland Levillain05e34f42018-05-24 13:19:05 +0000457 // Native memory usage isn't correctly tracked when running under ASan.
458 TEST_DISABLED_FOR_MEMORY_TOOL();
Andreas Gampef4a67fd2017-05-04 09:55:36 -0700459
Vladimir Marko57070da2017-02-14 16:16:30 +0000460 // The `native_alloc_2_ >= native_alloc_1_` assertion below may not
Evgeny Astigeevichd2ac3072020-01-29 11:51:40 +0000461 // hold true on some x86 or x86_64 systems; disable this test while we
Roland Levillain19772bf2017-02-16 11:28:10 +0000462 // investigate (b/29259363).
Alex Lighte0c6d432020-01-22 22:04:20 +0000463 TEST_DISABLED_FOR_X86();
Evgeny Astigeevichd2ac3072020-01-29 11:51:40 +0000464 TEST_DISABLED_FOR_X86_64();
Vladimir Marko57070da2017-02-14 16:16:30 +0000465
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100466 RunTest(/*use_fd=*/ false,
467 /*expect_use=*/ false);
Andreas Gampe7adeda82016-07-25 08:27:35 -0700468 GrabResult1();
469 std::string output_1 = output_;
470
471 output_ = "";
472
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100473 RunTest(/*use_fd=*/ false,
474 /*expect_use=*/ true,
Andreas Gampe7adeda82016-07-25 08:27:35 -0700475 { "--swap-dex-size-threshold=0", "--swap-dex-count-threshold=0" });
476 GrabResult2();
477 std::string output_2 = output_;
478
479 if (native_alloc_2_ >= native_alloc_1_ || swap_1_ >= swap_2_) {
480 EXPECT_LT(native_alloc_2_, native_alloc_1_);
481 EXPECT_LT(swap_1_, swap_2_);
482
483 LOG(ERROR) << output_1;
484 LOG(ERROR) << output_2;
485 }
486}
487
Andreas Gampe67f02822016-06-24 21:05:23 -0700488class Dex2oatVeryLargeTest : public Dex2oatTest {
489 protected:
490 void CheckFilter(CompilerFilter::Filter input ATTRIBUTE_UNUSED,
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100491 CompilerFilter::Filter result ATTRIBUTE_UNUSED) override {
Andreas Gampe67f02822016-06-24 21:05:23 -0700492 // Ignore, we'll do our own checks.
493 }
494
495 void RunTest(CompilerFilter::Filter filter,
496 bool expect_large,
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700497 bool expect_downgrade,
Andreas Gampe67f02822016-06-24 21:05:23 -0700498 const std::vector<std::string>& extra_args = {}) {
499 std::string dex_location = GetScratchDir() + "/DexNoOat.jar";
500 std::string odex_location = GetOdexDir() + "/DexOdexNoOat.odex";
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700501 std::string app_image_file = GetScratchDir() + "/Test.art";
Andreas Gampe67f02822016-06-24 21:05:23 -0700502
503 Copy(GetDexSrc1(), dex_location);
504
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700505 std::vector<std::string> new_args(extra_args);
506 new_args.push_back("--app-image-file=" + app_image_file);
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800507 ASSERT_TRUE(GenerateOdexForTest(dex_location, odex_location, filter, new_args));
Andreas Gampe67f02822016-06-24 21:05:23 -0700508
509 CheckValidity();
510 ASSERT_TRUE(success_);
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700511 CheckResult(dex_location,
512 odex_location,
513 app_image_file,
514 filter,
515 expect_large,
516 expect_downgrade);
Andreas Gampe67f02822016-06-24 21:05:23 -0700517 }
518
519 void CheckResult(const std::string& dex_location,
520 const std::string& odex_location,
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700521 const std::string& app_image_file,
Andreas Gampe67f02822016-06-24 21:05:23 -0700522 CompilerFilter::Filter filter,
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700523 bool expect_large,
524 bool expect_downgrade) {
525 if (expect_downgrade) {
526 EXPECT_TRUE(expect_large);
527 }
Andreas Gampe67f02822016-06-24 21:05:23 -0700528 // Host/target independent checks.
529 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100530 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +0100531 odex_location.c_str(),
Andreas Gampe67f02822016-06-24 21:05:23 -0700532 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100533 /*executable=*/ false,
534 /*low_4gb=*/ false,
Vladimir Markob7bf8432019-12-03 13:18:50 +0000535 dex_location,
Andreas Gampe67f02822016-06-24 21:05:23 -0700536 &error_msg));
537 ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700538 EXPECT_GT(app_image_file.length(), 0u);
539 std::unique_ptr<File> file(OS::OpenFileForReading(app_image_file.c_str()));
Andreas Gampe67f02822016-06-24 21:05:23 -0700540 if (expect_large) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700541 // Note: we cannot check the following
542 // EXPECT_FALSE(CompilerFilter::IsAotCompilationEnabled(odex_file->GetCompilerFilter()));
Andreas Gampe67f02822016-06-24 21:05:23 -0700543 // The reason is that the filter override currently happens when the dex files are
544 // loaded in dex2oat, which is after the oat file has been started. Thus, the header
545 // store cannot be changed, and the original filter is set in stone.
546
547 for (const OatDexFile* oat_dex_file : odex_file->GetOatDexFiles()) {
548 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
549 ASSERT_TRUE(dex_file != nullptr);
550 uint32_t class_def_count = dex_file->NumClassDefs();
551 ASSERT_LT(class_def_count, std::numeric_limits<uint16_t>::max());
552 for (uint16_t class_def_index = 0; class_def_index < class_def_count; ++class_def_index) {
553 OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
554 EXPECT_EQ(oat_class.GetType(), OatClassType::kOatClassNoneCompiled);
555 }
556 }
557
558 // If the input filter was "below," it should have been used.
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100559 if (!CompilerFilter::IsAsGoodAs(CompilerFilter::kExtract, filter)) {
Andreas Gampe67f02822016-06-24 21:05:23 -0700560 EXPECT_EQ(odex_file->GetCompilerFilter(), filter);
561 }
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700562
563 // If expect large, make sure the app image isn't generated or is empty.
564 if (file != nullptr) {
565 EXPECT_EQ(file->GetLength(), 0u);
566 }
Andreas Gampe67f02822016-06-24 21:05:23 -0700567 } else {
568 EXPECT_EQ(odex_file->GetCompilerFilter(), filter);
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700569 ASSERT_TRUE(file != nullptr) << app_image_file;
570 EXPECT_GT(file->GetLength(), 0u);
Andreas Gampe67f02822016-06-24 21:05:23 -0700571 }
572
573 // Host/target dependent checks.
574 if (kIsTargetBuild) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700575 CheckTargetResult(expect_downgrade);
Andreas Gampe67f02822016-06-24 21:05:23 -0700576 } else {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700577 CheckHostResult(expect_downgrade);
Andreas Gampe67f02822016-06-24 21:05:23 -0700578 }
579 }
580
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700581 void CheckTargetResult(bool expect_downgrade ATTRIBUTE_UNUSED) {
Andreas Gampe67f02822016-06-24 21:05:23 -0700582 // TODO: Ignore for now. May do something for fd things.
583 }
584
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700585 void CheckHostResult(bool expect_downgrade) {
Andreas Gampe67f02822016-06-24 21:05:23 -0700586 if (!kIsTargetBuild) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700587 if (expect_downgrade) {
588 EXPECT_NE(output_.find("Very large app, downgrading to"), std::string::npos) << output_;
Andreas Gampe67f02822016-06-24 21:05:23 -0700589 } else {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700590 EXPECT_EQ(output_.find("Very large app, downgrading to"), std::string::npos) << output_;
Andreas Gampe67f02822016-06-24 21:05:23 -0700591 }
592 }
593 }
594
595 // Check whether the dex2oat run was really successful.
596 void CheckValidity() {
597 if (kIsTargetBuild) {
598 CheckTargetValidity();
599 } else {
600 CheckHostValidity();
601 }
602 }
603
604 void CheckTargetValidity() {
605 // TODO: Ignore for now.
606 }
607
608 // On the host, we can get the dex2oat output. Here, look for "dex2oat took."
609 void CheckHostValidity() {
610 EXPECT_NE(output_.find("dex2oat took"), std::string::npos) << output_;
611 }
612};
613
614TEST_F(Dex2oatVeryLargeTest, DontUseVeryLarge) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700615 RunTest(CompilerFilter::kAssumeVerified, false, false);
616 RunTest(CompilerFilter::kExtract, false, false);
Ming-Shin Lu7e9fc9d2020-10-12 03:36:52 +0000617 RunTest(CompilerFilter::kQuicken, false, false);
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700618 RunTest(CompilerFilter::kSpeed, false, false);
Andreas Gampe67f02822016-06-24 21:05:23 -0700619
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700620 RunTest(CompilerFilter::kAssumeVerified, false, false, { "--very-large-app-threshold=10000000" });
621 RunTest(CompilerFilter::kExtract, false, false, { "--very-large-app-threshold=10000000" });
Ming-Shin Lu7e9fc9d2020-10-12 03:36:52 +0000622 RunTest(CompilerFilter::kQuicken, false, false, { "--very-large-app-threshold=10000000" });
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700623 RunTest(CompilerFilter::kSpeed, false, false, { "--very-large-app-threshold=10000000" });
Andreas Gampe67f02822016-06-24 21:05:23 -0700624}
625
626TEST_F(Dex2oatVeryLargeTest, UseVeryLarge) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700627 RunTest(CompilerFilter::kAssumeVerified, true, false, { "--very-large-app-threshold=100" });
628 RunTest(CompilerFilter::kExtract, true, false, { "--very-large-app-threshold=100" });
Ming-Shin Lu7e9fc9d2020-10-12 03:36:52 +0000629 RunTest(CompilerFilter::kQuicken, true, true, { "--very-large-app-threshold=100" });
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700630 RunTest(CompilerFilter::kSpeed, true, true, { "--very-large-app-threshold=100" });
Andreas Gampe67f02822016-06-24 21:05:23 -0700631}
632
Mathieu Chartier97ab5e32017-02-22 13:35:44 -0800633// Regressin test for b/35665292.
634TEST_F(Dex2oatVeryLargeTest, SpeedProfileNoProfile) {
635 // Test that dex2oat doesn't crash with speed-profile but no input profile.
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700636 RunTest(CompilerFilter::kSpeedProfile, false, false);
Mathieu Chartier97ab5e32017-02-22 13:35:44 -0800637}
638
Jeff Hao608f2ce2016-10-19 11:17:11 -0700639class Dex2oatLayoutTest : public Dex2oatTest {
640 protected:
641 void CheckFilter(CompilerFilter::Filter input ATTRIBUTE_UNUSED,
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100642 CompilerFilter::Filter result ATTRIBUTE_UNUSED) override {
Jeff Hao608f2ce2016-10-19 11:17:11 -0700643 // Ignore, we'll do our own checks.
644 }
645
Calin Juravle45cdd052019-09-23 23:03:18 -0400646 // Emits a profile with a single dex file with the given location and classes ranging
647 // from 0 to num_classes.
Jeff Hao41fba6a2016-11-28 11:53:33 -0800648 void GenerateProfile(const std::string& test_profile,
Calin Juravle45cdd052019-09-23 23:03:18 -0400649 const DexFile* dex,
650 size_t num_classes) {
Andreas Gampedfcd82c2018-10-16 20:22:37 -0700651 int profile_test_fd = open(test_profile.c_str(),
652 O_CREAT | O_TRUNC | O_WRONLY | O_CLOEXEC,
653 0644);
Jeff Hao41fba6a2016-11-28 11:53:33 -0800654 CHECK_GE(profile_test_fd, 0);
655
656 ProfileCompilationInfo info;
Calin Juravle45cdd052019-09-23 23:03:18 -0400657 std::vector<dex::TypeIndex> classes;;
Mathieu Chartier046854b2017-03-01 17:16:22 -0800658 for (size_t i = 0; i < num_classes; ++i) {
Calin Juravle45cdd052019-09-23 23:03:18 -0400659 classes.push_back(dex::TypeIndex(1 + i));
Mathieu Chartier046854b2017-03-01 17:16:22 -0800660 }
Calin Juravle45cdd052019-09-23 23:03:18 -0400661 info.AddClassesForDex(dex, classes.begin(), classes.end());
Jeff Hao41fba6a2016-11-28 11:53:33 -0800662 bool result = info.Save(profile_test_fd);
663 close(profile_test_fd);
664 ASSERT_TRUE(result);
665 }
666
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800667 void CompileProfileOdex(const std::string& dex_location,
668 const std::string& odex_location,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800669 const std::string& app_image_file_name,
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800670 bool use_fd,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800671 size_t num_profile_classes,
Nicolas Geoffray97fa9922017-03-09 13:13:25 +0000672 const std::vector<std::string>& extra_args = {},
673 bool expect_success = true) {
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800674 const std::string profile_location = GetScratchDir() + "/primary.prof";
Jeff Hao41fba6a2016-11-28 11:53:33 -0800675 const char* location = dex_location.c_str();
676 std::string error_msg;
677 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Sehr013fd802018-01-11 22:55:24 -0800678 const ArtDexFileLoader dex_file_loader;
679 ASSERT_TRUE(dex_file_loader.Open(
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100680 location, location, /*verify=*/ true, /*verify_checksum=*/ true, &error_msg, &dex_files));
Jeff Hao41fba6a2016-11-28 11:53:33 -0800681 EXPECT_EQ(dex_files.size(), 1U);
682 std::unique_ptr<const DexFile>& dex_file = dex_files[0];
Calin Juravle45cdd052019-09-23 23:03:18 -0400683 GenerateProfile(profile_location, dex_file.get(), num_profile_classes);
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800684 std::vector<std::string> copy(extra_args);
685 copy.push_back("--profile-file=" + profile_location);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800686 std::unique_ptr<File> app_image_file;
687 if (!app_image_file_name.empty()) {
688 if (use_fd) {
689 app_image_file.reset(OS::CreateEmptyFile(app_image_file_name.c_str()));
690 copy.push_back("--app-image-fd=" + std::to_string(app_image_file->Fd()));
691 } else {
692 copy.push_back("--app-image-file=" + app_image_file_name);
693 }
694 }
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800695 ASSERT_TRUE(GenerateOdexForTest(dex_location,
696 odex_location,
697 CompilerFilter::kSpeedProfile,
698 copy,
699 expect_success,
700 use_fd));
Mathieu Chartier046854b2017-03-01 17:16:22 -0800701 if (app_image_file != nullptr) {
702 ASSERT_EQ(app_image_file->FlushCloseOrErase(), 0) << "Could not flush and close art file";
703 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800704 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700705
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100706 uint64_t GetImageObjectSectionSize(const std::string& image_file_name) {
Mathieu Chartier046854b2017-03-01 17:16:22 -0800707 EXPECT_FALSE(image_file_name.empty());
708 std::unique_ptr<File> file(OS::OpenFileForReading(image_file_name.c_str()));
709 CHECK(file != nullptr);
710 ImageHeader image_header;
711 const bool success = file->ReadFully(&image_header, sizeof(image_header));
712 CHECK(success);
713 CHECK(image_header.IsValid());
714 ReaderMutexLock mu(Thread::Current(), *Locks::mutator_lock_);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100715 return image_header.GetObjectsSection().Size();
Mathieu Chartier046854b2017-03-01 17:16:22 -0800716 }
717
718 void RunTest(bool app_image) {
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800719 std::string dex_location = GetScratchDir() + "/DexNoOat.jar";
720 std::string odex_location = GetOdexDir() + "/DexOdexNoOat.odex";
Mathieu Chartier046854b2017-03-01 17:16:22 -0800721 std::string app_image_file = app_image ? (GetOdexDir() + "/DexOdexNoOat.art"): "";
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800722 Copy(GetDexSrc2(), dex_location);
723
Mathieu Chartier046854b2017-03-01 17:16:22 -0800724 uint64_t image_file_empty_profile = 0;
725 if (app_image) {
726 CompileProfileOdex(dex_location,
727 odex_location,
728 app_image_file,
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100729 /*use_fd=*/ false,
730 /*num_profile_classes=*/ 0);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800731 CheckValidity();
732 ASSERT_TRUE(success_);
733 // Don't check the result since CheckResult relies on the class being in the profile.
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100734 image_file_empty_profile = GetImageObjectSectionSize(app_image_file);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800735 EXPECT_GT(image_file_empty_profile, 0u);
736 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700737
Mathieu Chartier046854b2017-03-01 17:16:22 -0800738 // Small profile.
739 CompileProfileOdex(dex_location,
740 odex_location,
741 app_image_file,
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100742 /*use_fd=*/ false,
743 /*num_profile_classes=*/ 1);
Jeff Hao608f2ce2016-10-19 11:17:11 -0700744 CheckValidity();
745 ASSERT_TRUE(success_);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800746 CheckResult(dex_location, odex_location, app_image_file);
747
748 if (app_image) {
749 // Test that the profile made a difference by adding more classes.
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100750 const uint64_t image_file_small_profile = GetImageObjectSectionSize(app_image_file);
751 ASSERT_LT(image_file_empty_profile, image_file_small_profile);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800752 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700753 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800754
755 void RunTestVDex() {
756 std::string dex_location = GetScratchDir() + "/DexNoOat.jar";
757 std::string odex_location = GetOdexDir() + "/DexOdexNoOat.odex";
758 std::string vdex_location = GetOdexDir() + "/DexOdexNoOat.vdex";
Mathieu Chartier046854b2017-03-01 17:16:22 -0800759 std::string app_image_file_name = GetOdexDir() + "/DexOdexNoOat.art";
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800760 Copy(GetDexSrc2(), dex_location);
761
762 std::unique_ptr<File> vdex_file1(OS::CreateEmptyFile(vdex_location.c_str()));
763 CHECK(vdex_file1 != nullptr) << vdex_location;
764 ScratchFile vdex_file2;
765 {
766 std::string input_vdex = "--input-vdex-fd=-1";
767 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file1->Fd());
768 CompileProfileOdex(dex_location,
769 odex_location,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800770 app_image_file_name,
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100771 /*use_fd=*/ true,
772 /*num_profile_classes=*/ 1,
Mathieu Chartierf1609832018-01-31 03:09:56 -0800773 { input_vdex, output_vdex });
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800774 EXPECT_GT(vdex_file1->GetLength(), 0u);
775 }
776 {
Nicolas Geoffray97fa9922017-03-09 13:13:25 +0000777 // Test that vdex and dexlayout fail gracefully.
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800778 std::string input_vdex = StringPrintf("--input-vdex-fd=%d", vdex_file1->Fd());
779 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file2.GetFd());
780 CompileProfileOdex(dex_location,
781 odex_location,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800782 app_image_file_name,
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100783 /*use_fd=*/ true,
784 /*num_profile_classes=*/ 1,
Mathieu Chartierd27923c2018-02-08 21:00:03 -0800785 { input_vdex, output_vdex },
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100786 /*expect_success=*/ true);
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +0100787 EXPECT_GT(vdex_file2.GetFile()->GetLength(), 0u);
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800788 }
789 ASSERT_EQ(vdex_file1->FlushCloseOrErase(), 0) << "Could not flush and close vdex file";
790 CheckValidity();
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +0100791 ASSERT_TRUE(success_);
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800792 }
793
Mathieu Chartier046854b2017-03-01 17:16:22 -0800794 void CheckResult(const std::string& dex_location,
795 const std::string& odex_location,
796 const std::string& app_image_file_name) {
Jeff Hao608f2ce2016-10-19 11:17:11 -0700797 // Host/target independent checks.
798 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100799 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +0100800 odex_location.c_str(),
Jeff Hao608f2ce2016-10-19 11:17:11 -0700801 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100802 /*executable=*/ false,
803 /*low_4gb=*/ false,
Vladimir Markob7bf8432019-12-03 13:18:50 +0000804 dex_location,
Jeff Hao608f2ce2016-10-19 11:17:11 -0700805 &error_msg));
806 ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
807
Jeff Hao042e8982016-10-19 11:17:11 -0700808 const char* location = dex_location.c_str();
809 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Sehr013fd802018-01-11 22:55:24 -0800810 const ArtDexFileLoader dex_file_loader;
811 ASSERT_TRUE(dex_file_loader.Open(
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100812 location, location, /*verify=*/ true, /*verify_checksum=*/ true, &error_msg, &dex_files));
Jeff Hao042e8982016-10-19 11:17:11 -0700813 EXPECT_EQ(dex_files.size(), 1U);
814 std::unique_ptr<const DexFile>& old_dex_file = dex_files[0];
815
Jeff Hao608f2ce2016-10-19 11:17:11 -0700816 for (const OatDexFile* oat_dex_file : odex_file->GetOatDexFiles()) {
Jeff Hao042e8982016-10-19 11:17:11 -0700817 std::unique_ptr<const DexFile> new_dex_file = oat_dex_file->OpenDexFile(&error_msg);
818 ASSERT_TRUE(new_dex_file != nullptr);
819 uint32_t class_def_count = new_dex_file->NumClassDefs();
Jeff Hao608f2ce2016-10-19 11:17:11 -0700820 ASSERT_LT(class_def_count, std::numeric_limits<uint16_t>::max());
Jeff Hao042e8982016-10-19 11:17:11 -0700821 ASSERT_GE(class_def_count, 2U);
822
Mathieu Chartier24066ec2017-10-21 16:01:08 -0700823 // Make sure the indexes stay the same.
Jeff Hao042e8982016-10-19 11:17:11 -0700824 std::string old_class0 = old_dex_file->PrettyType(old_dex_file->GetClassDef(0).class_idx_);
825 std::string old_class1 = old_dex_file->PrettyType(old_dex_file->GetClassDef(1).class_idx_);
826 std::string new_class0 = new_dex_file->PrettyType(new_dex_file->GetClassDef(0).class_idx_);
827 std::string new_class1 = new_dex_file->PrettyType(new_dex_file->GetClassDef(1).class_idx_);
Mathieu Chartier24066ec2017-10-21 16:01:08 -0700828 EXPECT_EQ(old_class0, new_class0);
829 EXPECT_EQ(old_class1, new_class1);
Jeff Hao608f2ce2016-10-19 11:17:11 -0700830 }
831
Jeff Haoc155b052017-01-17 17:43:29 -0800832 EXPECT_EQ(odex_file->GetCompilerFilter(), CompilerFilter::kSpeedProfile);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800833
834 if (!app_image_file_name.empty()) {
835 // Go peek at the image header to make sure it was large enough to contain the class.
836 std::unique_ptr<File> file(OS::OpenFileForReading(app_image_file_name.c_str()));
837 ImageHeader image_header;
838 bool success = file->ReadFully(&image_header, sizeof(image_header));
839 ASSERT_TRUE(success);
840 ASSERT_TRUE(image_header.IsValid());
Vladimir Markocd87c3e2017-09-05 13:11:57 +0100841 EXPECT_GT(image_header.GetObjectsSection().Size(), 0u);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800842 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700843 }
844
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800845 // Check whether the dex2oat run was really successful.
846 void CheckValidity() {
847 if (kIsTargetBuild) {
848 CheckTargetValidity();
849 } else {
850 CheckHostValidity();
Jeff Hao608f2ce2016-10-19 11:17:11 -0700851 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800852 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700853
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800854 void CheckTargetValidity() {
855 // TODO: Ignore for now.
856 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700857
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800858 // On the host, we can get the dex2oat output. Here, look for "dex2oat took."
859 void CheckHostValidity() {
860 EXPECT_NE(output_.find("dex2oat took"), std::string::npos) << output_;
861 }
862};
Jeff Hao608f2ce2016-10-19 11:17:11 -0700863
864TEST_F(Dex2oatLayoutTest, TestLayout) {
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100865 RunTest(/*app_image=*/ false);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800866}
867
868TEST_F(Dex2oatLayoutTest, TestLayoutAppImage) {
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100869 RunTest(/*app_image=*/ true);
Jeff Hao608f2ce2016-10-19 11:17:11 -0700870}
871
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800872TEST_F(Dex2oatLayoutTest, TestVdexLayout) {
873 RunTestVDex();
874}
875
Ming-Shin Lu7e9fc9d2020-10-12 03:36:52 +0000876class Dex2oatUnquickenTest : public Dex2oatTest {
877 protected:
878 void RunUnquickenMultiDex() {
879 std::string dex_location = GetScratchDir() + "/UnquickenMultiDex.jar";
880 std::string odex_location = GetOdexDir() + "/UnquickenMultiDex.odex";
881 std::string vdex_location = GetOdexDir() + "/UnquickenMultiDex.vdex";
882 Copy(GetTestDexFileName("MultiDex"), dex_location);
883
884 std::unique_ptr<File> vdex_file1(OS::CreateEmptyFile(vdex_location.c_str()));
885 CHECK(vdex_file1 != nullptr) << vdex_location;
886 // Quicken the dex file into a vdex file.
887 {
888 std::string input_vdex = "--input-vdex-fd=-1";
889 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file1->Fd());
890 ASSERT_TRUE(GenerateOdexForTest(dex_location,
891 odex_location,
892 CompilerFilter::kQuicken,
893 { input_vdex, output_vdex },
894 /* expect_success= */ true,
895 /* use_fd= */ true));
896 EXPECT_GT(vdex_file1->GetLength(), 0u);
897 }
898 // Get the dex file checksums.
899 std::vector<uint32_t> checksums1;
900 GetDexFileChecksums(dex_location, odex_location, &checksums1);
901 // Unquicken by running the verify compiler filter on the vdex file.
902 {
903 std::string input_vdex = StringPrintf("--input-vdex-fd=%d", vdex_file1->Fd());
904 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file1->Fd());
905 ASSERT_TRUE(GenerateOdexForTest(dex_location,
906 odex_location,
907 CompilerFilter::kVerify,
908 { input_vdex, output_vdex, kDisableCompactDex },
909 /* expect_success= */ true,
910 /* use_fd= */ true));
911 }
912 ASSERT_EQ(vdex_file1->FlushCloseOrErase(), 0) << "Could not flush and close vdex file";
913 CheckResult(dex_location, odex_location);
914 // Verify that the checksums did not change.
915 std::vector<uint32_t> checksums2;
916 GetDexFileChecksums(dex_location, odex_location, &checksums2);
917 ASSERT_EQ(checksums1.size(), checksums2.size());
918 for (size_t i = 0; i != checksums1.size(); ++i) {
919 EXPECT_EQ(checksums1[i], checksums2[i]) << i;
920 }
921 ASSERT_TRUE(success_);
922 }
923
924 void RunUnquickenMultiDexCDex() {
925 std::string dex_location = GetScratchDir() + "/UnquickenMultiDex.jar";
926 std::string odex_location = GetOdexDir() + "/UnquickenMultiDex.odex";
927 std::string odex_location2 = GetOdexDir() + "/UnquickenMultiDex2.odex";
928 std::string vdex_location = GetOdexDir() + "/UnquickenMultiDex.vdex";
929 std::string vdex_location2 = GetOdexDir() + "/UnquickenMultiDex2.vdex";
930 Copy(GetTestDexFileName("MultiDex"), dex_location);
931
932 std::unique_ptr<File> vdex_file1(OS::CreateEmptyFile(vdex_location.c_str()));
933 std::unique_ptr<File> vdex_file2(OS::CreateEmptyFile(vdex_location2.c_str()));
934 CHECK(vdex_file1 != nullptr) << vdex_location;
935 CHECK(vdex_file2 != nullptr) << vdex_location2;
936
937 // Quicken the dex file into a vdex file.
938 {
939 std::string input_vdex = "--input-vdex-fd=-1";
940 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file1->Fd());
941 ASSERT_TRUE(GenerateOdexForTest(dex_location,
942 odex_location,
943 CompilerFilter::kQuicken,
944 { input_vdex, output_vdex, "--compact-dex-level=fast"},
945 /* expect_success= */ true,
946 /* use_fd= */ true));
947 EXPECT_GT(vdex_file1->GetLength(), 0u);
948 }
949 // Unquicken by running the verify compiler filter on the vdex file.
950 {
951 std::string input_vdex = StringPrintf("--input-vdex-fd=%d", vdex_file1->Fd());
952 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file2->Fd());
953 ASSERT_TRUE(GenerateOdexForTest(dex_location,
954 odex_location2,
955 CompilerFilter::kVerify,
956 { input_vdex, output_vdex, "--compact-dex-level=none"},
957 /* expect_success= */ true,
958 /* use_fd= */ true));
959 }
960 ASSERT_EQ(vdex_file1->FlushCloseOrErase(), 0) << "Could not flush and close vdex file";
961 ASSERT_EQ(vdex_file2->FlushCloseOrErase(), 0) << "Could not flush and close vdex file";
962 CheckResult(dex_location, odex_location2);
963 ASSERT_TRUE(success_);
964 }
965
966 void CheckResult(const std::string& dex_location, const std::string& odex_location) {
967 std::string error_msg;
968 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
969 odex_location.c_str(),
970 odex_location.c_str(),
971 /*executable=*/ false,
972 /*low_4gb=*/ false,
973 dex_location,
974 &error_msg));
975 ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
976 ASSERT_GE(odex_file->GetOatDexFiles().size(), 1u);
977
978 // Iterate over the dex files and ensure there is no quickened instruction.
979 for (const OatDexFile* oat_dex_file : odex_file->GetOatDexFiles()) {
980 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
981 for (ClassAccessor accessor : dex_file->GetClasses()) {
982 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
983 for (const DexInstructionPcPair& inst : method.GetInstructions()) {
984 ASSERT_FALSE(inst->IsQuickened()) << inst->Opcode() << " " << output_;
985 }
986 }
987 }
988 }
989 }
990
991 void GetDexFileChecksums(const std::string& dex_location,
992 const std::string& odex_location,
993 /*out*/std::vector<uint32_t>* checksums) {
994 std::string error_msg;
995 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
996 odex_location.c_str(),
997 odex_location.c_str(),
998 /*executable=*/ false,
999 /*low_4gb=*/ false,
1000 dex_location,
1001 &error_msg));
1002 ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
1003 ASSERT_GE(odex_file->GetOatDexFiles().size(), 1u);
1004 for (const OatDexFile* oat_dex_file : odex_file->GetOatDexFiles()) {
1005 checksums->push_back(oat_dex_file->GetDexFileLocationChecksum());
1006 }
1007 }
1008};
1009
1010TEST_F(Dex2oatUnquickenTest, UnquickenMultiDex) {
1011 RunUnquickenMultiDex();
1012}
1013
1014TEST_F(Dex2oatUnquickenTest, UnquickenMultiDexCDex) {
1015 RunUnquickenMultiDexCDex();
1016}
1017
Andreas Gampe2e8a2562017-01-18 20:39:02 -08001018class Dex2oatWatchdogTest : public Dex2oatTest {
1019 protected:
1020 void RunTest(bool expect_success, const std::vector<std::string>& extra_args = {}) {
1021 std::string dex_location = GetScratchDir() + "/Dex2OatSwapTest.jar";
1022 std::string odex_location = GetOdexDir() + "/Dex2OatSwapTest.odex";
1023
1024 Copy(GetTestDexFileName(), dex_location);
1025
1026 std::vector<std::string> copy(extra_args);
1027
1028 std::string swap_location = GetOdexDir() + "/Dex2OatSwapTest.odex.swap";
1029 copy.push_back("--swap-file=" + swap_location);
Andreas Gampe22fa3762017-10-23 20:58:12 -07001030 copy.push_back("-j512"); // Excessive idle threads just slow down dex2oat.
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001031 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1032 odex_location,
1033 CompilerFilter::kSpeed,
1034 copy,
1035 expect_success));
Andreas Gampe2e8a2562017-01-18 20:39:02 -08001036 }
1037
1038 std::string GetTestDexFileName() {
1039 return GetDexSrc1();
1040 }
1041};
1042
1043TEST_F(Dex2oatWatchdogTest, TestWatchdogOK) {
1044 // Check with default.
1045 RunTest(true);
1046
1047 // Check with ten minutes.
1048 RunTest(true, { "--watchdog-timeout=600000" });
1049}
1050
1051TEST_F(Dex2oatWatchdogTest, TestWatchdogTrigger) {
Andreas Gampe148c1602019-06-10 16:47:46 -07001052 // This test is frequently interrupted by signal_dumper on host (x86);
Roland Levillain1fb24e22019-01-09 13:33:37 +00001053 // disable it while we investigate (b/121352534).
1054 TEST_DISABLED_FOR_X86();
1055
Andreas Gampe80ddf272018-01-11 09:41:00 -08001056 // The watchdog is independent of dex2oat and will not delete intermediates. It is possible
1057 // that the compilation succeeds and the file is completely written by the time the watchdog
1058 // kills dex2oat (but the dex2oat threads must have been scheduled pretty badly).
1059 test_accepts_odex_file_on_failure = true;
1060
Andreas Gampe2e8a2562017-01-18 20:39:02 -08001061 // Check with ten milliseconds.
1062 RunTest(false, { "--watchdog-timeout=10" });
1063}
1064
Andreas Gampef7882972017-03-20 16:35:24 -07001065class Dex2oatReturnCodeTest : public Dex2oatTest {
1066 protected:
1067 int RunTest(const std::vector<std::string>& extra_args = {}) {
1068 std::string dex_location = GetScratchDir() + "/Dex2OatSwapTest.jar";
1069 std::string odex_location = GetOdexDir() + "/Dex2OatSwapTest.odex";
1070
1071 Copy(GetTestDexFileName(), dex_location);
1072
1073 std::string error_msg;
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001074 return GenerateOdexForTestWithStatus({dex_location},
Andreas Gampef7882972017-03-20 16:35:24 -07001075 odex_location,
1076 CompilerFilter::kSpeed,
1077 &error_msg,
1078 extra_args);
1079 }
1080
1081 std::string GetTestDexFileName() {
1082 return GetDexSrc1();
1083 }
1084};
1085
Calin Juravle1ce70852017-06-28 10:59:03 -07001086class Dex2oatClassLoaderContextTest : public Dex2oatTest {
1087 protected:
1088 void RunTest(const char* class_loader_context,
1089 const char* expected_classpath_key,
1090 bool expected_success,
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001091 bool use_second_source = false,
1092 bool generate_image = false) {
Calin Juravle1ce70852017-06-28 10:59:03 -07001093 std::string dex_location = GetUsedDexLocation();
1094 std::string odex_location = GetUsedOatLocation();
1095
1096 Copy(use_second_source ? GetDexSrc2() : GetDexSrc1(), dex_location);
1097
1098 std::string error_msg;
1099 std::vector<std::string> extra_args;
1100 if (class_loader_context != nullptr) {
1101 extra_args.push_back(std::string("--class-loader-context=") + class_loader_context);
1102 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001103 if (generate_image) {
1104 extra_args.push_back(std::string("--app-image-file=") + GetUsedImageLocation());
1105 }
Calin Juravle1ce70852017-06-28 10:59:03 -07001106 auto check_oat = [expected_classpath_key](const OatFile& oat_file) {
1107 ASSERT_TRUE(expected_classpath_key != nullptr);
1108 const char* classpath = oat_file.GetOatHeader().GetStoreValueByKey(OatHeader::kClassPathKey);
1109 ASSERT_TRUE(classpath != nullptr);
1110 ASSERT_STREQ(expected_classpath_key, classpath);
1111 };
1112
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001113 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1114 odex_location,
Ming-Shin Lu7e9fc9d2020-10-12 03:36:52 +00001115 CompilerFilter::kQuicken,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001116 extra_args,
1117 expected_success,
Vladimir Marko21910692019-11-06 13:27:03 +00001118 /*use_fd=*/ false,
1119 /*use_zip_fd=*/ false,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001120 check_oat));
Calin Juravle1ce70852017-06-28 10:59:03 -07001121 }
1122
1123 std::string GetUsedDexLocation() {
1124 return GetScratchDir() + "/Context.jar";
1125 }
1126
1127 std::string GetUsedOatLocation() {
1128 return GetOdexDir() + "/Context.odex";
1129 }
1130
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001131 std::string GetUsedImageLocation() {
1132 return GetOdexDir() + "/Context.art";
1133 }
1134
Calin Juravle7b0648a2017-07-07 18:40:50 -07001135 const char* kEmptyClassPathKey = "PCL[]";
Calin Juravle1ce70852017-06-28 10:59:03 -07001136};
1137
1138TEST_F(Dex2oatClassLoaderContextTest, InvalidContext) {
1139 RunTest("Invalid[]", /*expected_classpath_key*/ nullptr, /*expected_success*/ false);
1140}
1141
1142TEST_F(Dex2oatClassLoaderContextTest, EmptyContext) {
1143 RunTest("PCL[]", kEmptyClassPathKey, /*expected_success*/ true);
1144}
1145
1146TEST_F(Dex2oatClassLoaderContextTest, SpecialContext) {
1147 RunTest(OatFile::kSpecialSharedLibrary,
1148 OatFile::kSpecialSharedLibrary,
1149 /*expected_success*/ true);
1150}
1151
1152TEST_F(Dex2oatClassLoaderContextTest, ContextWithTheSourceDexFiles) {
1153 std::string context = "PCL[" + GetUsedDexLocation() + "]";
1154 RunTest(context.c_str(), kEmptyClassPathKey, /*expected_success*/ true);
1155}
1156
1157TEST_F(Dex2oatClassLoaderContextTest, ContextWithOtherDexFiles) {
1158 std::vector<std::unique_ptr<const DexFile>> dex_files = OpenTestDexFiles("Nested");
Calin Juravle1ce70852017-06-28 10:59:03 -07001159
1160 std::string context = "PCL[" + dex_files[0]->GetLocation() + "]";
Calin Juravle7b0648a2017-07-07 18:40:50 -07001161 std::string expected_classpath_key = "PCL[" +
1162 dex_files[0]->GetLocation() + "*" + std::to_string(dex_files[0]->GetLocationChecksum()) + "]";
Calin Juravle1ce70852017-06-28 10:59:03 -07001163 RunTest(context.c_str(), expected_classpath_key.c_str(), true);
1164}
1165
1166TEST_F(Dex2oatClassLoaderContextTest, ContextWithStrippedDexFiles) {
1167 std::string stripped_classpath = GetScratchDir() + "/stripped_classpath.jar";
1168 Copy(GetStrippedDexSrc1(), stripped_classpath);
1169
1170 std::string context = "PCL[" + stripped_classpath + "]";
1171 // Expect an empty context because stripped dex files cannot be open.
Calin Juravle7b0648a2017-07-07 18:40:50 -07001172 RunTest(context.c_str(), kEmptyClassPathKey , /*expected_success*/ true);
Calin Juravle1ce70852017-06-28 10:59:03 -07001173}
1174
1175TEST_F(Dex2oatClassLoaderContextTest, ContextWithStrippedDexFilesBackedByOdex) {
1176 std::string stripped_classpath = GetScratchDir() + "/stripped_classpath.jar";
1177 std::string odex_for_classpath = GetOdexDir() + "/stripped_classpath.odex";
1178
1179 Copy(GetDexSrc1(), stripped_classpath);
1180
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001181 ASSERT_TRUE(GenerateOdexForTest(stripped_classpath,
1182 odex_for_classpath,
Ming-Shin Lu7e9fc9d2020-10-12 03:36:52 +00001183 CompilerFilter::kQuicken,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001184 {},
1185 true));
Calin Juravle1ce70852017-06-28 10:59:03 -07001186
1187 // Strip the dex file
1188 Copy(GetStrippedDexSrc1(), stripped_classpath);
1189
1190 std::string context = "PCL[" + stripped_classpath + "]";
Calin Juravle7b0648a2017-07-07 18:40:50 -07001191 std::string expected_classpath_key;
Calin Juravle1ce70852017-06-28 10:59:03 -07001192 {
1193 // Open the oat file to get the expected classpath.
Nicolas Geoffray29742602017-12-14 10:09:03 +00001194 OatFileAssistant oat_file_assistant(stripped_classpath.c_str(), kRuntimeISA, false, false);
Calin Juravle1ce70852017-06-28 10:59:03 -07001195 std::unique_ptr<OatFile> oat_file(oat_file_assistant.GetBestOatFile());
1196 std::vector<std::unique_ptr<const DexFile>> oat_dex_files =
1197 OatFileAssistant::LoadDexFiles(*oat_file, stripped_classpath.c_str());
Calin Juravle7b0648a2017-07-07 18:40:50 -07001198 expected_classpath_key = "PCL[";
1199 for (size_t i = 0; i < oat_dex_files.size(); i++) {
1200 if (i > 0) {
1201 expected_classpath_key + ":";
1202 }
1203 expected_classpath_key += oat_dex_files[i]->GetLocation() + "*" +
1204 std::to_string(oat_dex_files[i]->GetLocationChecksum());
1205 }
1206 expected_classpath_key += "]";
Calin Juravle1ce70852017-06-28 10:59:03 -07001207 }
1208
1209 RunTest(context.c_str(),
Calin Juravle7b0648a2017-07-07 18:40:50 -07001210 expected_classpath_key.c_str(),
Calin Juravle1ce70852017-06-28 10:59:03 -07001211 /*expected_success*/ true,
1212 /*use_second_source*/ true);
1213}
1214
1215TEST_F(Dex2oatClassLoaderContextTest, ContextWithNotExistentDexFiles) {
1216 std::string context = "PCL[does_not_exists.dex]";
1217 // Expect an empty context because stripped dex files cannot be open.
1218 RunTest(context.c_str(), kEmptyClassPathKey, /*expected_success*/ true);
1219}
1220
Calin Juravlec79470d2017-07-12 17:37:42 -07001221TEST_F(Dex2oatClassLoaderContextTest, ChainContext) {
1222 std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested");
1223 std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex");
1224
1225 std::string context = "PCL[" + GetTestDexFileName("Nested") + "];" +
1226 "DLC[" + GetTestDexFileName("MultiDex") + "]";
1227 std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "];" +
1228 "DLC[" + CreateClassPathWithChecksums(dex_files2) + "]";
1229
1230 RunTest(context.c_str(), expected_classpath_key.c_str(), true);
1231}
1232
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00001233TEST_F(Dex2oatClassLoaderContextTest, ContextWithSharedLibrary) {
1234 std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested");
1235 std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex");
1236
1237 std::string context = "PCL[" + GetTestDexFileName("Nested") + "]" +
1238 "{PCL[" + GetTestDexFileName("MultiDex") + "]}";
1239 std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "]" +
1240 "{PCL[" + CreateClassPathWithChecksums(dex_files2) + "]}";
1241 RunTest(context.c_str(), expected_classpath_key.c_str(), true);
1242}
1243
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001244TEST_F(Dex2oatClassLoaderContextTest, ContextWithSharedLibraryAndImage) {
1245 std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested");
1246 std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex");
1247
1248 std::string context = "PCL[" + GetTestDexFileName("Nested") + "]" +
1249 "{PCL[" + GetTestDexFileName("MultiDex") + "]}";
1250 std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "]" +
1251 "{PCL[" + CreateClassPathWithChecksums(dex_files2) + "]}";
1252 RunTest(context.c_str(),
1253 expected_classpath_key.c_str(),
1254 /*expected_success=*/ true,
1255 /*use_second_source=*/ false,
1256 /*generate_image=*/ true);
1257}
1258
1259TEST_F(Dex2oatClassLoaderContextTest, ContextWithSameSharedLibrariesAndImage) {
1260 std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested");
1261 std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex");
1262
1263 std::string context = "PCL[" + GetTestDexFileName("Nested") + "]" +
1264 "{PCL[" + GetTestDexFileName("MultiDex") + "]" +
1265 "#PCL[" + GetTestDexFileName("MultiDex") + "]}";
1266 std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "]" +
1267 "{PCL[" + CreateClassPathWithChecksums(dex_files2) + "]" +
1268 "#PCL[" + CreateClassPathWithChecksums(dex_files2) + "]}";
1269 RunTest(context.c_str(),
1270 expected_classpath_key.c_str(),
1271 /*expected_success=*/ true,
1272 /*use_second_source=*/ false,
1273 /*generate_image=*/ true);
1274}
1275
1276TEST_F(Dex2oatClassLoaderContextTest, ContextWithSharedLibrariesDependenciesAndImage) {
1277 std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested");
1278 std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex");
1279
1280 std::string context = "PCL[" + GetTestDexFileName("Nested") + "]" +
1281 "{PCL[" + GetTestDexFileName("MultiDex") + "]" +
1282 "{PCL[" + GetTestDexFileName("Nested") + "]}}";
1283 std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "]" +
1284 "{PCL[" + CreateClassPathWithChecksums(dex_files2) + "]" +
1285 "{PCL[" + CreateClassPathWithChecksums(dex_files1) + "]}}";
1286 RunTest(context.c_str(),
1287 expected_classpath_key.c_str(),
1288 /*expected_success=*/ true,
1289 /*use_second_source=*/ false,
1290 /*generate_image=*/ true);
1291}
1292
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001293class Dex2oatDeterminism : public Dex2oatTest {};
1294
1295TEST_F(Dex2oatDeterminism, UnloadCompile) {
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001296 Runtime* const runtime = Runtime::Current();
1297 std::string out_dir = GetScratchDir();
1298 const std::string base_oat_name = out_dir + "/base.oat";
1299 const std::string base_vdex_name = out_dir + "/base.vdex";
1300 const std::string unload_oat_name = out_dir + "/unload.oat";
1301 const std::string unload_vdex_name = out_dir + "/unload.vdex";
1302 const std::string no_unload_oat_name = out_dir + "/nounload.oat";
1303 const std::string no_unload_vdex_name = out_dir + "/nounload.vdex";
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001304 std::string error_msg;
1305 const std::vector<gc::space::ImageSpace*>& spaces = runtime->GetHeap()->GetBootImageSpaces();
1306 ASSERT_GT(spaces.size(), 0u);
1307 const std::string image_location = spaces[0]->GetImageLocation();
1308 // Without passing in an app image, it will unload in between compilations.
1309 const int res = GenerateOdexForTestWithStatus(
1310 GetLibCoreDexFileNames(),
1311 base_oat_name,
Ming-Shin Lu7e9fc9d2020-10-12 03:36:52 +00001312 CompilerFilter::Filter::kQuicken,
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001313 &error_msg,
1314 {"--force-determinism", "--avoid-storing-invocation"});
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001315 ASSERT_EQ(res, 0);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001316 Copy(base_oat_name, unload_oat_name);
1317 Copy(base_vdex_name, unload_vdex_name);
1318 std::unique_ptr<File> unload_oat(OS::OpenFileForReading(unload_oat_name.c_str()));
1319 std::unique_ptr<File> unload_vdex(OS::OpenFileForReading(unload_vdex_name.c_str()));
1320 ASSERT_TRUE(unload_oat != nullptr);
1321 ASSERT_TRUE(unload_vdex != nullptr);
1322 EXPECT_GT(unload_oat->GetLength(), 0u);
1323 EXPECT_GT(unload_vdex->GetLength(), 0u);
1324 // Regenerate with an app image to disable the dex2oat unloading and verify that the output is
1325 // the same.
1326 const int res2 = GenerateOdexForTestWithStatus(
1327 GetLibCoreDexFileNames(),
1328 base_oat_name,
Ming-Shin Lu7e9fc9d2020-10-12 03:36:52 +00001329 CompilerFilter::Filter::kQuicken,
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001330 &error_msg,
Eric Holkbc89ed42020-04-29 19:59:24 +00001331 {"--force-determinism", "--avoid-storing-invocation", "--compile-individually"});
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001332 ASSERT_EQ(res2, 0);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001333 Copy(base_oat_name, no_unload_oat_name);
1334 Copy(base_vdex_name, no_unload_vdex_name);
1335 std::unique_ptr<File> no_unload_oat(OS::OpenFileForReading(no_unload_oat_name.c_str()));
1336 std::unique_ptr<File> no_unload_vdex(OS::OpenFileForReading(no_unload_vdex_name.c_str()));
1337 ASSERT_TRUE(no_unload_oat != nullptr);
1338 ASSERT_TRUE(no_unload_vdex != nullptr);
1339 EXPECT_GT(no_unload_oat->GetLength(), 0u);
1340 EXPECT_GT(no_unload_vdex->GetLength(), 0u);
1341 // Verify that both of the files are the same (odex and vdex).
1342 EXPECT_EQ(unload_oat->GetLength(), no_unload_oat->GetLength());
1343 EXPECT_EQ(unload_vdex->GetLength(), no_unload_vdex->GetLength());
1344 EXPECT_EQ(unload_oat->Compare(no_unload_oat.get()), 0)
1345 << unload_oat_name << " " << no_unload_oat_name;
1346 EXPECT_EQ(unload_vdex->Compare(no_unload_vdex.get()), 0)
1347 << unload_vdex_name << " " << no_unload_vdex_name;
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001348}
1349
Mathieu Chartier120aa282017-08-05 16:03:03 -07001350// Test that dexlayout section info is correctly written to the oat file for profile based
1351// compilation.
1352TEST_F(Dex2oatTest, LayoutSections) {
1353 using Hotness = ProfileCompilationInfo::MethodHotness;
1354 std::unique_ptr<const DexFile> dex(OpenTestDexFile("ManyMethods"));
1355 ScratchFile profile_file;
1356 // We can only layout method indices with code items, figure out which ones have this property
1357 // first.
1358 std::vector<uint16_t> methods;
1359 {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001360 const dex::TypeId* type_id = dex->FindTypeId("LManyMethods;");
Mathieu Chartier120aa282017-08-05 16:03:03 -07001361 dex::TypeIndex type_idx = dex->GetIndexForTypeId(*type_id);
Mathieu Chartier2242ef12018-07-23 18:14:13 -07001362 ClassAccessor accessor(*dex, *dex->FindClassDef(type_idx));
Mathieu Chartier120aa282017-08-05 16:03:03 -07001363 std::set<size_t> code_item_offsets;
Mathieu Chartier2242ef12018-07-23 18:14:13 -07001364 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
1365 const uint16_t method_idx = method.GetIndex();
1366 const size_t code_item_offset = method.GetCodeItemOffset();
Mathieu Chartier120aa282017-08-05 16:03:03 -07001367 if (code_item_offsets.insert(code_item_offset).second) {
1368 // Unique code item, add the method index.
1369 methods.push_back(method_idx);
1370 }
1371 }
Mathieu Chartier120aa282017-08-05 16:03:03 -07001372 }
1373 ASSERT_GE(methods.size(), 8u);
1374 std::vector<uint16_t> hot_methods = {methods[1], methods[3], methods[5]};
1375 std::vector<uint16_t> startup_methods = {methods[1], methods[2], methods[7]};
1376 std::vector<uint16_t> post_methods = {methods[0], methods[2], methods[6]};
1377 // Here, we build the profile from the method lists.
1378 ProfileCompilationInfo info;
1379 info.AddMethodsForDex(
1380 static_cast<Hotness::Flag>(Hotness::kFlagHot | Hotness::kFlagStartup),
1381 dex.get(),
1382 hot_methods.begin(),
1383 hot_methods.end());
1384 info.AddMethodsForDex(
1385 Hotness::kFlagStartup,
1386 dex.get(),
1387 startup_methods.begin(),
1388 startup_methods.end());
1389 info.AddMethodsForDex(
1390 Hotness::kFlagPostStartup,
1391 dex.get(),
1392 post_methods.begin(),
1393 post_methods.end());
1394 for (uint16_t id : hot_methods) {
1395 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsHot());
1396 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsStartup());
1397 }
1398 for (uint16_t id : startup_methods) {
1399 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsStartup());
1400 }
1401 for (uint16_t id : post_methods) {
1402 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsPostStartup());
1403 }
1404 // Save the profile since we want to use it with dex2oat to produce an oat file.
1405 ASSERT_TRUE(info.Save(profile_file.GetFd()));
1406 // Generate a profile based odex.
1407 const std::string dir = GetScratchDir();
1408 const std::string oat_filename = dir + "/base.oat";
1409 const std::string vdex_filename = dir + "/base.vdex";
1410 std::string error_msg;
1411 const int res = GenerateOdexForTestWithStatus(
1412 {dex->GetLocation()},
1413 oat_filename,
Ming-Shin Lu7e9fc9d2020-10-12 03:36:52 +00001414 CompilerFilter::Filter::kQuicken,
Mathieu Chartier120aa282017-08-05 16:03:03 -07001415 &error_msg,
1416 {"--profile-file=" + profile_file.GetFilename()});
1417 EXPECT_EQ(res, 0);
1418
1419 // Open our generated oat file.
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001420 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01001421 oat_filename.c_str(),
Mathieu Chartier120aa282017-08-05 16:03:03 -07001422 oat_filename.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001423 /*executable=*/ false,
1424 /*low_4gb=*/ false,
Vladimir Markob7bf8432019-12-03 13:18:50 +00001425 dex->GetLocation(),
Mathieu Chartier120aa282017-08-05 16:03:03 -07001426 &error_msg));
1427 ASSERT_TRUE(odex_file != nullptr);
1428 std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
1429 ASSERT_EQ(oat_dex_files.size(), 1u);
1430 // Check that the code sections match what we expect.
1431 for (const OatDexFile* oat_dex : oat_dex_files) {
1432 const DexLayoutSections* const sections = oat_dex->GetDexLayoutSections();
1433 // Testing of logging the sections.
1434 ASSERT_TRUE(sections != nullptr);
1435 LOG(INFO) << *sections;
1436
1437 // Load the sections into temporary variables for convenience.
1438 const DexLayoutSection& code_section =
1439 sections->sections_[static_cast<size_t>(DexLayoutSections::SectionType::kSectionTypeCode)];
1440 const DexLayoutSection::Subsection& section_hot_code =
1441 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeHot)];
1442 const DexLayoutSection::Subsection& section_sometimes_used =
1443 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeSometimesUsed)];
1444 const DexLayoutSection::Subsection& section_startup_only =
1445 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeStartupOnly)];
1446 const DexLayoutSection::Subsection& section_unused =
1447 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeUnused)];
1448
1449 // All the sections should be non-empty.
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001450 EXPECT_GT(section_hot_code.Size(), 0u);
1451 EXPECT_GT(section_sometimes_used.Size(), 0u);
1452 EXPECT_GT(section_startup_only.Size(), 0u);
1453 EXPECT_GT(section_unused.Size(), 0u);
Mathieu Chartier120aa282017-08-05 16:03:03 -07001454
1455 // Open the dex file since we need to peek at the code items to verify the layout matches what
1456 // we expect.
1457 std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1458 ASSERT_TRUE(dex_file != nullptr) << error_msg;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001459 const dex::TypeId* type_id = dex_file->FindTypeId("LManyMethods;");
Mathieu Chartier120aa282017-08-05 16:03:03 -07001460 ASSERT_TRUE(type_id != nullptr);
1461 dex::TypeIndex type_idx = dex_file->GetIndexForTypeId(*type_id);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001462 const dex::ClassDef* class_def = dex_file->FindClassDef(type_idx);
Mathieu Chartier120aa282017-08-05 16:03:03 -07001463 ASSERT_TRUE(class_def != nullptr);
1464
1465 // Count how many code items are for each category, there should be at least one per category.
1466 size_t hot_count = 0;
1467 size_t post_startup_count = 0;
1468 size_t startup_count = 0;
1469 size_t unused_count = 0;
1470 // Visit all of the methdos of the main class and cross reference the method indices to their
1471 // corresponding code item offsets to verify the layout.
Mathieu Chartier2242ef12018-07-23 18:14:13 -07001472 ClassAccessor accessor(*dex_file, *class_def);
1473 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
1474 const size_t method_idx = method.GetIndex();
1475 const size_t code_item_offset = method.GetCodeItemOffset();
Mathieu Chartier120aa282017-08-05 16:03:03 -07001476 const bool is_hot = ContainsElement(hot_methods, method_idx);
1477 const bool is_startup = ContainsElement(startup_methods, method_idx);
1478 const bool is_post_startup = ContainsElement(post_methods, method_idx);
1479 if (is_hot) {
1480 // Hot is highest precedence, check that the hot methods are in the hot section.
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001481 EXPECT_TRUE(section_hot_code.Contains(code_item_offset));
Mathieu Chartier120aa282017-08-05 16:03:03 -07001482 ++hot_count;
1483 } else if (is_post_startup) {
1484 // Post startup is sometimes used section.
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001485 EXPECT_TRUE(section_sometimes_used.Contains(code_item_offset));
Mathieu Chartier120aa282017-08-05 16:03:03 -07001486 ++post_startup_count;
1487 } else if (is_startup) {
1488 // Startup at this point means not hot or post startup, these must be startup only then.
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001489 EXPECT_TRUE(section_startup_only.Contains(code_item_offset));
Mathieu Chartier120aa282017-08-05 16:03:03 -07001490 ++startup_count;
1491 } else {
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001492 if (section_unused.Contains(code_item_offset)) {
Alan Leung9595fd32017-10-17 17:08:19 -07001493 // If no flags are set, the method should be unused ...
1494 ++unused_count;
1495 } else {
1496 // or this method is part of the last code item and the end is 4 byte aligned.
Mathieu Chartier2242ef12018-07-23 18:14:13 -07001497 for (const ClassAccessor::Method& method2 : accessor.GetMethods()) {
1498 EXPECT_LE(method2.GetCodeItemOffset(), code_item_offset);
Alan Leung9595fd32017-10-17 17:08:19 -07001499 }
1500 uint32_t code_item_size = dex_file->FindCodeItemOffset(*class_def, method_idx);
1501 EXPECT_EQ((code_item_offset + code_item_size) % 4, 0u);
1502 }
Mathieu Chartier120aa282017-08-05 16:03:03 -07001503 }
1504 }
Mathieu Chartier120aa282017-08-05 16:03:03 -07001505 EXPECT_GT(hot_count, 0u);
1506 EXPECT_GT(post_startup_count, 0u);
1507 EXPECT_GT(startup_count, 0u);
1508 EXPECT_GT(unused_count, 0u);
1509 }
1510}
1511
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001512// Test that generating compact dex works.
1513TEST_F(Dex2oatTest, GenerateCompactDex) {
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001514 // Generate a compact dex based odex.
1515 const std::string dir = GetScratchDir();
1516 const std::string oat_filename = dir + "/base.oat";
1517 const std::string vdex_filename = dir + "/base.vdex";
Mathieu Chartierc17b7d82018-03-14 14:00:04 -07001518 const std::string dex_location = GetTestDexFileName("MultiDex");
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001519 std::string error_msg;
1520 const int res = GenerateOdexForTestWithStatus(
Mathieu Chartierc17b7d82018-03-14 14:00:04 -07001521 { dex_location },
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001522 oat_filename,
Ming-Shin Lu7e9fc9d2020-10-12 03:36:52 +00001523 CompilerFilter::Filter::kQuicken,
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001524 &error_msg,
1525 {"--compact-dex-level=fast"});
1526 EXPECT_EQ(res, 0);
1527 // Open our generated oat file.
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001528 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01001529 oat_filename.c_str(),
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001530 oat_filename.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001531 /*executable=*/ false,
1532 /*low_4gb=*/ false,
Vladimir Markob7bf8432019-12-03 13:18:50 +00001533 dex_location,
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001534 &error_msg));
1535 ASSERT_TRUE(odex_file != nullptr);
1536 std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
Mathieu Chartierc17b7d82018-03-14 14:00:04 -07001537 ASSERT_GT(oat_dex_files.size(), 1u);
1538 // Check that each dex is a compact dex file.
1539 std::vector<std::unique_ptr<const CompactDexFile>> compact_dex_files;
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001540 for (const OatDexFile* oat_dex : oat_dex_files) {
1541 std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1542 ASSERT_TRUE(dex_file != nullptr) << error_msg;
1543 ASSERT_TRUE(dex_file->IsCompactDexFile());
Mathieu Chartierc17b7d82018-03-14 14:00:04 -07001544 compact_dex_files.push_back(
1545 std::unique_ptr<const CompactDexFile>(dex_file.release()->AsCompactDexFile()));
1546 }
1547 for (const std::unique_ptr<const CompactDexFile>& dex_file : compact_dex_files) {
1548 // Test that every code item is in the owned section.
1549 const CompactDexFile::Header& header = dex_file->GetHeader();
1550 EXPECT_LE(header.OwnedDataBegin(), header.OwnedDataEnd());
1551 EXPECT_LE(header.OwnedDataBegin(), header.data_size_);
1552 EXPECT_LE(header.OwnedDataEnd(), header.data_size_);
Mathieu Chartier2242ef12018-07-23 18:14:13 -07001553 for (ClassAccessor accessor : dex_file->GetClasses()) {
1554 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
1555 if (method.GetCodeItemOffset() != 0u) {
1556 ASSERT_GE(method.GetCodeItemOffset(), header.OwnedDataBegin());
1557 ASSERT_LT(method.GetCodeItemOffset(), header.OwnedDataEnd());
Mathieu Chartierc17b7d82018-03-14 14:00:04 -07001558 }
Mathieu Chartier2242ef12018-07-23 18:14:13 -07001559 }
Mathieu Chartierc17b7d82018-03-14 14:00:04 -07001560 }
1561 // Test that the owned sections don't overlap.
1562 for (const std::unique_ptr<const CompactDexFile>& other_dex : compact_dex_files) {
1563 if (dex_file != other_dex) {
1564 ASSERT_TRUE(
1565 (dex_file->GetHeader().OwnedDataBegin() >= other_dex->GetHeader().OwnedDataEnd()) ||
1566 (dex_file->GetHeader().OwnedDataEnd() <= other_dex->GetHeader().OwnedDataBegin()));
1567 }
1568 }
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001569 }
1570}
1571
Andreas Gampef39208f2017-10-19 15:06:59 -07001572class Dex2oatVerifierAbort : public Dex2oatTest {};
1573
1574TEST_F(Dex2oatVerifierAbort, HardFail) {
1575 // Use VerifierDeps as it has hard-failing classes.
1576 std::unique_ptr<const DexFile> dex(OpenTestDexFile("VerifierDeps"));
1577 std::string out_dir = GetScratchDir();
1578 const std::string base_oat_name = out_dir + "/base.oat";
1579 std::string error_msg;
1580 const int res_fail = GenerateOdexForTestWithStatus(
1581 {dex->GetLocation()},
1582 base_oat_name,
Ming-Shin Lu7e9fc9d2020-10-12 03:36:52 +00001583 CompilerFilter::Filter::kQuicken,
Andreas Gampef39208f2017-10-19 15:06:59 -07001584 &error_msg,
1585 {"--abort-on-hard-verifier-error"});
1586 EXPECT_NE(0, res_fail);
1587
1588 const int res_no_fail = GenerateOdexForTestWithStatus(
1589 {dex->GetLocation()},
1590 base_oat_name,
Ming-Shin Lu7e9fc9d2020-10-12 03:36:52 +00001591 CompilerFilter::Filter::kQuicken,
Andreas Gampef39208f2017-10-19 15:06:59 -07001592 &error_msg,
1593 {"--no-abort-on-hard-verifier-error"});
1594 EXPECT_EQ(0, res_no_fail);
1595}
1596
1597TEST_F(Dex2oatVerifierAbort, SoftFail) {
1598 // Use VerifierDepsMulti as it has hard-failing classes.
1599 std::unique_ptr<const DexFile> dex(OpenTestDexFile("VerifierDepsMulti"));
1600 std::string out_dir = GetScratchDir();
1601 const std::string base_oat_name = out_dir + "/base.oat";
1602 std::string error_msg;
1603 const int res_fail = GenerateOdexForTestWithStatus(
1604 {dex->GetLocation()},
1605 base_oat_name,
Ming-Shin Lu7e9fc9d2020-10-12 03:36:52 +00001606 CompilerFilter::Filter::kQuicken,
Andreas Gampef39208f2017-10-19 15:06:59 -07001607 &error_msg,
1608 {"--abort-on-soft-verifier-error"});
1609 EXPECT_NE(0, res_fail);
1610
1611 const int res_no_fail = GenerateOdexForTestWithStatus(
1612 {dex->GetLocation()},
1613 base_oat_name,
Ming-Shin Lu7e9fc9d2020-10-12 03:36:52 +00001614 CompilerFilter::Filter::kQuicken,
Andreas Gampef39208f2017-10-19 15:06:59 -07001615 &error_msg,
1616 {"--no-abort-on-soft-verifier-error"});
1617 EXPECT_EQ(0, res_no_fail);
1618}
1619
Andreas Gampecac31ad2017-11-06 20:01:17 -08001620class Dex2oatDedupeCode : public Dex2oatTest {};
1621
1622TEST_F(Dex2oatDedupeCode, DedupeTest) {
1623 // Use MyClassNatives. It has lots of native methods that will produce deduplicate-able code.
1624 std::unique_ptr<const DexFile> dex(OpenTestDexFile("MyClassNatives"));
1625 std::string out_dir = GetScratchDir();
1626 const std::string base_oat_name = out_dir + "/base.oat";
1627 size_t no_dedupe_size = 0;
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001628 ASSERT_TRUE(GenerateOdexForTest(dex->GetLocation(),
1629 base_oat_name,
1630 CompilerFilter::Filter::kSpeed,
1631 { "--deduplicate-code=false" },
Vladimir Marko21910692019-11-06 13:27:03 +00001632 /*expect_success=*/ true,
1633 /*use_fd=*/ false,
1634 /*use_zip_fd=*/ false,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001635 [&no_dedupe_size](const OatFile& o) {
1636 no_dedupe_size = o.Size();
1637 }));
Andreas Gampecac31ad2017-11-06 20:01:17 -08001638
1639 size_t dedupe_size = 0;
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001640 ASSERT_TRUE(GenerateOdexForTest(dex->GetLocation(),
1641 base_oat_name,
1642 CompilerFilter::Filter::kSpeed,
1643 { "--deduplicate-code=true" },
Vladimir Marko21910692019-11-06 13:27:03 +00001644 /*expect_success=*/ true,
1645 /*use_fd=*/ false,
1646 /*use_zip_fd=*/ false,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001647 [&dedupe_size](const OatFile& o) {
1648 dedupe_size = o.Size();
1649 }));
Andreas Gampecac31ad2017-11-06 20:01:17 -08001650
1651 EXPECT_LT(dedupe_size, no_dedupe_size);
1652}
1653
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00001654TEST_F(Dex2oatTest, UncompressedTest) {
David Srbecky8c8f1482020-02-05 20:17:10 +00001655 std::unique_ptr<const DexFile> dex(OpenTestDexFile("MainUncompressedAligned"));
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00001656 std::string out_dir = GetScratchDir();
1657 const std::string base_oat_name = out_dir + "/base.oat";
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001658 ASSERT_TRUE(GenerateOdexForTest(dex->GetLocation(),
1659 base_oat_name,
Ming-Shin Lu7e9fc9d2020-10-12 03:36:52 +00001660 CompilerFilter::Filter::kQuicken,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001661 { },
Vladimir Marko21910692019-11-06 13:27:03 +00001662 /*expect_success=*/ true,
1663 /*use_fd=*/ false,
1664 /*use_zip_fd=*/ false,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001665 [](const OatFile& o) {
1666 CHECK(!o.ContainsDexCode());
1667 }));
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00001668}
1669
Mathieu Chartier700a9852018-02-06 18:27:38 -08001670TEST_F(Dex2oatTest, EmptyUncompressedDexTest) {
1671 std::string out_dir = GetScratchDir();
1672 const std::string base_oat_name = out_dir + "/base.oat";
1673 std::string error_msg;
1674 int status = GenerateOdexForTestWithStatus(
1675 { GetTestDexFileName("MainEmptyUncompressed") },
1676 base_oat_name,
Ming-Shin Lu7e9fc9d2020-10-12 03:36:52 +00001677 CompilerFilter::Filter::kQuicken,
Mathieu Chartier700a9852018-02-06 18:27:38 -08001678 &error_msg,
1679 { },
1680 /*use_fd*/ false);
1681 // Expect to fail with code 1 and not SIGSEGV or SIGABRT.
1682 ASSERT_TRUE(WIFEXITED(status));
1683 ASSERT_EQ(WEXITSTATUS(status), 1) << error_msg;
1684}
1685
Nicolas Geoffrayc36a8cc2019-04-29 13:37:42 +01001686TEST_F(Dex2oatTest, EmptyUncompressedAlignedDexTest) {
1687 std::string out_dir = GetScratchDir();
1688 const std::string base_oat_name = out_dir + "/base.oat";
1689 std::string error_msg;
1690 int status = GenerateOdexForTestWithStatus(
1691 { GetTestDexFileName("MainEmptyUncompressedAligned") },
1692 base_oat_name,
Ming-Shin Lu7e9fc9d2020-10-12 03:36:52 +00001693 CompilerFilter::Filter::kQuicken,
Nicolas Geoffrayc36a8cc2019-04-29 13:37:42 +01001694 &error_msg,
1695 { },
1696 /*use_fd*/ false);
1697 // Expect to fail with code 1 and not SIGSEGV or SIGABRT.
1698 ASSERT_TRUE(WIFEXITED(status));
1699 ASSERT_EQ(WEXITSTATUS(status), 1) << error_msg;
1700}
1701
Mathieu Chartier05f90d12018-02-07 13:47:17 -08001702// Dex file that has duplicate methods have different code items and debug info.
1703static const char kDuplicateMethodInputDex[] =
1704 "ZGV4CjAzOQDEy8VPdj4qHpgPYFWtLCtOykfFP4kB8tGYDAAAcAAAAHhWNBIAAAAAAAAAANALAABI"
1705 "AAAAcAAAAA4AAACQAQAABQAAAMgBAAANAAAABAIAABkAAABsAgAABAAAADQDAADgCAAAuAMAADgI"
1706 "AABCCAAASggAAE8IAABcCAAAaggAAHkIAACICAAAlggAAKQIAACyCAAAwAgAAM4IAADcCAAA6ggA"
1707 "APgIAAD7CAAA/wgAABcJAAAuCQAARQkAAFQJAAB4CQAAmAkAALsJAADSCQAA5gkAAPoJAAAVCgAA"
1708 "KQoAADsKAABCCgAASgoAAFIKAABbCgAAZAoAAGwKAAB0CgAAfAoAAIQKAACMCgAAlAoAAJwKAACk"
1709 "CgAArQoAALcKAADACgAAwwoAAMcKAADcCgAA6QoAAPEKAAD3CgAA/QoAAAMLAAAJCwAAEAsAABcL"
1710 "AAAdCwAAIwsAACkLAAAvCwAANQsAADsLAABBCwAARwsAAE0LAABSCwAAWwsAAF4LAABoCwAAbwsA"
1711 "ABEAAAASAAAAEwAAABQAAAAVAAAAFgAAABcAAAAYAAAAGQAAABoAAAAbAAAAHAAAAC4AAAAwAAAA"
1712 "DwAAAAkAAAAAAAAAEAAAAAoAAACoBwAALgAAAAwAAAAAAAAALwAAAAwAAACoBwAALwAAAAwAAACw"
1713 "BwAAAgAJADUAAAACAAkANgAAAAIACQA3AAAAAgAJADgAAAACAAkAOQAAAAIACQA6AAAAAgAJADsA"
1714 "AAACAAkAPAAAAAIACQA9AAAAAgAJAD4AAAACAAkAPwAAAAIACQBAAAAACwAHAEIAAAAAAAIAAQAA"
1715 "AAAAAwAeAAAAAQACAAEAAAABAAMAHgAAAAIAAgAAAAAAAgACAAEAAAADAAIAAQAAAAMAAgAfAAAA"
1716 "AwACACAAAAADAAIAIQAAAAMAAgAiAAAAAwACACMAAAADAAIAJAAAAAMAAgAlAAAAAwACACYAAAAD"
1717 "AAIAJwAAAAMAAgAoAAAAAwACACkAAAADAAIAKgAAAAMABAA0AAAABwADAEMAAAAIAAIAAQAAAAoA"
1718 "AgABAAAACgABADIAAAAKAAAARQAAAAAAAAAAAAAACAAAAAAAAAAdAAAAaAcAALYHAAAAAAAAAQAA"
1719 "AAAAAAAIAAAAAAAAAB0AAAB4BwAAxAcAAAAAAAACAAAAAAAAAAgAAAAAAAAAHQAAAIgHAADSBwAA"
1720 "AAAAAAMAAAAAAAAACAAAAAAAAAAdAAAAmAcAAPoHAAAAAAAAAAAAAAEAAAAAAAAArAYAADEAAAAa"
1721 "AAMAaQAAABoABABpAAEAGgAHAGkABAAaAAgAaQAFABoACQBpAAYAGgAKAGkABwAaAAsAaQAIABoA"
1722 "DABpAAkAGgANAGkACgAaAA4AaQALABoABQBpAAIAGgAGAGkAAwAOAAAAAQABAAEAAACSBgAABAAA"
1723 "AHAQFQAAAA4ABAABAAIAAACWBgAAFwAAAGIADAAiAQoAcBAWAAEAGgICAG4gFwAhAG4gFwAxAG4Q"
1724 "GAABAAwBbiAUABAADgAAAAEAAQABAAAAngYAAAQAAABwEBUAAAAOAAIAAQACAAAAogYAAAYAAABi"
1725 "AAwAbiAUABAADgABAAEAAQAAAKgGAAAEAAAAcBAVAAAADgABAAEAAQAAALsGAAAEAAAAcBAVAAAA"
1726 "DgABAAAAAQAAAL8GAAAGAAAAYgAAAHEQAwAAAA4AAQAAAAEAAADEBgAABgAAAGIAAQBxEAMAAAAO"
1727 "AAEAAAABAAAA8QYAAAYAAABiAAIAcRABAAAADgABAAAAAQAAAPYGAAAGAAAAYgADAHEQAwAAAA4A"
1728 "AQAAAAEAAADJBgAABgAAAGIABABxEAMAAAAOAAEAAAABAAAAzgYAAAYAAABiAAEAcRADAAAADgAB"
1729 "AAAAAQAAANMGAAAGAAAAYgAGAHEQAwAAAA4AAQAAAAEAAADYBgAABgAAAGIABwBxEAMAAAAOAAEA"
1730 "AAABAAAA3QYAAAYAAABiAAgAcRABAAAADgABAAAAAQAAAOIGAAAGAAAAYgAJAHEQAwAAAA4AAQAA"
1731 "AAEAAADnBgAABgAAAGIACgBxEAMAAAAOAAEAAAABAAAA7AYAAAYAAABiAAsAcRABAAAADgABAAEA"
1732 "AAAAAPsGAAAlAAAAcQAHAAAAcQAIAAAAcQALAAAAcQAMAAAAcQANAAAAcQAOAAAAcQAPAAAAcQAQ"
1733 "AAAAcQARAAAAcQASAAAAcQAJAAAAcQAKAAAADgAnAA4AKQFFDgEWDwAhAA4AIwFFDloAEgAOABMA"
1734 "DktLS0tLS0tLS0tLABEADgAuAA5aADIADloANgAOWgA6AA5aAD4ADloAQgAOWgBGAA5aAEoADloA"
1735 "TgAOWgBSAA5aAFYADloAWgAOWgBeATQOPDw8PDw8PDw8PDw8AAIEAUYYAwIFAjEECEEXLAIFAjEE"
1736 "CEEXKwIFAjEECEEXLQIGAUYcAxgAGAEYAgAAAAIAAAAMBwAAEgcAAAIAAAAMBwAAGwcAAAIAAAAM"
1737 "BwAAJAcAAAEAAAAtBwAAPAcAAAAAAAAAAAAAAAAAAEgHAAAAAAAAAAAAAAAAAABUBwAAAAAAAAAA"
1738 "AAAAAAAAYAcAAAAAAAAAAAAAAAAAAAEAAAAJAAAAAQAAAA0AAAACAACAgASsCAEIxAgAAAIAAoCA"
1739 "BIQJAQicCQwAAgAACQEJAQkBCQEJAQkBCQEJAQkBCQEJAQkEiIAEuAcBgIAEuAkAAA4ABoCABNAJ"
1740 "AQnoCQAJhAoACaAKAAm8CgAJ2AoACfQKAAmQCwAJrAsACcgLAAnkCwAJgAwACZwMAAm4DAg8Y2xp"
1741 "bml0PgAGPGluaXQ+AANBQUEAC0hlbGxvIFdvcmxkAAxIZWxsbyBXb3JsZDEADUhlbGxvIFdvcmxk"
1742 "MTAADUhlbGxvIFdvcmxkMTEADEhlbGxvIFdvcmxkMgAMSGVsbG8gV29ybGQzAAxIZWxsbyBXb3Js"
1743 "ZDQADEhlbGxvIFdvcmxkNQAMSGVsbG8gV29ybGQ2AAxIZWxsbyBXb3JsZDcADEhlbGxvIFdvcmxk"
1744 "OAAMSGVsbG8gV29ybGQ5AAFMAAJMTAAWTE1hbnlNZXRob2RzJFByaW50ZXIyOwAVTE1hbnlNZXRo"
1745 "b2RzJFByaW50ZXI7ABVMTWFueU1ldGhvZHMkU3RyaW5nczsADUxNYW55TWV0aG9kczsAIkxkYWx2"
1746 "aWsvYW5ub3RhdGlvbi9FbmNsb3NpbmdDbGFzczsAHkxkYWx2aWsvYW5ub3RhdGlvbi9Jbm5lckNs"
1747 "YXNzOwAhTGRhbHZpay9hbm5vdGF0aW9uL01lbWJlckNsYXNzZXM7ABVMamF2YS9pby9QcmludFN0"
1748 "cmVhbTsAEkxqYXZhL2xhbmcvT2JqZWN0OwASTGphdmEvbGFuZy9TdHJpbmc7ABlMamF2YS9sYW5n"
1749 "L1N0cmluZ0J1aWxkZXI7ABJMamF2YS9sYW5nL1N5c3RlbTsAEE1hbnlNZXRob2RzLmphdmEABVBy"
1750 "aW50AAZQcmludDAABlByaW50MQAHUHJpbnQxMAAHUHJpbnQxMQAGUHJpbnQyAAZQcmludDMABlBy"
1751 "aW50NAAGUHJpbnQ1AAZQcmludDYABlByaW50NwAGUHJpbnQ4AAZQcmludDkAB1ByaW50ZXIACFBy"
1752 "aW50ZXIyAAdTdHJpbmdzAAFWAAJWTAATW0xqYXZhL2xhbmcvU3RyaW5nOwALYWNjZXNzRmxhZ3MA"
1753 "BmFwcGVuZAAEYXJncwAEbWFpbgAEbXNnMAAEbXNnMQAFbXNnMTAABW1zZzExAARtc2cyAARtc2cz"
1754 "AARtc2c0AARtc2c1AARtc2c2AARtc2c3AARtc2c4AARtc2c5AARuYW1lAANvdXQAB3ByaW50bG4A"
1755 "AXMACHRvU3RyaW5nAAV2YWx1ZQBffn5EOHsibWluLWFwaSI6MTAwMDAsInNoYS0xIjoiZmViODZj"
1756 "MDA2ZWZhY2YxZDc5ODRiODVlMTc5MGZlZjdhNzY3YWViYyIsInZlcnNpb24iOiJ2MS4xLjUtZGV2"
1757 "In0AEAAAAAAAAAABAAAAAAAAAAEAAABIAAAAcAAAAAIAAAAOAAAAkAEAAAMAAAAFAAAAyAEAAAQA"
1758 "AAANAAAABAIAAAUAAAAZAAAAbAIAAAYAAAAEAAAANAMAAAEgAAAUAAAAuAMAAAMgAAAUAAAAkgYA"
1759 "AAQgAAAFAAAADAcAAAMQAAAEAAAAOQcAAAYgAAAEAAAAaAcAAAEQAAACAAAAqAcAAAAgAAAEAAAA"
1760 "tgcAAAIgAABIAAAAOAgAAAAQAAABAAAA0AsAAAAAAAA=";
1761
1762static void WriteBase64ToFile(const char* base64, File* file) {
1763 // Decode base64.
1764 CHECK(base64 != nullptr);
1765 size_t length;
1766 std::unique_ptr<uint8_t[]> bytes(DecodeBase64(base64, &length));
1767 CHECK(bytes != nullptr);
1768 if (!file->WriteFully(bytes.get(), length)) {
1769 PLOG(FATAL) << "Failed to write base64 as file";
1770 }
1771}
1772
1773TEST_F(Dex2oatTest, CompactDexGenerationFailure) {
1774 ScratchFile temp_dex;
1775 WriteBase64ToFile(kDuplicateMethodInputDex, temp_dex.GetFile());
1776 std::string out_dir = GetScratchDir();
1777 const std::string oat_filename = out_dir + "/base.oat";
1778 // The dex won't pass the method verifier, only use the verify filter.
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001779 ASSERT_TRUE(GenerateOdexForTest(temp_dex.GetFilename(),
1780 oat_filename,
1781 CompilerFilter::Filter::kVerify,
1782 { },
Vladimir Marko21910692019-11-06 13:27:03 +00001783 /*expect_success=*/ true,
1784 /*use_fd=*/ false,
1785 /*use_zip_fd=*/ false,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001786 [](const OatFile& o) {
1787 CHECK(o.ContainsDexCode());
1788 }));
Mathieu Chartier05f90d12018-02-07 13:47:17 -08001789 // Open our generated oat file.
1790 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001791 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01001792 oat_filename.c_str(),
Mathieu Chartier05f90d12018-02-07 13:47:17 -08001793 oat_filename.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001794 /*executable=*/ false,
1795 /*low_4gb=*/ false,
Vladimir Markob7bf8432019-12-03 13:18:50 +00001796 temp_dex.GetFilename(),
Mathieu Chartier05f90d12018-02-07 13:47:17 -08001797 &error_msg));
1798 ASSERT_TRUE(odex_file != nullptr);
1799 std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
1800 ASSERT_EQ(oat_dex_files.size(), 1u);
1801 // The dexes should have failed to convert to compact dex.
1802 for (const OatDexFile* oat_dex : oat_dex_files) {
1803 std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1804 ASSERT_TRUE(dex_file != nullptr) << error_msg;
1805 ASSERT_TRUE(!dex_file->IsCompactDexFile());
1806 }
1807}
1808
Mathieu Chartiercda83be2018-03-01 23:55:55 -08001809TEST_F(Dex2oatTest, CompactDexGenerationFailureMultiDex) {
1810 // Create a multidex file with only one dex that gets rejected for cdex conversion.
1811 ScratchFile apk_file;
1812 {
Andreas Gampedfcd82c2018-10-16 20:22:37 -07001813 FILE* file = fdopen(DupCloexec(apk_file.GetFd()), "w+b");
Mathieu Chartiercda83be2018-03-01 23:55:55 -08001814 ZipWriter writer(file);
1815 // Add vdex to zip.
1816 writer.StartEntry("classes.dex", ZipWriter::kCompress);
1817 size_t length = 0u;
1818 std::unique_ptr<uint8_t[]> bytes(DecodeBase64(kDuplicateMethodInputDex, &length));
1819 ASSERT_GE(writer.WriteBytes(&bytes[0], length), 0);
1820 writer.FinishEntry();
1821 writer.StartEntry("classes2.dex", ZipWriter::kCompress);
1822 std::unique_ptr<const DexFile> dex(OpenTestDexFile("ManyMethods"));
1823 ASSERT_GE(writer.WriteBytes(dex->Begin(), dex->Size()), 0);
1824 writer.FinishEntry();
1825 writer.Finish();
1826 ASSERT_EQ(apk_file.GetFile()->Flush(), 0);
1827 }
Andreas Gampebc802de2018-06-20 17:24:11 -07001828 const std::string& dex_location = apk_file.GetFilename();
Mathieu Chartiercda83be2018-03-01 23:55:55 -08001829 const std::string odex_location = GetOdexDir() + "/output.odex";
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001830 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1831 odex_location,
Ming-Shin Lu7e9fc9d2020-10-12 03:36:52 +00001832 CompilerFilter::kQuicken,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001833 { "--compact-dex-level=fast" },
1834 true));
Mathieu Chartiercda83be2018-03-01 23:55:55 -08001835}
1836
Andreas Gampe25419b52018-02-08 21:30:26 -08001837TEST_F(Dex2oatTest, StderrLoggerOutput) {
1838 std::string dex_location = GetScratchDir() + "/Dex2OatStderrLoggerTest.jar";
1839 std::string odex_location = GetOdexDir() + "/Dex2OatStderrLoggerTest.odex";
1840
1841 // Test file doesn't matter.
1842 Copy(GetDexSrc1(), dex_location);
1843
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001844 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1845 odex_location,
Ming-Shin Lu7e9fc9d2020-10-12 03:36:52 +00001846 CompilerFilter::kQuicken,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001847 { "--runtime-arg", "-Xuse-stderr-logger" },
1848 true));
Andreas Gampe25419b52018-02-08 21:30:26 -08001849 // Look for some random part of dex2oat logging. With the stderr logger this should be captured,
1850 // even on device.
1851 EXPECT_NE(std::string::npos, output_.find("dex2oat took"));
1852}
1853
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001854TEST_F(Dex2oatTest, VerifyCompilationReason) {
1855 std::string dex_location = GetScratchDir() + "/Dex2OatCompilationReason.jar";
1856 std::string odex_location = GetOdexDir() + "/Dex2OatCompilationReason.odex";
1857
1858 // Test file doesn't matter.
1859 Copy(GetDexSrc1(), dex_location);
1860
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001861 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1862 odex_location,
1863 CompilerFilter::kVerify,
1864 { "--compilation-reason=install" },
1865 true));
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001866 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001867 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01001868 odex_location.c_str(),
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001869 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001870 /*executable=*/ false,
1871 /*low_4gb=*/ false,
Vladimir Markob7bf8432019-12-03 13:18:50 +00001872 dex_location,
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001873 &error_msg));
1874 ASSERT_TRUE(odex_file != nullptr);
1875 ASSERT_STREQ("install", odex_file->GetCompilationReason());
1876}
1877
1878TEST_F(Dex2oatTest, VerifyNoCompilationReason) {
1879 std::string dex_location = GetScratchDir() + "/Dex2OatNoCompilationReason.jar";
1880 std::string odex_location = GetOdexDir() + "/Dex2OatNoCompilationReason.odex";
1881
1882 // Test file doesn't matter.
1883 Copy(GetDexSrc1(), dex_location);
1884
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001885 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1886 odex_location,
1887 CompilerFilter::kVerify,
1888 {},
1889 true));
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001890 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001891 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01001892 odex_location.c_str(),
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001893 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001894 /*executable=*/ false,
1895 /*low_4gb=*/ false,
Vladimir Markob7bf8432019-12-03 13:18:50 +00001896 dex_location,
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001897 &error_msg));
1898 ASSERT_TRUE(odex_file != nullptr);
1899 ASSERT_EQ(nullptr, odex_file->GetCompilationReason());
1900}
1901
Mathieu Chartier792111c2018-02-15 13:02:15 -08001902TEST_F(Dex2oatTest, DontExtract) {
1903 std::unique_ptr<const DexFile> dex(OpenTestDexFile("ManyMethods"));
1904 std::string error_msg;
1905 const std::string out_dir = GetScratchDir();
1906 const std::string dex_location = dex->GetLocation();
1907 const std::string odex_location = out_dir + "/base.oat";
1908 const std::string vdex_location = out_dir + "/base.vdex";
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001909 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1910 odex_location,
1911 CompilerFilter::Filter::kVerify,
1912 { "--copy-dex-files=false" },
Vladimir Marko21910692019-11-06 13:27:03 +00001913 /*expect_success=*/ true,
1914 /*use_fd=*/ false,
1915 /*use_zip_fd=*/ false,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001916 [](const OatFile&) {}));
Mathieu Chartier792111c2018-02-15 13:02:15 -08001917 {
1918 // Check the vdex doesn't have dex.
1919 std::unique_ptr<VdexFile> vdex(VdexFile::Open(vdex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001920 /*writable=*/ false,
1921 /*low_4gb=*/ false,
1922 /*unquicken=*/ false,
Mathieu Chartier792111c2018-02-15 13:02:15 -08001923 &error_msg));
1924 ASSERT_TRUE(vdex != nullptr);
Nicolas Geoffray3a293552018-03-02 10:52:16 +00001925 EXPECT_FALSE(vdex->HasDexSection()) << output_;
Mathieu Chartier792111c2018-02-15 13:02:15 -08001926 }
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001927 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01001928 odex_location.c_str(),
Mathieu Chartier792111c2018-02-15 13:02:15 -08001929 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001930 /*executable=*/ false,
1931 /*low_4gb=*/ false,
Vladimir Markob7bf8432019-12-03 13:18:50 +00001932 dex_location,
Mathieu Chartier792111c2018-02-15 13:02:15 -08001933 &error_msg));
1934 ASSERT_TRUE(odex_file != nullptr) << dex_location;
1935 std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
1936 ASSERT_EQ(oat_dex_files.size(), 1u);
1937 // Verify that the oat file can still open the dex files.
1938 for (const OatDexFile* oat_dex : oat_dex_files) {
1939 std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1940 ASSERT_TRUE(dex_file != nullptr) << error_msg;
1941 }
1942 // Create a dm file and use it to verify.
1943 // Add produced artifacts to a zip file that doesn't contain the classes.dex.
1944 ScratchFile dm_file;
1945 {
1946 std::unique_ptr<File> vdex_file(OS::OpenFileForReading(vdex_location.c_str()));
1947 ASSERT_TRUE(vdex_file != nullptr);
1948 ASSERT_GT(vdex_file->GetLength(), 0u);
Andreas Gampedfcd82c2018-10-16 20:22:37 -07001949 FILE* file = fdopen(DupCloexec(dm_file.GetFd()), "w+b");
Mathieu Chartier792111c2018-02-15 13:02:15 -08001950 ZipWriter writer(file);
1951 auto write_all_bytes = [&](File* file) {
1952 std::unique_ptr<uint8_t[]> bytes(new uint8_t[file->GetLength()]);
1953 ASSERT_TRUE(file->ReadFully(&bytes[0], file->GetLength()));
1954 ASSERT_GE(writer.WriteBytes(&bytes[0], file->GetLength()), 0);
1955 };
1956 // Add vdex to zip.
1957 writer.StartEntry(VdexFile::kVdexNameInDmFile, ZipWriter::kCompress);
1958 write_all_bytes(vdex_file.get());
1959 writer.FinishEntry();
1960 writer.Finish();
1961 ASSERT_EQ(dm_file.GetFile()->Flush(), 0);
1962 }
1963
Mathieu Chartier2eabc612018-05-25 14:31:16 -07001964 auto generate_and_check = [&](CompilerFilter::Filter filter) {
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001965 output_.clear();
1966 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1967 odex_location,
1968 filter,
1969 { "--dump-timings",
1970 "--dm-file=" + dm_file.GetFilename(),
1971 // Pass -Xuse-stderr-logger have dex2oat output in output_ on
1972 // target.
1973 "--runtime-arg",
1974 "-Xuse-stderr-logger" },
Vladimir Marko21910692019-11-06 13:27:03 +00001975 /*expect_success=*/ true,
1976 /*use_fd=*/ false,
1977 /*use_zip_fd=*/ false,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001978 [](const OatFile& o) {
1979 CHECK(o.ContainsDexCode());
1980 }));
Mathieu Chartier2eabc612018-05-25 14:31:16 -07001981 // Check the output for "Fast verify", this is printed from --dump-timings.
1982 std::istringstream iss(output_);
1983 std::string line;
1984 bool found_fast_verify = false;
1985 const std::string kFastVerifyString = "Fast Verify";
1986 while (std::getline(iss, line) && !found_fast_verify) {
1987 found_fast_verify = found_fast_verify || line.find(kFastVerifyString) != std::string::npos;
1988 }
1989 EXPECT_TRUE(found_fast_verify) << "Expected to find " << kFastVerifyString << "\n" << output_;
1990 };
1991
Ming-Shin Lu7e9fc9d2020-10-12 03:36:52 +00001992 // Generate a quickened dex by using the input dm file to verify.
1993 generate_and_check(CompilerFilter::Filter::kQuicken);
Ian Pedowitz14464672020-07-24 09:40:26 -07001994 // Use verify compiler filter to check that FastVerify works for that filter too.
Mathieu Chartier2eabc612018-05-25 14:31:16 -07001995 generate_and_check(CompilerFilter::Filter::kVerify);
Mathieu Chartier792111c2018-02-15 13:02:15 -08001996}
1997
Ming-Shin Lu7e9fc9d2020-10-12 03:36:52 +00001998// Test that dex files with quickened opcodes aren't dequickened.
1999TEST_F(Dex2oatTest, QuickenedInput) {
2000 std::string error_msg;
2001 ScratchFile temp_dex;
2002 MutateDexFile(temp_dex.GetFile(), GetTestDexFileName("ManyMethods"), [] (DexFile* dex) {
2003 bool mutated_successfully = false;
2004 // Change the dex instructions to make an opcode that spans past the end of the code item.
2005 for (ClassAccessor accessor : dex->GetClasses()) {
2006 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
2007 CodeItemInstructionAccessor instructions = method.GetInstructions();
2008 // Make a quickened instruction that doesn't run past the end of the code item.
2009 if (instructions.InsnsSizeInCodeUnits() > 2) {
2010 const_cast<Instruction&>(instructions.InstructionAt(0)).SetOpcode(
2011 Instruction::IGET_BYTE_QUICK);
2012 mutated_successfully = true;
2013 }
2014 }
2015 }
2016 CHECK(mutated_successfully)
2017 << "Failed to find candidate code item with only one code unit in last instruction.";
2018 });
2019
2020 const std::string& dex_location = temp_dex.GetFilename();
2021 std::string odex_location = GetOdexDir() + "/quickened.odex";
2022 std::string vdex_location = GetOdexDir() + "/quickened.vdex";
2023 std::unique_ptr<File> vdex_output(OS::CreateEmptyFile(vdex_location.c_str()));
2024 // Quicken the dex
2025 {
2026 std::string input_vdex = "--input-vdex-fd=-1";
2027 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_output->Fd());
2028 ASSERT_TRUE(GenerateOdexForTest(dex_location,
2029 odex_location,
2030 CompilerFilter::kQuicken,
2031 // Disable cdex since we want to compare against the original
2032 // dex file after unquickening.
2033 { input_vdex, output_vdex, kDisableCompactDex },
2034 /* expect_success= */ true,
2035 /* use_fd= */ true));
2036 }
2037 // Unquicken by running the verify compiler filter on the vdex file and verify it matches.
2038 std::string odex_location2 = GetOdexDir() + "/unquickened.odex";
2039 std::string vdex_location2 = GetOdexDir() + "/unquickened.vdex";
2040 std::unique_ptr<File> vdex_unquickened(OS::CreateEmptyFile(vdex_location2.c_str()));
2041 {
2042 std::string input_vdex = StringPrintf("--input-vdex-fd=%d", vdex_output->Fd());
2043 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_unquickened->Fd());
2044 ASSERT_TRUE(GenerateOdexForTest(dex_location,
2045 odex_location2,
2046 CompilerFilter::kVerify,
2047 // Disable cdex to avoid needing to write out the shared
2048 // section.
2049 { input_vdex, output_vdex, kDisableCompactDex },
2050 /* expect_success= */ true,
2051 /* use_fd= */ true));
2052 }
2053 ASSERT_EQ(vdex_unquickened->Flush(), 0) << "Could not flush and close vdex file";
2054 ASSERT_TRUE(success_);
2055 {
2056 // Check that hte vdex has one dex and compare it to the original one.
2057 std::unique_ptr<VdexFile> vdex(VdexFile::Open(vdex_location2.c_str(),
2058 /*writable*/ false,
2059 /*low_4gb*/ false,
2060 /*unquicken*/ false,
2061 &error_msg));
2062 std::vector<std::unique_ptr<const DexFile>> dex_files;
2063 bool result = vdex->OpenAllDexFiles(&dex_files, &error_msg);
2064 ASSERT_TRUE(result) << error_msg;
2065 ASSERT_EQ(dex_files.size(), 1u) << error_msg;
2066 ScratchFile temp;
2067 ASSERT_TRUE(temp.GetFile()->WriteFully(dex_files[0]->Begin(), dex_files[0]->Size()));
2068 ASSERT_EQ(temp.GetFile()->Flush(), 0) << "Could not flush extracted dex";
2069 EXPECT_EQ(temp.GetFile()->Compare(temp_dex.GetFile()), 0);
2070 }
2071 ASSERT_EQ(vdex_output->FlushCloseOrErase(), 0) << "Could not flush and close";
2072 ASSERT_EQ(vdex_unquickened->FlushCloseOrErase(), 0) << "Could not flush and close";
2073}
2074
Mathieu Chartierd45863a2018-03-21 18:16:36 -07002075// Test that compact dex generation with invalid dex files doesn't crash dex2oat. b/75970654
2076TEST_F(Dex2oatTest, CompactDexInvalidSource) {
2077 ScratchFile invalid_dex;
2078 {
Andreas Gampedfcd82c2018-10-16 20:22:37 -07002079 FILE* file = fdopen(DupCloexec(invalid_dex.GetFd()), "w+b");
Mathieu Chartierd45863a2018-03-21 18:16:36 -07002080 ZipWriter writer(file);
2081 writer.StartEntry("classes.dex", ZipWriter::kAlign32);
2082 DexFile::Header header = {};
2083 StandardDexFile::WriteMagic(header.magic_);
2084 StandardDexFile::WriteCurrentVersion(header.magic_);
2085 header.file_size_ = 4 * KB;
2086 header.data_size_ = 4 * KB;
2087 header.data_off_ = 10 * MB;
2088 header.map_off_ = 10 * MB;
2089 header.class_defs_off_ = 10 * MB;
2090 header.class_defs_size_ = 10000;
2091 ASSERT_GE(writer.WriteBytes(&header, sizeof(header)), 0);
2092 writer.FinishEntry();
2093 writer.Finish();
2094 ASSERT_EQ(invalid_dex.GetFile()->Flush(), 0);
2095 }
Andreas Gampebc802de2018-06-20 17:24:11 -07002096 const std::string& dex_location = invalid_dex.GetFilename();
Mathieu Chartierd45863a2018-03-21 18:16:36 -07002097 const std::string odex_location = GetOdexDir() + "/output.odex";
2098 std::string error_msg;
2099 int status = GenerateOdexForTestWithStatus(
2100 {dex_location},
2101 odex_location,
Ming-Shin Lu7e9fc9d2020-10-12 03:36:52 +00002102 CompilerFilter::kQuicken,
Mathieu Chartierd45863a2018-03-21 18:16:36 -07002103 &error_msg,
2104 { "--compact-dex-level=fast" });
2105 ASSERT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) != 0) << status << " " << output_;
2106}
2107
Mathieu Chartier14e7bad2018-03-22 14:33:20 -07002108// Test that dex2oat with a CompactDex file in the APK fails.
2109TEST_F(Dex2oatTest, CompactDexInZip) {
2110 CompactDexFile::Header header = {};
2111 CompactDexFile::WriteMagic(header.magic_);
2112 CompactDexFile::WriteCurrentVersion(header.magic_);
2113 header.file_size_ = sizeof(CompactDexFile::Header);
2114 header.data_off_ = 10 * MB;
2115 header.map_off_ = 10 * MB;
2116 header.class_defs_off_ = 10 * MB;
2117 header.class_defs_size_ = 10000;
2118 // Create a zip containing the invalid dex.
2119 ScratchFile invalid_dex_zip;
2120 {
Andreas Gampedfcd82c2018-10-16 20:22:37 -07002121 FILE* file = fdopen(DupCloexec(invalid_dex_zip.GetFd()), "w+b");
Mathieu Chartier14e7bad2018-03-22 14:33:20 -07002122 ZipWriter writer(file);
2123 writer.StartEntry("classes.dex", ZipWriter::kCompress);
2124 ASSERT_GE(writer.WriteBytes(&header, sizeof(header)), 0);
2125 writer.FinishEntry();
2126 writer.Finish();
2127 ASSERT_EQ(invalid_dex_zip.GetFile()->Flush(), 0);
2128 }
2129 // Create the dex file directly.
2130 ScratchFile invalid_dex;
2131 {
2132 ASSERT_GE(invalid_dex.GetFile()->WriteFully(&header, sizeof(header)), 0);
2133 ASSERT_EQ(invalid_dex.GetFile()->Flush(), 0);
2134 }
2135 std::string error_msg;
2136 int status = 0u;
2137
2138 status = GenerateOdexForTestWithStatus(
2139 { invalid_dex_zip.GetFilename() },
2140 GetOdexDir() + "/output_apk.odex",
Ming-Shin Lu7e9fc9d2020-10-12 03:36:52 +00002141 CompilerFilter::kQuicken,
Mathieu Chartier14e7bad2018-03-22 14:33:20 -07002142 &error_msg,
2143 { "--compact-dex-level=fast" });
2144 ASSERT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) != 0) << status << " " << output_;
2145
2146 status = GenerateOdexForTestWithStatus(
2147 { invalid_dex.GetFilename() },
2148 GetOdexDir() + "/output.odex",
Ming-Shin Lu7e9fc9d2020-10-12 03:36:52 +00002149 CompilerFilter::kQuicken,
Mathieu Chartier14e7bad2018-03-22 14:33:20 -07002150 &error_msg,
2151 { "--compact-dex-level=fast" });
2152 ASSERT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) != 0) << status << " " << output_;
2153}
2154
Mathieu Chartierf85b3db2018-04-02 18:16:21 -07002155TEST_F(Dex2oatTest, AppImageNoProfile) {
2156 ScratchFile app_image_file;
2157 const std::string out_dir = GetScratchDir();
2158 const std::string odex_location = out_dir + "/base.odex";
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002159 ASSERT_TRUE(GenerateOdexForTest(GetTestDexFileName("ManyMethods"),
2160 odex_location,
2161 CompilerFilter::Filter::kSpeedProfile,
2162 { "--app-image-fd=" + std::to_string(app_image_file.GetFd()) },
Vladimir Marko21910692019-11-06 13:27:03 +00002163 /*expect_success=*/ true,
2164 /*use_fd=*/ false,
2165 /*use_zip_fd=*/ false,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002166 [](const OatFile&) {}));
Mathieu Chartierf85b3db2018-04-02 18:16:21 -07002167 // Open our generated oat file.
2168 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002169 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01002170 odex_location.c_str(),
Mathieu Chartierf85b3db2018-04-02 18:16:21 -07002171 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002172 /*executable=*/ false,
2173 /*low_4gb=*/ false,
Mathieu Chartierf85b3db2018-04-02 18:16:21 -07002174 &error_msg));
2175 ASSERT_TRUE(odex_file != nullptr);
2176 ImageHeader header = {};
2177 ASSERT_TRUE(app_image_file.GetFile()->PreadFully(
2178 reinterpret_cast<void*>(&header),
2179 sizeof(header),
2180 /*offset*/ 0u)) << app_image_file.GetFile()->GetLength();
2181 EXPECT_GT(header.GetImageSection(ImageHeader::kSectionObjects).Size(), 0u);
2182 EXPECT_EQ(header.GetImageSection(ImageHeader::kSectionArtMethods).Size(), 0u);
2183 EXPECT_EQ(header.GetImageSection(ImageHeader::kSectionArtFields).Size(), 0u);
2184}
2185
Vladimir Marko21910692019-11-06 13:27:03 +00002186TEST_F(Dex2oatTest, ZipFd) {
David Srbecky8c8f1482020-02-05 20:17:10 +00002187 std::string zip_location = GetTestDexFileName("MainUncompressedAligned");
Vladimir Marko21910692019-11-06 13:27:03 +00002188 std::unique_ptr<File> dex_file(OS::OpenFileForReading(zip_location.c_str()));
2189 std::vector<std::string> extra_args{
2190 StringPrintf("--zip-fd=%d", dex_file->Fd()),
2191 "--zip-location=" + zip_location,
2192 };
2193 std::string out_dir = GetScratchDir();
2194 const std::string base_oat_name = out_dir + "/base.oat";
2195 ASSERT_TRUE(GenerateOdexForTest(zip_location,
2196 base_oat_name,
Ming-Shin Lu7e9fc9d2020-10-12 03:36:52 +00002197 CompilerFilter::Filter::kQuicken,
Vladimir Marko21910692019-11-06 13:27:03 +00002198 extra_args,
2199 /*expect_success=*/ true,
2200 /*use_fd=*/ false,
2201 /*use_zip_fd=*/ true));
2202}
2203
Mathieu Chartier9c06d442020-04-01 14:11:05 -07002204TEST_F(Dex2oatTest, AppImageEmptyDex) {
2205 // Create a profile with the startup method marked.
2206 ScratchFile profile_file;
2207 ScratchFile temp_dex;
2208 const std::string& dex_location = temp_dex.GetFilename();
2209 std::vector<uint16_t> methods;
2210 std::vector<dex::TypeIndex> classes;
2211 {
2212 MutateDexFile(temp_dex.GetFile(), GetTestDexFileName("StringLiterals"), [&] (DexFile* dex) {
2213 // Modify the header to make the dex file valid but empty.
2214 DexFile::Header* header = const_cast<DexFile::Header*>(&dex->GetHeader());
2215 header->string_ids_size_ = 0;
2216 header->string_ids_off_ = 0;
2217 header->type_ids_size_ = 0;
2218 header->type_ids_off_ = 0;
2219 header->proto_ids_size_ = 0;
2220 header->proto_ids_off_ = 0;
2221 header->field_ids_size_ = 0;
2222 header->field_ids_off_ = 0;
2223 header->method_ids_size_ = 0;
2224 header->method_ids_off_ = 0;
2225 header->class_defs_size_ = 0;
2226 header->class_defs_off_ = 0;
2227 ASSERT_GT(header->file_size_,
2228 sizeof(*header) + sizeof(dex::MapList) + sizeof(dex::MapItem) * 2);
2229 // Move map list to be right after the header.
2230 header->map_off_ = sizeof(DexFile::Header);
2231 dex::MapList* map_list = const_cast<dex::MapList*>(dex->GetMapList());
2232 map_list->list_[0].type_ = DexFile::kDexTypeHeaderItem;
2233 map_list->list_[0].size_ = 1u;
2234 map_list->list_[0].offset_ = 0u;
2235 map_list->list_[1].type_ = DexFile::kDexTypeMapList;
2236 map_list->list_[1].size_ = 1u;
2237 map_list->list_[1].offset_ = header->map_off_;
2238 map_list->size_ = 2;
2239 header->data_off_ = header->map_off_;
2240 header->data_size_ = map_list->Size();
2241 });
2242 }
2243 std::unique_ptr<const DexFile> dex_file(OpenDexFile(temp_dex.GetFilename().c_str()));
2244 const std::string out_dir = GetScratchDir();
2245 const std::string odex_location = out_dir + "/base.odex";
2246 const std::string app_image_location = out_dir + "/base.art";
2247 ASSERT_TRUE(GenerateOdexForTest(dex_location,
2248 odex_location,
2249 CompilerFilter::Filter::kSpeedProfile,
2250 { "--app-image-file=" + app_image_location,
2251 "--resolve-startup-const-strings=true",
2252 "--profile-file=" + profile_file.GetFilename()},
2253 /*expect_success=*/ true,
2254 /*use_fd=*/ false,
2255 /*use_zip_fd=*/ false,
2256 [](const OatFile&) {}));
2257 // Open our generated oat file.
2258 std::string error_msg;
2259 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
2260 odex_location.c_str(),
2261 odex_location.c_str(),
2262 /*executable=*/ false,
2263 /*low_4gb=*/ false,
2264 &error_msg));
2265 ASSERT_TRUE(odex_file != nullptr);
2266}
2267
wangshumin3949e5e2019-11-08 19:25:50 +08002268TEST_F(Dex2oatTest, DexFileFd) {
2269 std::string error_msg;
2270 std::string zip_location = GetTestDexFileName("Main");
2271 std::unique_ptr<File> zip_file(OS::OpenFileForReading(zip_location.c_str()));
2272 ASSERT_NE(-1, zip_file->Fd());
2273
2274 std::unique_ptr<ZipArchive> zip_archive(
2275 ZipArchive::OpenFromFd(zip_file->Release(), zip_location.c_str(), &error_msg));
2276 ASSERT_TRUE(zip_archive != nullptr);
2277
2278 std::string entry_name = DexFileLoader::GetMultiDexClassesDexName(0);
2279 std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
2280 ASSERT_TRUE(entry != nullptr);
2281
2282 ScratchFile dex_file;
2283 const std::string& dex_location = dex_file.GetFilename();
2284 const std::string base_oat_name = GetScratchDir() + "/base.oat";
2285
2286 bool success = entry->ExtractToFile(*(dex_file.GetFile()), &error_msg);
2287 ASSERT_TRUE(success);
2288 ASSERT_EQ(0, lseek(dex_file.GetFd(), 0, SEEK_SET));
2289
2290 std::vector<std::string> extra_args{
2291 StringPrintf("--zip-fd=%d", dex_file.GetFd()),
2292 "--zip-location=" + dex_location,
2293 };
2294 ASSERT_TRUE(GenerateOdexForTest(dex_location,
2295 base_oat_name,
Ming-Shin Lu7e9fc9d2020-10-12 03:36:52 +00002296 CompilerFilter::Filter::kQuicken,
wangshumin3949e5e2019-11-08 19:25:50 +08002297 extra_args,
2298 /*expect_success=*/ true,
2299 /*use_fd=*/ false,
2300 /*use_zip_fd=*/ true));
2301}
Mathieu Chartier9c06d442020-04-01 14:11:05 -07002302
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002303TEST_F(Dex2oatTest, AppImageResolveStrings) {
2304 using Hotness = ProfileCompilationInfo::MethodHotness;
2305 // Create a profile with the startup method marked.
2306 ScratchFile profile_file;
Mathieu Chartierc2109c62019-03-20 13:34:39 -07002307 ScratchFile temp_dex;
2308 const std::string& dex_location = temp_dex.GetFilename();
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002309 std::vector<uint16_t> methods;
Mathieu Chartier22752772018-10-18 14:18:59 -07002310 std::vector<dex::TypeIndex> classes;
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002311 {
Mathieu Chartierc2109c62019-03-20 13:34:39 -07002312 MutateDexFile(temp_dex.GetFile(), GetTestDexFileName("StringLiterals"), [&] (DexFile* dex) {
2313 bool mutated_successfully = false;
2314 // Change the dex instructions to make an opcode that spans past the end of the code item.
2315 for (ClassAccessor accessor : dex->GetClasses()) {
2316 if (accessor.GetDescriptor() == std::string("LStringLiterals$StartupClass;")) {
2317 classes.push_back(accessor.GetClassIdx());
2318 }
2319 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
2320 std::string method_name(dex->GetMethodName(dex->GetMethodId(method.GetIndex())));
2321 CodeItemInstructionAccessor instructions = method.GetInstructions();
2322 if (method_name == "startUpMethod2") {
2323 // Make an instruction that runs past the end of the code item and verify that it
2324 // doesn't cause dex2oat to crash.
2325 ASSERT_TRUE(instructions.begin() != instructions.end());
2326 DexInstructionIterator last_instruction = instructions.begin();
2327 for (auto dex_it = instructions.begin(); dex_it != instructions.end(); ++dex_it) {
2328 last_instruction = dex_it;
2329 }
2330 ASSERT_EQ(last_instruction->SizeInCodeUnits(), 1u);
2331 // Set the opcode to something that will go past the end of the code item.
2332 const_cast<Instruction&>(last_instruction.Inst()).SetOpcode(
2333 Instruction::CONST_STRING_JUMBO);
2334 mutated_successfully = true;
2335 // Test that the safe iterator doesn't go past the end.
2336 SafeDexInstructionIterator it2(instructions.begin(), instructions.end());
2337 while (!it2.IsErrorState()) {
2338 ++it2;
2339 }
2340 EXPECT_TRUE(it2 == last_instruction);
2341 EXPECT_TRUE(it2 < instructions.end());
2342 methods.push_back(method.GetIndex());
2343 mutated_successfully = true;
2344 } else if (method_name == "startUpMethod") {
2345 methods.push_back(method.GetIndex());
2346 }
Mathieu Chartier22752772018-10-18 14:18:59 -07002347 }
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002348 }
Mathieu Chartierc2109c62019-03-20 13:34:39 -07002349 CHECK(mutated_successfully)
2350 << "Failed to find candidate code item with only one code unit in last instruction.";
2351 });
2352 }
2353 std::unique_ptr<const DexFile> dex_file(OpenDexFile(temp_dex.GetFilename().c_str()));
2354 {
Mathieu Chartier22752772018-10-18 14:18:59 -07002355 ASSERT_GT(classes.size(), 0u);
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002356 ASSERT_GT(methods.size(), 0u);
2357 // Here, we build the profile from the method lists.
2358 ProfileCompilationInfo info;
Mathieu Chartierc2109c62019-03-20 13:34:39 -07002359 info.AddClassesForDex(dex_file.get(), classes.begin(), classes.end());
2360 info.AddMethodsForDex(Hotness::kFlagStartup, dex_file.get(), methods.begin(), methods.end());
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002361 // Save the profile since we want to use it with dex2oat to produce an oat file.
2362 ASSERT_TRUE(info.Save(profile_file.GetFd()));
2363 }
2364 const std::string out_dir = GetScratchDir();
2365 const std::string odex_location = out_dir + "/base.odex";
2366 const std::string app_image_location = out_dir + "/base.art";
Mathieu Chartierc2109c62019-03-20 13:34:39 -07002367 ASSERT_TRUE(GenerateOdexForTest(dex_location,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002368 odex_location,
2369 CompilerFilter::Filter::kSpeedProfile,
2370 { "--app-image-file=" + app_image_location,
2371 "--resolve-startup-const-strings=true",
2372 "--profile-file=" + profile_file.GetFilename()},
Vladimir Marko21910692019-11-06 13:27:03 +00002373 /*expect_success=*/ true,
2374 /*use_fd=*/ false,
2375 /*use_zip_fd=*/ false,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002376 [](const OatFile&) {}));
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002377 // Open our generated oat file.
2378 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002379 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002380 odex_location.c_str(),
2381 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002382 /*executable=*/ false,
2383 /*low_4gb=*/ false,
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002384 &error_msg));
2385 ASSERT_TRUE(odex_file != nullptr);
2386 // Check the strings in the app image intern table only contain the "startup" strigs.
2387 {
2388 ScopedObjectAccess soa(Thread::Current());
2389 std::unique_ptr<gc::space::ImageSpace> space =
2390 gc::space::ImageSpace::CreateFromAppImage(app_image_location.c_str(),
2391 odex_file.get(),
2392 &error_msg);
2393 ASSERT_TRUE(space != nullptr) << error_msg;
2394 std::set<std::string> seen;
2395 InternTable intern_table;
2396 intern_table.AddImageStringsToTable(space.get(), [&](InternTable::UnorderedSet& interns)
2397 REQUIRES_SHARED(Locks::mutator_lock_) {
2398 for (const GcRoot<mirror::String>& str : interns) {
2399 seen.insert(str.Read()->ToModifiedUtf8());
2400 }
2401 });
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07002402 // Ensure that the dex cache has a preresolved string array.
2403 std::set<std::string> preresolved_seen;
2404 bool saw_dexcache = false;
2405 space->GetLiveBitmap()->VisitAllMarked(
2406 [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
2407 if (obj->IsDexCache<kVerifyNone>()) {
2408 ObjPtr<mirror::DexCache> dex_cache = obj->AsDexCache();
2409 GcRoot<mirror::String>* preresolved_strings = dex_cache->GetPreResolvedStrings();
Mathieu Chartierc2109c62019-03-20 13:34:39 -07002410 ASSERT_EQ(dex_file->NumStringIds(), dex_cache->NumPreResolvedStrings());
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07002411 for (size_t i = 0; i < dex_cache->NumPreResolvedStrings(); ++i) {
2412 ObjPtr<mirror::String> string = preresolved_strings[i].Read<kWithoutReadBarrier>();
2413 if (string != nullptr) {
2414 preresolved_seen.insert(string->ToModifiedUtf8());
2415 }
2416 }
2417 saw_dexcache = true;
2418 }
2419 });
2420 ASSERT_TRUE(saw_dexcache);
2421 // Everything in the preresolved array should also be in the intern table.
2422 for (const std::string& str : preresolved_seen) {
2423 EXPECT_TRUE(seen.find(str) != seen.end());
2424 }
Mathieu Chartier22752772018-10-18 14:18:59 -07002425 // Normal methods
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07002426 EXPECT_TRUE(preresolved_seen.find("Loading ") != preresolved_seen.end());
2427 EXPECT_TRUE(preresolved_seen.find("Starting up") != preresolved_seen.end());
2428 EXPECT_TRUE(preresolved_seen.find("abcd.apk") != preresolved_seen.end());
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002429 EXPECT_TRUE(seen.find("Unexpected error") == seen.end());
2430 EXPECT_TRUE(seen.find("Shutting down!") == seen.end());
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07002431 EXPECT_TRUE(preresolved_seen.find("Unexpected error") == preresolved_seen.end());
2432 EXPECT_TRUE(preresolved_seen.find("Shutting down!") == preresolved_seen.end());
Mathieu Chartier22752772018-10-18 14:18:59 -07002433 // Classes initializers
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07002434 EXPECT_TRUE(preresolved_seen.find("Startup init") != preresolved_seen.end());
Mathieu Chartier22752772018-10-18 14:18:59 -07002435 EXPECT_TRUE(seen.find("Other class init") == seen.end());
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07002436 EXPECT_TRUE(preresolved_seen.find("Other class init") == preresolved_seen.end());
2437 // Expect the sets match.
2438 EXPECT_GE(seen.size(), preresolved_seen.size());
Mathieu Chartier8cc418e2018-10-31 10:54:30 -07002439
2440 // Verify what strings are marked as boot image.
2441 std::set<std::string> boot_image_strings;
2442 std::set<std::string> app_image_strings;
2443
2444 MutexLock mu(Thread::Current(), *Locks::intern_table_lock_);
2445 intern_table.VisitInterns([&](const GcRoot<mirror::String>& root)
2446 REQUIRES_SHARED(Locks::mutator_lock_) {
2447 boot_image_strings.insert(root.Read()->ToModifiedUtf8());
2448 }, /*visit_boot_images=*/true, /*visit_non_boot_images=*/false);
2449 intern_table.VisitInterns([&](const GcRoot<mirror::String>& root)
2450 REQUIRES_SHARED(Locks::mutator_lock_) {
2451 app_image_strings.insert(root.Read()->ToModifiedUtf8());
2452 }, /*visit_boot_images=*/false, /*visit_non_boot_images=*/true);
2453 EXPECT_EQ(boot_image_strings.size(), 0u);
2454 EXPECT_TRUE(app_image_strings == seen);
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002455 }
2456}
2457
2458
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002459TEST_F(Dex2oatClassLoaderContextTest, StoredClassLoaderContext) {
Mathieu Chartierc4440772018-04-16 14:40:56 -07002460 std::vector<std::unique_ptr<const DexFile>> dex_files = OpenTestDexFiles("MultiDex");
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002461 const std::string out_dir = GetScratchDir();
2462 const std::string odex_location = out_dir + "/base.odex";
Mathieu Chartierc4440772018-04-16 14:40:56 -07002463 const std::string valid_context = "PCL[" + dex_files[0]->GetLocation() + "]";
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002464 const std::string stored_context = "PCL[/system/not_real_lib.jar]";
Mathieu Chartierc4440772018-04-16 14:40:56 -07002465 std::string expected_stored_context = "PCL[";
2466 size_t index = 1;
2467 for (const std::unique_ptr<const DexFile>& dex_file : dex_files) {
2468 const bool is_first = index == 1u;
2469 if (!is_first) {
2470 expected_stored_context += ":";
2471 }
2472 expected_stored_context += "/system/not_real_lib.jar";
2473 if (!is_first) {
2474 expected_stored_context += "!classes" + std::to_string(index) + ".dex";
2475 }
2476 expected_stored_context += "*" + std::to_string(dex_file->GetLocationChecksum());
2477 ++index;
2478 }
2479 expected_stored_context += + "]";
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002480 // The class path should not be valid and should fail being stored.
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002481 EXPECT_TRUE(GenerateOdexForTest(GetTestDexFileName("ManyMethods"),
2482 odex_location,
Ming-Shin Lu7e9fc9d2020-10-12 03:36:52 +00002483 CompilerFilter::Filter::kQuicken,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002484 { "--class-loader-context=" + stored_context },
Vladimir Marko21910692019-11-06 13:27:03 +00002485 /*expect_success=*/ true,
2486 /*use_fd=*/ false,
2487 /*use_zip_fd=*/ false,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002488 [&](const OatFile& oat_file) {
Mathieu Chartierc4440772018-04-16 14:40:56 -07002489 EXPECT_NE(oat_file.GetClassLoaderContext(), stored_context) << output_;
2490 EXPECT_NE(oat_file.GetClassLoaderContext(), valid_context) << output_;
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002491 }));
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002492 // The stored context should match what we expect even though it's invalid.
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002493 EXPECT_TRUE(GenerateOdexForTest(GetTestDexFileName("ManyMethods"),
2494 odex_location,
Ming-Shin Lu7e9fc9d2020-10-12 03:36:52 +00002495 CompilerFilter::Filter::kQuicken,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002496 { "--class-loader-context=" + valid_context,
2497 "--stored-class-loader-context=" + stored_context },
Vladimir Marko21910692019-11-06 13:27:03 +00002498 /*expect_success=*/ true,
2499 /*use_fd=*/ false,
2500 /*use_zip_fd=*/ false,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002501 [&](const OatFile& oat_file) {
Mathieu Chartierc4440772018-04-16 14:40:56 -07002502 EXPECT_EQ(oat_file.GetClassLoaderContext(), expected_stored_context) << output_;
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002503 }));
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002504}
2505
xueliang.zhong7f88c1a2018-11-06 11:42:41 +00002506class Dex2oatISAFeaturesRuntimeDetectionTest : public Dex2oatTest {
2507 protected:
2508 void RunTest(const std::vector<std::string>& extra_args = {}) {
2509 std::string dex_location = GetScratchDir() + "/Dex2OatSwapTest.jar";
2510 std::string odex_location = GetOdexDir() + "/Dex2OatSwapTest.odex";
2511
2512 Copy(GetTestDexFileName(), dex_location);
2513
2514 ASSERT_TRUE(GenerateOdexForTest(dex_location,
2515 odex_location,
2516 CompilerFilter::kSpeed,
2517 extra_args));
2518 }
2519
2520 std::string GetTestDexFileName() {
2521 return GetDexSrc1();
2522 }
2523};
2524
2525TEST_F(Dex2oatISAFeaturesRuntimeDetectionTest, TestCurrentRuntimeFeaturesAsDex2OatArguments) {
2526 std::vector<std::string> argv;
2527 Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv);
2528 auto option_pos =
2529 std::find(std::begin(argv), std::end(argv), "--instruction-set-features=runtime");
2530 if (InstructionSetFeatures::IsRuntimeDetectionSupported()) {
2531 EXPECT_TRUE(kIsTargetBuild);
2532 EXPECT_NE(option_pos, std::end(argv));
2533 } else {
2534 EXPECT_EQ(option_pos, std::end(argv));
2535 }
2536
2537 RunTest();
2538}
2539
David Sehrfe57c2b2020-03-27 14:58:54 +00002540class LinkageTest : public Dex2oatTest {};
2541
2542TEST_F(LinkageTest, LinkageEnabled) {
2543 TEST_DISABLED_FOR_TARGET();
2544 std::unique_ptr<const DexFile> dex(OpenTestDexFile("LinkageTest"));
2545 std::string out_dir = GetScratchDir();
2546 const std::string base_oat_name = out_dir + "/base.oat";
2547 std::string error_msg;
2548 const int res_fail = GenerateOdexForTestWithStatus(
2549 {dex->GetLocation()},
2550 base_oat_name,
Ming-Shin Lu7e9fc9d2020-10-12 03:36:52 +00002551 CompilerFilter::Filter::kQuicken,
David Sehrfe57c2b2020-03-27 14:58:54 +00002552 &error_msg,
2553 {"--check-linkage-conditions", "--crash-on-linkage-violation"});
2554 EXPECT_NE(0, res_fail);
2555
2556 const int res_no_fail = GenerateOdexForTestWithStatus(
2557 {dex->GetLocation()},
2558 base_oat_name,
Ming-Shin Lu7e9fc9d2020-10-12 03:36:52 +00002559 CompilerFilter::Filter::kQuicken,
David Sehrfe57c2b2020-03-27 14:58:54 +00002560 &error_msg,
2561 {"--check-linkage-conditions"});
2562 EXPECT_EQ(0, res_no_fail);
2563}
2564
Andreas Gampee1459ae2016-06-29 09:36:30 -07002565} // namespace art