blob: 524bce05b5f5335b8766427a35e0e19e5a9f444e [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
Igor Murashkin5573c372017-11-16 13:34:30 -080017#include <regex>
Andreas Gampe7adeda82016-07-25 08:27:35 -070018#include <sstream>
Andreas Gampee1459ae2016-06-29 09:36:30 -070019#include <string>
20#include <vector>
Andreas Gampee1459ae2016-06-29 09:36:30 -070021
Andreas Gampe46ee31b2016-12-14 10:11:49 -080022#include <sys/wait.h>
23#include <unistd.h>
24
Andreas Gampe57943812017-12-06 21:39:13 -080025#include <android-base/logging.h>
Andreas Gampe50f9dc22018-11-05 10:29:43 -080026#include <android-base/macros.h>
Andreas Gampe57943812017-12-06 21:39:13 -080027#include <android-base/stringprintf.h>
Andreas Gampe46ee31b2016-12-14 10:11:49 -080028
Andreas Gampee1459ae2016-06-29 09:36:30 -070029#include "common_runtime_test.h"
30
Andreas Gampee1459ae2016-06-29 09:36:30 -070031#include "base/macros.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070032#include "base/mutex-inl.h"
David Sehrc431b9d2018-03-02 12:01:51 -080033#include "base/utils.h"
David Sehr013fd802018-01-11 22:55:24 -080034#include "dex/art_dex_file_loader.h"
Mathieu Chartier05f90d12018-02-07 13:47:17 -080035#include "dex/base64_test_util.h"
David Sehr312f3b22018-03-19 08:39:26 -070036#include "dex/bytecode_utils.h"
Mathieu Chartier2242ef12018-07-23 18:14:13 -070037#include "dex/class_accessor-inl.h"
David Sehr9e734c72018-01-04 17:56:19 -080038#include "dex/code_item_accessors-inl.h"
39#include "dex/dex_file-inl.h"
40#include "dex/dex_file_loader.h"
Andreas Gampee1459ae2016-06-29 09:36:30 -070041#include "dex2oat_environment_test.h"
Andreas Gampef7882972017-03-20 16:35:24 -070042#include "dex2oat_return_codes.h"
Andreas Gampee15b9b12018-10-29 12:54:27 -070043#include "gc_root-inl.h"
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -070044#include "intern_table-inl.h"
Andreas Gampe67f02822016-06-24 21:05:23 -070045#include "oat.h"
46#include "oat_file.h"
David Sehr82d046e2018-04-23 08:14:19 -070047#include "profile/profile_compilation_info.h"
Mathieu Chartier792111c2018-02-15 13:02:15 -080048#include "vdex_file.h"
49#include "ziparchive/zip_writer.h"
Andreas Gampee1459ae2016-06-29 09:36:30 -070050
Andreas Gampee1459ae2016-06-29 09:36:30 -070051namespace art {
52
Mathieu Chartierea650f32017-05-24 12:04:13 -070053static constexpr size_t kMaxMethodIds = 65535;
Mathieu Chartier9e050df2017-08-09 10:05:47 -070054static constexpr bool kDebugArgs = false;
Mathieu Chartier02129102017-12-22 11:04:01 -080055static const char* kDisableCompactDex = "--compact-dex-level=none";
Mathieu Chartierea650f32017-05-24 12:04:13 -070056
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080057using android::base::StringPrintf;
58
Andreas Gampee1459ae2016-06-29 09:36:30 -070059class Dex2oatTest : public Dex2oatEnvironmentTest {
60 public:
Roland Levillainf73caca2018-08-24 17:19:07 +010061 void TearDown() override {
Andreas Gampee1459ae2016-06-29 09:36:30 -070062 Dex2oatEnvironmentTest::TearDown();
63
64 output_ = "";
65 error_msg_ = "";
66 success_ = false;
67 }
68
69 protected:
Mathieu Chartier9e050df2017-08-09 10:05:47 -070070 int GenerateOdexForTestWithStatus(const std::vector<std::string>& dex_locations,
Andreas Gampef7882972017-03-20 16:35:24 -070071 const std::string& odex_location,
72 CompilerFilter::Filter filter,
73 std::string* error_msg,
74 const std::vector<std::string>& extra_args = {},
75 bool use_fd = false) {
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080076 std::unique_ptr<File> oat_file;
Andreas Gampee1459ae2016-06-29 09:36:30 -070077 std::vector<std::string> args;
Mathieu Chartier9e050df2017-08-09 10:05:47 -070078 // Add dex file args.
79 for (const std::string& dex_location : dex_locations) {
80 args.push_back("--dex-file=" + dex_location);
81 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080082 if (use_fd) {
83 oat_file.reset(OS::CreateEmptyFile(odex_location.c_str()));
84 CHECK(oat_file != nullptr) << odex_location;
85 args.push_back("--oat-fd=" + std::to_string(oat_file->Fd()));
Mathieu Chartier046854b2017-03-01 17:16:22 -080086 args.push_back("--oat-location=" + odex_location);
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080087 } else {
88 args.push_back("--oat-file=" + odex_location);
89 }
Andreas Gampee1459ae2016-06-29 09:36:30 -070090 args.push_back("--compiler-filter=" + CompilerFilter::NameOfFilter(filter));
91 args.push_back("--runtime-arg");
92 args.push_back("-Xnorelocate");
93
Andreas Gampe50f9dc22018-11-05 10:29:43 -080094 // Unless otherwise stated, use a small amount of threads, so that potential aborts are
95 // shorter. This can be overridden with extra_args.
96 args.push_back("-j4");
97
Andreas Gampee1459ae2016-06-29 09:36:30 -070098 args.insert(args.end(), extra_args.begin(), extra_args.end());
99
Andreas Gampef7882972017-03-20 16:35:24 -0700100 int status = Dex2Oat(args, error_msg);
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800101 if (oat_file != nullptr) {
Andreas Gampef7882972017-03-20 16:35:24 -0700102 CHECK_EQ(oat_file->FlushClose(), 0) << "Could not flush and close oat file";
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800103 }
Andreas Gampef7882972017-03-20 16:35:24 -0700104 return status;
105 }
Andreas Gampee1459ae2016-06-29 09:36:30 -0700106
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800107 ::testing::AssertionResult GenerateOdexForTest(
Andreas Gampe641a4732017-08-24 13:21:35 -0700108 const std::string& dex_location,
109 const std::string& odex_location,
110 CompilerFilter::Filter filter,
111 const std::vector<std::string>& extra_args = {},
112 bool expect_success = true,
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800113 bool use_fd = false) WARN_UNUSED {
114 return GenerateOdexForTest(dex_location,
115 odex_location,
116 filter,
117 extra_args,
118 expect_success,
119 use_fd,
120 [](const OatFile&) {});
Andreas Gampe641a4732017-08-24 13:21:35 -0700121 }
122
Andreas Gampe80ddf272018-01-11 09:41:00 -0800123 bool test_accepts_odex_file_on_failure = false;
124
Andreas Gampe641a4732017-08-24 13:21:35 -0700125 template <typename T>
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800126 ::testing::AssertionResult GenerateOdexForTest(
Andreas Gampe641a4732017-08-24 13:21:35 -0700127 const std::string& dex_location,
128 const std::string& odex_location,
129 CompilerFilter::Filter filter,
130 const std::vector<std::string>& extra_args,
131 bool expect_success,
132 bool use_fd,
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800133 T check_oat) WARN_UNUSED {
Andreas Gampef7882972017-03-20 16:35:24 -0700134 std::string error_msg;
Mathieu Chartier9e050df2017-08-09 10:05:47 -0700135 int status = GenerateOdexForTestWithStatus({dex_location},
Andreas Gampef7882972017-03-20 16:35:24 -0700136 odex_location,
137 filter,
138 &error_msg,
139 extra_args,
140 use_fd);
Andreas Gampe80ddf272018-01-11 09:41:00 -0800141 bool success = (WIFEXITED(status) && WEXITSTATUS(status) == 0);
Andreas Gampee1459ae2016-06-29 09:36:30 -0700142 if (expect_success) {
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800143 if (!success) {
144 return ::testing::AssertionFailure()
145 << "Failed to compile odex: " << error_msg << std::endl << output_;
146 }
Andreas Gampee1459ae2016-06-29 09:36:30 -0700147
148 // Verify the odex file was generated as expected.
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100149 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +0100150 odex_location.c_str(),
Andreas Gampee1459ae2016-06-29 09:36:30 -0700151 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100152 /*executable=*/ false,
153 /*low_4gb=*/ false,
Andreas Gampee1459ae2016-06-29 09:36:30 -0700154 dex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100155 /*reservation=*/ nullptr,
Andreas Gampee1459ae2016-06-29 09:36:30 -0700156 &error_msg));
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800157 if (odex_file == nullptr) {
158 return ::testing::AssertionFailure() << "Could not open odex file: " << error_msg;
159 }
Andreas Gampee1459ae2016-06-29 09:36:30 -0700160
161 CheckFilter(filter, odex_file->GetCompilerFilter());
Calin Juravle1ce70852017-06-28 10:59:03 -0700162 check_oat(*(odex_file.get()));
Andreas Gampee1459ae2016-06-29 09:36:30 -0700163 } else {
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800164 if (success) {
165 return ::testing::AssertionFailure() << "Succeeded to compile odex: " << output_;
166 }
Andreas Gampee1459ae2016-06-29 09:36:30 -0700167
168 error_msg_ = error_msg;
169
Andreas Gampe80ddf272018-01-11 09:41:00 -0800170 if (!test_accepts_odex_file_on_failure) {
171 // Verify there's no loadable odex file.
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100172 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +0100173 odex_location.c_str(),
Andreas Gampe80ddf272018-01-11 09:41:00 -0800174 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100175 /*executable=*/ false,
176 /*low_4gb=*/ false,
Andreas Gampe80ddf272018-01-11 09:41:00 -0800177 dex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100178 /*reservation=*/ nullptr,
Andreas Gampe80ddf272018-01-11 09:41:00 -0800179 &error_msg));
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800180 if (odex_file != nullptr) {
181 return ::testing::AssertionFailure() << "Could open odex file: " << error_msg;
182 }
Andreas Gampe80ddf272018-01-11 09:41:00 -0800183 }
Andreas Gampee1459ae2016-06-29 09:36:30 -0700184 }
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800185 return ::testing::AssertionSuccess();
Andreas Gampee1459ae2016-06-29 09:36:30 -0700186 }
187
Calin Juravle1ccf6132017-08-02 17:46:53 -0700188 // Check the input compiler filter against the generated oat file's filter. May be overridden
Andreas Gampee1459ae2016-06-29 09:36:30 -0700189 // in subclasses when equality is not expected.
190 virtual void CheckFilter(CompilerFilter::Filter expected, CompilerFilter::Filter actual) {
191 EXPECT_EQ(expected, actual);
192 }
193
Andreas Gampef7882972017-03-20 16:35:24 -0700194 int Dex2Oat(const std::vector<std::string>& dex2oat_args, std::string* error_msg) {
Vladimir Marko7a85e702018-12-03 18:47:23 +0000195 std::vector<std::string> argv;
196 if (!CommonRuntimeTest::StartDex2OatCommandLine(&argv, error_msg)) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700197 return false;
198 }
Andreas Gampee1459ae2016-06-29 09:36:30 -0700199
Vladimir Marko7a85e702018-12-03 18:47:23 +0000200 Runtime* runtime = Runtime::Current();
Andreas Gampee1459ae2016-06-29 09:36:30 -0700201 if (!runtime->IsVerificationEnabled()) {
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100202 argv.push_back("--compiler-filter=assume-verified");
Andreas Gampee1459ae2016-06-29 09:36:30 -0700203 }
204
205 if (runtime->MustRelocateIfPossible()) {
206 argv.push_back("--runtime-arg");
207 argv.push_back("-Xrelocate");
208 } else {
209 argv.push_back("--runtime-arg");
210 argv.push_back("-Xnorelocate");
211 }
212
213 if (!kIsTargetBuild) {
214 argv.push_back("--host");
215 }
216
Andreas Gampee1459ae2016-06-29 09:36:30 -0700217 argv.insert(argv.end(), dex2oat_args.begin(), dex2oat_args.end());
218
219 // We must set --android-root.
220 const char* android_root = getenv("ANDROID_ROOT");
221 CHECK(android_root != nullptr);
222 argv.push_back("--android-root=" + std::string(android_root));
223
Mathieu Chartier9e050df2017-08-09 10:05:47 -0700224 if (kDebugArgs) {
225 std::string all_args;
226 for (const std::string& arg : argv) {
227 all_args += arg + " ";
228 }
229 LOG(ERROR) << all_args;
230 }
231
Andreas Gampe38aa0b52018-07-10 23:26:55 -0700232 // We need dex2oat to actually log things.
233 auto post_fork_fn = []() { return setenv("ANDROID_LOG_TAGS", "*:d", 1) == 0; };
234 ForkAndExecResult res = ForkAndExec(argv, post_fork_fn, &output_);
235 if (res.stage != ForkAndExecResult::kFinished) {
236 *error_msg = strerror(errno);
237 return -1;
Nicolas Geoffray56fe0f02016-06-30 15:07:46 +0100238 }
Andreas Gampe38aa0b52018-07-10 23:26:55 -0700239 success_ = res.StandardSuccess();
240 return res.status_code;
Andreas Gampee1459ae2016-06-29 09:36:30 -0700241 }
242
243 std::string output_ = "";
244 std::string error_msg_ = "";
245 bool success_ = false;
246};
247
248class Dex2oatSwapTest : public Dex2oatTest {
249 protected:
250 void RunTest(bool use_fd, bool expect_use, const std::vector<std::string>& extra_args = {}) {
251 std::string dex_location = GetScratchDir() + "/Dex2OatSwapTest.jar";
252 std::string odex_location = GetOdexDir() + "/Dex2OatSwapTest.odex";
253
Andreas Gampe7adeda82016-07-25 08:27:35 -0700254 Copy(GetTestDexFileName(), dex_location);
Andreas Gampee1459ae2016-06-29 09:36:30 -0700255
256 std::vector<std::string> copy(extra_args);
257
258 std::unique_ptr<ScratchFile> sf;
259 if (use_fd) {
260 sf.reset(new ScratchFile());
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800261 copy.push_back(android::base::StringPrintf("--swap-fd=%d", sf->GetFd()));
Andreas Gampee1459ae2016-06-29 09:36:30 -0700262 } else {
263 std::string swap_location = GetOdexDir() + "/Dex2OatSwapTest.odex.swap";
264 copy.push_back("--swap-file=" + swap_location);
265 }
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800266 ASSERT_TRUE(GenerateOdexForTest(dex_location, odex_location, CompilerFilter::kSpeed, copy));
Andreas Gampee1459ae2016-06-29 09:36:30 -0700267
268 CheckValidity();
269 ASSERT_TRUE(success_);
270 CheckResult(expect_use);
271 }
272
Andreas Gampe7adeda82016-07-25 08:27:35 -0700273 virtual std::string GetTestDexFileName() {
Vladimir Marko15357702017-02-09 10:37:31 +0000274 return Dex2oatEnvironmentTest::GetTestDexFileName("VerifierDeps");
Andreas Gampe7adeda82016-07-25 08:27:35 -0700275 }
276
277 virtual void CheckResult(bool expect_use) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700278 if (kIsTargetBuild) {
279 CheckTargetResult(expect_use);
280 } else {
281 CheckHostResult(expect_use);
282 }
283 }
284
Andreas Gampe7adeda82016-07-25 08:27:35 -0700285 virtual void CheckTargetResult(bool expect_use ATTRIBUTE_UNUSED) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700286 // TODO: Ignore for now, as we won't capture any output (it goes to the logcat). We may do
287 // something for variants with file descriptor where we can control the lifetime of
288 // the swap file and thus take a look at it.
289 }
290
Andreas Gampe7adeda82016-07-25 08:27:35 -0700291 virtual void CheckHostResult(bool expect_use) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700292 if (!kIsTargetBuild) {
293 if (expect_use) {
294 EXPECT_NE(output_.find("Large app, accepted running with swap."), std::string::npos)
295 << output_;
296 } else {
297 EXPECT_EQ(output_.find("Large app, accepted running with swap."), std::string::npos)
298 << output_;
299 }
300 }
301 }
302
303 // Check whether the dex2oat run was really successful.
Andreas Gampe7adeda82016-07-25 08:27:35 -0700304 virtual void CheckValidity() {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700305 if (kIsTargetBuild) {
306 CheckTargetValidity();
307 } else {
308 CheckHostValidity();
309 }
310 }
311
Andreas Gampe7adeda82016-07-25 08:27:35 -0700312 virtual void CheckTargetValidity() {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700313 // TODO: Ignore for now, as we won't capture any output (it goes to the logcat). We may do
314 // something for variants with file descriptor where we can control the lifetime of
315 // the swap file and thus take a look at it.
316 }
317
318 // On the host, we can get the dex2oat output. Here, look for "dex2oat took."
Andreas Gampe7adeda82016-07-25 08:27:35 -0700319 virtual void CheckHostValidity() {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700320 EXPECT_NE(output_.find("dex2oat took"), std::string::npos) << output_;
321 }
322};
323
324TEST_F(Dex2oatSwapTest, DoNotUseSwapDefaultSingleSmall) {
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100325 RunTest(/*use_fd=*/ false, /*expect_use=*/ false);
326 RunTest(/*use_fd=*/ true, /*expect_use=*/ false);
Andreas Gampee1459ae2016-06-29 09:36:30 -0700327}
328
329TEST_F(Dex2oatSwapTest, DoNotUseSwapSingle) {
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100330 RunTest(/*use_fd=*/ false, /*expect_use=*/ false, { "--swap-dex-size-threshold=0" });
331 RunTest(/*use_fd=*/ true, /*expect_use=*/ false, { "--swap-dex-size-threshold=0" });
Andreas Gampee1459ae2016-06-29 09:36:30 -0700332}
333
334TEST_F(Dex2oatSwapTest, DoNotUseSwapSmall) {
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100335 RunTest(/*use_fd=*/ false, /*expect_use=*/ false, { "--swap-dex-count-threshold=0" });
336 RunTest(/*use_fd=*/ true, /*expect_use=*/ false, { "--swap-dex-count-threshold=0" });
Andreas Gampee1459ae2016-06-29 09:36:30 -0700337}
338
339TEST_F(Dex2oatSwapTest, DoUseSwapSingleSmall) {
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100340 RunTest(/*use_fd=*/ false,
341 /*expect_use=*/ true,
Andreas Gampee1459ae2016-06-29 09:36:30 -0700342 { "--swap-dex-size-threshold=0", "--swap-dex-count-threshold=0" });
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100343 RunTest(/*use_fd=*/ true,
344 /*expect_use=*/ true,
Andreas Gampee1459ae2016-06-29 09:36:30 -0700345 { "--swap-dex-size-threshold=0", "--swap-dex-count-threshold=0" });
346}
347
Andreas Gampe7adeda82016-07-25 08:27:35 -0700348class Dex2oatSwapUseTest : public Dex2oatSwapTest {
349 protected:
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100350 void CheckHostResult(bool expect_use) override {
Andreas Gampe7adeda82016-07-25 08:27:35 -0700351 if (!kIsTargetBuild) {
352 if (expect_use) {
353 EXPECT_NE(output_.find("Large app, accepted running with swap."), std::string::npos)
354 << output_;
355 } else {
356 EXPECT_EQ(output_.find("Large app, accepted running with swap."), std::string::npos)
357 << output_;
358 }
359 }
360 }
361
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100362 std::string GetTestDexFileName() override {
Andreas Gampe7adeda82016-07-25 08:27:35 -0700363 // Use Statics as it has a handful of functions.
364 return CommonRuntimeTest::GetTestDexFileName("Statics");
365 }
366
367 void GrabResult1() {
368 if (!kIsTargetBuild) {
369 native_alloc_1_ = ParseNativeAlloc();
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100370 swap_1_ = ParseSwap(/*expected=*/ false);
Andreas Gampe7adeda82016-07-25 08:27:35 -0700371 } else {
372 native_alloc_1_ = std::numeric_limits<size_t>::max();
373 swap_1_ = 0;
374 }
375 }
376
377 void GrabResult2() {
378 if (!kIsTargetBuild) {
379 native_alloc_2_ = ParseNativeAlloc();
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100380 swap_2_ = ParseSwap(/*expected=*/ true);
Andreas Gampe7adeda82016-07-25 08:27:35 -0700381 } else {
382 native_alloc_2_ = 0;
383 swap_2_ = std::numeric_limits<size_t>::max();
384 }
385 }
386
387 private:
388 size_t ParseNativeAlloc() {
389 std::regex native_alloc_regex("dex2oat took.*native alloc=[^ ]+ \\(([0-9]+)B\\)");
390 std::smatch native_alloc_match;
391 bool found = std::regex_search(output_, native_alloc_match, native_alloc_regex);
392 if (!found) {
393 EXPECT_TRUE(found);
394 return 0;
395 }
396 if (native_alloc_match.size() != 2U) {
397 EXPECT_EQ(native_alloc_match.size(), 2U);
398 return 0;
399 }
400
401 std::istringstream stream(native_alloc_match[1].str());
402 size_t value;
403 stream >> value;
404
405 return value;
406 }
407
408 size_t ParseSwap(bool expected) {
409 std::regex swap_regex("dex2oat took[^\\n]+swap=[^ ]+ \\(([0-9]+)B\\)");
410 std::smatch swap_match;
411 bool found = std::regex_search(output_, swap_match, swap_regex);
412 if (found != expected) {
413 EXPECT_EQ(expected, found);
414 return 0;
415 }
416
417 if (!found) {
418 return 0;
419 }
420
421 if (swap_match.size() != 2U) {
422 EXPECT_EQ(swap_match.size(), 2U);
423 return 0;
424 }
425
426 std::istringstream stream(swap_match[1].str());
427 size_t value;
428 stream >> value;
429
430 return value;
431 }
432
433 protected:
434 size_t native_alloc_1_;
435 size_t native_alloc_2_;
436
437 size_t swap_1_;
438 size_t swap_2_;
439};
440
441TEST_F(Dex2oatSwapUseTest, CheckSwapUsage) {
Roland Levillain05e34f42018-05-24 13:19:05 +0000442 // Native memory usage isn't correctly tracked when running under ASan.
443 TEST_DISABLED_FOR_MEMORY_TOOL();
Andreas Gampef4a67fd2017-05-04 09:55:36 -0700444
Vladimir Marko57070da2017-02-14 16:16:30 +0000445 // The `native_alloc_2_ >= native_alloc_1_` assertion below may not
Roland Levillain19772bf2017-02-16 11:28:10 +0000446 // hold true on some x86 systems; disable this test while we
447 // investigate (b/29259363).
448 TEST_DISABLED_FOR_X86();
Vladimir Marko57070da2017-02-14 16:16:30 +0000449
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100450 RunTest(/*use_fd=*/ false,
451 /*expect_use=*/ false);
Andreas Gampe7adeda82016-07-25 08:27:35 -0700452 GrabResult1();
453 std::string output_1 = output_;
454
455 output_ = "";
456
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100457 RunTest(/*use_fd=*/ false,
458 /*expect_use=*/ true,
Andreas Gampe7adeda82016-07-25 08:27:35 -0700459 { "--swap-dex-size-threshold=0", "--swap-dex-count-threshold=0" });
460 GrabResult2();
461 std::string output_2 = output_;
462
463 if (native_alloc_2_ >= native_alloc_1_ || swap_1_ >= swap_2_) {
464 EXPECT_LT(native_alloc_2_, native_alloc_1_);
465 EXPECT_LT(swap_1_, swap_2_);
466
467 LOG(ERROR) << output_1;
468 LOG(ERROR) << output_2;
469 }
470}
471
Andreas Gampe67f02822016-06-24 21:05:23 -0700472class Dex2oatVeryLargeTest : public Dex2oatTest {
473 protected:
474 void CheckFilter(CompilerFilter::Filter input ATTRIBUTE_UNUSED,
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100475 CompilerFilter::Filter result ATTRIBUTE_UNUSED) override {
Andreas Gampe67f02822016-06-24 21:05:23 -0700476 // Ignore, we'll do our own checks.
477 }
478
479 void RunTest(CompilerFilter::Filter filter,
480 bool expect_large,
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700481 bool expect_downgrade,
Andreas Gampe67f02822016-06-24 21:05:23 -0700482 const std::vector<std::string>& extra_args = {}) {
483 std::string dex_location = GetScratchDir() + "/DexNoOat.jar";
484 std::string odex_location = GetOdexDir() + "/DexOdexNoOat.odex";
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700485 std::string app_image_file = GetScratchDir() + "/Test.art";
Andreas Gampe67f02822016-06-24 21:05:23 -0700486
487 Copy(GetDexSrc1(), dex_location);
488
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700489 std::vector<std::string> new_args(extra_args);
490 new_args.push_back("--app-image-file=" + app_image_file);
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800491 ASSERT_TRUE(GenerateOdexForTest(dex_location, odex_location, filter, new_args));
Andreas Gampe67f02822016-06-24 21:05:23 -0700492
493 CheckValidity();
494 ASSERT_TRUE(success_);
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700495 CheckResult(dex_location,
496 odex_location,
497 app_image_file,
498 filter,
499 expect_large,
500 expect_downgrade);
Andreas Gampe67f02822016-06-24 21:05:23 -0700501 }
502
503 void CheckResult(const std::string& dex_location,
504 const std::string& odex_location,
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700505 const std::string& app_image_file,
Andreas Gampe67f02822016-06-24 21:05:23 -0700506 CompilerFilter::Filter filter,
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700507 bool expect_large,
508 bool expect_downgrade) {
509 if (expect_downgrade) {
510 EXPECT_TRUE(expect_large);
511 }
Andreas Gampe67f02822016-06-24 21:05:23 -0700512 // Host/target independent checks.
513 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100514 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +0100515 odex_location.c_str(),
Andreas Gampe67f02822016-06-24 21:05:23 -0700516 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100517 /*executable=*/ false,
518 /*low_4gb=*/ false,
Andreas Gampe67f02822016-06-24 21:05:23 -0700519 dex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100520 /*reservation=*/ nullptr,
Andreas Gampe67f02822016-06-24 21:05:23 -0700521 &error_msg));
522 ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700523 EXPECT_GT(app_image_file.length(), 0u);
524 std::unique_ptr<File> file(OS::OpenFileForReading(app_image_file.c_str()));
Andreas Gampe67f02822016-06-24 21:05:23 -0700525 if (expect_large) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700526 // Note: we cannot check the following
527 // EXPECT_FALSE(CompilerFilter::IsAotCompilationEnabled(odex_file->GetCompilerFilter()));
Andreas Gampe67f02822016-06-24 21:05:23 -0700528 // The reason is that the filter override currently happens when the dex files are
529 // loaded in dex2oat, which is after the oat file has been started. Thus, the header
530 // store cannot be changed, and the original filter is set in stone.
531
532 for (const OatDexFile* oat_dex_file : odex_file->GetOatDexFiles()) {
533 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
534 ASSERT_TRUE(dex_file != nullptr);
535 uint32_t class_def_count = dex_file->NumClassDefs();
536 ASSERT_LT(class_def_count, std::numeric_limits<uint16_t>::max());
537 for (uint16_t class_def_index = 0; class_def_index < class_def_count; ++class_def_index) {
538 OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
539 EXPECT_EQ(oat_class.GetType(), OatClassType::kOatClassNoneCompiled);
540 }
541 }
542
543 // If the input filter was "below," it should have been used.
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100544 if (!CompilerFilter::IsAsGoodAs(CompilerFilter::kExtract, filter)) {
Andreas Gampe67f02822016-06-24 21:05:23 -0700545 EXPECT_EQ(odex_file->GetCompilerFilter(), filter);
546 }
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700547
548 // If expect large, make sure the app image isn't generated or is empty.
549 if (file != nullptr) {
550 EXPECT_EQ(file->GetLength(), 0u);
551 }
Andreas Gampe67f02822016-06-24 21:05:23 -0700552 } else {
553 EXPECT_EQ(odex_file->GetCompilerFilter(), filter);
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700554 ASSERT_TRUE(file != nullptr) << app_image_file;
555 EXPECT_GT(file->GetLength(), 0u);
Andreas Gampe67f02822016-06-24 21:05:23 -0700556 }
557
558 // Host/target dependent checks.
559 if (kIsTargetBuild) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700560 CheckTargetResult(expect_downgrade);
Andreas Gampe67f02822016-06-24 21:05:23 -0700561 } else {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700562 CheckHostResult(expect_downgrade);
Andreas Gampe67f02822016-06-24 21:05:23 -0700563 }
564 }
565
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700566 void CheckTargetResult(bool expect_downgrade ATTRIBUTE_UNUSED) {
Andreas Gampe67f02822016-06-24 21:05:23 -0700567 // TODO: Ignore for now. May do something for fd things.
568 }
569
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700570 void CheckHostResult(bool expect_downgrade) {
Andreas Gampe67f02822016-06-24 21:05:23 -0700571 if (!kIsTargetBuild) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700572 if (expect_downgrade) {
573 EXPECT_NE(output_.find("Very large app, downgrading to"), std::string::npos) << output_;
Andreas Gampe67f02822016-06-24 21:05:23 -0700574 } else {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700575 EXPECT_EQ(output_.find("Very large app, downgrading to"), std::string::npos) << output_;
Andreas Gampe67f02822016-06-24 21:05:23 -0700576 }
577 }
578 }
579
580 // Check whether the dex2oat run was really successful.
581 void CheckValidity() {
582 if (kIsTargetBuild) {
583 CheckTargetValidity();
584 } else {
585 CheckHostValidity();
586 }
587 }
588
589 void CheckTargetValidity() {
590 // TODO: Ignore for now.
591 }
592
593 // On the host, we can get the dex2oat output. Here, look for "dex2oat took."
594 void CheckHostValidity() {
595 EXPECT_NE(output_.find("dex2oat took"), std::string::npos) << output_;
596 }
597};
598
599TEST_F(Dex2oatVeryLargeTest, DontUseVeryLarge) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700600 RunTest(CompilerFilter::kAssumeVerified, false, false);
601 RunTest(CompilerFilter::kExtract, false, false);
602 RunTest(CompilerFilter::kQuicken, false, false);
603 RunTest(CompilerFilter::kSpeed, false, false);
Andreas Gampe67f02822016-06-24 21:05:23 -0700604
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700605 RunTest(CompilerFilter::kAssumeVerified, false, false, { "--very-large-app-threshold=10000000" });
606 RunTest(CompilerFilter::kExtract, false, false, { "--very-large-app-threshold=10000000" });
607 RunTest(CompilerFilter::kQuicken, false, false, { "--very-large-app-threshold=10000000" });
608 RunTest(CompilerFilter::kSpeed, false, false, { "--very-large-app-threshold=10000000" });
Andreas Gampe67f02822016-06-24 21:05:23 -0700609}
610
611TEST_F(Dex2oatVeryLargeTest, UseVeryLarge) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700612 RunTest(CompilerFilter::kAssumeVerified, true, false, { "--very-large-app-threshold=100" });
613 RunTest(CompilerFilter::kExtract, true, false, { "--very-large-app-threshold=100" });
614 RunTest(CompilerFilter::kQuicken, true, true, { "--very-large-app-threshold=100" });
615 RunTest(CompilerFilter::kSpeed, true, true, { "--very-large-app-threshold=100" });
Andreas Gampe67f02822016-06-24 21:05:23 -0700616}
617
Mathieu Chartier97ab5e32017-02-22 13:35:44 -0800618// Regressin test for b/35665292.
619TEST_F(Dex2oatVeryLargeTest, SpeedProfileNoProfile) {
620 // Test that dex2oat doesn't crash with speed-profile but no input profile.
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700621 RunTest(CompilerFilter::kSpeedProfile, false, false);
Mathieu Chartier97ab5e32017-02-22 13:35:44 -0800622}
623
Jeff Hao608f2ce2016-10-19 11:17:11 -0700624class Dex2oatLayoutTest : public Dex2oatTest {
625 protected:
626 void CheckFilter(CompilerFilter::Filter input ATTRIBUTE_UNUSED,
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100627 CompilerFilter::Filter result ATTRIBUTE_UNUSED) override {
Jeff Hao608f2ce2016-10-19 11:17:11 -0700628 // Ignore, we'll do our own checks.
629 }
630
Jeff Hao41fba6a2016-11-28 11:53:33 -0800631 // Emits a profile with a single dex file with the given location and a single class index of 1.
632 void GenerateProfile(const std::string& test_profile,
633 const std::string& dex_location,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800634 size_t num_classes,
Jeff Hao41fba6a2016-11-28 11:53:33 -0800635 uint32_t checksum) {
Andreas Gampedfcd82c2018-10-16 20:22:37 -0700636 int profile_test_fd = open(test_profile.c_str(),
637 O_CREAT | O_TRUNC | O_WRONLY | O_CLOEXEC,
638 0644);
Jeff Hao41fba6a2016-11-28 11:53:33 -0800639 CHECK_GE(profile_test_fd, 0);
640
641 ProfileCompilationInfo info;
642 std::string profile_key = ProfileCompilationInfo::GetProfileDexFileKey(dex_location);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800643 for (size_t i = 0; i < num_classes; ++i) {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700644 info.AddClassIndex(profile_key, checksum, dex::TypeIndex(1 + i), kMaxMethodIds);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800645 }
Jeff Hao41fba6a2016-11-28 11:53:33 -0800646 bool result = info.Save(profile_test_fd);
647 close(profile_test_fd);
648 ASSERT_TRUE(result);
649 }
650
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800651 void CompileProfileOdex(const std::string& dex_location,
652 const std::string& odex_location,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800653 const std::string& app_image_file_name,
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800654 bool use_fd,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800655 size_t num_profile_classes,
Nicolas Geoffray97fa9922017-03-09 13:13:25 +0000656 const std::vector<std::string>& extra_args = {},
657 bool expect_success = true) {
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800658 const std::string profile_location = GetScratchDir() + "/primary.prof";
Jeff Hao41fba6a2016-11-28 11:53:33 -0800659 const char* location = dex_location.c_str();
660 std::string error_msg;
661 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Sehr013fd802018-01-11 22:55:24 -0800662 const ArtDexFileLoader dex_file_loader;
663 ASSERT_TRUE(dex_file_loader.Open(
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100664 location, location, /*verify=*/ true, /*verify_checksum=*/ true, &error_msg, &dex_files));
Jeff Hao41fba6a2016-11-28 11:53:33 -0800665 EXPECT_EQ(dex_files.size(), 1U);
666 std::unique_ptr<const DexFile>& dex_file = dex_files[0];
Mathieu Chartier046854b2017-03-01 17:16:22 -0800667 GenerateProfile(profile_location,
668 dex_location,
669 num_profile_classes,
670 dex_file->GetLocationChecksum());
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800671 std::vector<std::string> copy(extra_args);
672 copy.push_back("--profile-file=" + profile_location);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800673 std::unique_ptr<File> app_image_file;
674 if (!app_image_file_name.empty()) {
675 if (use_fd) {
676 app_image_file.reset(OS::CreateEmptyFile(app_image_file_name.c_str()));
677 copy.push_back("--app-image-fd=" + std::to_string(app_image_file->Fd()));
678 } else {
679 copy.push_back("--app-image-file=" + app_image_file_name);
680 }
681 }
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800682 ASSERT_TRUE(GenerateOdexForTest(dex_location,
683 odex_location,
684 CompilerFilter::kSpeedProfile,
685 copy,
686 expect_success,
687 use_fd));
Mathieu Chartier046854b2017-03-01 17:16:22 -0800688 if (app_image_file != nullptr) {
689 ASSERT_EQ(app_image_file->FlushCloseOrErase(), 0) << "Could not flush and close art file";
690 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800691 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700692
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100693 uint64_t GetImageObjectSectionSize(const std::string& image_file_name) {
Mathieu Chartier046854b2017-03-01 17:16:22 -0800694 EXPECT_FALSE(image_file_name.empty());
695 std::unique_ptr<File> file(OS::OpenFileForReading(image_file_name.c_str()));
696 CHECK(file != nullptr);
697 ImageHeader image_header;
698 const bool success = file->ReadFully(&image_header, sizeof(image_header));
699 CHECK(success);
700 CHECK(image_header.IsValid());
701 ReaderMutexLock mu(Thread::Current(), *Locks::mutator_lock_);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100702 return image_header.GetObjectsSection().Size();
Mathieu Chartier046854b2017-03-01 17:16:22 -0800703 }
704
705 void RunTest(bool app_image) {
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800706 std::string dex_location = GetScratchDir() + "/DexNoOat.jar";
707 std::string odex_location = GetOdexDir() + "/DexOdexNoOat.odex";
Mathieu Chartier046854b2017-03-01 17:16:22 -0800708 std::string app_image_file = app_image ? (GetOdexDir() + "/DexOdexNoOat.art"): "";
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800709 Copy(GetDexSrc2(), dex_location);
710
Mathieu Chartier046854b2017-03-01 17:16:22 -0800711 uint64_t image_file_empty_profile = 0;
712 if (app_image) {
713 CompileProfileOdex(dex_location,
714 odex_location,
715 app_image_file,
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100716 /*use_fd=*/ false,
717 /*num_profile_classes=*/ 0);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800718 CheckValidity();
719 ASSERT_TRUE(success_);
720 // Don't check the result since CheckResult relies on the class being in the profile.
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100721 image_file_empty_profile = GetImageObjectSectionSize(app_image_file);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800722 EXPECT_GT(image_file_empty_profile, 0u);
723 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700724
Mathieu Chartier046854b2017-03-01 17:16:22 -0800725 // Small profile.
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=*/ 1);
Jeff Hao608f2ce2016-10-19 11:17:11 -0700731 CheckValidity();
732 ASSERT_TRUE(success_);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800733 CheckResult(dex_location, odex_location, app_image_file);
734
735 if (app_image) {
736 // Test that the profile made a difference by adding more classes.
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100737 const uint64_t image_file_small_profile = GetImageObjectSectionSize(app_image_file);
738 ASSERT_LT(image_file_empty_profile, image_file_small_profile);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800739 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700740 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800741
742 void RunTestVDex() {
743 std::string dex_location = GetScratchDir() + "/DexNoOat.jar";
744 std::string odex_location = GetOdexDir() + "/DexOdexNoOat.odex";
745 std::string vdex_location = GetOdexDir() + "/DexOdexNoOat.vdex";
Mathieu Chartier046854b2017-03-01 17:16:22 -0800746 std::string app_image_file_name = GetOdexDir() + "/DexOdexNoOat.art";
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800747 Copy(GetDexSrc2(), dex_location);
748
749 std::unique_ptr<File> vdex_file1(OS::CreateEmptyFile(vdex_location.c_str()));
750 CHECK(vdex_file1 != nullptr) << vdex_location;
751 ScratchFile vdex_file2;
752 {
753 std::string input_vdex = "--input-vdex-fd=-1";
754 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file1->Fd());
755 CompileProfileOdex(dex_location,
756 odex_location,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800757 app_image_file_name,
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100758 /*use_fd=*/ true,
759 /*num_profile_classes=*/ 1,
Mathieu Chartierf1609832018-01-31 03:09:56 -0800760 { input_vdex, output_vdex });
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800761 EXPECT_GT(vdex_file1->GetLength(), 0u);
762 }
763 {
Nicolas Geoffray97fa9922017-03-09 13:13:25 +0000764 // Test that vdex and dexlayout fail gracefully.
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800765 std::string input_vdex = StringPrintf("--input-vdex-fd=%d", vdex_file1->Fd());
766 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file2.GetFd());
767 CompileProfileOdex(dex_location,
768 odex_location,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800769 app_image_file_name,
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100770 /*use_fd=*/ true,
771 /*num_profile_classes=*/ 1,
Mathieu Chartierd27923c2018-02-08 21:00:03 -0800772 { input_vdex, output_vdex },
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100773 /*expect_success=*/ true);
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +0100774 EXPECT_GT(vdex_file2.GetFile()->GetLength(), 0u);
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800775 }
776 ASSERT_EQ(vdex_file1->FlushCloseOrErase(), 0) << "Could not flush and close vdex file";
777 CheckValidity();
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +0100778 ASSERT_TRUE(success_);
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800779 }
780
Mathieu Chartier046854b2017-03-01 17:16:22 -0800781 void CheckResult(const std::string& dex_location,
782 const std::string& odex_location,
783 const std::string& app_image_file_name) {
Jeff Hao608f2ce2016-10-19 11:17:11 -0700784 // Host/target independent checks.
785 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100786 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +0100787 odex_location.c_str(),
Jeff Hao608f2ce2016-10-19 11:17:11 -0700788 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100789 /*executable=*/ false,
790 /*low_4gb=*/ false,
Jeff Hao608f2ce2016-10-19 11:17:11 -0700791 dex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100792 /*reservation=*/ nullptr,
Jeff Hao608f2ce2016-10-19 11:17:11 -0700793 &error_msg));
794 ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
795
Jeff Hao042e8982016-10-19 11:17:11 -0700796 const char* location = dex_location.c_str();
797 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Sehr013fd802018-01-11 22:55:24 -0800798 const ArtDexFileLoader dex_file_loader;
799 ASSERT_TRUE(dex_file_loader.Open(
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100800 location, location, /*verify=*/ true, /*verify_checksum=*/ true, &error_msg, &dex_files));
Jeff Hao042e8982016-10-19 11:17:11 -0700801 EXPECT_EQ(dex_files.size(), 1U);
802 std::unique_ptr<const DexFile>& old_dex_file = dex_files[0];
803
Jeff Hao608f2ce2016-10-19 11:17:11 -0700804 for (const OatDexFile* oat_dex_file : odex_file->GetOatDexFiles()) {
Jeff Hao042e8982016-10-19 11:17:11 -0700805 std::unique_ptr<const DexFile> new_dex_file = oat_dex_file->OpenDexFile(&error_msg);
806 ASSERT_TRUE(new_dex_file != nullptr);
807 uint32_t class_def_count = new_dex_file->NumClassDefs();
Jeff Hao608f2ce2016-10-19 11:17:11 -0700808 ASSERT_LT(class_def_count, std::numeric_limits<uint16_t>::max());
Jeff Hao042e8982016-10-19 11:17:11 -0700809 ASSERT_GE(class_def_count, 2U);
810
Mathieu Chartier24066ec2017-10-21 16:01:08 -0700811 // Make sure the indexes stay the same.
Jeff Hao042e8982016-10-19 11:17:11 -0700812 std::string old_class0 = old_dex_file->PrettyType(old_dex_file->GetClassDef(0).class_idx_);
813 std::string old_class1 = old_dex_file->PrettyType(old_dex_file->GetClassDef(1).class_idx_);
814 std::string new_class0 = new_dex_file->PrettyType(new_dex_file->GetClassDef(0).class_idx_);
815 std::string new_class1 = new_dex_file->PrettyType(new_dex_file->GetClassDef(1).class_idx_);
Mathieu Chartier24066ec2017-10-21 16:01:08 -0700816 EXPECT_EQ(old_class0, new_class0);
817 EXPECT_EQ(old_class1, new_class1);
Jeff Hao608f2ce2016-10-19 11:17:11 -0700818 }
819
Jeff Haoc155b052017-01-17 17:43:29 -0800820 EXPECT_EQ(odex_file->GetCompilerFilter(), CompilerFilter::kSpeedProfile);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800821
822 if (!app_image_file_name.empty()) {
823 // Go peek at the image header to make sure it was large enough to contain the class.
824 std::unique_ptr<File> file(OS::OpenFileForReading(app_image_file_name.c_str()));
825 ImageHeader image_header;
826 bool success = file->ReadFully(&image_header, sizeof(image_header));
827 ASSERT_TRUE(success);
828 ASSERT_TRUE(image_header.IsValid());
Vladimir Markocd87c3e2017-09-05 13:11:57 +0100829 EXPECT_GT(image_header.GetObjectsSection().Size(), 0u);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800830 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700831 }
832
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800833 // Check whether the dex2oat run was really successful.
834 void CheckValidity() {
835 if (kIsTargetBuild) {
836 CheckTargetValidity();
837 } else {
838 CheckHostValidity();
Jeff Hao608f2ce2016-10-19 11:17:11 -0700839 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800840 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700841
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800842 void CheckTargetValidity() {
843 // TODO: Ignore for now.
844 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700845
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800846 // On the host, we can get the dex2oat output. Here, look for "dex2oat took."
847 void CheckHostValidity() {
848 EXPECT_NE(output_.find("dex2oat took"), std::string::npos) << output_;
849 }
850};
Jeff Hao608f2ce2016-10-19 11:17:11 -0700851
852TEST_F(Dex2oatLayoutTest, TestLayout) {
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100853 RunTest(/*app_image=*/ false);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800854}
855
856TEST_F(Dex2oatLayoutTest, TestLayoutAppImage) {
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100857 RunTest(/*app_image=*/ true);
Jeff Hao608f2ce2016-10-19 11:17:11 -0700858}
859
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800860TEST_F(Dex2oatLayoutTest, TestVdexLayout) {
861 RunTestVDex();
862}
863
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100864class Dex2oatUnquickenTest : public Dex2oatTest {
865 protected:
866 void RunUnquickenMultiDex() {
867 std::string dex_location = GetScratchDir() + "/UnquickenMultiDex.jar";
868 std::string odex_location = GetOdexDir() + "/UnquickenMultiDex.odex";
869 std::string vdex_location = GetOdexDir() + "/UnquickenMultiDex.vdex";
870 Copy(GetTestDexFileName("MultiDex"), dex_location);
871
872 std::unique_ptr<File> vdex_file1(OS::CreateEmptyFile(vdex_location.c_str()));
873 CHECK(vdex_file1 != nullptr) << vdex_location;
874 // Quicken the dex file into a vdex file.
875 {
876 std::string input_vdex = "--input-vdex-fd=-1";
877 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file1->Fd());
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800878 ASSERT_TRUE(GenerateOdexForTest(dex_location,
879 odex_location,
880 CompilerFilter::kQuicken,
881 { input_vdex, output_vdex },
882 /* expect_success= */ true,
883 /* use_fd= */ true));
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100884 EXPECT_GT(vdex_file1->GetLength(), 0u);
885 }
886 // Unquicken by running the verify compiler filter on the vdex file.
887 {
888 std::string input_vdex = StringPrintf("--input-vdex-fd=%d", vdex_file1->Fd());
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::kVerify,
893 { input_vdex, output_vdex, kDisableCompactDex },
894 /* expect_success= */ true,
895 /* use_fd= */ true));
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100896 }
897 ASSERT_EQ(vdex_file1->FlushCloseOrErase(), 0) << "Could not flush and close vdex file";
898 CheckResult(dex_location, odex_location);
899 ASSERT_TRUE(success_);
900 }
901
Mathieu Chartierd27923c2018-02-08 21:00:03 -0800902 void RunUnquickenMultiDexCDex() {
903 std::string dex_location = GetScratchDir() + "/UnquickenMultiDex.jar";
904 std::string odex_location = GetOdexDir() + "/UnquickenMultiDex.odex";
905 std::string odex_location2 = GetOdexDir() + "/UnquickenMultiDex2.odex";
906 std::string vdex_location = GetOdexDir() + "/UnquickenMultiDex.vdex";
907 std::string vdex_location2 = GetOdexDir() + "/UnquickenMultiDex2.vdex";
908 Copy(GetTestDexFileName("MultiDex"), dex_location);
909
910 std::unique_ptr<File> vdex_file1(OS::CreateEmptyFile(vdex_location.c_str()));
911 std::unique_ptr<File> vdex_file2(OS::CreateEmptyFile(vdex_location2.c_str()));
912 CHECK(vdex_file1 != nullptr) << vdex_location;
913 CHECK(vdex_file2 != nullptr) << vdex_location2;
914
915 // Quicken the dex file into a vdex file.
916 {
917 std::string input_vdex = "--input-vdex-fd=-1";
918 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file1->Fd());
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800919 ASSERT_TRUE(GenerateOdexForTest(dex_location,
920 odex_location,
921 CompilerFilter::kQuicken,
922 { input_vdex, output_vdex, "--compact-dex-level=fast"},
923 /* expect_success= */ true,
924 /* use_fd= */ true));
Mathieu Chartierd27923c2018-02-08 21:00:03 -0800925 EXPECT_GT(vdex_file1->GetLength(), 0u);
926 }
927
928 // Unquicken by running the verify compiler filter on the vdex file.
929 {
930 std::string input_vdex = StringPrintf("--input-vdex-fd=%d", vdex_file1->Fd());
931 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file2->Fd());
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800932 ASSERT_TRUE(GenerateOdexForTest(dex_location,
933 odex_location2,
934 CompilerFilter::kVerify,
935 { input_vdex, output_vdex, "--compact-dex-level=none"},
936 /* expect_success= */ true,
937 /* use_fd= */ true));
Mathieu Chartierd27923c2018-02-08 21:00:03 -0800938 }
939 ASSERT_EQ(vdex_file1->FlushCloseOrErase(), 0) << "Could not flush and close vdex file";
940 ASSERT_EQ(vdex_file2->FlushCloseOrErase(), 0) << "Could not flush and close vdex file";
941 CheckResult(dex_location, odex_location2);
942 ASSERT_TRUE(success_);
943 }
944
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100945 void CheckResult(const std::string& dex_location, const std::string& odex_location) {
946 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100947 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +0100948 odex_location.c_str(),
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100949 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100950 /*executable=*/ false,
951 /*low_4gb=*/ false,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100952 dex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100953 /*reservation=*/ nullptr,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100954 &error_msg));
955 ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
956 ASSERT_GE(odex_file->GetOatDexFiles().size(), 1u);
957
958 // Iterate over the dex files and ensure there is no quickened instruction.
959 for (const OatDexFile* oat_dex_file : odex_file->GetOatDexFiles()) {
960 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
Mathieu Chartier2242ef12018-07-23 18:14:13 -0700961 for (ClassAccessor accessor : dex_file->GetClasses()) {
962 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
963 for (const DexInstructionPcPair& inst : method.GetInstructions()) {
964 ASSERT_FALSE(inst->IsQuickened()) << inst->Opcode() << " " << output_;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100965 }
966 }
967 }
968 }
969 }
970};
971
972TEST_F(Dex2oatUnquickenTest, UnquickenMultiDex) {
973 RunUnquickenMultiDex();
974}
975
Mathieu Chartierd27923c2018-02-08 21:00:03 -0800976TEST_F(Dex2oatUnquickenTest, UnquickenMultiDexCDex) {
977 RunUnquickenMultiDexCDex();
978}
979
Andreas Gampe2e8a2562017-01-18 20:39:02 -0800980class Dex2oatWatchdogTest : public Dex2oatTest {
981 protected:
982 void RunTest(bool expect_success, const std::vector<std::string>& extra_args = {}) {
983 std::string dex_location = GetScratchDir() + "/Dex2OatSwapTest.jar";
984 std::string odex_location = GetOdexDir() + "/Dex2OatSwapTest.odex";
985
986 Copy(GetTestDexFileName(), dex_location);
987
988 std::vector<std::string> copy(extra_args);
989
990 std::string swap_location = GetOdexDir() + "/Dex2OatSwapTest.odex.swap";
991 copy.push_back("--swap-file=" + swap_location);
Andreas Gampe22fa3762017-10-23 20:58:12 -0700992 copy.push_back("-j512"); // Excessive idle threads just slow down dex2oat.
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800993 ASSERT_TRUE(GenerateOdexForTest(dex_location,
994 odex_location,
995 CompilerFilter::kSpeed,
996 copy,
997 expect_success));
Andreas Gampe2e8a2562017-01-18 20:39:02 -0800998 }
999
1000 std::string GetTestDexFileName() {
1001 return GetDexSrc1();
1002 }
1003};
1004
1005TEST_F(Dex2oatWatchdogTest, TestWatchdogOK) {
1006 // Check with default.
1007 RunTest(true);
1008
1009 // Check with ten minutes.
1010 RunTest(true, { "--watchdog-timeout=600000" });
1011}
1012
1013TEST_F(Dex2oatWatchdogTest, TestWatchdogTrigger) {
Roland Levillain1fb24e22019-01-09 13:33:37 +00001014 // This test is frequently interrupted by timeout_dumper on host (x86);
1015 // disable it while we investigate (b/121352534).
1016 TEST_DISABLED_FOR_X86();
1017
Andreas Gampe80ddf272018-01-11 09:41:00 -08001018 // The watchdog is independent of dex2oat and will not delete intermediates. It is possible
1019 // that the compilation succeeds and the file is completely written by the time the watchdog
1020 // kills dex2oat (but the dex2oat threads must have been scheduled pretty badly).
1021 test_accepts_odex_file_on_failure = true;
1022
Andreas Gampe2e8a2562017-01-18 20:39:02 -08001023 // Check with ten milliseconds.
1024 RunTest(false, { "--watchdog-timeout=10" });
1025}
1026
Andreas Gampef7882972017-03-20 16:35:24 -07001027class Dex2oatReturnCodeTest : public Dex2oatTest {
1028 protected:
1029 int RunTest(const std::vector<std::string>& extra_args = {}) {
1030 std::string dex_location = GetScratchDir() + "/Dex2OatSwapTest.jar";
1031 std::string odex_location = GetOdexDir() + "/Dex2OatSwapTest.odex";
1032
1033 Copy(GetTestDexFileName(), dex_location);
1034
1035 std::string error_msg;
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001036 return GenerateOdexForTestWithStatus({dex_location},
Andreas Gampef7882972017-03-20 16:35:24 -07001037 odex_location,
1038 CompilerFilter::kSpeed,
1039 &error_msg,
1040 extra_args);
1041 }
1042
1043 std::string GetTestDexFileName() {
1044 return GetDexSrc1();
1045 }
1046};
1047
1048TEST_F(Dex2oatReturnCodeTest, TestCreateRuntime) {
Andreas Gampefd80b172017-04-26 22:25:31 -07001049 TEST_DISABLED_FOR_MEMORY_TOOL(); // b/19100793
Andreas Gampef7882972017-03-20 16:35:24 -07001050 int status = RunTest({ "--boot-image=/this/does/not/exist/yolo.oat" });
1051 EXPECT_EQ(static_cast<int>(dex2oat::ReturnCode::kCreateRuntime), WEXITSTATUS(status)) << output_;
1052}
1053
Calin Juravle1ce70852017-06-28 10:59:03 -07001054class Dex2oatClassLoaderContextTest : public Dex2oatTest {
1055 protected:
1056 void RunTest(const char* class_loader_context,
1057 const char* expected_classpath_key,
1058 bool expected_success,
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001059 bool use_second_source = false,
1060 bool generate_image = false) {
Calin Juravle1ce70852017-06-28 10:59:03 -07001061 std::string dex_location = GetUsedDexLocation();
1062 std::string odex_location = GetUsedOatLocation();
1063
1064 Copy(use_second_source ? GetDexSrc2() : GetDexSrc1(), dex_location);
1065
1066 std::string error_msg;
1067 std::vector<std::string> extra_args;
1068 if (class_loader_context != nullptr) {
1069 extra_args.push_back(std::string("--class-loader-context=") + class_loader_context);
1070 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001071 if (generate_image) {
1072 extra_args.push_back(std::string("--app-image-file=") + GetUsedImageLocation());
1073 }
Calin Juravle1ce70852017-06-28 10:59:03 -07001074 auto check_oat = [expected_classpath_key](const OatFile& oat_file) {
1075 ASSERT_TRUE(expected_classpath_key != nullptr);
1076 const char* classpath = oat_file.GetOatHeader().GetStoreValueByKey(OatHeader::kClassPathKey);
1077 ASSERT_TRUE(classpath != nullptr);
1078 ASSERT_STREQ(expected_classpath_key, classpath);
1079 };
1080
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001081 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1082 odex_location,
1083 CompilerFilter::kQuicken,
1084 extra_args,
1085 expected_success,
1086 /*use_fd*/ false,
1087 check_oat));
Calin Juravle1ce70852017-06-28 10:59:03 -07001088 }
1089
1090 std::string GetUsedDexLocation() {
1091 return GetScratchDir() + "/Context.jar";
1092 }
1093
1094 std::string GetUsedOatLocation() {
1095 return GetOdexDir() + "/Context.odex";
1096 }
1097
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001098 std::string GetUsedImageLocation() {
1099 return GetOdexDir() + "/Context.art";
1100 }
1101
Calin Juravle7b0648a2017-07-07 18:40:50 -07001102 const char* kEmptyClassPathKey = "PCL[]";
Calin Juravle1ce70852017-06-28 10:59:03 -07001103};
1104
1105TEST_F(Dex2oatClassLoaderContextTest, InvalidContext) {
1106 RunTest("Invalid[]", /*expected_classpath_key*/ nullptr, /*expected_success*/ false);
1107}
1108
1109TEST_F(Dex2oatClassLoaderContextTest, EmptyContext) {
1110 RunTest("PCL[]", kEmptyClassPathKey, /*expected_success*/ true);
1111}
1112
1113TEST_F(Dex2oatClassLoaderContextTest, SpecialContext) {
1114 RunTest(OatFile::kSpecialSharedLibrary,
1115 OatFile::kSpecialSharedLibrary,
1116 /*expected_success*/ true);
1117}
1118
1119TEST_F(Dex2oatClassLoaderContextTest, ContextWithTheSourceDexFiles) {
1120 std::string context = "PCL[" + GetUsedDexLocation() + "]";
1121 RunTest(context.c_str(), kEmptyClassPathKey, /*expected_success*/ true);
1122}
1123
1124TEST_F(Dex2oatClassLoaderContextTest, ContextWithOtherDexFiles) {
1125 std::vector<std::unique_ptr<const DexFile>> dex_files = OpenTestDexFiles("Nested");
Calin Juravle1ce70852017-06-28 10:59:03 -07001126
1127 std::string context = "PCL[" + dex_files[0]->GetLocation() + "]";
Calin Juravle7b0648a2017-07-07 18:40:50 -07001128 std::string expected_classpath_key = "PCL[" +
1129 dex_files[0]->GetLocation() + "*" + std::to_string(dex_files[0]->GetLocationChecksum()) + "]";
Calin Juravle1ce70852017-06-28 10:59:03 -07001130 RunTest(context.c_str(), expected_classpath_key.c_str(), true);
1131}
1132
1133TEST_F(Dex2oatClassLoaderContextTest, ContextWithStrippedDexFiles) {
1134 std::string stripped_classpath = GetScratchDir() + "/stripped_classpath.jar";
1135 Copy(GetStrippedDexSrc1(), stripped_classpath);
1136
1137 std::string context = "PCL[" + stripped_classpath + "]";
1138 // Expect an empty context because stripped dex files cannot be open.
Calin Juravle7b0648a2017-07-07 18:40:50 -07001139 RunTest(context.c_str(), kEmptyClassPathKey , /*expected_success*/ true);
Calin Juravle1ce70852017-06-28 10:59:03 -07001140}
1141
1142TEST_F(Dex2oatClassLoaderContextTest, ContextWithStrippedDexFilesBackedByOdex) {
1143 std::string stripped_classpath = GetScratchDir() + "/stripped_classpath.jar";
1144 std::string odex_for_classpath = GetOdexDir() + "/stripped_classpath.odex";
1145
1146 Copy(GetDexSrc1(), stripped_classpath);
1147
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001148 ASSERT_TRUE(GenerateOdexForTest(stripped_classpath,
1149 odex_for_classpath,
1150 CompilerFilter::kQuicken,
1151 {},
1152 true));
Calin Juravle1ce70852017-06-28 10:59:03 -07001153
1154 // Strip the dex file
1155 Copy(GetStrippedDexSrc1(), stripped_classpath);
1156
1157 std::string context = "PCL[" + stripped_classpath + "]";
Calin Juravle7b0648a2017-07-07 18:40:50 -07001158 std::string expected_classpath_key;
Calin Juravle1ce70852017-06-28 10:59:03 -07001159 {
1160 // Open the oat file to get the expected classpath.
Nicolas Geoffray29742602017-12-14 10:09:03 +00001161 OatFileAssistant oat_file_assistant(stripped_classpath.c_str(), kRuntimeISA, false, false);
Calin Juravle1ce70852017-06-28 10:59:03 -07001162 std::unique_ptr<OatFile> oat_file(oat_file_assistant.GetBestOatFile());
1163 std::vector<std::unique_ptr<const DexFile>> oat_dex_files =
1164 OatFileAssistant::LoadDexFiles(*oat_file, stripped_classpath.c_str());
Calin Juravle7b0648a2017-07-07 18:40:50 -07001165 expected_classpath_key = "PCL[";
1166 for (size_t i = 0; i < oat_dex_files.size(); i++) {
1167 if (i > 0) {
1168 expected_classpath_key + ":";
1169 }
1170 expected_classpath_key += oat_dex_files[i]->GetLocation() + "*" +
1171 std::to_string(oat_dex_files[i]->GetLocationChecksum());
1172 }
1173 expected_classpath_key += "]";
Calin Juravle1ce70852017-06-28 10:59:03 -07001174 }
1175
1176 RunTest(context.c_str(),
Calin Juravle7b0648a2017-07-07 18:40:50 -07001177 expected_classpath_key.c_str(),
Calin Juravle1ce70852017-06-28 10:59:03 -07001178 /*expected_success*/ true,
1179 /*use_second_source*/ true);
1180}
1181
1182TEST_F(Dex2oatClassLoaderContextTest, ContextWithNotExistentDexFiles) {
1183 std::string context = "PCL[does_not_exists.dex]";
1184 // Expect an empty context because stripped dex files cannot be open.
1185 RunTest(context.c_str(), kEmptyClassPathKey, /*expected_success*/ true);
1186}
1187
Calin Juravlec79470d2017-07-12 17:37:42 -07001188TEST_F(Dex2oatClassLoaderContextTest, ChainContext) {
1189 std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested");
1190 std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex");
1191
1192 std::string context = "PCL[" + GetTestDexFileName("Nested") + "];" +
1193 "DLC[" + GetTestDexFileName("MultiDex") + "]";
1194 std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "];" +
1195 "DLC[" + CreateClassPathWithChecksums(dex_files2) + "]";
1196
1197 RunTest(context.c_str(), expected_classpath_key.c_str(), true);
1198}
1199
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00001200TEST_F(Dex2oatClassLoaderContextTest, ContextWithSharedLibrary) {
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 "{PCL[" + GetTestDexFileName("MultiDex") + "]}";
1206 std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "]" +
1207 "{PCL[" + CreateClassPathWithChecksums(dex_files2) + "]}";
1208 RunTest(context.c_str(), expected_classpath_key.c_str(), true);
1209}
1210
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001211TEST_F(Dex2oatClassLoaderContextTest, ContextWithSharedLibraryAndImage) {
1212 std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested");
1213 std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex");
1214
1215 std::string context = "PCL[" + GetTestDexFileName("Nested") + "]" +
1216 "{PCL[" + GetTestDexFileName("MultiDex") + "]}";
1217 std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "]" +
1218 "{PCL[" + CreateClassPathWithChecksums(dex_files2) + "]}";
1219 RunTest(context.c_str(),
1220 expected_classpath_key.c_str(),
1221 /*expected_success=*/ true,
1222 /*use_second_source=*/ false,
1223 /*generate_image=*/ true);
1224}
1225
1226TEST_F(Dex2oatClassLoaderContextTest, ContextWithSameSharedLibrariesAndImage) {
1227 std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested");
1228 std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex");
1229
1230 std::string context = "PCL[" + GetTestDexFileName("Nested") + "]" +
1231 "{PCL[" + GetTestDexFileName("MultiDex") + "]" +
1232 "#PCL[" + GetTestDexFileName("MultiDex") + "]}";
1233 std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "]" +
1234 "{PCL[" + CreateClassPathWithChecksums(dex_files2) + "]" +
1235 "#PCL[" + CreateClassPathWithChecksums(dex_files2) + "]}";
1236 RunTest(context.c_str(),
1237 expected_classpath_key.c_str(),
1238 /*expected_success=*/ true,
1239 /*use_second_source=*/ false,
1240 /*generate_image=*/ true);
1241}
1242
1243TEST_F(Dex2oatClassLoaderContextTest, ContextWithSharedLibrariesDependenciesAndImage) {
1244 std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested");
1245 std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex");
1246
1247 std::string context = "PCL[" + GetTestDexFileName("Nested") + "]" +
1248 "{PCL[" + GetTestDexFileName("MultiDex") + "]" +
1249 "{PCL[" + GetTestDexFileName("Nested") + "]}}";
1250 std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "]" +
1251 "{PCL[" + CreateClassPathWithChecksums(dex_files2) + "]" +
1252 "{PCL[" + CreateClassPathWithChecksums(dex_files1) + "]}}";
1253 RunTest(context.c_str(),
1254 expected_classpath_key.c_str(),
1255 /*expected_success=*/ true,
1256 /*use_second_source=*/ false,
1257 /*generate_image=*/ true);
1258}
1259
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001260class Dex2oatDeterminism : public Dex2oatTest {};
1261
1262TEST_F(Dex2oatDeterminism, UnloadCompile) {
1263 if (!kUseReadBarrier &&
1264 gc::kCollectorTypeDefault != gc::kCollectorTypeCMS &&
1265 gc::kCollectorTypeDefault != gc::kCollectorTypeMS) {
1266 LOG(INFO) << "Test requires determinism support.";
1267 return;
1268 }
1269 Runtime* const runtime = Runtime::Current();
1270 std::string out_dir = GetScratchDir();
1271 const std::string base_oat_name = out_dir + "/base.oat";
1272 const std::string base_vdex_name = out_dir + "/base.vdex";
1273 const std::string unload_oat_name = out_dir + "/unload.oat";
1274 const std::string unload_vdex_name = out_dir + "/unload.vdex";
1275 const std::string no_unload_oat_name = out_dir + "/nounload.oat";
1276 const std::string no_unload_vdex_name = out_dir + "/nounload.vdex";
1277 const std::string app_image_name = out_dir + "/unload.art";
1278 std::string error_msg;
1279 const std::vector<gc::space::ImageSpace*>& spaces = runtime->GetHeap()->GetBootImageSpaces();
1280 ASSERT_GT(spaces.size(), 0u);
1281 const std::string image_location = spaces[0]->GetImageLocation();
1282 // Without passing in an app image, it will unload in between compilations.
1283 const int res = GenerateOdexForTestWithStatus(
1284 GetLibCoreDexFileNames(),
1285 base_oat_name,
1286 CompilerFilter::Filter::kQuicken,
1287 &error_msg,
1288 {"--force-determinism", "--avoid-storing-invocation"});
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001289 ASSERT_EQ(res, 0);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001290 Copy(base_oat_name, unload_oat_name);
1291 Copy(base_vdex_name, unload_vdex_name);
1292 std::unique_ptr<File> unload_oat(OS::OpenFileForReading(unload_oat_name.c_str()));
1293 std::unique_ptr<File> unload_vdex(OS::OpenFileForReading(unload_vdex_name.c_str()));
1294 ASSERT_TRUE(unload_oat != nullptr);
1295 ASSERT_TRUE(unload_vdex != nullptr);
1296 EXPECT_GT(unload_oat->GetLength(), 0u);
1297 EXPECT_GT(unload_vdex->GetLength(), 0u);
1298 // Regenerate with an app image to disable the dex2oat unloading and verify that the output is
1299 // the same.
1300 const int res2 = GenerateOdexForTestWithStatus(
1301 GetLibCoreDexFileNames(),
1302 base_oat_name,
1303 CompilerFilter::Filter::kQuicken,
1304 &error_msg,
1305 {"--force-determinism", "--avoid-storing-invocation", "--app-image-file=" + app_image_name});
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001306 ASSERT_EQ(res2, 0);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001307 Copy(base_oat_name, no_unload_oat_name);
1308 Copy(base_vdex_name, no_unload_vdex_name);
1309 std::unique_ptr<File> no_unload_oat(OS::OpenFileForReading(no_unload_oat_name.c_str()));
1310 std::unique_ptr<File> no_unload_vdex(OS::OpenFileForReading(no_unload_vdex_name.c_str()));
1311 ASSERT_TRUE(no_unload_oat != nullptr);
1312 ASSERT_TRUE(no_unload_vdex != nullptr);
1313 EXPECT_GT(no_unload_oat->GetLength(), 0u);
1314 EXPECT_GT(no_unload_vdex->GetLength(), 0u);
1315 // Verify that both of the files are the same (odex and vdex).
1316 EXPECT_EQ(unload_oat->GetLength(), no_unload_oat->GetLength());
1317 EXPECT_EQ(unload_vdex->GetLength(), no_unload_vdex->GetLength());
1318 EXPECT_EQ(unload_oat->Compare(no_unload_oat.get()), 0)
1319 << unload_oat_name << " " << no_unload_oat_name;
1320 EXPECT_EQ(unload_vdex->Compare(no_unload_vdex.get()), 0)
1321 << unload_vdex_name << " " << no_unload_vdex_name;
1322 // App image file.
1323 std::unique_ptr<File> app_image_file(OS::OpenFileForReading(app_image_name.c_str()));
1324 ASSERT_TRUE(app_image_file != nullptr);
1325 EXPECT_GT(app_image_file->GetLength(), 0u);
1326}
1327
Mathieu Chartier120aa282017-08-05 16:03:03 -07001328// Test that dexlayout section info is correctly written to the oat file for profile based
1329// compilation.
1330TEST_F(Dex2oatTest, LayoutSections) {
1331 using Hotness = ProfileCompilationInfo::MethodHotness;
1332 std::unique_ptr<const DexFile> dex(OpenTestDexFile("ManyMethods"));
1333 ScratchFile profile_file;
1334 // We can only layout method indices with code items, figure out which ones have this property
1335 // first.
1336 std::vector<uint16_t> methods;
1337 {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001338 const dex::TypeId* type_id = dex->FindTypeId("LManyMethods;");
Mathieu Chartier120aa282017-08-05 16:03:03 -07001339 dex::TypeIndex type_idx = dex->GetIndexForTypeId(*type_id);
Mathieu Chartier2242ef12018-07-23 18:14:13 -07001340 ClassAccessor accessor(*dex, *dex->FindClassDef(type_idx));
Mathieu Chartier120aa282017-08-05 16:03:03 -07001341 std::set<size_t> code_item_offsets;
Mathieu Chartier2242ef12018-07-23 18:14:13 -07001342 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
1343 const uint16_t method_idx = method.GetIndex();
1344 const size_t code_item_offset = method.GetCodeItemOffset();
Mathieu Chartier120aa282017-08-05 16:03:03 -07001345 if (code_item_offsets.insert(code_item_offset).second) {
1346 // Unique code item, add the method index.
1347 methods.push_back(method_idx);
1348 }
1349 }
Mathieu Chartier120aa282017-08-05 16:03:03 -07001350 }
1351 ASSERT_GE(methods.size(), 8u);
1352 std::vector<uint16_t> hot_methods = {methods[1], methods[3], methods[5]};
1353 std::vector<uint16_t> startup_methods = {methods[1], methods[2], methods[7]};
1354 std::vector<uint16_t> post_methods = {methods[0], methods[2], methods[6]};
1355 // Here, we build the profile from the method lists.
1356 ProfileCompilationInfo info;
1357 info.AddMethodsForDex(
1358 static_cast<Hotness::Flag>(Hotness::kFlagHot | Hotness::kFlagStartup),
1359 dex.get(),
1360 hot_methods.begin(),
1361 hot_methods.end());
1362 info.AddMethodsForDex(
1363 Hotness::kFlagStartup,
1364 dex.get(),
1365 startup_methods.begin(),
1366 startup_methods.end());
1367 info.AddMethodsForDex(
1368 Hotness::kFlagPostStartup,
1369 dex.get(),
1370 post_methods.begin(),
1371 post_methods.end());
1372 for (uint16_t id : hot_methods) {
1373 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsHot());
1374 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsStartup());
1375 }
1376 for (uint16_t id : startup_methods) {
1377 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsStartup());
1378 }
1379 for (uint16_t id : post_methods) {
1380 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsPostStartup());
1381 }
1382 // Save the profile since we want to use it with dex2oat to produce an oat file.
1383 ASSERT_TRUE(info.Save(profile_file.GetFd()));
1384 // Generate a profile based odex.
1385 const std::string dir = GetScratchDir();
1386 const std::string oat_filename = dir + "/base.oat";
1387 const std::string vdex_filename = dir + "/base.vdex";
1388 std::string error_msg;
1389 const int res = GenerateOdexForTestWithStatus(
1390 {dex->GetLocation()},
1391 oat_filename,
1392 CompilerFilter::Filter::kQuicken,
1393 &error_msg,
1394 {"--profile-file=" + profile_file.GetFilename()});
1395 EXPECT_EQ(res, 0);
1396
1397 // Open our generated oat file.
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001398 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01001399 oat_filename.c_str(),
Mathieu Chartier120aa282017-08-05 16:03:03 -07001400 oat_filename.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001401 /*executable=*/ false,
1402 /*low_4gb=*/ false,
Mathieu Chartier120aa282017-08-05 16:03:03 -07001403 dex->GetLocation().c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001404 /*reservation=*/ nullptr,
Mathieu Chartier120aa282017-08-05 16:03:03 -07001405 &error_msg));
1406 ASSERT_TRUE(odex_file != nullptr);
1407 std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
1408 ASSERT_EQ(oat_dex_files.size(), 1u);
1409 // Check that the code sections match what we expect.
1410 for (const OatDexFile* oat_dex : oat_dex_files) {
1411 const DexLayoutSections* const sections = oat_dex->GetDexLayoutSections();
1412 // Testing of logging the sections.
1413 ASSERT_TRUE(sections != nullptr);
1414 LOG(INFO) << *sections;
1415
1416 // Load the sections into temporary variables for convenience.
1417 const DexLayoutSection& code_section =
1418 sections->sections_[static_cast<size_t>(DexLayoutSections::SectionType::kSectionTypeCode)];
1419 const DexLayoutSection::Subsection& section_hot_code =
1420 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeHot)];
1421 const DexLayoutSection::Subsection& section_sometimes_used =
1422 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeSometimesUsed)];
1423 const DexLayoutSection::Subsection& section_startup_only =
1424 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeStartupOnly)];
1425 const DexLayoutSection::Subsection& section_unused =
1426 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeUnused)];
1427
1428 // All the sections should be non-empty.
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001429 EXPECT_GT(section_hot_code.Size(), 0u);
1430 EXPECT_GT(section_sometimes_used.Size(), 0u);
1431 EXPECT_GT(section_startup_only.Size(), 0u);
1432 EXPECT_GT(section_unused.Size(), 0u);
Mathieu Chartier120aa282017-08-05 16:03:03 -07001433
1434 // Open the dex file since we need to peek at the code items to verify the layout matches what
1435 // we expect.
1436 std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1437 ASSERT_TRUE(dex_file != nullptr) << error_msg;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001438 const dex::TypeId* type_id = dex_file->FindTypeId("LManyMethods;");
Mathieu Chartier120aa282017-08-05 16:03:03 -07001439 ASSERT_TRUE(type_id != nullptr);
1440 dex::TypeIndex type_idx = dex_file->GetIndexForTypeId(*type_id);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001441 const dex::ClassDef* class_def = dex_file->FindClassDef(type_idx);
Mathieu Chartier120aa282017-08-05 16:03:03 -07001442 ASSERT_TRUE(class_def != nullptr);
1443
1444 // Count how many code items are for each category, there should be at least one per category.
1445 size_t hot_count = 0;
1446 size_t post_startup_count = 0;
1447 size_t startup_count = 0;
1448 size_t unused_count = 0;
1449 // Visit all of the methdos of the main class and cross reference the method indices to their
1450 // corresponding code item offsets to verify the layout.
Mathieu Chartier2242ef12018-07-23 18:14:13 -07001451 ClassAccessor accessor(*dex_file, *class_def);
1452 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
1453 const size_t method_idx = method.GetIndex();
1454 const size_t code_item_offset = method.GetCodeItemOffset();
Mathieu Chartier120aa282017-08-05 16:03:03 -07001455 const bool is_hot = ContainsElement(hot_methods, method_idx);
1456 const bool is_startup = ContainsElement(startup_methods, method_idx);
1457 const bool is_post_startup = ContainsElement(post_methods, method_idx);
1458 if (is_hot) {
1459 // Hot is highest precedence, check that the hot methods are in the hot section.
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001460 EXPECT_TRUE(section_hot_code.Contains(code_item_offset));
Mathieu Chartier120aa282017-08-05 16:03:03 -07001461 ++hot_count;
1462 } else if (is_post_startup) {
1463 // Post startup is sometimes used section.
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001464 EXPECT_TRUE(section_sometimes_used.Contains(code_item_offset));
Mathieu Chartier120aa282017-08-05 16:03:03 -07001465 ++post_startup_count;
1466 } else if (is_startup) {
1467 // Startup at this point means not hot or post startup, these must be startup only then.
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001468 EXPECT_TRUE(section_startup_only.Contains(code_item_offset));
Mathieu Chartier120aa282017-08-05 16:03:03 -07001469 ++startup_count;
1470 } else {
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001471 if (section_unused.Contains(code_item_offset)) {
Alan Leung9595fd32017-10-17 17:08:19 -07001472 // If no flags are set, the method should be unused ...
1473 ++unused_count;
1474 } else {
1475 // or this method is part of the last code item and the end is 4 byte aligned.
Mathieu Chartier2242ef12018-07-23 18:14:13 -07001476 for (const ClassAccessor::Method& method2 : accessor.GetMethods()) {
1477 EXPECT_LE(method2.GetCodeItemOffset(), code_item_offset);
Alan Leung9595fd32017-10-17 17:08:19 -07001478 }
1479 uint32_t code_item_size = dex_file->FindCodeItemOffset(*class_def, method_idx);
1480 EXPECT_EQ((code_item_offset + code_item_size) % 4, 0u);
1481 }
Mathieu Chartier120aa282017-08-05 16:03:03 -07001482 }
1483 }
Mathieu Chartier120aa282017-08-05 16:03:03 -07001484 EXPECT_GT(hot_count, 0u);
1485 EXPECT_GT(post_startup_count, 0u);
1486 EXPECT_GT(startup_count, 0u);
1487 EXPECT_GT(unused_count, 0u);
1488 }
1489}
1490
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001491// Test that generating compact dex works.
1492TEST_F(Dex2oatTest, GenerateCompactDex) {
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001493 // Generate a compact dex based odex.
1494 const std::string dir = GetScratchDir();
1495 const std::string oat_filename = dir + "/base.oat";
1496 const std::string vdex_filename = dir + "/base.vdex";
Mathieu Chartierc17b7d82018-03-14 14:00:04 -07001497 const std::string dex_location = GetTestDexFileName("MultiDex");
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001498 std::string error_msg;
1499 const int res = GenerateOdexForTestWithStatus(
Mathieu Chartierc17b7d82018-03-14 14:00:04 -07001500 { dex_location },
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001501 oat_filename,
1502 CompilerFilter::Filter::kQuicken,
1503 &error_msg,
1504 {"--compact-dex-level=fast"});
1505 EXPECT_EQ(res, 0);
1506 // Open our generated oat file.
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001507 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01001508 oat_filename.c_str(),
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001509 oat_filename.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001510 /*executable=*/ false,
1511 /*low_4gb=*/ false,
Mathieu Chartierc17b7d82018-03-14 14:00:04 -07001512 dex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001513 /*reservation=*/ nullptr,
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001514 &error_msg));
1515 ASSERT_TRUE(odex_file != nullptr);
1516 std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
Mathieu Chartierc17b7d82018-03-14 14:00:04 -07001517 ASSERT_GT(oat_dex_files.size(), 1u);
1518 // Check that each dex is a compact dex file.
1519 std::vector<std::unique_ptr<const CompactDexFile>> compact_dex_files;
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001520 for (const OatDexFile* oat_dex : oat_dex_files) {
1521 std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1522 ASSERT_TRUE(dex_file != nullptr) << error_msg;
1523 ASSERT_TRUE(dex_file->IsCompactDexFile());
Mathieu Chartierc17b7d82018-03-14 14:00:04 -07001524 compact_dex_files.push_back(
1525 std::unique_ptr<const CompactDexFile>(dex_file.release()->AsCompactDexFile()));
1526 }
1527 for (const std::unique_ptr<const CompactDexFile>& dex_file : compact_dex_files) {
1528 // Test that every code item is in the owned section.
1529 const CompactDexFile::Header& header = dex_file->GetHeader();
1530 EXPECT_LE(header.OwnedDataBegin(), header.OwnedDataEnd());
1531 EXPECT_LE(header.OwnedDataBegin(), header.data_size_);
1532 EXPECT_LE(header.OwnedDataEnd(), header.data_size_);
Mathieu Chartier2242ef12018-07-23 18:14:13 -07001533 for (ClassAccessor accessor : dex_file->GetClasses()) {
1534 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
1535 if (method.GetCodeItemOffset() != 0u) {
1536 ASSERT_GE(method.GetCodeItemOffset(), header.OwnedDataBegin());
1537 ASSERT_LT(method.GetCodeItemOffset(), header.OwnedDataEnd());
Mathieu Chartierc17b7d82018-03-14 14:00:04 -07001538 }
Mathieu Chartier2242ef12018-07-23 18:14:13 -07001539 }
Mathieu Chartierc17b7d82018-03-14 14:00:04 -07001540 }
1541 // Test that the owned sections don't overlap.
1542 for (const std::unique_ptr<const CompactDexFile>& other_dex : compact_dex_files) {
1543 if (dex_file != other_dex) {
1544 ASSERT_TRUE(
1545 (dex_file->GetHeader().OwnedDataBegin() >= other_dex->GetHeader().OwnedDataEnd()) ||
1546 (dex_file->GetHeader().OwnedDataEnd() <= other_dex->GetHeader().OwnedDataBegin()));
1547 }
1548 }
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001549 }
1550}
1551
Andreas Gampef39208f2017-10-19 15:06:59 -07001552class Dex2oatVerifierAbort : public Dex2oatTest {};
1553
1554TEST_F(Dex2oatVerifierAbort, HardFail) {
1555 // Use VerifierDeps as it has hard-failing classes.
1556 std::unique_ptr<const DexFile> dex(OpenTestDexFile("VerifierDeps"));
1557 std::string out_dir = GetScratchDir();
1558 const std::string base_oat_name = out_dir + "/base.oat";
1559 std::string error_msg;
1560 const int res_fail = GenerateOdexForTestWithStatus(
1561 {dex->GetLocation()},
1562 base_oat_name,
1563 CompilerFilter::Filter::kQuicken,
1564 &error_msg,
1565 {"--abort-on-hard-verifier-error"});
1566 EXPECT_NE(0, res_fail);
1567
1568 const int res_no_fail = GenerateOdexForTestWithStatus(
1569 {dex->GetLocation()},
1570 base_oat_name,
1571 CompilerFilter::Filter::kQuicken,
1572 &error_msg,
1573 {"--no-abort-on-hard-verifier-error"});
1574 EXPECT_EQ(0, res_no_fail);
1575}
1576
1577TEST_F(Dex2oatVerifierAbort, SoftFail) {
1578 // Use VerifierDepsMulti as it has hard-failing classes.
1579 std::unique_ptr<const DexFile> dex(OpenTestDexFile("VerifierDepsMulti"));
1580 std::string out_dir = GetScratchDir();
1581 const std::string base_oat_name = out_dir + "/base.oat";
1582 std::string error_msg;
1583 const int res_fail = GenerateOdexForTestWithStatus(
1584 {dex->GetLocation()},
1585 base_oat_name,
1586 CompilerFilter::Filter::kQuicken,
1587 &error_msg,
1588 {"--abort-on-soft-verifier-error"});
1589 EXPECT_NE(0, res_fail);
1590
1591 const int res_no_fail = GenerateOdexForTestWithStatus(
1592 {dex->GetLocation()},
1593 base_oat_name,
1594 CompilerFilter::Filter::kQuicken,
1595 &error_msg,
1596 {"--no-abort-on-soft-verifier-error"});
1597 EXPECT_EQ(0, res_no_fail);
1598}
1599
Andreas Gampecac31ad2017-11-06 20:01:17 -08001600class Dex2oatDedupeCode : public Dex2oatTest {};
1601
1602TEST_F(Dex2oatDedupeCode, DedupeTest) {
1603 // Use MyClassNatives. It has lots of native methods that will produce deduplicate-able code.
1604 std::unique_ptr<const DexFile> dex(OpenTestDexFile("MyClassNatives"));
1605 std::string out_dir = GetScratchDir();
1606 const std::string base_oat_name = out_dir + "/base.oat";
1607 size_t no_dedupe_size = 0;
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001608 ASSERT_TRUE(GenerateOdexForTest(dex->GetLocation(),
1609 base_oat_name,
1610 CompilerFilter::Filter::kSpeed,
1611 { "--deduplicate-code=false" },
1612 true, // expect_success
1613 false, // use_fd
1614 [&no_dedupe_size](const OatFile& o) {
1615 no_dedupe_size = o.Size();
1616 }));
Andreas Gampecac31ad2017-11-06 20:01:17 -08001617
1618 size_t dedupe_size = 0;
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001619 ASSERT_TRUE(GenerateOdexForTest(dex->GetLocation(),
1620 base_oat_name,
1621 CompilerFilter::Filter::kSpeed,
1622 { "--deduplicate-code=true" },
1623 true, // expect_success
1624 false, // use_fd
1625 [&dedupe_size](const OatFile& o) {
1626 dedupe_size = o.Size();
1627 }));
Andreas Gampecac31ad2017-11-06 20:01:17 -08001628
1629 EXPECT_LT(dedupe_size, no_dedupe_size);
1630}
1631
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00001632TEST_F(Dex2oatTest, UncompressedTest) {
1633 std::unique_ptr<const DexFile> dex(OpenTestDexFile("MainUncompressed"));
1634 std::string out_dir = GetScratchDir();
1635 const std::string base_oat_name = out_dir + "/base.oat";
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001636 ASSERT_TRUE(GenerateOdexForTest(dex->GetLocation(),
1637 base_oat_name,
1638 CompilerFilter::Filter::kQuicken,
1639 { },
1640 true, // expect_success
1641 false, // use_fd
1642 [](const OatFile& o) {
1643 CHECK(!o.ContainsDexCode());
1644 }));
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00001645}
1646
Mathieu Chartier700a9852018-02-06 18:27:38 -08001647TEST_F(Dex2oatTest, EmptyUncompressedDexTest) {
1648 std::string out_dir = GetScratchDir();
1649 const std::string base_oat_name = out_dir + "/base.oat";
1650 std::string error_msg;
1651 int status = GenerateOdexForTestWithStatus(
1652 { GetTestDexFileName("MainEmptyUncompressed") },
1653 base_oat_name,
1654 CompilerFilter::Filter::kQuicken,
1655 &error_msg,
1656 { },
1657 /*use_fd*/ false);
1658 // Expect to fail with code 1 and not SIGSEGV or SIGABRT.
1659 ASSERT_TRUE(WIFEXITED(status));
1660 ASSERT_EQ(WEXITSTATUS(status), 1) << error_msg;
1661}
1662
Mathieu Chartier05f90d12018-02-07 13:47:17 -08001663// Dex file that has duplicate methods have different code items and debug info.
1664static const char kDuplicateMethodInputDex[] =
1665 "ZGV4CjAzOQDEy8VPdj4qHpgPYFWtLCtOykfFP4kB8tGYDAAAcAAAAHhWNBIAAAAAAAAAANALAABI"
1666 "AAAAcAAAAA4AAACQAQAABQAAAMgBAAANAAAABAIAABkAAABsAgAABAAAADQDAADgCAAAuAMAADgI"
1667 "AABCCAAASggAAE8IAABcCAAAaggAAHkIAACICAAAlggAAKQIAACyCAAAwAgAAM4IAADcCAAA6ggA"
1668 "APgIAAD7CAAA/wgAABcJAAAuCQAARQkAAFQJAAB4CQAAmAkAALsJAADSCQAA5gkAAPoJAAAVCgAA"
1669 "KQoAADsKAABCCgAASgoAAFIKAABbCgAAZAoAAGwKAAB0CgAAfAoAAIQKAACMCgAAlAoAAJwKAACk"
1670 "CgAArQoAALcKAADACgAAwwoAAMcKAADcCgAA6QoAAPEKAAD3CgAA/QoAAAMLAAAJCwAAEAsAABcL"
1671 "AAAdCwAAIwsAACkLAAAvCwAANQsAADsLAABBCwAARwsAAE0LAABSCwAAWwsAAF4LAABoCwAAbwsA"
1672 "ABEAAAASAAAAEwAAABQAAAAVAAAAFgAAABcAAAAYAAAAGQAAABoAAAAbAAAAHAAAAC4AAAAwAAAA"
1673 "DwAAAAkAAAAAAAAAEAAAAAoAAACoBwAALgAAAAwAAAAAAAAALwAAAAwAAACoBwAALwAAAAwAAACw"
1674 "BwAAAgAJADUAAAACAAkANgAAAAIACQA3AAAAAgAJADgAAAACAAkAOQAAAAIACQA6AAAAAgAJADsA"
1675 "AAACAAkAPAAAAAIACQA9AAAAAgAJAD4AAAACAAkAPwAAAAIACQBAAAAACwAHAEIAAAAAAAIAAQAA"
1676 "AAAAAwAeAAAAAQACAAEAAAABAAMAHgAAAAIAAgAAAAAAAgACAAEAAAADAAIAAQAAAAMAAgAfAAAA"
1677 "AwACACAAAAADAAIAIQAAAAMAAgAiAAAAAwACACMAAAADAAIAJAAAAAMAAgAlAAAAAwACACYAAAAD"
1678 "AAIAJwAAAAMAAgAoAAAAAwACACkAAAADAAIAKgAAAAMABAA0AAAABwADAEMAAAAIAAIAAQAAAAoA"
1679 "AgABAAAACgABADIAAAAKAAAARQAAAAAAAAAAAAAACAAAAAAAAAAdAAAAaAcAALYHAAAAAAAAAQAA"
1680 "AAAAAAAIAAAAAAAAAB0AAAB4BwAAxAcAAAAAAAACAAAAAAAAAAgAAAAAAAAAHQAAAIgHAADSBwAA"
1681 "AAAAAAMAAAAAAAAACAAAAAAAAAAdAAAAmAcAAPoHAAAAAAAAAAAAAAEAAAAAAAAArAYAADEAAAAa"
1682 "AAMAaQAAABoABABpAAEAGgAHAGkABAAaAAgAaQAFABoACQBpAAYAGgAKAGkABwAaAAsAaQAIABoA"
1683 "DABpAAkAGgANAGkACgAaAA4AaQALABoABQBpAAIAGgAGAGkAAwAOAAAAAQABAAEAAACSBgAABAAA"
1684 "AHAQFQAAAA4ABAABAAIAAACWBgAAFwAAAGIADAAiAQoAcBAWAAEAGgICAG4gFwAhAG4gFwAxAG4Q"
1685 "GAABAAwBbiAUABAADgAAAAEAAQABAAAAngYAAAQAAABwEBUAAAAOAAIAAQACAAAAogYAAAYAAABi"
1686 "AAwAbiAUABAADgABAAEAAQAAAKgGAAAEAAAAcBAVAAAADgABAAEAAQAAALsGAAAEAAAAcBAVAAAA"
1687 "DgABAAAAAQAAAL8GAAAGAAAAYgAAAHEQAwAAAA4AAQAAAAEAAADEBgAABgAAAGIAAQBxEAMAAAAO"
1688 "AAEAAAABAAAA8QYAAAYAAABiAAIAcRABAAAADgABAAAAAQAAAPYGAAAGAAAAYgADAHEQAwAAAA4A"
1689 "AQAAAAEAAADJBgAABgAAAGIABABxEAMAAAAOAAEAAAABAAAAzgYAAAYAAABiAAEAcRADAAAADgAB"
1690 "AAAAAQAAANMGAAAGAAAAYgAGAHEQAwAAAA4AAQAAAAEAAADYBgAABgAAAGIABwBxEAMAAAAOAAEA"
1691 "AAABAAAA3QYAAAYAAABiAAgAcRABAAAADgABAAAAAQAAAOIGAAAGAAAAYgAJAHEQAwAAAA4AAQAA"
1692 "AAEAAADnBgAABgAAAGIACgBxEAMAAAAOAAEAAAABAAAA7AYAAAYAAABiAAsAcRABAAAADgABAAEA"
1693 "AAAAAPsGAAAlAAAAcQAHAAAAcQAIAAAAcQALAAAAcQAMAAAAcQANAAAAcQAOAAAAcQAPAAAAcQAQ"
1694 "AAAAcQARAAAAcQASAAAAcQAJAAAAcQAKAAAADgAnAA4AKQFFDgEWDwAhAA4AIwFFDloAEgAOABMA"
1695 "DktLS0tLS0tLS0tLABEADgAuAA5aADIADloANgAOWgA6AA5aAD4ADloAQgAOWgBGAA5aAEoADloA"
1696 "TgAOWgBSAA5aAFYADloAWgAOWgBeATQOPDw8PDw8PDw8PDw8AAIEAUYYAwIFAjEECEEXLAIFAjEE"
1697 "CEEXKwIFAjEECEEXLQIGAUYcAxgAGAEYAgAAAAIAAAAMBwAAEgcAAAIAAAAMBwAAGwcAAAIAAAAM"
1698 "BwAAJAcAAAEAAAAtBwAAPAcAAAAAAAAAAAAAAAAAAEgHAAAAAAAAAAAAAAAAAABUBwAAAAAAAAAA"
1699 "AAAAAAAAYAcAAAAAAAAAAAAAAAAAAAEAAAAJAAAAAQAAAA0AAAACAACAgASsCAEIxAgAAAIAAoCA"
1700 "BIQJAQicCQwAAgAACQEJAQkBCQEJAQkBCQEJAQkBCQEJAQkEiIAEuAcBgIAEuAkAAA4ABoCABNAJ"
1701 "AQnoCQAJhAoACaAKAAm8CgAJ2AoACfQKAAmQCwAJrAsACcgLAAnkCwAJgAwACZwMAAm4DAg8Y2xp"
1702 "bml0PgAGPGluaXQ+AANBQUEAC0hlbGxvIFdvcmxkAAxIZWxsbyBXb3JsZDEADUhlbGxvIFdvcmxk"
1703 "MTAADUhlbGxvIFdvcmxkMTEADEhlbGxvIFdvcmxkMgAMSGVsbG8gV29ybGQzAAxIZWxsbyBXb3Js"
1704 "ZDQADEhlbGxvIFdvcmxkNQAMSGVsbG8gV29ybGQ2AAxIZWxsbyBXb3JsZDcADEhlbGxvIFdvcmxk"
1705 "OAAMSGVsbG8gV29ybGQ5AAFMAAJMTAAWTE1hbnlNZXRob2RzJFByaW50ZXIyOwAVTE1hbnlNZXRo"
1706 "b2RzJFByaW50ZXI7ABVMTWFueU1ldGhvZHMkU3RyaW5nczsADUxNYW55TWV0aG9kczsAIkxkYWx2"
1707 "aWsvYW5ub3RhdGlvbi9FbmNsb3NpbmdDbGFzczsAHkxkYWx2aWsvYW5ub3RhdGlvbi9Jbm5lckNs"
1708 "YXNzOwAhTGRhbHZpay9hbm5vdGF0aW9uL01lbWJlckNsYXNzZXM7ABVMamF2YS9pby9QcmludFN0"
1709 "cmVhbTsAEkxqYXZhL2xhbmcvT2JqZWN0OwASTGphdmEvbGFuZy9TdHJpbmc7ABlMamF2YS9sYW5n"
1710 "L1N0cmluZ0J1aWxkZXI7ABJMamF2YS9sYW5nL1N5c3RlbTsAEE1hbnlNZXRob2RzLmphdmEABVBy"
1711 "aW50AAZQcmludDAABlByaW50MQAHUHJpbnQxMAAHUHJpbnQxMQAGUHJpbnQyAAZQcmludDMABlBy"
1712 "aW50NAAGUHJpbnQ1AAZQcmludDYABlByaW50NwAGUHJpbnQ4AAZQcmludDkAB1ByaW50ZXIACFBy"
1713 "aW50ZXIyAAdTdHJpbmdzAAFWAAJWTAATW0xqYXZhL2xhbmcvU3RyaW5nOwALYWNjZXNzRmxhZ3MA"
1714 "BmFwcGVuZAAEYXJncwAEbWFpbgAEbXNnMAAEbXNnMQAFbXNnMTAABW1zZzExAARtc2cyAARtc2cz"
1715 "AARtc2c0AARtc2c1AARtc2c2AARtc2c3AARtc2c4AARtc2c5AARuYW1lAANvdXQAB3ByaW50bG4A"
1716 "AXMACHRvU3RyaW5nAAV2YWx1ZQBffn5EOHsibWluLWFwaSI6MTAwMDAsInNoYS0xIjoiZmViODZj"
1717 "MDA2ZWZhY2YxZDc5ODRiODVlMTc5MGZlZjdhNzY3YWViYyIsInZlcnNpb24iOiJ2MS4xLjUtZGV2"
1718 "In0AEAAAAAAAAAABAAAAAAAAAAEAAABIAAAAcAAAAAIAAAAOAAAAkAEAAAMAAAAFAAAAyAEAAAQA"
1719 "AAANAAAABAIAAAUAAAAZAAAAbAIAAAYAAAAEAAAANAMAAAEgAAAUAAAAuAMAAAMgAAAUAAAAkgYA"
1720 "AAQgAAAFAAAADAcAAAMQAAAEAAAAOQcAAAYgAAAEAAAAaAcAAAEQAAACAAAAqAcAAAAgAAAEAAAA"
1721 "tgcAAAIgAABIAAAAOAgAAAAQAAABAAAA0AsAAAAAAAA=";
1722
1723static void WriteBase64ToFile(const char* base64, File* file) {
1724 // Decode base64.
1725 CHECK(base64 != nullptr);
1726 size_t length;
1727 std::unique_ptr<uint8_t[]> bytes(DecodeBase64(base64, &length));
1728 CHECK(bytes != nullptr);
1729 if (!file->WriteFully(bytes.get(), length)) {
1730 PLOG(FATAL) << "Failed to write base64 as file";
1731 }
1732}
1733
1734TEST_F(Dex2oatTest, CompactDexGenerationFailure) {
1735 ScratchFile temp_dex;
1736 WriteBase64ToFile(kDuplicateMethodInputDex, temp_dex.GetFile());
1737 std::string out_dir = GetScratchDir();
1738 const std::string oat_filename = out_dir + "/base.oat";
1739 // The dex won't pass the method verifier, only use the verify filter.
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001740 ASSERT_TRUE(GenerateOdexForTest(temp_dex.GetFilename(),
1741 oat_filename,
1742 CompilerFilter::Filter::kVerify,
1743 { },
1744 true, // expect_success
1745 false, // use_fd
1746 [](const OatFile& o) {
1747 CHECK(o.ContainsDexCode());
1748 }));
Mathieu Chartier05f90d12018-02-07 13:47:17 -08001749 // Open our generated oat file.
1750 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001751 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01001752 oat_filename.c_str(),
Mathieu Chartier05f90d12018-02-07 13:47:17 -08001753 oat_filename.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001754 /*executable=*/ false,
1755 /*low_4gb=*/ false,
Mathieu Chartier05f90d12018-02-07 13:47:17 -08001756 temp_dex.GetFilename().c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001757 /*reservation=*/ nullptr,
Mathieu Chartier05f90d12018-02-07 13:47:17 -08001758 &error_msg));
1759 ASSERT_TRUE(odex_file != nullptr);
1760 std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
1761 ASSERT_EQ(oat_dex_files.size(), 1u);
1762 // The dexes should have failed to convert to compact dex.
1763 for (const OatDexFile* oat_dex : oat_dex_files) {
1764 std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1765 ASSERT_TRUE(dex_file != nullptr) << error_msg;
1766 ASSERT_TRUE(!dex_file->IsCompactDexFile());
1767 }
1768}
1769
Mathieu Chartiercda83be2018-03-01 23:55:55 -08001770TEST_F(Dex2oatTest, CompactDexGenerationFailureMultiDex) {
1771 // Create a multidex file with only one dex that gets rejected for cdex conversion.
1772 ScratchFile apk_file;
1773 {
Andreas Gampedfcd82c2018-10-16 20:22:37 -07001774 FILE* file = fdopen(DupCloexec(apk_file.GetFd()), "w+b");
Mathieu Chartiercda83be2018-03-01 23:55:55 -08001775 ZipWriter writer(file);
1776 // Add vdex to zip.
1777 writer.StartEntry("classes.dex", ZipWriter::kCompress);
1778 size_t length = 0u;
1779 std::unique_ptr<uint8_t[]> bytes(DecodeBase64(kDuplicateMethodInputDex, &length));
1780 ASSERT_GE(writer.WriteBytes(&bytes[0], length), 0);
1781 writer.FinishEntry();
1782 writer.StartEntry("classes2.dex", ZipWriter::kCompress);
1783 std::unique_ptr<const DexFile> dex(OpenTestDexFile("ManyMethods"));
1784 ASSERT_GE(writer.WriteBytes(dex->Begin(), dex->Size()), 0);
1785 writer.FinishEntry();
1786 writer.Finish();
1787 ASSERT_EQ(apk_file.GetFile()->Flush(), 0);
1788 }
Andreas Gampebc802de2018-06-20 17:24:11 -07001789 const std::string& dex_location = apk_file.GetFilename();
Mathieu Chartiercda83be2018-03-01 23:55:55 -08001790 const std::string odex_location = GetOdexDir() + "/output.odex";
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001791 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1792 odex_location,
1793 CompilerFilter::kQuicken,
1794 { "--compact-dex-level=fast" },
1795 true));
Mathieu Chartiercda83be2018-03-01 23:55:55 -08001796}
1797
Andreas Gampe25419b52018-02-08 21:30:26 -08001798TEST_F(Dex2oatTest, StderrLoggerOutput) {
1799 std::string dex_location = GetScratchDir() + "/Dex2OatStderrLoggerTest.jar";
1800 std::string odex_location = GetOdexDir() + "/Dex2OatStderrLoggerTest.odex";
1801
1802 // Test file doesn't matter.
1803 Copy(GetDexSrc1(), dex_location);
1804
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001805 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1806 odex_location,
1807 CompilerFilter::kQuicken,
1808 { "--runtime-arg", "-Xuse-stderr-logger" },
1809 true));
Andreas Gampe25419b52018-02-08 21:30:26 -08001810 // Look for some random part of dex2oat logging. With the stderr logger this should be captured,
1811 // even on device.
1812 EXPECT_NE(std::string::npos, output_.find("dex2oat took"));
1813}
1814
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001815TEST_F(Dex2oatTest, VerifyCompilationReason) {
1816 std::string dex_location = GetScratchDir() + "/Dex2OatCompilationReason.jar";
1817 std::string odex_location = GetOdexDir() + "/Dex2OatCompilationReason.odex";
1818
1819 // Test file doesn't matter.
1820 Copy(GetDexSrc1(), dex_location);
1821
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001822 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1823 odex_location,
1824 CompilerFilter::kVerify,
1825 { "--compilation-reason=install" },
1826 true));
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001827 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001828 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01001829 odex_location.c_str(),
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001830 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001831 /*executable=*/ false,
1832 /*low_4gb=*/ false,
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001833 dex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001834 /*reservation=*/ nullptr,
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001835 &error_msg));
1836 ASSERT_TRUE(odex_file != nullptr);
1837 ASSERT_STREQ("install", odex_file->GetCompilationReason());
1838}
1839
1840TEST_F(Dex2oatTest, VerifyNoCompilationReason) {
1841 std::string dex_location = GetScratchDir() + "/Dex2OatNoCompilationReason.jar";
1842 std::string odex_location = GetOdexDir() + "/Dex2OatNoCompilationReason.odex";
1843
1844 // Test file doesn't matter.
1845 Copy(GetDexSrc1(), dex_location);
1846
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001847 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1848 odex_location,
1849 CompilerFilter::kVerify,
1850 {},
1851 true));
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001852 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001853 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01001854 odex_location.c_str(),
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001855 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001856 /*executable=*/ false,
1857 /*low_4gb=*/ false,
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001858 dex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001859 /*reservation=*/ nullptr,
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001860 &error_msg));
1861 ASSERT_TRUE(odex_file != nullptr);
1862 ASSERT_EQ(nullptr, odex_file->GetCompilationReason());
1863}
1864
Mathieu Chartier792111c2018-02-15 13:02:15 -08001865TEST_F(Dex2oatTest, DontExtract) {
1866 std::unique_ptr<const DexFile> dex(OpenTestDexFile("ManyMethods"));
1867 std::string error_msg;
1868 const std::string out_dir = GetScratchDir();
1869 const std::string dex_location = dex->GetLocation();
1870 const std::string odex_location = out_dir + "/base.oat";
1871 const std::string vdex_location = out_dir + "/base.vdex";
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001872 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1873 odex_location,
1874 CompilerFilter::Filter::kVerify,
1875 { "--copy-dex-files=false" },
1876 true, // expect_success
1877 false, // use_fd
1878 [](const OatFile&) {}));
Mathieu Chartier792111c2018-02-15 13:02:15 -08001879 {
1880 // Check the vdex doesn't have dex.
1881 std::unique_ptr<VdexFile> vdex(VdexFile::Open(vdex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001882 /*writable=*/ false,
1883 /*low_4gb=*/ false,
1884 /*unquicken=*/ false,
Mathieu Chartier792111c2018-02-15 13:02:15 -08001885 &error_msg));
1886 ASSERT_TRUE(vdex != nullptr);
Nicolas Geoffray3a293552018-03-02 10:52:16 +00001887 EXPECT_FALSE(vdex->HasDexSection()) << output_;
Mathieu Chartier792111c2018-02-15 13:02:15 -08001888 }
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001889 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01001890 odex_location.c_str(),
Mathieu Chartier792111c2018-02-15 13:02:15 -08001891 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001892 /*executable=*/ false,
1893 /*low_4gb=*/ false,
Mathieu Chartier792111c2018-02-15 13:02:15 -08001894 dex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001895 /*reservation=*/ nullptr,
Mathieu Chartier792111c2018-02-15 13:02:15 -08001896 &error_msg));
1897 ASSERT_TRUE(odex_file != nullptr) << dex_location;
1898 std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
1899 ASSERT_EQ(oat_dex_files.size(), 1u);
1900 // Verify that the oat file can still open the dex files.
1901 for (const OatDexFile* oat_dex : oat_dex_files) {
1902 std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1903 ASSERT_TRUE(dex_file != nullptr) << error_msg;
1904 }
1905 // Create a dm file and use it to verify.
1906 // Add produced artifacts to a zip file that doesn't contain the classes.dex.
1907 ScratchFile dm_file;
1908 {
1909 std::unique_ptr<File> vdex_file(OS::OpenFileForReading(vdex_location.c_str()));
1910 ASSERT_TRUE(vdex_file != nullptr);
1911 ASSERT_GT(vdex_file->GetLength(), 0u);
Andreas Gampedfcd82c2018-10-16 20:22:37 -07001912 FILE* file = fdopen(DupCloexec(dm_file.GetFd()), "w+b");
Mathieu Chartier792111c2018-02-15 13:02:15 -08001913 ZipWriter writer(file);
1914 auto write_all_bytes = [&](File* file) {
1915 std::unique_ptr<uint8_t[]> bytes(new uint8_t[file->GetLength()]);
1916 ASSERT_TRUE(file->ReadFully(&bytes[0], file->GetLength()));
1917 ASSERT_GE(writer.WriteBytes(&bytes[0], file->GetLength()), 0);
1918 };
1919 // Add vdex to zip.
1920 writer.StartEntry(VdexFile::kVdexNameInDmFile, ZipWriter::kCompress);
1921 write_all_bytes(vdex_file.get());
1922 writer.FinishEntry();
1923 writer.Finish();
1924 ASSERT_EQ(dm_file.GetFile()->Flush(), 0);
1925 }
1926
Mathieu Chartier2eabc612018-05-25 14:31:16 -07001927 auto generate_and_check = [&](CompilerFilter::Filter filter) {
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001928 output_.clear();
1929 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1930 odex_location,
1931 filter,
1932 { "--dump-timings",
1933 "--dm-file=" + dm_file.GetFilename(),
1934 // Pass -Xuse-stderr-logger have dex2oat output in output_ on
1935 // target.
1936 "--runtime-arg",
1937 "-Xuse-stderr-logger" },
1938 true, // expect_success
1939 false, // use_fd
1940 [](const OatFile& o) {
1941 CHECK(o.ContainsDexCode());
1942 }));
Mathieu Chartier2eabc612018-05-25 14:31:16 -07001943 // Check the output for "Fast verify", this is printed from --dump-timings.
1944 std::istringstream iss(output_);
1945 std::string line;
1946 bool found_fast_verify = false;
1947 const std::string kFastVerifyString = "Fast Verify";
1948 while (std::getline(iss, line) && !found_fast_verify) {
1949 found_fast_verify = found_fast_verify || line.find(kFastVerifyString) != std::string::npos;
1950 }
1951 EXPECT_TRUE(found_fast_verify) << "Expected to find " << kFastVerifyString << "\n" << output_;
1952 };
1953
Mathieu Chartier792111c2018-02-15 13:02:15 -08001954 // Generate a quickened dex by using the input dm file to verify.
Mathieu Chartier2eabc612018-05-25 14:31:16 -07001955 generate_and_check(CompilerFilter::Filter::kQuicken);
1956 // Use verify compiler filter to sanity check that FastVerify works for that filter too.
1957 generate_and_check(CompilerFilter::Filter::kVerify);
Mathieu Chartier792111c2018-02-15 13:02:15 -08001958}
1959
Mathieu Chartier2daa1342018-02-20 16:19:28 -08001960// Test that dex files with quickened opcodes aren't dequickened.
1961TEST_F(Dex2oatTest, QuickenedInput) {
1962 std::string error_msg;
1963 ScratchFile temp_dex;
1964 MutateDexFile(temp_dex.GetFile(), GetTestDexFileName("ManyMethods"), [] (DexFile* dex) {
1965 bool mutated_successfully = false;
1966 // Change the dex instructions to make an opcode that spans past the end of the code item.
Mathieu Chartier2242ef12018-07-23 18:14:13 -07001967 for (ClassAccessor accessor : dex->GetClasses()) {
1968 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
1969 CodeItemInstructionAccessor instructions = method.GetInstructions();
1970 // Make a quickened instruction that doesn't run past the end of the code item.
1971 if (instructions.InsnsSizeInCodeUnits() > 2) {
1972 const_cast<Instruction&>(instructions.InstructionAt(0)).SetOpcode(
1973 Instruction::IGET_BYTE_QUICK);
1974 mutated_successfully = true;
Mathieu Chartier2daa1342018-02-20 16:19:28 -08001975 }
Mathieu Chartier2daa1342018-02-20 16:19:28 -08001976 }
1977 }
1978 CHECK(mutated_successfully)
1979 << "Failed to find candidate code item with only one code unit in last instruction.";
1980 });
1981
Andreas Gampebc802de2018-06-20 17:24:11 -07001982 const std::string& dex_location = temp_dex.GetFilename();
Mathieu Chartier2daa1342018-02-20 16:19:28 -08001983 std::string odex_location = GetOdexDir() + "/quickened.odex";
1984 std::string vdex_location = GetOdexDir() + "/quickened.vdex";
1985 std::unique_ptr<File> vdex_output(OS::CreateEmptyFile(vdex_location.c_str()));
1986 // Quicken the dex
1987 {
1988 std::string input_vdex = "--input-vdex-fd=-1";
1989 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_output->Fd());
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001990 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1991 odex_location,
1992 CompilerFilter::kQuicken,
1993 // Disable cdex since we want to compare against the original
1994 // dex file after unquickening.
1995 { input_vdex, output_vdex, kDisableCompactDex },
1996 /* expect_success= */ true,
1997 /* use_fd= */ true));
Mathieu Chartier2daa1342018-02-20 16:19:28 -08001998 }
1999 // Unquicken by running the verify compiler filter on the vdex file and verify it matches.
2000 std::string odex_location2 = GetOdexDir() + "/unquickened.odex";
2001 std::string vdex_location2 = GetOdexDir() + "/unquickened.vdex";
2002 std::unique_ptr<File> vdex_unquickened(OS::CreateEmptyFile(vdex_location2.c_str()));
2003 {
2004 std::string input_vdex = StringPrintf("--input-vdex-fd=%d", vdex_output->Fd());
2005 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_unquickened->Fd());
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002006 ASSERT_TRUE(GenerateOdexForTest(dex_location,
2007 odex_location2,
2008 CompilerFilter::kVerify,
2009 // Disable cdex to avoid needing to write out the shared
2010 // section.
2011 { input_vdex, output_vdex, kDisableCompactDex },
2012 /* expect_success= */ true,
2013 /* use_fd= */ true));
Mathieu Chartier2daa1342018-02-20 16:19:28 -08002014 }
2015 ASSERT_EQ(vdex_unquickened->Flush(), 0) << "Could not flush and close vdex file";
2016 ASSERT_TRUE(success_);
2017 {
2018 // Check that hte vdex has one dex and compare it to the original one.
2019 std::unique_ptr<VdexFile> vdex(VdexFile::Open(vdex_location2.c_str(),
2020 /*writable*/ false,
2021 /*low_4gb*/ false,
2022 /*unquicken*/ false,
2023 &error_msg));
2024 std::vector<std::unique_ptr<const DexFile>> dex_files;
2025 bool result = vdex->OpenAllDexFiles(&dex_files, &error_msg);
2026 ASSERT_TRUE(result) << error_msg;
2027 ASSERT_EQ(dex_files.size(), 1u) << error_msg;
2028 ScratchFile temp;
2029 ASSERT_TRUE(temp.GetFile()->WriteFully(dex_files[0]->Begin(), dex_files[0]->Size()));
2030 ASSERT_EQ(temp.GetFile()->Flush(), 0) << "Could not flush extracted dex";
2031 EXPECT_EQ(temp.GetFile()->Compare(temp_dex.GetFile()), 0);
2032 }
2033 ASSERT_EQ(vdex_output->FlushCloseOrErase(), 0) << "Could not flush and close";
2034 ASSERT_EQ(vdex_unquickened->FlushCloseOrErase(), 0) << "Could not flush and close";
2035}
2036
Mathieu Chartierd45863a2018-03-21 18:16:36 -07002037// Test that compact dex generation with invalid dex files doesn't crash dex2oat. b/75970654
2038TEST_F(Dex2oatTest, CompactDexInvalidSource) {
2039 ScratchFile invalid_dex;
2040 {
Andreas Gampedfcd82c2018-10-16 20:22:37 -07002041 FILE* file = fdopen(DupCloexec(invalid_dex.GetFd()), "w+b");
Mathieu Chartierd45863a2018-03-21 18:16:36 -07002042 ZipWriter writer(file);
2043 writer.StartEntry("classes.dex", ZipWriter::kAlign32);
2044 DexFile::Header header = {};
2045 StandardDexFile::WriteMagic(header.magic_);
2046 StandardDexFile::WriteCurrentVersion(header.magic_);
2047 header.file_size_ = 4 * KB;
2048 header.data_size_ = 4 * KB;
2049 header.data_off_ = 10 * MB;
2050 header.map_off_ = 10 * MB;
2051 header.class_defs_off_ = 10 * MB;
2052 header.class_defs_size_ = 10000;
2053 ASSERT_GE(writer.WriteBytes(&header, sizeof(header)), 0);
2054 writer.FinishEntry();
2055 writer.Finish();
2056 ASSERT_EQ(invalid_dex.GetFile()->Flush(), 0);
2057 }
Andreas Gampebc802de2018-06-20 17:24:11 -07002058 const std::string& dex_location = invalid_dex.GetFilename();
Mathieu Chartierd45863a2018-03-21 18:16:36 -07002059 const std::string odex_location = GetOdexDir() + "/output.odex";
2060 std::string error_msg;
2061 int status = GenerateOdexForTestWithStatus(
2062 {dex_location},
2063 odex_location,
2064 CompilerFilter::kQuicken,
2065 &error_msg,
2066 { "--compact-dex-level=fast" });
2067 ASSERT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) != 0) << status << " " << output_;
2068}
2069
Mathieu Chartier14e7bad2018-03-22 14:33:20 -07002070// Test that dex2oat with a CompactDex file in the APK fails.
2071TEST_F(Dex2oatTest, CompactDexInZip) {
2072 CompactDexFile::Header header = {};
2073 CompactDexFile::WriteMagic(header.magic_);
2074 CompactDexFile::WriteCurrentVersion(header.magic_);
2075 header.file_size_ = sizeof(CompactDexFile::Header);
2076 header.data_off_ = 10 * MB;
2077 header.map_off_ = 10 * MB;
2078 header.class_defs_off_ = 10 * MB;
2079 header.class_defs_size_ = 10000;
2080 // Create a zip containing the invalid dex.
2081 ScratchFile invalid_dex_zip;
2082 {
Andreas Gampedfcd82c2018-10-16 20:22:37 -07002083 FILE* file = fdopen(DupCloexec(invalid_dex_zip.GetFd()), "w+b");
Mathieu Chartier14e7bad2018-03-22 14:33:20 -07002084 ZipWriter writer(file);
2085 writer.StartEntry("classes.dex", ZipWriter::kCompress);
2086 ASSERT_GE(writer.WriteBytes(&header, sizeof(header)), 0);
2087 writer.FinishEntry();
2088 writer.Finish();
2089 ASSERT_EQ(invalid_dex_zip.GetFile()->Flush(), 0);
2090 }
2091 // Create the dex file directly.
2092 ScratchFile invalid_dex;
2093 {
2094 ASSERT_GE(invalid_dex.GetFile()->WriteFully(&header, sizeof(header)), 0);
2095 ASSERT_EQ(invalid_dex.GetFile()->Flush(), 0);
2096 }
2097 std::string error_msg;
2098 int status = 0u;
2099
2100 status = GenerateOdexForTestWithStatus(
2101 { invalid_dex_zip.GetFilename() },
2102 GetOdexDir() + "/output_apk.odex",
2103 CompilerFilter::kQuicken,
2104 &error_msg,
2105 { "--compact-dex-level=fast" });
2106 ASSERT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) != 0) << status << " " << output_;
2107
2108 status = GenerateOdexForTestWithStatus(
2109 { invalid_dex.GetFilename() },
2110 GetOdexDir() + "/output.odex",
2111 CompilerFilter::kQuicken,
2112 &error_msg,
2113 { "--compact-dex-level=fast" });
2114 ASSERT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) != 0) << status << " " << output_;
2115}
2116
Mathieu Chartierf85b3db2018-04-02 18:16:21 -07002117TEST_F(Dex2oatTest, AppImageNoProfile) {
2118 ScratchFile app_image_file;
2119 const std::string out_dir = GetScratchDir();
2120 const std::string odex_location = out_dir + "/base.odex";
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002121 ASSERT_TRUE(GenerateOdexForTest(GetTestDexFileName("ManyMethods"),
2122 odex_location,
2123 CompilerFilter::Filter::kSpeedProfile,
2124 { "--app-image-fd=" + std::to_string(app_image_file.GetFd()) },
2125 true, // expect_success
2126 false, // use_fd
2127 [](const OatFile&) {}));
Mathieu Chartierf85b3db2018-04-02 18:16:21 -07002128 // Open our generated oat file.
2129 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002130 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01002131 odex_location.c_str(),
Mathieu Chartierf85b3db2018-04-02 18:16:21 -07002132 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002133 /*executable=*/ false,
2134 /*low_4gb=*/ false,
Mathieu Chartierf85b3db2018-04-02 18:16:21 -07002135 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002136 /*reservation=*/ nullptr,
Mathieu Chartierf85b3db2018-04-02 18:16:21 -07002137 &error_msg));
2138 ASSERT_TRUE(odex_file != nullptr);
2139 ImageHeader header = {};
2140 ASSERT_TRUE(app_image_file.GetFile()->PreadFully(
2141 reinterpret_cast<void*>(&header),
2142 sizeof(header),
2143 /*offset*/ 0u)) << app_image_file.GetFile()->GetLength();
2144 EXPECT_GT(header.GetImageSection(ImageHeader::kSectionObjects).Size(), 0u);
2145 EXPECT_EQ(header.GetImageSection(ImageHeader::kSectionArtMethods).Size(), 0u);
2146 EXPECT_EQ(header.GetImageSection(ImageHeader::kSectionArtFields).Size(), 0u);
2147}
2148
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002149TEST_F(Dex2oatTest, AppImageResolveStrings) {
2150 using Hotness = ProfileCompilationInfo::MethodHotness;
2151 // Create a profile with the startup method marked.
2152 ScratchFile profile_file;
2153 std::vector<uint16_t> methods;
Mathieu Chartier22752772018-10-18 14:18:59 -07002154 std::vector<dex::TypeIndex> classes;
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07002155 std::unique_ptr<const DexFile> dex(OpenTestDexFile("StringLiterals"));
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002156 {
Mathieu Chartier22752772018-10-18 14:18:59 -07002157 for (ClassAccessor accessor : dex->GetClasses()) {
2158 if (accessor.GetDescriptor() == std::string("LStringLiterals$StartupClass;")) {
2159 classes.push_back(accessor.GetClassIdx());
2160 }
2161 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
2162 std::string method_name(dex->GetMethodName(dex->GetMethodId(method.GetIndex())));
2163 if (method_name == "startUpMethod") {
2164 methods.push_back(method.GetIndex());
2165 }
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002166 }
2167 }
Mathieu Chartier22752772018-10-18 14:18:59 -07002168 ASSERT_GT(classes.size(), 0u);
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002169 ASSERT_GT(methods.size(), 0u);
2170 // Here, we build the profile from the method lists.
2171 ProfileCompilationInfo info;
Mathieu Chartier22752772018-10-18 14:18:59 -07002172 info.AddClassesForDex(dex.get(), classes.begin(), classes.end());
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002173 info.AddMethodsForDex(Hotness::kFlagStartup, dex.get(), methods.begin(), methods.end());
2174 // Save the profile since we want to use it with dex2oat to produce an oat file.
2175 ASSERT_TRUE(info.Save(profile_file.GetFd()));
2176 }
2177 const std::string out_dir = GetScratchDir();
2178 const std::string odex_location = out_dir + "/base.odex";
2179 const std::string app_image_location = out_dir + "/base.art";
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002180 ASSERT_TRUE(GenerateOdexForTest(GetTestDexFileName("StringLiterals"),
2181 odex_location,
2182 CompilerFilter::Filter::kSpeedProfile,
2183 { "--app-image-file=" + app_image_location,
2184 "--resolve-startup-const-strings=true",
2185 "--profile-file=" + profile_file.GetFilename()},
2186 /* expect_success= */ true,
2187 /* use_fd= */ false,
2188 [](const OatFile&) {}));
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002189 // Open our generated oat file.
2190 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002191 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002192 odex_location.c_str(),
2193 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002194 /*executable=*/ false,
2195 /*low_4gb=*/ false,
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002196 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002197 /*reservation=*/ nullptr,
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002198 &error_msg));
2199 ASSERT_TRUE(odex_file != nullptr);
2200 // Check the strings in the app image intern table only contain the "startup" strigs.
2201 {
2202 ScopedObjectAccess soa(Thread::Current());
2203 std::unique_ptr<gc::space::ImageSpace> space =
2204 gc::space::ImageSpace::CreateFromAppImage(app_image_location.c_str(),
2205 odex_file.get(),
2206 &error_msg);
2207 ASSERT_TRUE(space != nullptr) << error_msg;
2208 std::set<std::string> seen;
2209 InternTable intern_table;
2210 intern_table.AddImageStringsToTable(space.get(), [&](InternTable::UnorderedSet& interns)
2211 REQUIRES_SHARED(Locks::mutator_lock_) {
2212 for (const GcRoot<mirror::String>& str : interns) {
2213 seen.insert(str.Read()->ToModifiedUtf8());
2214 }
2215 });
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07002216 // Ensure that the dex cache has a preresolved string array.
2217 std::set<std::string> preresolved_seen;
2218 bool saw_dexcache = false;
2219 space->GetLiveBitmap()->VisitAllMarked(
2220 [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
2221 if (obj->IsDexCache<kVerifyNone>()) {
2222 ObjPtr<mirror::DexCache> dex_cache = obj->AsDexCache();
2223 GcRoot<mirror::String>* preresolved_strings = dex_cache->GetPreResolvedStrings();
2224 ASSERT_EQ(dex->NumStringIds(), dex_cache->NumPreResolvedStrings());
2225 for (size_t i = 0; i < dex_cache->NumPreResolvedStrings(); ++i) {
2226 ObjPtr<mirror::String> string = preresolved_strings[i].Read<kWithoutReadBarrier>();
2227 if (string != nullptr) {
2228 preresolved_seen.insert(string->ToModifiedUtf8());
2229 }
2230 }
2231 saw_dexcache = true;
2232 }
2233 });
2234 ASSERT_TRUE(saw_dexcache);
2235 // Everything in the preresolved array should also be in the intern table.
2236 for (const std::string& str : preresolved_seen) {
2237 EXPECT_TRUE(seen.find(str) != seen.end());
2238 }
Mathieu Chartier22752772018-10-18 14:18:59 -07002239 // Normal methods
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07002240 EXPECT_TRUE(preresolved_seen.find("Loading ") != preresolved_seen.end());
2241 EXPECT_TRUE(preresolved_seen.find("Starting up") != preresolved_seen.end());
2242 EXPECT_TRUE(preresolved_seen.find("abcd.apk") != preresolved_seen.end());
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002243 EXPECT_TRUE(seen.find("Unexpected error") == seen.end());
2244 EXPECT_TRUE(seen.find("Shutting down!") == seen.end());
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07002245 EXPECT_TRUE(preresolved_seen.find("Unexpected error") == preresolved_seen.end());
2246 EXPECT_TRUE(preresolved_seen.find("Shutting down!") == preresolved_seen.end());
Mathieu Chartier22752772018-10-18 14:18:59 -07002247 // Classes initializers
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07002248 EXPECT_TRUE(preresolved_seen.find("Startup init") != preresolved_seen.end());
Mathieu Chartier22752772018-10-18 14:18:59 -07002249 EXPECT_TRUE(seen.find("Other class init") == seen.end());
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07002250 EXPECT_TRUE(preresolved_seen.find("Other class init") == preresolved_seen.end());
2251 // Expect the sets match.
2252 EXPECT_GE(seen.size(), preresolved_seen.size());
Mathieu Chartier8cc418e2018-10-31 10:54:30 -07002253
2254 // Verify what strings are marked as boot image.
2255 std::set<std::string> boot_image_strings;
2256 std::set<std::string> app_image_strings;
2257
2258 MutexLock mu(Thread::Current(), *Locks::intern_table_lock_);
2259 intern_table.VisitInterns([&](const GcRoot<mirror::String>& root)
2260 REQUIRES_SHARED(Locks::mutator_lock_) {
2261 boot_image_strings.insert(root.Read()->ToModifiedUtf8());
2262 }, /*visit_boot_images=*/true, /*visit_non_boot_images=*/false);
2263 intern_table.VisitInterns([&](const GcRoot<mirror::String>& root)
2264 REQUIRES_SHARED(Locks::mutator_lock_) {
2265 app_image_strings.insert(root.Read()->ToModifiedUtf8());
2266 }, /*visit_boot_images=*/false, /*visit_non_boot_images=*/true);
2267 EXPECT_EQ(boot_image_strings.size(), 0u);
2268 EXPECT_TRUE(app_image_strings == seen);
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002269 }
2270}
2271
2272
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002273TEST_F(Dex2oatClassLoaderContextTest, StoredClassLoaderContext) {
Mathieu Chartierc4440772018-04-16 14:40:56 -07002274 std::vector<std::unique_ptr<const DexFile>> dex_files = OpenTestDexFiles("MultiDex");
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002275 const std::string out_dir = GetScratchDir();
2276 const std::string odex_location = out_dir + "/base.odex";
Mathieu Chartierc4440772018-04-16 14:40:56 -07002277 const std::string valid_context = "PCL[" + dex_files[0]->GetLocation() + "]";
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002278 const std::string stored_context = "PCL[/system/not_real_lib.jar]";
Mathieu Chartierc4440772018-04-16 14:40:56 -07002279 std::string expected_stored_context = "PCL[";
2280 size_t index = 1;
2281 for (const std::unique_ptr<const DexFile>& dex_file : dex_files) {
2282 const bool is_first = index == 1u;
2283 if (!is_first) {
2284 expected_stored_context += ":";
2285 }
2286 expected_stored_context += "/system/not_real_lib.jar";
2287 if (!is_first) {
2288 expected_stored_context += "!classes" + std::to_string(index) + ".dex";
2289 }
2290 expected_stored_context += "*" + std::to_string(dex_file->GetLocationChecksum());
2291 ++index;
2292 }
2293 expected_stored_context += + "]";
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002294 // The class path should not be valid and should fail being stored.
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002295 EXPECT_TRUE(GenerateOdexForTest(GetTestDexFileName("ManyMethods"),
2296 odex_location,
2297 CompilerFilter::Filter::kQuicken,
2298 { "--class-loader-context=" + stored_context },
2299 true, // expect_success
2300 false, // use_fd
2301 [&](const OatFile& oat_file) {
Mathieu Chartierc4440772018-04-16 14:40:56 -07002302 EXPECT_NE(oat_file.GetClassLoaderContext(), stored_context) << output_;
2303 EXPECT_NE(oat_file.GetClassLoaderContext(), valid_context) << output_;
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002304 }));
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002305 // The stored context should match what we expect even though it's invalid.
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002306 EXPECT_TRUE(GenerateOdexForTest(GetTestDexFileName("ManyMethods"),
2307 odex_location,
2308 CompilerFilter::Filter::kQuicken,
2309 { "--class-loader-context=" + valid_context,
2310 "--stored-class-loader-context=" + stored_context },
2311 true, // expect_success
2312 false, // use_fd
2313 [&](const OatFile& oat_file) {
Mathieu Chartierc4440772018-04-16 14:40:56 -07002314 EXPECT_EQ(oat_file.GetClassLoaderContext(), expected_stored_context) << output_;
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002315 }));
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002316}
2317
Andreas Gampee1459ae2016-06-29 09:36:30 -07002318} // namespace art