blob: 372ee354c86739cb13dabd07b767d91b5ef6e07e [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"
David Sehr013fd802018-01-11 22:55:24 -080037#include "dex/art_dex_file_loader.h"
Mathieu Chartier05f90d12018-02-07 13:47:17 -080038#include "dex/base64_test_util.h"
David Sehr312f3b22018-03-19 08:39:26 -070039#include "dex/bytecode_utils.h"
Mathieu Chartier2242ef12018-07-23 18:14:13 -070040#include "dex/class_accessor-inl.h"
David Sehr9e734c72018-01-04 17:56:19 -080041#include "dex/code_item_accessors-inl.h"
42#include "dex/dex_file-inl.h"
43#include "dex/dex_file_loader.h"
Andreas Gampee1459ae2016-06-29 09:36:30 -070044#include "dex2oat_environment_test.h"
Andreas Gampef7882972017-03-20 16:35:24 -070045#include "dex2oat_return_codes.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;
Mathieu Chartier02129102017-12-22 11:04:01 -080057static 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);
617 RunTest(CompilerFilter::kQuicken, false, false);
618 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" });
622 RunTest(CompilerFilter::kQuicken, false, false, { "--very-large-app-threshold=10000000" });
623 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" });
629 RunTest(CompilerFilter::kQuicken, true, true, { "--very-large-app-threshold=100" });
630 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
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100876class 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());
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800890 ASSERT_TRUE(GenerateOdexForTest(dex_location,
891 odex_location,
892 CompilerFilter::kQuicken,
893 { input_vdex, output_vdex },
894 /* expect_success= */ true,
895 /* use_fd= */ true));
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100896 EXPECT_GT(vdex_file1->GetLength(), 0u);
897 }
898 // Unquicken by running the verify compiler filter on the vdex file.
899 {
900 std::string input_vdex = StringPrintf("--input-vdex-fd=%d", vdex_file1->Fd());
901 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file1->Fd());
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800902 ASSERT_TRUE(GenerateOdexForTest(dex_location,
903 odex_location,
904 CompilerFilter::kVerify,
905 { input_vdex, output_vdex, kDisableCompactDex },
906 /* expect_success= */ true,
907 /* use_fd= */ true));
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100908 }
909 ASSERT_EQ(vdex_file1->FlushCloseOrErase(), 0) << "Could not flush and close vdex file";
910 CheckResult(dex_location, odex_location);
911 ASSERT_TRUE(success_);
912 }
913
Mathieu Chartierd27923c2018-02-08 21:00:03 -0800914 void RunUnquickenMultiDexCDex() {
915 std::string dex_location = GetScratchDir() + "/UnquickenMultiDex.jar";
916 std::string odex_location = GetOdexDir() + "/UnquickenMultiDex.odex";
917 std::string odex_location2 = GetOdexDir() + "/UnquickenMultiDex2.odex";
918 std::string vdex_location = GetOdexDir() + "/UnquickenMultiDex.vdex";
919 std::string vdex_location2 = GetOdexDir() + "/UnquickenMultiDex2.vdex";
920 Copy(GetTestDexFileName("MultiDex"), dex_location);
921
922 std::unique_ptr<File> vdex_file1(OS::CreateEmptyFile(vdex_location.c_str()));
923 std::unique_ptr<File> vdex_file2(OS::CreateEmptyFile(vdex_location2.c_str()));
924 CHECK(vdex_file1 != nullptr) << vdex_location;
925 CHECK(vdex_file2 != nullptr) << vdex_location2;
926
927 // Quicken the dex file into a vdex file.
928 {
929 std::string input_vdex = "--input-vdex-fd=-1";
930 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file1->Fd());
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800931 ASSERT_TRUE(GenerateOdexForTest(dex_location,
932 odex_location,
933 CompilerFilter::kQuicken,
934 { input_vdex, output_vdex, "--compact-dex-level=fast"},
935 /* expect_success= */ true,
936 /* use_fd= */ true));
Mathieu Chartierd27923c2018-02-08 21:00:03 -0800937 EXPECT_GT(vdex_file1->GetLength(), 0u);
938 }
939
940 // Unquicken by running the verify compiler filter on the vdex file.
941 {
942 std::string input_vdex = StringPrintf("--input-vdex-fd=%d", vdex_file1->Fd());
943 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file2->Fd());
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800944 ASSERT_TRUE(GenerateOdexForTest(dex_location,
945 odex_location2,
946 CompilerFilter::kVerify,
947 { input_vdex, output_vdex, "--compact-dex-level=none"},
948 /* expect_success= */ true,
949 /* use_fd= */ true));
Mathieu Chartierd27923c2018-02-08 21:00:03 -0800950 }
951 ASSERT_EQ(vdex_file1->FlushCloseOrErase(), 0) << "Could not flush and close vdex file";
952 ASSERT_EQ(vdex_file2->FlushCloseOrErase(), 0) << "Could not flush and close vdex file";
953 CheckResult(dex_location, odex_location2);
954 ASSERT_TRUE(success_);
955 }
956
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100957 void CheckResult(const std::string& dex_location, const std::string& odex_location) {
958 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100959 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +0100960 odex_location.c_str(),
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100961 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100962 /*executable=*/ false,
963 /*low_4gb=*/ false,
Vladimir Markob7bf8432019-12-03 13:18:50 +0000964 dex_location,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100965 &error_msg));
966 ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
967 ASSERT_GE(odex_file->GetOatDexFiles().size(), 1u);
968
969 // Iterate over the dex files and ensure there is no quickened instruction.
970 for (const OatDexFile* oat_dex_file : odex_file->GetOatDexFiles()) {
971 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
Mathieu Chartier2242ef12018-07-23 18:14:13 -0700972 for (ClassAccessor accessor : dex_file->GetClasses()) {
973 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
974 for (const DexInstructionPcPair& inst : method.GetInstructions()) {
975 ASSERT_FALSE(inst->IsQuickened()) << inst->Opcode() << " " << output_;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100976 }
977 }
978 }
979 }
980 }
981};
982
983TEST_F(Dex2oatUnquickenTest, UnquickenMultiDex) {
984 RunUnquickenMultiDex();
985}
986
Mathieu Chartierd27923c2018-02-08 21:00:03 -0800987TEST_F(Dex2oatUnquickenTest, UnquickenMultiDexCDex) {
988 RunUnquickenMultiDexCDex();
989}
990
Andreas Gampe2e8a2562017-01-18 20:39:02 -0800991class Dex2oatWatchdogTest : public Dex2oatTest {
992 protected:
993 void RunTest(bool expect_success, const std::vector<std::string>& extra_args = {}) {
994 std::string dex_location = GetScratchDir() + "/Dex2OatSwapTest.jar";
995 std::string odex_location = GetOdexDir() + "/Dex2OatSwapTest.odex";
996
997 Copy(GetTestDexFileName(), dex_location);
998
999 std::vector<std::string> copy(extra_args);
1000
1001 std::string swap_location = GetOdexDir() + "/Dex2OatSwapTest.odex.swap";
1002 copy.push_back("--swap-file=" + swap_location);
Andreas Gampe22fa3762017-10-23 20:58:12 -07001003 copy.push_back("-j512"); // Excessive idle threads just slow down dex2oat.
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001004 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1005 odex_location,
1006 CompilerFilter::kSpeed,
1007 copy,
1008 expect_success));
Andreas Gampe2e8a2562017-01-18 20:39:02 -08001009 }
1010
1011 std::string GetTestDexFileName() {
1012 return GetDexSrc1();
1013 }
1014};
1015
1016TEST_F(Dex2oatWatchdogTest, TestWatchdogOK) {
1017 // Check with default.
1018 RunTest(true);
1019
1020 // Check with ten minutes.
1021 RunTest(true, { "--watchdog-timeout=600000" });
1022}
1023
1024TEST_F(Dex2oatWatchdogTest, TestWatchdogTrigger) {
Andreas Gampe148c1602019-06-10 16:47:46 -07001025 // This test is frequently interrupted by signal_dumper on host (x86);
Roland Levillain1fb24e22019-01-09 13:33:37 +00001026 // disable it while we investigate (b/121352534).
1027 TEST_DISABLED_FOR_X86();
1028
Andreas Gampe80ddf272018-01-11 09:41:00 -08001029 // The watchdog is independent of dex2oat and will not delete intermediates. It is possible
1030 // that the compilation succeeds and the file is completely written by the time the watchdog
1031 // kills dex2oat (but the dex2oat threads must have been scheduled pretty badly).
1032 test_accepts_odex_file_on_failure = true;
1033
Andreas Gampe2e8a2562017-01-18 20:39:02 -08001034 // Check with ten milliseconds.
1035 RunTest(false, { "--watchdog-timeout=10" });
1036}
1037
Andreas Gampef7882972017-03-20 16:35:24 -07001038class Dex2oatReturnCodeTest : public Dex2oatTest {
1039 protected:
1040 int RunTest(const std::vector<std::string>& extra_args = {}) {
1041 std::string dex_location = GetScratchDir() + "/Dex2OatSwapTest.jar";
1042 std::string odex_location = GetOdexDir() + "/Dex2OatSwapTest.odex";
1043
1044 Copy(GetTestDexFileName(), dex_location);
1045
1046 std::string error_msg;
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001047 return GenerateOdexForTestWithStatus({dex_location},
Andreas Gampef7882972017-03-20 16:35:24 -07001048 odex_location,
1049 CompilerFilter::kSpeed,
1050 &error_msg,
1051 extra_args);
1052 }
1053
1054 std::string GetTestDexFileName() {
1055 return GetDexSrc1();
1056 }
1057};
1058
1059TEST_F(Dex2oatReturnCodeTest, TestCreateRuntime) {
Andreas Gampefd80b172017-04-26 22:25:31 -07001060 TEST_DISABLED_FOR_MEMORY_TOOL(); // b/19100793
Andreas Gampef7882972017-03-20 16:35:24 -07001061 int status = RunTest({ "--boot-image=/this/does/not/exist/yolo.oat" });
1062 EXPECT_EQ(static_cast<int>(dex2oat::ReturnCode::kCreateRuntime), WEXITSTATUS(status)) << output_;
1063}
1064
Calin Juravle1ce70852017-06-28 10:59:03 -07001065class Dex2oatClassLoaderContextTest : public Dex2oatTest {
1066 protected:
1067 void RunTest(const char* class_loader_context,
1068 const char* expected_classpath_key,
1069 bool expected_success,
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001070 bool use_second_source = false,
1071 bool generate_image = false) {
Calin Juravle1ce70852017-06-28 10:59:03 -07001072 std::string dex_location = GetUsedDexLocation();
1073 std::string odex_location = GetUsedOatLocation();
1074
1075 Copy(use_second_source ? GetDexSrc2() : GetDexSrc1(), dex_location);
1076
1077 std::string error_msg;
1078 std::vector<std::string> extra_args;
1079 if (class_loader_context != nullptr) {
1080 extra_args.push_back(std::string("--class-loader-context=") + class_loader_context);
1081 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001082 if (generate_image) {
1083 extra_args.push_back(std::string("--app-image-file=") + GetUsedImageLocation());
1084 }
Calin Juravle1ce70852017-06-28 10:59:03 -07001085 auto check_oat = [expected_classpath_key](const OatFile& oat_file) {
1086 ASSERT_TRUE(expected_classpath_key != nullptr);
1087 const char* classpath = oat_file.GetOatHeader().GetStoreValueByKey(OatHeader::kClassPathKey);
1088 ASSERT_TRUE(classpath != nullptr);
1089 ASSERT_STREQ(expected_classpath_key, classpath);
1090 };
1091
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001092 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1093 odex_location,
1094 CompilerFilter::kQuicken,
1095 extra_args,
1096 expected_success,
Vladimir Marko21910692019-11-06 13:27:03 +00001097 /*use_fd=*/ false,
1098 /*use_zip_fd=*/ false,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001099 check_oat));
Calin Juravle1ce70852017-06-28 10:59:03 -07001100 }
1101
1102 std::string GetUsedDexLocation() {
1103 return GetScratchDir() + "/Context.jar";
1104 }
1105
1106 std::string GetUsedOatLocation() {
1107 return GetOdexDir() + "/Context.odex";
1108 }
1109
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001110 std::string GetUsedImageLocation() {
1111 return GetOdexDir() + "/Context.art";
1112 }
1113
Calin Juravle7b0648a2017-07-07 18:40:50 -07001114 const char* kEmptyClassPathKey = "PCL[]";
Calin Juravle1ce70852017-06-28 10:59:03 -07001115};
1116
1117TEST_F(Dex2oatClassLoaderContextTest, InvalidContext) {
1118 RunTest("Invalid[]", /*expected_classpath_key*/ nullptr, /*expected_success*/ false);
1119}
1120
1121TEST_F(Dex2oatClassLoaderContextTest, EmptyContext) {
1122 RunTest("PCL[]", kEmptyClassPathKey, /*expected_success*/ true);
1123}
1124
1125TEST_F(Dex2oatClassLoaderContextTest, SpecialContext) {
1126 RunTest(OatFile::kSpecialSharedLibrary,
1127 OatFile::kSpecialSharedLibrary,
1128 /*expected_success*/ true);
1129}
1130
1131TEST_F(Dex2oatClassLoaderContextTest, ContextWithTheSourceDexFiles) {
1132 std::string context = "PCL[" + GetUsedDexLocation() + "]";
1133 RunTest(context.c_str(), kEmptyClassPathKey, /*expected_success*/ true);
1134}
1135
1136TEST_F(Dex2oatClassLoaderContextTest, ContextWithOtherDexFiles) {
1137 std::vector<std::unique_ptr<const DexFile>> dex_files = OpenTestDexFiles("Nested");
Calin Juravle1ce70852017-06-28 10:59:03 -07001138
1139 std::string context = "PCL[" + dex_files[0]->GetLocation() + "]";
Calin Juravle7b0648a2017-07-07 18:40:50 -07001140 std::string expected_classpath_key = "PCL[" +
1141 dex_files[0]->GetLocation() + "*" + std::to_string(dex_files[0]->GetLocationChecksum()) + "]";
Calin Juravle1ce70852017-06-28 10:59:03 -07001142 RunTest(context.c_str(), expected_classpath_key.c_str(), true);
1143}
1144
1145TEST_F(Dex2oatClassLoaderContextTest, ContextWithStrippedDexFiles) {
1146 std::string stripped_classpath = GetScratchDir() + "/stripped_classpath.jar";
1147 Copy(GetStrippedDexSrc1(), stripped_classpath);
1148
1149 std::string context = "PCL[" + stripped_classpath + "]";
1150 // Expect an empty context because stripped dex files cannot be open.
Calin Juravle7b0648a2017-07-07 18:40:50 -07001151 RunTest(context.c_str(), kEmptyClassPathKey , /*expected_success*/ true);
Calin Juravle1ce70852017-06-28 10:59:03 -07001152}
1153
1154TEST_F(Dex2oatClassLoaderContextTest, ContextWithStrippedDexFilesBackedByOdex) {
1155 std::string stripped_classpath = GetScratchDir() + "/stripped_classpath.jar";
1156 std::string odex_for_classpath = GetOdexDir() + "/stripped_classpath.odex";
1157
1158 Copy(GetDexSrc1(), stripped_classpath);
1159
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001160 ASSERT_TRUE(GenerateOdexForTest(stripped_classpath,
1161 odex_for_classpath,
1162 CompilerFilter::kQuicken,
1163 {},
1164 true));
Calin Juravle1ce70852017-06-28 10:59:03 -07001165
1166 // Strip the dex file
1167 Copy(GetStrippedDexSrc1(), stripped_classpath);
1168
1169 std::string context = "PCL[" + stripped_classpath + "]";
Calin Juravle7b0648a2017-07-07 18:40:50 -07001170 std::string expected_classpath_key;
Calin Juravle1ce70852017-06-28 10:59:03 -07001171 {
1172 // Open the oat file to get the expected classpath.
Nicolas Geoffray29742602017-12-14 10:09:03 +00001173 OatFileAssistant oat_file_assistant(stripped_classpath.c_str(), kRuntimeISA, false, false);
Calin Juravle1ce70852017-06-28 10:59:03 -07001174 std::unique_ptr<OatFile> oat_file(oat_file_assistant.GetBestOatFile());
1175 std::vector<std::unique_ptr<const DexFile>> oat_dex_files =
1176 OatFileAssistant::LoadDexFiles(*oat_file, stripped_classpath.c_str());
Calin Juravle7b0648a2017-07-07 18:40:50 -07001177 expected_classpath_key = "PCL[";
1178 for (size_t i = 0; i < oat_dex_files.size(); i++) {
1179 if (i > 0) {
1180 expected_classpath_key + ":";
1181 }
1182 expected_classpath_key += oat_dex_files[i]->GetLocation() + "*" +
1183 std::to_string(oat_dex_files[i]->GetLocationChecksum());
1184 }
1185 expected_classpath_key += "]";
Calin Juravle1ce70852017-06-28 10:59:03 -07001186 }
1187
1188 RunTest(context.c_str(),
Calin Juravle7b0648a2017-07-07 18:40:50 -07001189 expected_classpath_key.c_str(),
Calin Juravle1ce70852017-06-28 10:59:03 -07001190 /*expected_success*/ true,
1191 /*use_second_source*/ true);
1192}
1193
1194TEST_F(Dex2oatClassLoaderContextTest, ContextWithNotExistentDexFiles) {
1195 std::string context = "PCL[does_not_exists.dex]";
1196 // Expect an empty context because stripped dex files cannot be open.
1197 RunTest(context.c_str(), kEmptyClassPathKey, /*expected_success*/ true);
1198}
1199
Calin Juravlec79470d2017-07-12 17:37:42 -07001200TEST_F(Dex2oatClassLoaderContextTest, ChainContext) {
1201 std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested");
1202 std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex");
1203
1204 std::string context = "PCL[" + GetTestDexFileName("Nested") + "];" +
1205 "DLC[" + GetTestDexFileName("MultiDex") + "]";
1206 std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "];" +
1207 "DLC[" + CreateClassPathWithChecksums(dex_files2) + "]";
1208
1209 RunTest(context.c_str(), expected_classpath_key.c_str(), true);
1210}
1211
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00001212TEST_F(Dex2oatClassLoaderContextTest, ContextWithSharedLibrary) {
1213 std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested");
1214 std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex");
1215
1216 std::string context = "PCL[" + GetTestDexFileName("Nested") + "]" +
1217 "{PCL[" + GetTestDexFileName("MultiDex") + "]}";
1218 std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "]" +
1219 "{PCL[" + CreateClassPathWithChecksums(dex_files2) + "]}";
1220 RunTest(context.c_str(), expected_classpath_key.c_str(), true);
1221}
1222
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001223TEST_F(Dex2oatClassLoaderContextTest, ContextWithSharedLibraryAndImage) {
1224 std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested");
1225 std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex");
1226
1227 std::string context = "PCL[" + GetTestDexFileName("Nested") + "]" +
1228 "{PCL[" + GetTestDexFileName("MultiDex") + "]}";
1229 std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "]" +
1230 "{PCL[" + CreateClassPathWithChecksums(dex_files2) + "]}";
1231 RunTest(context.c_str(),
1232 expected_classpath_key.c_str(),
1233 /*expected_success=*/ true,
1234 /*use_second_source=*/ false,
1235 /*generate_image=*/ true);
1236}
1237
1238TEST_F(Dex2oatClassLoaderContextTest, ContextWithSameSharedLibrariesAndImage) {
1239 std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested");
1240 std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex");
1241
1242 std::string context = "PCL[" + GetTestDexFileName("Nested") + "]" +
1243 "{PCL[" + GetTestDexFileName("MultiDex") + "]" +
1244 "#PCL[" + GetTestDexFileName("MultiDex") + "]}";
1245 std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "]" +
1246 "{PCL[" + CreateClassPathWithChecksums(dex_files2) + "]" +
1247 "#PCL[" + CreateClassPathWithChecksums(dex_files2) + "]}";
1248 RunTest(context.c_str(),
1249 expected_classpath_key.c_str(),
1250 /*expected_success=*/ true,
1251 /*use_second_source=*/ false,
1252 /*generate_image=*/ true);
1253}
1254
1255TEST_F(Dex2oatClassLoaderContextTest, ContextWithSharedLibrariesDependenciesAndImage) {
1256 std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested");
1257 std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex");
1258
1259 std::string context = "PCL[" + GetTestDexFileName("Nested") + "]" +
1260 "{PCL[" + GetTestDexFileName("MultiDex") + "]" +
1261 "{PCL[" + GetTestDexFileName("Nested") + "]}}";
1262 std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "]" +
1263 "{PCL[" + CreateClassPathWithChecksums(dex_files2) + "]" +
1264 "{PCL[" + CreateClassPathWithChecksums(dex_files1) + "]}}";
1265 RunTest(context.c_str(),
1266 expected_classpath_key.c_str(),
1267 /*expected_success=*/ true,
1268 /*use_second_source=*/ false,
1269 /*generate_image=*/ true);
1270}
1271
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001272class Dex2oatDeterminism : public Dex2oatTest {};
1273
1274TEST_F(Dex2oatDeterminism, UnloadCompile) {
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001275 Runtime* const runtime = Runtime::Current();
1276 std::string out_dir = GetScratchDir();
1277 const std::string base_oat_name = out_dir + "/base.oat";
1278 const std::string base_vdex_name = out_dir + "/base.vdex";
1279 const std::string unload_oat_name = out_dir + "/unload.oat";
1280 const std::string unload_vdex_name = out_dir + "/unload.vdex";
1281 const std::string no_unload_oat_name = out_dir + "/nounload.oat";
1282 const std::string no_unload_vdex_name = out_dir + "/nounload.vdex";
1283 const std::string app_image_name = out_dir + "/unload.art";
1284 std::string error_msg;
1285 const std::vector<gc::space::ImageSpace*>& spaces = runtime->GetHeap()->GetBootImageSpaces();
1286 ASSERT_GT(spaces.size(), 0u);
1287 const std::string image_location = spaces[0]->GetImageLocation();
1288 // Without passing in an app image, it will unload in between compilations.
1289 const int res = GenerateOdexForTestWithStatus(
1290 GetLibCoreDexFileNames(),
1291 base_oat_name,
1292 CompilerFilter::Filter::kQuicken,
1293 &error_msg,
1294 {"--force-determinism", "--avoid-storing-invocation"});
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001295 ASSERT_EQ(res, 0);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001296 Copy(base_oat_name, unload_oat_name);
1297 Copy(base_vdex_name, unload_vdex_name);
1298 std::unique_ptr<File> unload_oat(OS::OpenFileForReading(unload_oat_name.c_str()));
1299 std::unique_ptr<File> unload_vdex(OS::OpenFileForReading(unload_vdex_name.c_str()));
1300 ASSERT_TRUE(unload_oat != nullptr);
1301 ASSERT_TRUE(unload_vdex != nullptr);
1302 EXPECT_GT(unload_oat->GetLength(), 0u);
1303 EXPECT_GT(unload_vdex->GetLength(), 0u);
1304 // Regenerate with an app image to disable the dex2oat unloading and verify that the output is
1305 // the same.
1306 const int res2 = GenerateOdexForTestWithStatus(
1307 GetLibCoreDexFileNames(),
1308 base_oat_name,
1309 CompilerFilter::Filter::kQuicken,
1310 &error_msg,
1311 {"--force-determinism", "--avoid-storing-invocation", "--app-image-file=" + app_image_name});
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001312 ASSERT_EQ(res2, 0);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001313 Copy(base_oat_name, no_unload_oat_name);
1314 Copy(base_vdex_name, no_unload_vdex_name);
1315 std::unique_ptr<File> no_unload_oat(OS::OpenFileForReading(no_unload_oat_name.c_str()));
1316 std::unique_ptr<File> no_unload_vdex(OS::OpenFileForReading(no_unload_vdex_name.c_str()));
1317 ASSERT_TRUE(no_unload_oat != nullptr);
1318 ASSERT_TRUE(no_unload_vdex != nullptr);
1319 EXPECT_GT(no_unload_oat->GetLength(), 0u);
1320 EXPECT_GT(no_unload_vdex->GetLength(), 0u);
1321 // Verify that both of the files are the same (odex and vdex).
1322 EXPECT_EQ(unload_oat->GetLength(), no_unload_oat->GetLength());
1323 EXPECT_EQ(unload_vdex->GetLength(), no_unload_vdex->GetLength());
1324 EXPECT_EQ(unload_oat->Compare(no_unload_oat.get()), 0)
1325 << unload_oat_name << " " << no_unload_oat_name;
1326 EXPECT_EQ(unload_vdex->Compare(no_unload_vdex.get()), 0)
1327 << unload_vdex_name << " " << no_unload_vdex_name;
1328 // App image file.
1329 std::unique_ptr<File> app_image_file(OS::OpenFileForReading(app_image_name.c_str()));
1330 ASSERT_TRUE(app_image_file != nullptr);
1331 EXPECT_GT(app_image_file->GetLength(), 0u);
1332}
1333
Mathieu Chartier120aa282017-08-05 16:03:03 -07001334// Test that dexlayout section info is correctly written to the oat file for profile based
1335// compilation.
1336TEST_F(Dex2oatTest, LayoutSections) {
1337 using Hotness = ProfileCompilationInfo::MethodHotness;
1338 std::unique_ptr<const DexFile> dex(OpenTestDexFile("ManyMethods"));
1339 ScratchFile profile_file;
1340 // We can only layout method indices with code items, figure out which ones have this property
1341 // first.
1342 std::vector<uint16_t> methods;
1343 {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001344 const dex::TypeId* type_id = dex->FindTypeId("LManyMethods;");
Mathieu Chartier120aa282017-08-05 16:03:03 -07001345 dex::TypeIndex type_idx = dex->GetIndexForTypeId(*type_id);
Mathieu Chartier2242ef12018-07-23 18:14:13 -07001346 ClassAccessor accessor(*dex, *dex->FindClassDef(type_idx));
Mathieu Chartier120aa282017-08-05 16:03:03 -07001347 std::set<size_t> code_item_offsets;
Mathieu Chartier2242ef12018-07-23 18:14:13 -07001348 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
1349 const uint16_t method_idx = method.GetIndex();
1350 const size_t code_item_offset = method.GetCodeItemOffset();
Mathieu Chartier120aa282017-08-05 16:03:03 -07001351 if (code_item_offsets.insert(code_item_offset).second) {
1352 // Unique code item, add the method index.
1353 methods.push_back(method_idx);
1354 }
1355 }
Mathieu Chartier120aa282017-08-05 16:03:03 -07001356 }
1357 ASSERT_GE(methods.size(), 8u);
1358 std::vector<uint16_t> hot_methods = {methods[1], methods[3], methods[5]};
1359 std::vector<uint16_t> startup_methods = {methods[1], methods[2], methods[7]};
1360 std::vector<uint16_t> post_methods = {methods[0], methods[2], methods[6]};
1361 // Here, we build the profile from the method lists.
1362 ProfileCompilationInfo info;
1363 info.AddMethodsForDex(
1364 static_cast<Hotness::Flag>(Hotness::kFlagHot | Hotness::kFlagStartup),
1365 dex.get(),
1366 hot_methods.begin(),
1367 hot_methods.end());
1368 info.AddMethodsForDex(
1369 Hotness::kFlagStartup,
1370 dex.get(),
1371 startup_methods.begin(),
1372 startup_methods.end());
1373 info.AddMethodsForDex(
1374 Hotness::kFlagPostStartup,
1375 dex.get(),
1376 post_methods.begin(),
1377 post_methods.end());
1378 for (uint16_t id : hot_methods) {
1379 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsHot());
1380 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsStartup());
1381 }
1382 for (uint16_t id : startup_methods) {
1383 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsStartup());
1384 }
1385 for (uint16_t id : post_methods) {
1386 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsPostStartup());
1387 }
1388 // Save the profile since we want to use it with dex2oat to produce an oat file.
1389 ASSERT_TRUE(info.Save(profile_file.GetFd()));
1390 // Generate a profile based odex.
1391 const std::string dir = GetScratchDir();
1392 const std::string oat_filename = dir + "/base.oat";
1393 const std::string vdex_filename = dir + "/base.vdex";
1394 std::string error_msg;
1395 const int res = GenerateOdexForTestWithStatus(
1396 {dex->GetLocation()},
1397 oat_filename,
1398 CompilerFilter::Filter::kQuicken,
1399 &error_msg,
1400 {"--profile-file=" + profile_file.GetFilename()});
1401 EXPECT_EQ(res, 0);
1402
1403 // Open our generated oat file.
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001404 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01001405 oat_filename.c_str(),
Mathieu Chartier120aa282017-08-05 16:03:03 -07001406 oat_filename.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001407 /*executable=*/ false,
1408 /*low_4gb=*/ false,
Vladimir Markob7bf8432019-12-03 13:18:50 +00001409 dex->GetLocation(),
Mathieu Chartier120aa282017-08-05 16:03:03 -07001410 &error_msg));
1411 ASSERT_TRUE(odex_file != nullptr);
1412 std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
1413 ASSERT_EQ(oat_dex_files.size(), 1u);
1414 // Check that the code sections match what we expect.
1415 for (const OatDexFile* oat_dex : oat_dex_files) {
1416 const DexLayoutSections* const sections = oat_dex->GetDexLayoutSections();
1417 // Testing of logging the sections.
1418 ASSERT_TRUE(sections != nullptr);
1419 LOG(INFO) << *sections;
1420
1421 // Load the sections into temporary variables for convenience.
1422 const DexLayoutSection& code_section =
1423 sections->sections_[static_cast<size_t>(DexLayoutSections::SectionType::kSectionTypeCode)];
1424 const DexLayoutSection::Subsection& section_hot_code =
1425 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeHot)];
1426 const DexLayoutSection::Subsection& section_sometimes_used =
1427 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeSometimesUsed)];
1428 const DexLayoutSection::Subsection& section_startup_only =
1429 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeStartupOnly)];
1430 const DexLayoutSection::Subsection& section_unused =
1431 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeUnused)];
1432
1433 // All the sections should be non-empty.
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001434 EXPECT_GT(section_hot_code.Size(), 0u);
1435 EXPECT_GT(section_sometimes_used.Size(), 0u);
1436 EXPECT_GT(section_startup_only.Size(), 0u);
1437 EXPECT_GT(section_unused.Size(), 0u);
Mathieu Chartier120aa282017-08-05 16:03:03 -07001438
1439 // Open the dex file since we need to peek at the code items to verify the layout matches what
1440 // we expect.
1441 std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1442 ASSERT_TRUE(dex_file != nullptr) << error_msg;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001443 const dex::TypeId* type_id = dex_file->FindTypeId("LManyMethods;");
Mathieu Chartier120aa282017-08-05 16:03:03 -07001444 ASSERT_TRUE(type_id != nullptr);
1445 dex::TypeIndex type_idx = dex_file->GetIndexForTypeId(*type_id);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001446 const dex::ClassDef* class_def = dex_file->FindClassDef(type_idx);
Mathieu Chartier120aa282017-08-05 16:03:03 -07001447 ASSERT_TRUE(class_def != nullptr);
1448
1449 // Count how many code items are for each category, there should be at least one per category.
1450 size_t hot_count = 0;
1451 size_t post_startup_count = 0;
1452 size_t startup_count = 0;
1453 size_t unused_count = 0;
1454 // Visit all of the methdos of the main class and cross reference the method indices to their
1455 // corresponding code item offsets to verify the layout.
Mathieu Chartier2242ef12018-07-23 18:14:13 -07001456 ClassAccessor accessor(*dex_file, *class_def);
1457 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
1458 const size_t method_idx = method.GetIndex();
1459 const size_t code_item_offset = method.GetCodeItemOffset();
Mathieu Chartier120aa282017-08-05 16:03:03 -07001460 const bool is_hot = ContainsElement(hot_methods, method_idx);
1461 const bool is_startup = ContainsElement(startup_methods, method_idx);
1462 const bool is_post_startup = ContainsElement(post_methods, method_idx);
1463 if (is_hot) {
1464 // Hot is highest precedence, check that the hot methods are in the hot section.
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001465 EXPECT_TRUE(section_hot_code.Contains(code_item_offset));
Mathieu Chartier120aa282017-08-05 16:03:03 -07001466 ++hot_count;
1467 } else if (is_post_startup) {
1468 // Post startup is sometimes used section.
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001469 EXPECT_TRUE(section_sometimes_used.Contains(code_item_offset));
Mathieu Chartier120aa282017-08-05 16:03:03 -07001470 ++post_startup_count;
1471 } else if (is_startup) {
1472 // Startup at this point means not hot or post startup, these must be startup only then.
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001473 EXPECT_TRUE(section_startup_only.Contains(code_item_offset));
Mathieu Chartier120aa282017-08-05 16:03:03 -07001474 ++startup_count;
1475 } else {
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001476 if (section_unused.Contains(code_item_offset)) {
Alan Leung9595fd32017-10-17 17:08:19 -07001477 // If no flags are set, the method should be unused ...
1478 ++unused_count;
1479 } else {
1480 // or this method is part of the last code item and the end is 4 byte aligned.
Mathieu Chartier2242ef12018-07-23 18:14:13 -07001481 for (const ClassAccessor::Method& method2 : accessor.GetMethods()) {
1482 EXPECT_LE(method2.GetCodeItemOffset(), code_item_offset);
Alan Leung9595fd32017-10-17 17:08:19 -07001483 }
1484 uint32_t code_item_size = dex_file->FindCodeItemOffset(*class_def, method_idx);
1485 EXPECT_EQ((code_item_offset + code_item_size) % 4, 0u);
1486 }
Mathieu Chartier120aa282017-08-05 16:03:03 -07001487 }
1488 }
Mathieu Chartier120aa282017-08-05 16:03:03 -07001489 EXPECT_GT(hot_count, 0u);
1490 EXPECT_GT(post_startup_count, 0u);
1491 EXPECT_GT(startup_count, 0u);
1492 EXPECT_GT(unused_count, 0u);
1493 }
1494}
1495
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001496// Test that generating compact dex works.
1497TEST_F(Dex2oatTest, GenerateCompactDex) {
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001498 // Generate a compact dex based odex.
1499 const std::string dir = GetScratchDir();
1500 const std::string oat_filename = dir + "/base.oat";
1501 const std::string vdex_filename = dir + "/base.vdex";
Mathieu Chartierc17b7d82018-03-14 14:00:04 -07001502 const std::string dex_location = GetTestDexFileName("MultiDex");
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001503 std::string error_msg;
1504 const int res = GenerateOdexForTestWithStatus(
Mathieu Chartierc17b7d82018-03-14 14:00:04 -07001505 { dex_location },
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001506 oat_filename,
1507 CompilerFilter::Filter::kQuicken,
1508 &error_msg,
1509 {"--compact-dex-level=fast"});
1510 EXPECT_EQ(res, 0);
1511 // Open our generated oat file.
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001512 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01001513 oat_filename.c_str(),
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001514 oat_filename.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001515 /*executable=*/ false,
1516 /*low_4gb=*/ false,
Vladimir Markob7bf8432019-12-03 13:18:50 +00001517 dex_location,
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001518 &error_msg));
1519 ASSERT_TRUE(odex_file != nullptr);
1520 std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
Mathieu Chartierc17b7d82018-03-14 14:00:04 -07001521 ASSERT_GT(oat_dex_files.size(), 1u);
1522 // Check that each dex is a compact dex file.
1523 std::vector<std::unique_ptr<const CompactDexFile>> compact_dex_files;
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001524 for (const OatDexFile* oat_dex : oat_dex_files) {
1525 std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1526 ASSERT_TRUE(dex_file != nullptr) << error_msg;
1527 ASSERT_TRUE(dex_file->IsCompactDexFile());
Mathieu Chartierc17b7d82018-03-14 14:00:04 -07001528 compact_dex_files.push_back(
1529 std::unique_ptr<const CompactDexFile>(dex_file.release()->AsCompactDexFile()));
1530 }
1531 for (const std::unique_ptr<const CompactDexFile>& dex_file : compact_dex_files) {
1532 // Test that every code item is in the owned section.
1533 const CompactDexFile::Header& header = dex_file->GetHeader();
1534 EXPECT_LE(header.OwnedDataBegin(), header.OwnedDataEnd());
1535 EXPECT_LE(header.OwnedDataBegin(), header.data_size_);
1536 EXPECT_LE(header.OwnedDataEnd(), header.data_size_);
Mathieu Chartier2242ef12018-07-23 18:14:13 -07001537 for (ClassAccessor accessor : dex_file->GetClasses()) {
1538 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
1539 if (method.GetCodeItemOffset() != 0u) {
1540 ASSERT_GE(method.GetCodeItemOffset(), header.OwnedDataBegin());
1541 ASSERT_LT(method.GetCodeItemOffset(), header.OwnedDataEnd());
Mathieu Chartierc17b7d82018-03-14 14:00:04 -07001542 }
Mathieu Chartier2242ef12018-07-23 18:14:13 -07001543 }
Mathieu Chartierc17b7d82018-03-14 14:00:04 -07001544 }
1545 // Test that the owned sections don't overlap.
1546 for (const std::unique_ptr<const CompactDexFile>& other_dex : compact_dex_files) {
1547 if (dex_file != other_dex) {
1548 ASSERT_TRUE(
1549 (dex_file->GetHeader().OwnedDataBegin() >= other_dex->GetHeader().OwnedDataEnd()) ||
1550 (dex_file->GetHeader().OwnedDataEnd() <= other_dex->GetHeader().OwnedDataBegin()));
1551 }
1552 }
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001553 }
1554}
1555
Andreas Gampef39208f2017-10-19 15:06:59 -07001556class Dex2oatVerifierAbort : public Dex2oatTest {};
1557
1558TEST_F(Dex2oatVerifierAbort, HardFail) {
1559 // Use VerifierDeps as it has hard-failing classes.
1560 std::unique_ptr<const DexFile> dex(OpenTestDexFile("VerifierDeps"));
1561 std::string out_dir = GetScratchDir();
1562 const std::string base_oat_name = out_dir + "/base.oat";
1563 std::string error_msg;
1564 const int res_fail = GenerateOdexForTestWithStatus(
1565 {dex->GetLocation()},
1566 base_oat_name,
1567 CompilerFilter::Filter::kQuicken,
1568 &error_msg,
1569 {"--abort-on-hard-verifier-error"});
1570 EXPECT_NE(0, res_fail);
1571
1572 const int res_no_fail = GenerateOdexForTestWithStatus(
1573 {dex->GetLocation()},
1574 base_oat_name,
1575 CompilerFilter::Filter::kQuicken,
1576 &error_msg,
1577 {"--no-abort-on-hard-verifier-error"});
1578 EXPECT_EQ(0, res_no_fail);
1579}
1580
1581TEST_F(Dex2oatVerifierAbort, SoftFail) {
1582 // Use VerifierDepsMulti as it has hard-failing classes.
1583 std::unique_ptr<const DexFile> dex(OpenTestDexFile("VerifierDepsMulti"));
1584 std::string out_dir = GetScratchDir();
1585 const std::string base_oat_name = out_dir + "/base.oat";
1586 std::string error_msg;
1587 const int res_fail = GenerateOdexForTestWithStatus(
1588 {dex->GetLocation()},
1589 base_oat_name,
1590 CompilerFilter::Filter::kQuicken,
1591 &error_msg,
1592 {"--abort-on-soft-verifier-error"});
1593 EXPECT_NE(0, res_fail);
1594
1595 const int res_no_fail = GenerateOdexForTestWithStatus(
1596 {dex->GetLocation()},
1597 base_oat_name,
1598 CompilerFilter::Filter::kQuicken,
1599 &error_msg,
1600 {"--no-abort-on-soft-verifier-error"});
1601 EXPECT_EQ(0, res_no_fail);
1602}
1603
Andreas Gampecac31ad2017-11-06 20:01:17 -08001604class Dex2oatDedupeCode : public Dex2oatTest {};
1605
1606TEST_F(Dex2oatDedupeCode, DedupeTest) {
1607 // Use MyClassNatives. It has lots of native methods that will produce deduplicate-able code.
1608 std::unique_ptr<const DexFile> dex(OpenTestDexFile("MyClassNatives"));
1609 std::string out_dir = GetScratchDir();
1610 const std::string base_oat_name = out_dir + "/base.oat";
1611 size_t no_dedupe_size = 0;
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001612 ASSERT_TRUE(GenerateOdexForTest(dex->GetLocation(),
1613 base_oat_name,
1614 CompilerFilter::Filter::kSpeed,
1615 { "--deduplicate-code=false" },
Vladimir Marko21910692019-11-06 13:27:03 +00001616 /*expect_success=*/ true,
1617 /*use_fd=*/ false,
1618 /*use_zip_fd=*/ false,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001619 [&no_dedupe_size](const OatFile& o) {
1620 no_dedupe_size = o.Size();
1621 }));
Andreas Gampecac31ad2017-11-06 20:01:17 -08001622
1623 size_t dedupe_size = 0;
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001624 ASSERT_TRUE(GenerateOdexForTest(dex->GetLocation(),
1625 base_oat_name,
1626 CompilerFilter::Filter::kSpeed,
1627 { "--deduplicate-code=true" },
Vladimir Marko21910692019-11-06 13:27:03 +00001628 /*expect_success=*/ true,
1629 /*use_fd=*/ false,
1630 /*use_zip_fd=*/ false,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001631 [&dedupe_size](const OatFile& o) {
1632 dedupe_size = o.Size();
1633 }));
Andreas Gampecac31ad2017-11-06 20:01:17 -08001634
1635 EXPECT_LT(dedupe_size, no_dedupe_size);
1636}
1637
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00001638TEST_F(Dex2oatTest, UncompressedTest) {
David Srbecky8c8f1482020-02-05 20:17:10 +00001639 std::unique_ptr<const DexFile> dex(OpenTestDexFile("MainUncompressedAligned"));
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00001640 std::string out_dir = GetScratchDir();
1641 const std::string base_oat_name = out_dir + "/base.oat";
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001642 ASSERT_TRUE(GenerateOdexForTest(dex->GetLocation(),
1643 base_oat_name,
1644 CompilerFilter::Filter::kQuicken,
1645 { },
Vladimir Marko21910692019-11-06 13:27:03 +00001646 /*expect_success=*/ true,
1647 /*use_fd=*/ false,
1648 /*use_zip_fd=*/ false,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001649 [](const OatFile& o) {
1650 CHECK(!o.ContainsDexCode());
1651 }));
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00001652}
1653
Mathieu Chartier700a9852018-02-06 18:27:38 -08001654TEST_F(Dex2oatTest, EmptyUncompressedDexTest) {
1655 std::string out_dir = GetScratchDir();
1656 const std::string base_oat_name = out_dir + "/base.oat";
1657 std::string error_msg;
1658 int status = GenerateOdexForTestWithStatus(
1659 { GetTestDexFileName("MainEmptyUncompressed") },
1660 base_oat_name,
1661 CompilerFilter::Filter::kQuicken,
1662 &error_msg,
1663 { },
1664 /*use_fd*/ false);
1665 // Expect to fail with code 1 and not SIGSEGV or SIGABRT.
1666 ASSERT_TRUE(WIFEXITED(status));
1667 ASSERT_EQ(WEXITSTATUS(status), 1) << error_msg;
1668}
1669
Nicolas Geoffrayc36a8cc2019-04-29 13:37:42 +01001670TEST_F(Dex2oatTest, EmptyUncompressedAlignedDexTest) {
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("MainEmptyUncompressedAligned") },
1676 base_oat_name,
1677 CompilerFilter::Filter::kQuicken,
1678 &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
Mathieu Chartier05f90d12018-02-07 13:47:17 -08001686// Dex file that has duplicate methods have different code items and debug info.
1687static const char kDuplicateMethodInputDex[] =
1688 "ZGV4CjAzOQDEy8VPdj4qHpgPYFWtLCtOykfFP4kB8tGYDAAAcAAAAHhWNBIAAAAAAAAAANALAABI"
1689 "AAAAcAAAAA4AAACQAQAABQAAAMgBAAANAAAABAIAABkAAABsAgAABAAAADQDAADgCAAAuAMAADgI"
1690 "AABCCAAASggAAE8IAABcCAAAaggAAHkIAACICAAAlggAAKQIAACyCAAAwAgAAM4IAADcCAAA6ggA"
1691 "APgIAAD7CAAA/wgAABcJAAAuCQAARQkAAFQJAAB4CQAAmAkAALsJAADSCQAA5gkAAPoJAAAVCgAA"
1692 "KQoAADsKAABCCgAASgoAAFIKAABbCgAAZAoAAGwKAAB0CgAAfAoAAIQKAACMCgAAlAoAAJwKAACk"
1693 "CgAArQoAALcKAADACgAAwwoAAMcKAADcCgAA6QoAAPEKAAD3CgAA/QoAAAMLAAAJCwAAEAsAABcL"
1694 "AAAdCwAAIwsAACkLAAAvCwAANQsAADsLAABBCwAARwsAAE0LAABSCwAAWwsAAF4LAABoCwAAbwsA"
1695 "ABEAAAASAAAAEwAAABQAAAAVAAAAFgAAABcAAAAYAAAAGQAAABoAAAAbAAAAHAAAAC4AAAAwAAAA"
1696 "DwAAAAkAAAAAAAAAEAAAAAoAAACoBwAALgAAAAwAAAAAAAAALwAAAAwAAACoBwAALwAAAAwAAACw"
1697 "BwAAAgAJADUAAAACAAkANgAAAAIACQA3AAAAAgAJADgAAAACAAkAOQAAAAIACQA6AAAAAgAJADsA"
1698 "AAACAAkAPAAAAAIACQA9AAAAAgAJAD4AAAACAAkAPwAAAAIACQBAAAAACwAHAEIAAAAAAAIAAQAA"
1699 "AAAAAwAeAAAAAQACAAEAAAABAAMAHgAAAAIAAgAAAAAAAgACAAEAAAADAAIAAQAAAAMAAgAfAAAA"
1700 "AwACACAAAAADAAIAIQAAAAMAAgAiAAAAAwACACMAAAADAAIAJAAAAAMAAgAlAAAAAwACACYAAAAD"
1701 "AAIAJwAAAAMAAgAoAAAAAwACACkAAAADAAIAKgAAAAMABAA0AAAABwADAEMAAAAIAAIAAQAAAAoA"
1702 "AgABAAAACgABADIAAAAKAAAARQAAAAAAAAAAAAAACAAAAAAAAAAdAAAAaAcAALYHAAAAAAAAAQAA"
1703 "AAAAAAAIAAAAAAAAAB0AAAB4BwAAxAcAAAAAAAACAAAAAAAAAAgAAAAAAAAAHQAAAIgHAADSBwAA"
1704 "AAAAAAMAAAAAAAAACAAAAAAAAAAdAAAAmAcAAPoHAAAAAAAAAAAAAAEAAAAAAAAArAYAADEAAAAa"
1705 "AAMAaQAAABoABABpAAEAGgAHAGkABAAaAAgAaQAFABoACQBpAAYAGgAKAGkABwAaAAsAaQAIABoA"
1706 "DABpAAkAGgANAGkACgAaAA4AaQALABoABQBpAAIAGgAGAGkAAwAOAAAAAQABAAEAAACSBgAABAAA"
1707 "AHAQFQAAAA4ABAABAAIAAACWBgAAFwAAAGIADAAiAQoAcBAWAAEAGgICAG4gFwAhAG4gFwAxAG4Q"
1708 "GAABAAwBbiAUABAADgAAAAEAAQABAAAAngYAAAQAAABwEBUAAAAOAAIAAQACAAAAogYAAAYAAABi"
1709 "AAwAbiAUABAADgABAAEAAQAAAKgGAAAEAAAAcBAVAAAADgABAAEAAQAAALsGAAAEAAAAcBAVAAAA"
1710 "DgABAAAAAQAAAL8GAAAGAAAAYgAAAHEQAwAAAA4AAQAAAAEAAADEBgAABgAAAGIAAQBxEAMAAAAO"
1711 "AAEAAAABAAAA8QYAAAYAAABiAAIAcRABAAAADgABAAAAAQAAAPYGAAAGAAAAYgADAHEQAwAAAA4A"
1712 "AQAAAAEAAADJBgAABgAAAGIABABxEAMAAAAOAAEAAAABAAAAzgYAAAYAAABiAAEAcRADAAAADgAB"
1713 "AAAAAQAAANMGAAAGAAAAYgAGAHEQAwAAAA4AAQAAAAEAAADYBgAABgAAAGIABwBxEAMAAAAOAAEA"
1714 "AAABAAAA3QYAAAYAAABiAAgAcRABAAAADgABAAAAAQAAAOIGAAAGAAAAYgAJAHEQAwAAAA4AAQAA"
1715 "AAEAAADnBgAABgAAAGIACgBxEAMAAAAOAAEAAAABAAAA7AYAAAYAAABiAAsAcRABAAAADgABAAEA"
1716 "AAAAAPsGAAAlAAAAcQAHAAAAcQAIAAAAcQALAAAAcQAMAAAAcQANAAAAcQAOAAAAcQAPAAAAcQAQ"
1717 "AAAAcQARAAAAcQASAAAAcQAJAAAAcQAKAAAADgAnAA4AKQFFDgEWDwAhAA4AIwFFDloAEgAOABMA"
1718 "DktLS0tLS0tLS0tLABEADgAuAA5aADIADloANgAOWgA6AA5aAD4ADloAQgAOWgBGAA5aAEoADloA"
1719 "TgAOWgBSAA5aAFYADloAWgAOWgBeATQOPDw8PDw8PDw8PDw8AAIEAUYYAwIFAjEECEEXLAIFAjEE"
1720 "CEEXKwIFAjEECEEXLQIGAUYcAxgAGAEYAgAAAAIAAAAMBwAAEgcAAAIAAAAMBwAAGwcAAAIAAAAM"
1721 "BwAAJAcAAAEAAAAtBwAAPAcAAAAAAAAAAAAAAAAAAEgHAAAAAAAAAAAAAAAAAABUBwAAAAAAAAAA"
1722 "AAAAAAAAYAcAAAAAAAAAAAAAAAAAAAEAAAAJAAAAAQAAAA0AAAACAACAgASsCAEIxAgAAAIAAoCA"
1723 "BIQJAQicCQwAAgAACQEJAQkBCQEJAQkBCQEJAQkBCQEJAQkEiIAEuAcBgIAEuAkAAA4ABoCABNAJ"
1724 "AQnoCQAJhAoACaAKAAm8CgAJ2AoACfQKAAmQCwAJrAsACcgLAAnkCwAJgAwACZwMAAm4DAg8Y2xp"
1725 "bml0PgAGPGluaXQ+AANBQUEAC0hlbGxvIFdvcmxkAAxIZWxsbyBXb3JsZDEADUhlbGxvIFdvcmxk"
1726 "MTAADUhlbGxvIFdvcmxkMTEADEhlbGxvIFdvcmxkMgAMSGVsbG8gV29ybGQzAAxIZWxsbyBXb3Js"
1727 "ZDQADEhlbGxvIFdvcmxkNQAMSGVsbG8gV29ybGQ2AAxIZWxsbyBXb3JsZDcADEhlbGxvIFdvcmxk"
1728 "OAAMSGVsbG8gV29ybGQ5AAFMAAJMTAAWTE1hbnlNZXRob2RzJFByaW50ZXIyOwAVTE1hbnlNZXRo"
1729 "b2RzJFByaW50ZXI7ABVMTWFueU1ldGhvZHMkU3RyaW5nczsADUxNYW55TWV0aG9kczsAIkxkYWx2"
1730 "aWsvYW5ub3RhdGlvbi9FbmNsb3NpbmdDbGFzczsAHkxkYWx2aWsvYW5ub3RhdGlvbi9Jbm5lckNs"
1731 "YXNzOwAhTGRhbHZpay9hbm5vdGF0aW9uL01lbWJlckNsYXNzZXM7ABVMamF2YS9pby9QcmludFN0"
1732 "cmVhbTsAEkxqYXZhL2xhbmcvT2JqZWN0OwASTGphdmEvbGFuZy9TdHJpbmc7ABlMamF2YS9sYW5n"
1733 "L1N0cmluZ0J1aWxkZXI7ABJMamF2YS9sYW5nL1N5c3RlbTsAEE1hbnlNZXRob2RzLmphdmEABVBy"
1734 "aW50AAZQcmludDAABlByaW50MQAHUHJpbnQxMAAHUHJpbnQxMQAGUHJpbnQyAAZQcmludDMABlBy"
1735 "aW50NAAGUHJpbnQ1AAZQcmludDYABlByaW50NwAGUHJpbnQ4AAZQcmludDkAB1ByaW50ZXIACFBy"
1736 "aW50ZXIyAAdTdHJpbmdzAAFWAAJWTAATW0xqYXZhL2xhbmcvU3RyaW5nOwALYWNjZXNzRmxhZ3MA"
1737 "BmFwcGVuZAAEYXJncwAEbWFpbgAEbXNnMAAEbXNnMQAFbXNnMTAABW1zZzExAARtc2cyAARtc2cz"
1738 "AARtc2c0AARtc2c1AARtc2c2AARtc2c3AARtc2c4AARtc2c5AARuYW1lAANvdXQAB3ByaW50bG4A"
1739 "AXMACHRvU3RyaW5nAAV2YWx1ZQBffn5EOHsibWluLWFwaSI6MTAwMDAsInNoYS0xIjoiZmViODZj"
1740 "MDA2ZWZhY2YxZDc5ODRiODVlMTc5MGZlZjdhNzY3YWViYyIsInZlcnNpb24iOiJ2MS4xLjUtZGV2"
1741 "In0AEAAAAAAAAAABAAAAAAAAAAEAAABIAAAAcAAAAAIAAAAOAAAAkAEAAAMAAAAFAAAAyAEAAAQA"
1742 "AAANAAAABAIAAAUAAAAZAAAAbAIAAAYAAAAEAAAANAMAAAEgAAAUAAAAuAMAAAMgAAAUAAAAkgYA"
1743 "AAQgAAAFAAAADAcAAAMQAAAEAAAAOQcAAAYgAAAEAAAAaAcAAAEQAAACAAAAqAcAAAAgAAAEAAAA"
1744 "tgcAAAIgAABIAAAAOAgAAAAQAAABAAAA0AsAAAAAAAA=";
1745
1746static void WriteBase64ToFile(const char* base64, File* file) {
1747 // Decode base64.
1748 CHECK(base64 != nullptr);
1749 size_t length;
1750 std::unique_ptr<uint8_t[]> bytes(DecodeBase64(base64, &length));
1751 CHECK(bytes != nullptr);
1752 if (!file->WriteFully(bytes.get(), length)) {
1753 PLOG(FATAL) << "Failed to write base64 as file";
1754 }
1755}
1756
1757TEST_F(Dex2oatTest, CompactDexGenerationFailure) {
1758 ScratchFile temp_dex;
1759 WriteBase64ToFile(kDuplicateMethodInputDex, temp_dex.GetFile());
1760 std::string out_dir = GetScratchDir();
1761 const std::string oat_filename = out_dir + "/base.oat";
1762 // The dex won't pass the method verifier, only use the verify filter.
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001763 ASSERT_TRUE(GenerateOdexForTest(temp_dex.GetFilename(),
1764 oat_filename,
1765 CompilerFilter::Filter::kVerify,
1766 { },
Vladimir Marko21910692019-11-06 13:27:03 +00001767 /*expect_success=*/ true,
1768 /*use_fd=*/ false,
1769 /*use_zip_fd=*/ false,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001770 [](const OatFile& o) {
1771 CHECK(o.ContainsDexCode());
1772 }));
Mathieu Chartier05f90d12018-02-07 13:47:17 -08001773 // Open our generated oat file.
1774 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001775 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01001776 oat_filename.c_str(),
Mathieu Chartier05f90d12018-02-07 13:47:17 -08001777 oat_filename.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001778 /*executable=*/ false,
1779 /*low_4gb=*/ false,
Vladimir Markob7bf8432019-12-03 13:18:50 +00001780 temp_dex.GetFilename(),
Mathieu Chartier05f90d12018-02-07 13:47:17 -08001781 &error_msg));
1782 ASSERT_TRUE(odex_file != nullptr);
1783 std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
1784 ASSERT_EQ(oat_dex_files.size(), 1u);
1785 // The dexes should have failed to convert to compact dex.
1786 for (const OatDexFile* oat_dex : oat_dex_files) {
1787 std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1788 ASSERT_TRUE(dex_file != nullptr) << error_msg;
1789 ASSERT_TRUE(!dex_file->IsCompactDexFile());
1790 }
1791}
1792
Mathieu Chartiercda83be2018-03-01 23:55:55 -08001793TEST_F(Dex2oatTest, CompactDexGenerationFailureMultiDex) {
1794 // Create a multidex file with only one dex that gets rejected for cdex conversion.
1795 ScratchFile apk_file;
1796 {
Andreas Gampedfcd82c2018-10-16 20:22:37 -07001797 FILE* file = fdopen(DupCloexec(apk_file.GetFd()), "w+b");
Mathieu Chartiercda83be2018-03-01 23:55:55 -08001798 ZipWriter writer(file);
1799 // Add vdex to zip.
1800 writer.StartEntry("classes.dex", ZipWriter::kCompress);
1801 size_t length = 0u;
1802 std::unique_ptr<uint8_t[]> bytes(DecodeBase64(kDuplicateMethodInputDex, &length));
1803 ASSERT_GE(writer.WriteBytes(&bytes[0], length), 0);
1804 writer.FinishEntry();
1805 writer.StartEntry("classes2.dex", ZipWriter::kCompress);
1806 std::unique_ptr<const DexFile> dex(OpenTestDexFile("ManyMethods"));
1807 ASSERT_GE(writer.WriteBytes(dex->Begin(), dex->Size()), 0);
1808 writer.FinishEntry();
1809 writer.Finish();
1810 ASSERT_EQ(apk_file.GetFile()->Flush(), 0);
1811 }
Andreas Gampebc802de2018-06-20 17:24:11 -07001812 const std::string& dex_location = apk_file.GetFilename();
Mathieu Chartiercda83be2018-03-01 23:55:55 -08001813 const std::string odex_location = GetOdexDir() + "/output.odex";
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001814 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1815 odex_location,
1816 CompilerFilter::kQuicken,
1817 { "--compact-dex-level=fast" },
1818 true));
Mathieu Chartiercda83be2018-03-01 23:55:55 -08001819}
1820
Andreas Gampe25419b52018-02-08 21:30:26 -08001821TEST_F(Dex2oatTest, StderrLoggerOutput) {
1822 std::string dex_location = GetScratchDir() + "/Dex2OatStderrLoggerTest.jar";
1823 std::string odex_location = GetOdexDir() + "/Dex2OatStderrLoggerTest.odex";
1824
1825 // Test file doesn't matter.
1826 Copy(GetDexSrc1(), dex_location);
1827
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001828 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1829 odex_location,
1830 CompilerFilter::kQuicken,
1831 { "--runtime-arg", "-Xuse-stderr-logger" },
1832 true));
Andreas Gampe25419b52018-02-08 21:30:26 -08001833 // Look for some random part of dex2oat logging. With the stderr logger this should be captured,
1834 // even on device.
1835 EXPECT_NE(std::string::npos, output_.find("dex2oat took"));
1836}
1837
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001838TEST_F(Dex2oatTest, VerifyCompilationReason) {
1839 std::string dex_location = GetScratchDir() + "/Dex2OatCompilationReason.jar";
1840 std::string odex_location = GetOdexDir() + "/Dex2OatCompilationReason.odex";
1841
1842 // Test file doesn't matter.
1843 Copy(GetDexSrc1(), dex_location);
1844
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001845 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1846 odex_location,
1847 CompilerFilter::kVerify,
1848 { "--compilation-reason=install" },
1849 true));
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001850 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001851 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01001852 odex_location.c_str(),
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001853 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001854 /*executable=*/ false,
1855 /*low_4gb=*/ false,
Vladimir Markob7bf8432019-12-03 13:18:50 +00001856 dex_location,
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001857 &error_msg));
1858 ASSERT_TRUE(odex_file != nullptr);
1859 ASSERT_STREQ("install", odex_file->GetCompilationReason());
1860}
1861
1862TEST_F(Dex2oatTest, VerifyNoCompilationReason) {
1863 std::string dex_location = GetScratchDir() + "/Dex2OatNoCompilationReason.jar";
1864 std::string odex_location = GetOdexDir() + "/Dex2OatNoCompilationReason.odex";
1865
1866 // Test file doesn't matter.
1867 Copy(GetDexSrc1(), dex_location);
1868
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001869 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1870 odex_location,
1871 CompilerFilter::kVerify,
1872 {},
1873 true));
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001874 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001875 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01001876 odex_location.c_str(),
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001877 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001878 /*executable=*/ false,
1879 /*low_4gb=*/ false,
Vladimir Markob7bf8432019-12-03 13:18:50 +00001880 dex_location,
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001881 &error_msg));
1882 ASSERT_TRUE(odex_file != nullptr);
1883 ASSERT_EQ(nullptr, odex_file->GetCompilationReason());
1884}
1885
Mathieu Chartier792111c2018-02-15 13:02:15 -08001886TEST_F(Dex2oatTest, DontExtract) {
1887 std::unique_ptr<const DexFile> dex(OpenTestDexFile("ManyMethods"));
1888 std::string error_msg;
1889 const std::string out_dir = GetScratchDir();
1890 const std::string dex_location = dex->GetLocation();
1891 const std::string odex_location = out_dir + "/base.oat";
1892 const std::string vdex_location = out_dir + "/base.vdex";
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001893 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1894 odex_location,
1895 CompilerFilter::Filter::kVerify,
1896 { "--copy-dex-files=false" },
Vladimir Marko21910692019-11-06 13:27:03 +00001897 /*expect_success=*/ true,
1898 /*use_fd=*/ false,
1899 /*use_zip_fd=*/ false,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001900 [](const OatFile&) {}));
Mathieu Chartier792111c2018-02-15 13:02:15 -08001901 {
1902 // Check the vdex doesn't have dex.
1903 std::unique_ptr<VdexFile> vdex(VdexFile::Open(vdex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001904 /*writable=*/ false,
1905 /*low_4gb=*/ false,
1906 /*unquicken=*/ false,
Mathieu Chartier792111c2018-02-15 13:02:15 -08001907 &error_msg));
1908 ASSERT_TRUE(vdex != nullptr);
Nicolas Geoffray3a293552018-03-02 10:52:16 +00001909 EXPECT_FALSE(vdex->HasDexSection()) << output_;
Mathieu Chartier792111c2018-02-15 13:02:15 -08001910 }
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001911 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01001912 odex_location.c_str(),
Mathieu Chartier792111c2018-02-15 13:02:15 -08001913 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001914 /*executable=*/ false,
1915 /*low_4gb=*/ false,
Vladimir Markob7bf8432019-12-03 13:18:50 +00001916 dex_location,
Mathieu Chartier792111c2018-02-15 13:02:15 -08001917 &error_msg));
1918 ASSERT_TRUE(odex_file != nullptr) << dex_location;
1919 std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
1920 ASSERT_EQ(oat_dex_files.size(), 1u);
1921 // Verify that the oat file can still open the dex files.
1922 for (const OatDexFile* oat_dex : oat_dex_files) {
1923 std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1924 ASSERT_TRUE(dex_file != nullptr) << error_msg;
1925 }
1926 // Create a dm file and use it to verify.
1927 // Add produced artifacts to a zip file that doesn't contain the classes.dex.
1928 ScratchFile dm_file;
1929 {
1930 std::unique_ptr<File> vdex_file(OS::OpenFileForReading(vdex_location.c_str()));
1931 ASSERT_TRUE(vdex_file != nullptr);
1932 ASSERT_GT(vdex_file->GetLength(), 0u);
Andreas Gampedfcd82c2018-10-16 20:22:37 -07001933 FILE* file = fdopen(DupCloexec(dm_file.GetFd()), "w+b");
Mathieu Chartier792111c2018-02-15 13:02:15 -08001934 ZipWriter writer(file);
1935 auto write_all_bytes = [&](File* file) {
1936 std::unique_ptr<uint8_t[]> bytes(new uint8_t[file->GetLength()]);
1937 ASSERT_TRUE(file->ReadFully(&bytes[0], file->GetLength()));
1938 ASSERT_GE(writer.WriteBytes(&bytes[0], file->GetLength()), 0);
1939 };
1940 // Add vdex to zip.
1941 writer.StartEntry(VdexFile::kVdexNameInDmFile, ZipWriter::kCompress);
1942 write_all_bytes(vdex_file.get());
1943 writer.FinishEntry();
1944 writer.Finish();
1945 ASSERT_EQ(dm_file.GetFile()->Flush(), 0);
1946 }
1947
Mathieu Chartier2eabc612018-05-25 14:31:16 -07001948 auto generate_and_check = [&](CompilerFilter::Filter filter) {
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001949 output_.clear();
1950 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1951 odex_location,
1952 filter,
1953 { "--dump-timings",
1954 "--dm-file=" + dm_file.GetFilename(),
1955 // Pass -Xuse-stderr-logger have dex2oat output in output_ on
1956 // target.
1957 "--runtime-arg",
1958 "-Xuse-stderr-logger" },
Vladimir Marko21910692019-11-06 13:27:03 +00001959 /*expect_success=*/ true,
1960 /*use_fd=*/ false,
1961 /*use_zip_fd=*/ false,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001962 [](const OatFile& o) {
1963 CHECK(o.ContainsDexCode());
1964 }));
Mathieu Chartier2eabc612018-05-25 14:31:16 -07001965 // Check the output for "Fast verify", this is printed from --dump-timings.
1966 std::istringstream iss(output_);
1967 std::string line;
1968 bool found_fast_verify = false;
1969 const std::string kFastVerifyString = "Fast Verify";
1970 while (std::getline(iss, line) && !found_fast_verify) {
1971 found_fast_verify = found_fast_verify || line.find(kFastVerifyString) != std::string::npos;
1972 }
1973 EXPECT_TRUE(found_fast_verify) << "Expected to find " << kFastVerifyString << "\n" << output_;
1974 };
1975
Mathieu Chartier792111c2018-02-15 13:02:15 -08001976 // Generate a quickened dex by using the input dm file to verify.
Mathieu Chartier2eabc612018-05-25 14:31:16 -07001977 generate_and_check(CompilerFilter::Filter::kQuicken);
1978 // Use verify compiler filter to sanity check that FastVerify works for that filter too.
1979 generate_and_check(CompilerFilter::Filter::kVerify);
Mathieu Chartier792111c2018-02-15 13:02:15 -08001980}
1981
Mathieu Chartier2daa1342018-02-20 16:19:28 -08001982// Test that dex files with quickened opcodes aren't dequickened.
1983TEST_F(Dex2oatTest, QuickenedInput) {
1984 std::string error_msg;
1985 ScratchFile temp_dex;
1986 MutateDexFile(temp_dex.GetFile(), GetTestDexFileName("ManyMethods"), [] (DexFile* dex) {
1987 bool mutated_successfully = false;
1988 // Change the dex instructions to make an opcode that spans past the end of the code item.
Mathieu Chartier2242ef12018-07-23 18:14:13 -07001989 for (ClassAccessor accessor : dex->GetClasses()) {
1990 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
1991 CodeItemInstructionAccessor instructions = method.GetInstructions();
1992 // Make a quickened instruction that doesn't run past the end of the code item.
1993 if (instructions.InsnsSizeInCodeUnits() > 2) {
1994 const_cast<Instruction&>(instructions.InstructionAt(0)).SetOpcode(
1995 Instruction::IGET_BYTE_QUICK);
1996 mutated_successfully = true;
Mathieu Chartier2daa1342018-02-20 16:19:28 -08001997 }
Mathieu Chartier2daa1342018-02-20 16:19:28 -08001998 }
1999 }
2000 CHECK(mutated_successfully)
2001 << "Failed to find candidate code item with only one code unit in last instruction.";
2002 });
2003
Andreas Gampebc802de2018-06-20 17:24:11 -07002004 const std::string& dex_location = temp_dex.GetFilename();
Mathieu Chartier2daa1342018-02-20 16:19:28 -08002005 std::string odex_location = GetOdexDir() + "/quickened.odex";
2006 std::string vdex_location = GetOdexDir() + "/quickened.vdex";
2007 std::unique_ptr<File> vdex_output(OS::CreateEmptyFile(vdex_location.c_str()));
2008 // Quicken the dex
2009 {
2010 std::string input_vdex = "--input-vdex-fd=-1";
2011 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_output->Fd());
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002012 ASSERT_TRUE(GenerateOdexForTest(dex_location,
2013 odex_location,
2014 CompilerFilter::kQuicken,
2015 // Disable cdex since we want to compare against the original
2016 // dex file after unquickening.
2017 { input_vdex, output_vdex, kDisableCompactDex },
2018 /* expect_success= */ true,
2019 /* use_fd= */ true));
Mathieu Chartier2daa1342018-02-20 16:19:28 -08002020 }
2021 // Unquicken by running the verify compiler filter on the vdex file and verify it matches.
2022 std::string odex_location2 = GetOdexDir() + "/unquickened.odex";
2023 std::string vdex_location2 = GetOdexDir() + "/unquickened.vdex";
2024 std::unique_ptr<File> vdex_unquickened(OS::CreateEmptyFile(vdex_location2.c_str()));
2025 {
2026 std::string input_vdex = StringPrintf("--input-vdex-fd=%d", vdex_output->Fd());
2027 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_unquickened->Fd());
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002028 ASSERT_TRUE(GenerateOdexForTest(dex_location,
2029 odex_location2,
2030 CompilerFilter::kVerify,
2031 // Disable cdex to avoid needing to write out the shared
2032 // section.
2033 { input_vdex, output_vdex, kDisableCompactDex },
2034 /* expect_success= */ true,
2035 /* use_fd= */ true));
Mathieu Chartier2daa1342018-02-20 16:19:28 -08002036 }
2037 ASSERT_EQ(vdex_unquickened->Flush(), 0) << "Could not flush and close vdex file";
2038 ASSERT_TRUE(success_);
2039 {
2040 // Check that hte vdex has one dex and compare it to the original one.
2041 std::unique_ptr<VdexFile> vdex(VdexFile::Open(vdex_location2.c_str(),
2042 /*writable*/ false,
2043 /*low_4gb*/ false,
2044 /*unquicken*/ false,
2045 &error_msg));
2046 std::vector<std::unique_ptr<const DexFile>> dex_files;
2047 bool result = vdex->OpenAllDexFiles(&dex_files, &error_msg);
2048 ASSERT_TRUE(result) << error_msg;
2049 ASSERT_EQ(dex_files.size(), 1u) << error_msg;
2050 ScratchFile temp;
2051 ASSERT_TRUE(temp.GetFile()->WriteFully(dex_files[0]->Begin(), dex_files[0]->Size()));
2052 ASSERT_EQ(temp.GetFile()->Flush(), 0) << "Could not flush extracted dex";
2053 EXPECT_EQ(temp.GetFile()->Compare(temp_dex.GetFile()), 0);
2054 }
2055 ASSERT_EQ(vdex_output->FlushCloseOrErase(), 0) << "Could not flush and close";
2056 ASSERT_EQ(vdex_unquickened->FlushCloseOrErase(), 0) << "Could not flush and close";
2057}
2058
Mathieu Chartierd45863a2018-03-21 18:16:36 -07002059// Test that compact dex generation with invalid dex files doesn't crash dex2oat. b/75970654
2060TEST_F(Dex2oatTest, CompactDexInvalidSource) {
2061 ScratchFile invalid_dex;
2062 {
Andreas Gampedfcd82c2018-10-16 20:22:37 -07002063 FILE* file = fdopen(DupCloexec(invalid_dex.GetFd()), "w+b");
Mathieu Chartierd45863a2018-03-21 18:16:36 -07002064 ZipWriter writer(file);
2065 writer.StartEntry("classes.dex", ZipWriter::kAlign32);
2066 DexFile::Header header = {};
2067 StandardDexFile::WriteMagic(header.magic_);
2068 StandardDexFile::WriteCurrentVersion(header.magic_);
2069 header.file_size_ = 4 * KB;
2070 header.data_size_ = 4 * KB;
2071 header.data_off_ = 10 * MB;
2072 header.map_off_ = 10 * MB;
2073 header.class_defs_off_ = 10 * MB;
2074 header.class_defs_size_ = 10000;
2075 ASSERT_GE(writer.WriteBytes(&header, sizeof(header)), 0);
2076 writer.FinishEntry();
2077 writer.Finish();
2078 ASSERT_EQ(invalid_dex.GetFile()->Flush(), 0);
2079 }
Andreas Gampebc802de2018-06-20 17:24:11 -07002080 const std::string& dex_location = invalid_dex.GetFilename();
Mathieu Chartierd45863a2018-03-21 18:16:36 -07002081 const std::string odex_location = GetOdexDir() + "/output.odex";
2082 std::string error_msg;
2083 int status = GenerateOdexForTestWithStatus(
2084 {dex_location},
2085 odex_location,
2086 CompilerFilter::kQuicken,
2087 &error_msg,
2088 { "--compact-dex-level=fast" });
2089 ASSERT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) != 0) << status << " " << output_;
2090}
2091
Mathieu Chartier14e7bad2018-03-22 14:33:20 -07002092// Test that dex2oat with a CompactDex file in the APK fails.
2093TEST_F(Dex2oatTest, CompactDexInZip) {
2094 CompactDexFile::Header header = {};
2095 CompactDexFile::WriteMagic(header.magic_);
2096 CompactDexFile::WriteCurrentVersion(header.magic_);
2097 header.file_size_ = sizeof(CompactDexFile::Header);
2098 header.data_off_ = 10 * MB;
2099 header.map_off_ = 10 * MB;
2100 header.class_defs_off_ = 10 * MB;
2101 header.class_defs_size_ = 10000;
2102 // Create a zip containing the invalid dex.
2103 ScratchFile invalid_dex_zip;
2104 {
Andreas Gampedfcd82c2018-10-16 20:22:37 -07002105 FILE* file = fdopen(DupCloexec(invalid_dex_zip.GetFd()), "w+b");
Mathieu Chartier14e7bad2018-03-22 14:33:20 -07002106 ZipWriter writer(file);
2107 writer.StartEntry("classes.dex", ZipWriter::kCompress);
2108 ASSERT_GE(writer.WriteBytes(&header, sizeof(header)), 0);
2109 writer.FinishEntry();
2110 writer.Finish();
2111 ASSERT_EQ(invalid_dex_zip.GetFile()->Flush(), 0);
2112 }
2113 // Create the dex file directly.
2114 ScratchFile invalid_dex;
2115 {
2116 ASSERT_GE(invalid_dex.GetFile()->WriteFully(&header, sizeof(header)), 0);
2117 ASSERT_EQ(invalid_dex.GetFile()->Flush(), 0);
2118 }
2119 std::string error_msg;
2120 int status = 0u;
2121
2122 status = GenerateOdexForTestWithStatus(
2123 { invalid_dex_zip.GetFilename() },
2124 GetOdexDir() + "/output_apk.odex",
2125 CompilerFilter::kQuicken,
2126 &error_msg,
2127 { "--compact-dex-level=fast" });
2128 ASSERT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) != 0) << status << " " << output_;
2129
2130 status = GenerateOdexForTestWithStatus(
2131 { invalid_dex.GetFilename() },
2132 GetOdexDir() + "/output.odex",
2133 CompilerFilter::kQuicken,
2134 &error_msg,
2135 { "--compact-dex-level=fast" });
2136 ASSERT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) != 0) << status << " " << output_;
2137}
2138
Mathieu Chartierf85b3db2018-04-02 18:16:21 -07002139TEST_F(Dex2oatTest, AppImageNoProfile) {
2140 ScratchFile app_image_file;
2141 const std::string out_dir = GetScratchDir();
2142 const std::string odex_location = out_dir + "/base.odex";
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002143 ASSERT_TRUE(GenerateOdexForTest(GetTestDexFileName("ManyMethods"),
2144 odex_location,
2145 CompilerFilter::Filter::kSpeedProfile,
2146 { "--app-image-fd=" + std::to_string(app_image_file.GetFd()) },
Vladimir Marko21910692019-11-06 13:27:03 +00002147 /*expect_success=*/ true,
2148 /*use_fd=*/ false,
2149 /*use_zip_fd=*/ false,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002150 [](const OatFile&) {}));
Mathieu Chartierf85b3db2018-04-02 18:16:21 -07002151 // Open our generated oat file.
2152 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002153 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01002154 odex_location.c_str(),
Mathieu Chartierf85b3db2018-04-02 18:16:21 -07002155 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002156 /*executable=*/ false,
2157 /*low_4gb=*/ false,
Mathieu Chartierf85b3db2018-04-02 18:16:21 -07002158 &error_msg));
2159 ASSERT_TRUE(odex_file != nullptr);
2160 ImageHeader header = {};
2161 ASSERT_TRUE(app_image_file.GetFile()->PreadFully(
2162 reinterpret_cast<void*>(&header),
2163 sizeof(header),
2164 /*offset*/ 0u)) << app_image_file.GetFile()->GetLength();
2165 EXPECT_GT(header.GetImageSection(ImageHeader::kSectionObjects).Size(), 0u);
2166 EXPECT_EQ(header.GetImageSection(ImageHeader::kSectionArtMethods).Size(), 0u);
2167 EXPECT_EQ(header.GetImageSection(ImageHeader::kSectionArtFields).Size(), 0u);
2168}
2169
Vladimir Marko21910692019-11-06 13:27:03 +00002170TEST_F(Dex2oatTest, ZipFd) {
David Srbecky8c8f1482020-02-05 20:17:10 +00002171 std::string zip_location = GetTestDexFileName("MainUncompressedAligned");
Vladimir Marko21910692019-11-06 13:27:03 +00002172 std::unique_ptr<File> dex_file(OS::OpenFileForReading(zip_location.c_str()));
2173 std::vector<std::string> extra_args{
2174 StringPrintf("--zip-fd=%d", dex_file->Fd()),
2175 "--zip-location=" + zip_location,
2176 };
2177 std::string out_dir = GetScratchDir();
2178 const std::string base_oat_name = out_dir + "/base.oat";
2179 ASSERT_TRUE(GenerateOdexForTest(zip_location,
2180 base_oat_name,
2181 CompilerFilter::Filter::kQuicken,
2182 extra_args,
2183 /*expect_success=*/ true,
2184 /*use_fd=*/ false,
2185 /*use_zip_fd=*/ true));
2186}
2187
Mathieu Chartier9c06d442020-04-01 14:11:05 -07002188TEST_F(Dex2oatTest, AppImageEmptyDex) {
2189 // Create a profile with the startup method marked.
2190 ScratchFile profile_file;
2191 ScratchFile temp_dex;
2192 const std::string& dex_location = temp_dex.GetFilename();
2193 std::vector<uint16_t> methods;
2194 std::vector<dex::TypeIndex> classes;
2195 {
2196 MutateDexFile(temp_dex.GetFile(), GetTestDexFileName("StringLiterals"), [&] (DexFile* dex) {
2197 // Modify the header to make the dex file valid but empty.
2198 DexFile::Header* header = const_cast<DexFile::Header*>(&dex->GetHeader());
2199 header->string_ids_size_ = 0;
2200 header->string_ids_off_ = 0;
2201 header->type_ids_size_ = 0;
2202 header->type_ids_off_ = 0;
2203 header->proto_ids_size_ = 0;
2204 header->proto_ids_off_ = 0;
2205 header->field_ids_size_ = 0;
2206 header->field_ids_off_ = 0;
2207 header->method_ids_size_ = 0;
2208 header->method_ids_off_ = 0;
2209 header->class_defs_size_ = 0;
2210 header->class_defs_off_ = 0;
2211 ASSERT_GT(header->file_size_,
2212 sizeof(*header) + sizeof(dex::MapList) + sizeof(dex::MapItem) * 2);
2213 // Move map list to be right after the header.
2214 header->map_off_ = sizeof(DexFile::Header);
2215 dex::MapList* map_list = const_cast<dex::MapList*>(dex->GetMapList());
2216 map_list->list_[0].type_ = DexFile::kDexTypeHeaderItem;
2217 map_list->list_[0].size_ = 1u;
2218 map_list->list_[0].offset_ = 0u;
2219 map_list->list_[1].type_ = DexFile::kDexTypeMapList;
2220 map_list->list_[1].size_ = 1u;
2221 map_list->list_[1].offset_ = header->map_off_;
2222 map_list->size_ = 2;
2223 header->data_off_ = header->map_off_;
2224 header->data_size_ = map_list->Size();
2225 });
2226 }
2227 std::unique_ptr<const DexFile> dex_file(OpenDexFile(temp_dex.GetFilename().c_str()));
2228 const std::string out_dir = GetScratchDir();
2229 const std::string odex_location = out_dir + "/base.odex";
2230 const std::string app_image_location = out_dir + "/base.art";
2231 ASSERT_TRUE(GenerateOdexForTest(dex_location,
2232 odex_location,
2233 CompilerFilter::Filter::kSpeedProfile,
2234 { "--app-image-file=" + app_image_location,
2235 "--resolve-startup-const-strings=true",
2236 "--profile-file=" + profile_file.GetFilename()},
2237 /*expect_success=*/ true,
2238 /*use_fd=*/ false,
2239 /*use_zip_fd=*/ false,
2240 [](const OatFile&) {}));
2241 // Open our generated oat file.
2242 std::string error_msg;
2243 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
2244 odex_location.c_str(),
2245 odex_location.c_str(),
2246 /*executable=*/ false,
2247 /*low_4gb=*/ false,
2248 &error_msg));
2249 ASSERT_TRUE(odex_file != nullptr);
2250}
2251
2252
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002253TEST_F(Dex2oatTest, AppImageResolveStrings) {
2254 using Hotness = ProfileCompilationInfo::MethodHotness;
2255 // Create a profile with the startup method marked.
2256 ScratchFile profile_file;
Mathieu Chartierc2109c62019-03-20 13:34:39 -07002257 ScratchFile temp_dex;
2258 const std::string& dex_location = temp_dex.GetFilename();
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002259 std::vector<uint16_t> methods;
Mathieu Chartier22752772018-10-18 14:18:59 -07002260 std::vector<dex::TypeIndex> classes;
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002261 {
Mathieu Chartierc2109c62019-03-20 13:34:39 -07002262 MutateDexFile(temp_dex.GetFile(), GetTestDexFileName("StringLiterals"), [&] (DexFile* dex) {
2263 bool mutated_successfully = false;
2264 // Change the dex instructions to make an opcode that spans past the end of the code item.
2265 for (ClassAccessor accessor : dex->GetClasses()) {
2266 if (accessor.GetDescriptor() == std::string("LStringLiterals$StartupClass;")) {
2267 classes.push_back(accessor.GetClassIdx());
2268 }
2269 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
2270 std::string method_name(dex->GetMethodName(dex->GetMethodId(method.GetIndex())));
2271 CodeItemInstructionAccessor instructions = method.GetInstructions();
2272 if (method_name == "startUpMethod2") {
2273 // Make an instruction that runs past the end of the code item and verify that it
2274 // doesn't cause dex2oat to crash.
2275 ASSERT_TRUE(instructions.begin() != instructions.end());
2276 DexInstructionIterator last_instruction = instructions.begin();
2277 for (auto dex_it = instructions.begin(); dex_it != instructions.end(); ++dex_it) {
2278 last_instruction = dex_it;
2279 }
2280 ASSERT_EQ(last_instruction->SizeInCodeUnits(), 1u);
2281 // Set the opcode to something that will go past the end of the code item.
2282 const_cast<Instruction&>(last_instruction.Inst()).SetOpcode(
2283 Instruction::CONST_STRING_JUMBO);
2284 mutated_successfully = true;
2285 // Test that the safe iterator doesn't go past the end.
2286 SafeDexInstructionIterator it2(instructions.begin(), instructions.end());
2287 while (!it2.IsErrorState()) {
2288 ++it2;
2289 }
2290 EXPECT_TRUE(it2 == last_instruction);
2291 EXPECT_TRUE(it2 < instructions.end());
2292 methods.push_back(method.GetIndex());
2293 mutated_successfully = true;
2294 } else if (method_name == "startUpMethod") {
2295 methods.push_back(method.GetIndex());
2296 }
Mathieu Chartier22752772018-10-18 14:18:59 -07002297 }
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002298 }
Mathieu Chartierc2109c62019-03-20 13:34:39 -07002299 CHECK(mutated_successfully)
2300 << "Failed to find candidate code item with only one code unit in last instruction.";
2301 });
2302 }
2303 std::unique_ptr<const DexFile> dex_file(OpenDexFile(temp_dex.GetFilename().c_str()));
2304 {
Mathieu Chartier22752772018-10-18 14:18:59 -07002305 ASSERT_GT(classes.size(), 0u);
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002306 ASSERT_GT(methods.size(), 0u);
2307 // Here, we build the profile from the method lists.
2308 ProfileCompilationInfo info;
Mathieu Chartierc2109c62019-03-20 13:34:39 -07002309 info.AddClassesForDex(dex_file.get(), classes.begin(), classes.end());
2310 info.AddMethodsForDex(Hotness::kFlagStartup, dex_file.get(), methods.begin(), methods.end());
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002311 // Save the profile since we want to use it with dex2oat to produce an oat file.
2312 ASSERT_TRUE(info.Save(profile_file.GetFd()));
2313 }
2314 const std::string out_dir = GetScratchDir();
2315 const std::string odex_location = out_dir + "/base.odex";
2316 const std::string app_image_location = out_dir + "/base.art";
Mathieu Chartierc2109c62019-03-20 13:34:39 -07002317 ASSERT_TRUE(GenerateOdexForTest(dex_location,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002318 odex_location,
2319 CompilerFilter::Filter::kSpeedProfile,
2320 { "--app-image-file=" + app_image_location,
2321 "--resolve-startup-const-strings=true",
2322 "--profile-file=" + profile_file.GetFilename()},
Vladimir Marko21910692019-11-06 13:27:03 +00002323 /*expect_success=*/ true,
2324 /*use_fd=*/ false,
2325 /*use_zip_fd=*/ false,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002326 [](const OatFile&) {}));
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002327 // Open our generated oat file.
2328 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002329 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002330 odex_location.c_str(),
2331 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002332 /*executable=*/ false,
2333 /*low_4gb=*/ false,
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002334 &error_msg));
2335 ASSERT_TRUE(odex_file != nullptr);
2336 // Check the strings in the app image intern table only contain the "startup" strigs.
2337 {
2338 ScopedObjectAccess soa(Thread::Current());
2339 std::unique_ptr<gc::space::ImageSpace> space =
2340 gc::space::ImageSpace::CreateFromAppImage(app_image_location.c_str(),
2341 odex_file.get(),
2342 &error_msg);
2343 ASSERT_TRUE(space != nullptr) << error_msg;
2344 std::set<std::string> seen;
2345 InternTable intern_table;
2346 intern_table.AddImageStringsToTable(space.get(), [&](InternTable::UnorderedSet& interns)
2347 REQUIRES_SHARED(Locks::mutator_lock_) {
2348 for (const GcRoot<mirror::String>& str : interns) {
2349 seen.insert(str.Read()->ToModifiedUtf8());
2350 }
2351 });
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07002352 // Ensure that the dex cache has a preresolved string array.
2353 std::set<std::string> preresolved_seen;
2354 bool saw_dexcache = false;
2355 space->GetLiveBitmap()->VisitAllMarked(
2356 [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
2357 if (obj->IsDexCache<kVerifyNone>()) {
2358 ObjPtr<mirror::DexCache> dex_cache = obj->AsDexCache();
2359 GcRoot<mirror::String>* preresolved_strings = dex_cache->GetPreResolvedStrings();
Mathieu Chartierc2109c62019-03-20 13:34:39 -07002360 ASSERT_EQ(dex_file->NumStringIds(), dex_cache->NumPreResolvedStrings());
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07002361 for (size_t i = 0; i < dex_cache->NumPreResolvedStrings(); ++i) {
2362 ObjPtr<mirror::String> string = preresolved_strings[i].Read<kWithoutReadBarrier>();
2363 if (string != nullptr) {
2364 preresolved_seen.insert(string->ToModifiedUtf8());
2365 }
2366 }
2367 saw_dexcache = true;
2368 }
2369 });
2370 ASSERT_TRUE(saw_dexcache);
2371 // Everything in the preresolved array should also be in the intern table.
2372 for (const std::string& str : preresolved_seen) {
2373 EXPECT_TRUE(seen.find(str) != seen.end());
2374 }
Mathieu Chartier22752772018-10-18 14:18:59 -07002375 // Normal methods
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07002376 EXPECT_TRUE(preresolved_seen.find("Loading ") != preresolved_seen.end());
2377 EXPECT_TRUE(preresolved_seen.find("Starting up") != preresolved_seen.end());
2378 EXPECT_TRUE(preresolved_seen.find("abcd.apk") != preresolved_seen.end());
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002379 EXPECT_TRUE(seen.find("Unexpected error") == seen.end());
2380 EXPECT_TRUE(seen.find("Shutting down!") == seen.end());
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07002381 EXPECT_TRUE(preresolved_seen.find("Unexpected error") == preresolved_seen.end());
2382 EXPECT_TRUE(preresolved_seen.find("Shutting down!") == preresolved_seen.end());
Mathieu Chartier22752772018-10-18 14:18:59 -07002383 // Classes initializers
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07002384 EXPECT_TRUE(preresolved_seen.find("Startup init") != preresolved_seen.end());
Mathieu Chartier22752772018-10-18 14:18:59 -07002385 EXPECT_TRUE(seen.find("Other class init") == seen.end());
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07002386 EXPECT_TRUE(preresolved_seen.find("Other class init") == preresolved_seen.end());
2387 // Expect the sets match.
2388 EXPECT_GE(seen.size(), preresolved_seen.size());
Mathieu Chartier8cc418e2018-10-31 10:54:30 -07002389
2390 // Verify what strings are marked as boot image.
2391 std::set<std::string> boot_image_strings;
2392 std::set<std::string> app_image_strings;
2393
2394 MutexLock mu(Thread::Current(), *Locks::intern_table_lock_);
2395 intern_table.VisitInterns([&](const GcRoot<mirror::String>& root)
2396 REQUIRES_SHARED(Locks::mutator_lock_) {
2397 boot_image_strings.insert(root.Read()->ToModifiedUtf8());
2398 }, /*visit_boot_images=*/true, /*visit_non_boot_images=*/false);
2399 intern_table.VisitInterns([&](const GcRoot<mirror::String>& root)
2400 REQUIRES_SHARED(Locks::mutator_lock_) {
2401 app_image_strings.insert(root.Read()->ToModifiedUtf8());
2402 }, /*visit_boot_images=*/false, /*visit_non_boot_images=*/true);
2403 EXPECT_EQ(boot_image_strings.size(), 0u);
2404 EXPECT_TRUE(app_image_strings == seen);
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002405 }
2406}
2407
2408
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002409TEST_F(Dex2oatClassLoaderContextTest, StoredClassLoaderContext) {
Mathieu Chartierc4440772018-04-16 14:40:56 -07002410 std::vector<std::unique_ptr<const DexFile>> dex_files = OpenTestDexFiles("MultiDex");
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002411 const std::string out_dir = GetScratchDir();
2412 const std::string odex_location = out_dir + "/base.odex";
Mathieu Chartierc4440772018-04-16 14:40:56 -07002413 const std::string valid_context = "PCL[" + dex_files[0]->GetLocation() + "]";
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002414 const std::string stored_context = "PCL[/system/not_real_lib.jar]";
Mathieu Chartierc4440772018-04-16 14:40:56 -07002415 std::string expected_stored_context = "PCL[";
2416 size_t index = 1;
2417 for (const std::unique_ptr<const DexFile>& dex_file : dex_files) {
2418 const bool is_first = index == 1u;
2419 if (!is_first) {
2420 expected_stored_context += ":";
2421 }
2422 expected_stored_context += "/system/not_real_lib.jar";
2423 if (!is_first) {
2424 expected_stored_context += "!classes" + std::to_string(index) + ".dex";
2425 }
2426 expected_stored_context += "*" + std::to_string(dex_file->GetLocationChecksum());
2427 ++index;
2428 }
2429 expected_stored_context += + "]";
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002430 // The class path should not be valid and should fail being stored.
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002431 EXPECT_TRUE(GenerateOdexForTest(GetTestDexFileName("ManyMethods"),
2432 odex_location,
2433 CompilerFilter::Filter::kQuicken,
2434 { "--class-loader-context=" + stored_context },
Vladimir Marko21910692019-11-06 13:27:03 +00002435 /*expect_success=*/ true,
2436 /*use_fd=*/ false,
2437 /*use_zip_fd=*/ false,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002438 [&](const OatFile& oat_file) {
Mathieu Chartierc4440772018-04-16 14:40:56 -07002439 EXPECT_NE(oat_file.GetClassLoaderContext(), stored_context) << output_;
2440 EXPECT_NE(oat_file.GetClassLoaderContext(), valid_context) << output_;
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002441 }));
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002442 // The stored context should match what we expect even though it's invalid.
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002443 EXPECT_TRUE(GenerateOdexForTest(GetTestDexFileName("ManyMethods"),
2444 odex_location,
2445 CompilerFilter::Filter::kQuicken,
2446 { "--class-loader-context=" + valid_context,
2447 "--stored-class-loader-context=" + stored_context },
Vladimir Marko21910692019-11-06 13:27:03 +00002448 /*expect_success=*/ true,
2449 /*use_fd=*/ false,
2450 /*use_zip_fd=*/ false,
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002451 [&](const OatFile& oat_file) {
Mathieu Chartierc4440772018-04-16 14:40:56 -07002452 EXPECT_EQ(oat_file.GetClassLoaderContext(), expected_stored_context) << output_;
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002453 }));
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002454}
2455
xueliang.zhong7f88c1a2018-11-06 11:42:41 +00002456class Dex2oatISAFeaturesRuntimeDetectionTest : public Dex2oatTest {
2457 protected:
2458 void RunTest(const std::vector<std::string>& extra_args = {}) {
2459 std::string dex_location = GetScratchDir() + "/Dex2OatSwapTest.jar";
2460 std::string odex_location = GetOdexDir() + "/Dex2OatSwapTest.odex";
2461
2462 Copy(GetTestDexFileName(), dex_location);
2463
2464 ASSERT_TRUE(GenerateOdexForTest(dex_location,
2465 odex_location,
2466 CompilerFilter::kSpeed,
2467 extra_args));
2468 }
2469
2470 std::string GetTestDexFileName() {
2471 return GetDexSrc1();
2472 }
2473};
2474
2475TEST_F(Dex2oatISAFeaturesRuntimeDetectionTest, TestCurrentRuntimeFeaturesAsDex2OatArguments) {
2476 std::vector<std::string> argv;
2477 Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv);
2478 auto option_pos =
2479 std::find(std::begin(argv), std::end(argv), "--instruction-set-features=runtime");
2480 if (InstructionSetFeatures::IsRuntimeDetectionSupported()) {
2481 EXPECT_TRUE(kIsTargetBuild);
2482 EXPECT_NE(option_pos, std::end(argv));
2483 } else {
2484 EXPECT_EQ(option_pos, std::end(argv));
2485 }
2486
2487 RunTest();
2488}
2489
David Sehrfe57c2b2020-03-27 14:58:54 +00002490class LinkageTest : public Dex2oatTest {};
2491
2492TEST_F(LinkageTest, LinkageEnabled) {
2493 TEST_DISABLED_FOR_TARGET();
2494 std::unique_ptr<const DexFile> dex(OpenTestDexFile("LinkageTest"));
2495 std::string out_dir = GetScratchDir();
2496 const std::string base_oat_name = out_dir + "/base.oat";
2497 std::string error_msg;
2498 const int res_fail = GenerateOdexForTestWithStatus(
2499 {dex->GetLocation()},
2500 base_oat_name,
2501 CompilerFilter::Filter::kQuicken,
2502 &error_msg,
2503 {"--check-linkage-conditions", "--crash-on-linkage-violation"});
2504 EXPECT_NE(0, res_fail);
2505
2506 const int res_no_fail = GenerateOdexForTestWithStatus(
2507 {dex->GetLocation()},
2508 base_oat_name,
2509 CompilerFilter::Filter::kQuicken,
2510 &error_msg,
2511 {"--check-linkage-conditions"});
2512 EXPECT_EQ(0, res_no_fail);
2513}
2514
Andreas Gampee1459ae2016-06-29 09:36:30 -07002515} // namespace art