blob: 1fa21d51fc46bf8b28c7fabe7a1672c7b4f371e5 [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) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700195 Runtime* runtime = Runtime::Current();
196
197 const std::vector<gc::space::ImageSpace*>& image_spaces =
198 runtime->GetHeap()->GetBootImageSpaces();
199 if (image_spaces.empty()) {
200 *error_msg = "No image location found for Dex2Oat.";
201 return false;
202 }
203 std::string image_location = image_spaces[0]->GetImageLocation();
204
205 std::vector<std::string> argv;
206 argv.push_back(runtime->GetCompilerExecutable());
Calin Juravle1ccf6132017-08-02 17:46:53 -0700207
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000208 if (runtime->IsJavaDebuggable()) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700209 argv.push_back("--debuggable");
210 }
211 runtime->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv);
212
213 if (!runtime->IsVerificationEnabled()) {
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100214 argv.push_back("--compiler-filter=assume-verified");
Andreas Gampee1459ae2016-06-29 09:36:30 -0700215 }
216
217 if (runtime->MustRelocateIfPossible()) {
218 argv.push_back("--runtime-arg");
219 argv.push_back("-Xrelocate");
220 } else {
221 argv.push_back("--runtime-arg");
222 argv.push_back("-Xnorelocate");
223 }
224
225 if (!kIsTargetBuild) {
226 argv.push_back("--host");
227 }
228
229 argv.push_back("--boot-image=" + image_location);
230
231 std::vector<std::string> compiler_options = runtime->GetCompilerOptions();
232 argv.insert(argv.end(), compiler_options.begin(), compiler_options.end());
233
234 argv.insert(argv.end(), dex2oat_args.begin(), dex2oat_args.end());
235
236 // We must set --android-root.
237 const char* android_root = getenv("ANDROID_ROOT");
238 CHECK(android_root != nullptr);
239 argv.push_back("--android-root=" + std::string(android_root));
240
Mathieu Chartier9e050df2017-08-09 10:05:47 -0700241 if (kDebugArgs) {
242 std::string all_args;
243 for (const std::string& arg : argv) {
244 all_args += arg + " ";
245 }
246 LOG(ERROR) << all_args;
247 }
248
Andreas Gampe38aa0b52018-07-10 23:26:55 -0700249 // We need dex2oat to actually log things.
250 auto post_fork_fn = []() { return setenv("ANDROID_LOG_TAGS", "*:d", 1) == 0; };
251 ForkAndExecResult res = ForkAndExec(argv, post_fork_fn, &output_);
252 if (res.stage != ForkAndExecResult::kFinished) {
253 *error_msg = strerror(errno);
254 return -1;
Nicolas Geoffray56fe0f02016-06-30 15:07:46 +0100255 }
Andreas Gampe38aa0b52018-07-10 23:26:55 -0700256 success_ = res.StandardSuccess();
257 return res.status_code;
Andreas Gampee1459ae2016-06-29 09:36:30 -0700258 }
259
260 std::string output_ = "";
261 std::string error_msg_ = "";
262 bool success_ = false;
263};
264
265class Dex2oatSwapTest : public Dex2oatTest {
266 protected:
267 void RunTest(bool use_fd, bool expect_use, const std::vector<std::string>& extra_args = {}) {
268 std::string dex_location = GetScratchDir() + "/Dex2OatSwapTest.jar";
269 std::string odex_location = GetOdexDir() + "/Dex2OatSwapTest.odex";
270
Andreas Gampe7adeda82016-07-25 08:27:35 -0700271 Copy(GetTestDexFileName(), dex_location);
Andreas Gampee1459ae2016-06-29 09:36:30 -0700272
273 std::vector<std::string> copy(extra_args);
274
275 std::unique_ptr<ScratchFile> sf;
276 if (use_fd) {
277 sf.reset(new ScratchFile());
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800278 copy.push_back(android::base::StringPrintf("--swap-fd=%d", sf->GetFd()));
Andreas Gampee1459ae2016-06-29 09:36:30 -0700279 } else {
280 std::string swap_location = GetOdexDir() + "/Dex2OatSwapTest.odex.swap";
281 copy.push_back("--swap-file=" + swap_location);
282 }
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800283 ASSERT_TRUE(GenerateOdexForTest(dex_location, odex_location, CompilerFilter::kSpeed, copy));
Andreas Gampee1459ae2016-06-29 09:36:30 -0700284
285 CheckValidity();
286 ASSERT_TRUE(success_);
287 CheckResult(expect_use);
288 }
289
Andreas Gampe7adeda82016-07-25 08:27:35 -0700290 virtual std::string GetTestDexFileName() {
Vladimir Marko15357702017-02-09 10:37:31 +0000291 return Dex2oatEnvironmentTest::GetTestDexFileName("VerifierDeps");
Andreas Gampe7adeda82016-07-25 08:27:35 -0700292 }
293
294 virtual void CheckResult(bool expect_use) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700295 if (kIsTargetBuild) {
296 CheckTargetResult(expect_use);
297 } else {
298 CheckHostResult(expect_use);
299 }
300 }
301
Andreas Gampe7adeda82016-07-25 08:27:35 -0700302 virtual void CheckTargetResult(bool expect_use ATTRIBUTE_UNUSED) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700303 // TODO: Ignore for now, as we won't capture any output (it goes to the logcat). We may do
304 // something for variants with file descriptor where we can control the lifetime of
305 // the swap file and thus take a look at it.
306 }
307
Andreas Gampe7adeda82016-07-25 08:27:35 -0700308 virtual void CheckHostResult(bool expect_use) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700309 if (!kIsTargetBuild) {
310 if (expect_use) {
311 EXPECT_NE(output_.find("Large app, accepted running with swap."), std::string::npos)
312 << output_;
313 } else {
314 EXPECT_EQ(output_.find("Large app, accepted running with swap."), std::string::npos)
315 << output_;
316 }
317 }
318 }
319
320 // Check whether the dex2oat run was really successful.
Andreas Gampe7adeda82016-07-25 08:27:35 -0700321 virtual void CheckValidity() {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700322 if (kIsTargetBuild) {
323 CheckTargetValidity();
324 } else {
325 CheckHostValidity();
326 }
327 }
328
Andreas Gampe7adeda82016-07-25 08:27:35 -0700329 virtual void CheckTargetValidity() {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700330 // TODO: Ignore for now, as we won't capture any output (it goes to the logcat). We may do
331 // something for variants with file descriptor where we can control the lifetime of
332 // the swap file and thus take a look at it.
333 }
334
335 // On the host, we can get the dex2oat output. Here, look for "dex2oat took."
Andreas Gampe7adeda82016-07-25 08:27:35 -0700336 virtual void CheckHostValidity() {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700337 EXPECT_NE(output_.find("dex2oat took"), std::string::npos) << output_;
338 }
339};
340
341TEST_F(Dex2oatSwapTest, DoNotUseSwapDefaultSingleSmall) {
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100342 RunTest(/*use_fd=*/ false, /*expect_use=*/ false);
343 RunTest(/*use_fd=*/ true, /*expect_use=*/ false);
Andreas Gampee1459ae2016-06-29 09:36:30 -0700344}
345
346TEST_F(Dex2oatSwapTest, DoNotUseSwapSingle) {
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100347 RunTest(/*use_fd=*/ false, /*expect_use=*/ false, { "--swap-dex-size-threshold=0" });
348 RunTest(/*use_fd=*/ true, /*expect_use=*/ false, { "--swap-dex-size-threshold=0" });
Andreas Gampee1459ae2016-06-29 09:36:30 -0700349}
350
351TEST_F(Dex2oatSwapTest, DoNotUseSwapSmall) {
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100352 RunTest(/*use_fd=*/ false, /*expect_use=*/ false, { "--swap-dex-count-threshold=0" });
353 RunTest(/*use_fd=*/ true, /*expect_use=*/ false, { "--swap-dex-count-threshold=0" });
Andreas Gampee1459ae2016-06-29 09:36:30 -0700354}
355
356TEST_F(Dex2oatSwapTest, DoUseSwapSingleSmall) {
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100357 RunTest(/*use_fd=*/ false,
358 /*expect_use=*/ true,
Andreas Gampee1459ae2016-06-29 09:36:30 -0700359 { "--swap-dex-size-threshold=0", "--swap-dex-count-threshold=0" });
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100360 RunTest(/*use_fd=*/ true,
361 /*expect_use=*/ true,
Andreas Gampee1459ae2016-06-29 09:36:30 -0700362 { "--swap-dex-size-threshold=0", "--swap-dex-count-threshold=0" });
363}
364
Andreas Gampe7adeda82016-07-25 08:27:35 -0700365class Dex2oatSwapUseTest : public Dex2oatSwapTest {
366 protected:
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100367 void CheckHostResult(bool expect_use) override {
Andreas Gampe7adeda82016-07-25 08:27:35 -0700368 if (!kIsTargetBuild) {
369 if (expect_use) {
370 EXPECT_NE(output_.find("Large app, accepted running with swap."), std::string::npos)
371 << output_;
372 } else {
373 EXPECT_EQ(output_.find("Large app, accepted running with swap."), std::string::npos)
374 << output_;
375 }
376 }
377 }
378
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100379 std::string GetTestDexFileName() override {
Andreas Gampe7adeda82016-07-25 08:27:35 -0700380 // Use Statics as it has a handful of functions.
381 return CommonRuntimeTest::GetTestDexFileName("Statics");
382 }
383
384 void GrabResult1() {
385 if (!kIsTargetBuild) {
386 native_alloc_1_ = ParseNativeAlloc();
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100387 swap_1_ = ParseSwap(/*expected=*/ false);
Andreas Gampe7adeda82016-07-25 08:27:35 -0700388 } else {
389 native_alloc_1_ = std::numeric_limits<size_t>::max();
390 swap_1_ = 0;
391 }
392 }
393
394 void GrabResult2() {
395 if (!kIsTargetBuild) {
396 native_alloc_2_ = ParseNativeAlloc();
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100397 swap_2_ = ParseSwap(/*expected=*/ true);
Andreas Gampe7adeda82016-07-25 08:27:35 -0700398 } else {
399 native_alloc_2_ = 0;
400 swap_2_ = std::numeric_limits<size_t>::max();
401 }
402 }
403
404 private:
405 size_t ParseNativeAlloc() {
406 std::regex native_alloc_regex("dex2oat took.*native alloc=[^ ]+ \\(([0-9]+)B\\)");
407 std::smatch native_alloc_match;
408 bool found = std::regex_search(output_, native_alloc_match, native_alloc_regex);
409 if (!found) {
410 EXPECT_TRUE(found);
411 return 0;
412 }
413 if (native_alloc_match.size() != 2U) {
414 EXPECT_EQ(native_alloc_match.size(), 2U);
415 return 0;
416 }
417
418 std::istringstream stream(native_alloc_match[1].str());
419 size_t value;
420 stream >> value;
421
422 return value;
423 }
424
425 size_t ParseSwap(bool expected) {
426 std::regex swap_regex("dex2oat took[^\\n]+swap=[^ ]+ \\(([0-9]+)B\\)");
427 std::smatch swap_match;
428 bool found = std::regex_search(output_, swap_match, swap_regex);
429 if (found != expected) {
430 EXPECT_EQ(expected, found);
431 return 0;
432 }
433
434 if (!found) {
435 return 0;
436 }
437
438 if (swap_match.size() != 2U) {
439 EXPECT_EQ(swap_match.size(), 2U);
440 return 0;
441 }
442
443 std::istringstream stream(swap_match[1].str());
444 size_t value;
445 stream >> value;
446
447 return value;
448 }
449
450 protected:
451 size_t native_alloc_1_;
452 size_t native_alloc_2_;
453
454 size_t swap_1_;
455 size_t swap_2_;
456};
457
458TEST_F(Dex2oatSwapUseTest, CheckSwapUsage) {
Roland Levillain05e34f42018-05-24 13:19:05 +0000459 // Native memory usage isn't correctly tracked when running under ASan.
460 TEST_DISABLED_FOR_MEMORY_TOOL();
Andreas Gampef4a67fd2017-05-04 09:55:36 -0700461
Vladimir Marko57070da2017-02-14 16:16:30 +0000462 // The `native_alloc_2_ >= native_alloc_1_` assertion below may not
Roland Levillain19772bf2017-02-16 11:28:10 +0000463 // hold true on some x86 systems; disable this test while we
464 // investigate (b/29259363).
465 TEST_DISABLED_FOR_X86();
Vladimir Marko57070da2017-02-14 16:16:30 +0000466
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100467 RunTest(/*use_fd=*/ false,
468 /*expect_use=*/ false);
Andreas Gampe7adeda82016-07-25 08:27:35 -0700469 GrabResult1();
470 std::string output_1 = output_;
471
472 output_ = "";
473
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100474 RunTest(/*use_fd=*/ false,
475 /*expect_use=*/ true,
Andreas Gampe7adeda82016-07-25 08:27:35 -0700476 { "--swap-dex-size-threshold=0", "--swap-dex-count-threshold=0" });
477 GrabResult2();
478 std::string output_2 = output_;
479
480 if (native_alloc_2_ >= native_alloc_1_ || swap_1_ >= swap_2_) {
481 EXPECT_LT(native_alloc_2_, native_alloc_1_);
482 EXPECT_LT(swap_1_, swap_2_);
483
484 LOG(ERROR) << output_1;
485 LOG(ERROR) << output_2;
486 }
487}
488
Andreas Gampe67f02822016-06-24 21:05:23 -0700489class Dex2oatVeryLargeTest : public Dex2oatTest {
490 protected:
491 void CheckFilter(CompilerFilter::Filter input ATTRIBUTE_UNUSED,
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100492 CompilerFilter::Filter result ATTRIBUTE_UNUSED) override {
Andreas Gampe67f02822016-06-24 21:05:23 -0700493 // Ignore, we'll do our own checks.
494 }
495
496 void RunTest(CompilerFilter::Filter filter,
497 bool expect_large,
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700498 bool expect_downgrade,
Andreas Gampe67f02822016-06-24 21:05:23 -0700499 const std::vector<std::string>& extra_args = {}) {
500 std::string dex_location = GetScratchDir() + "/DexNoOat.jar";
501 std::string odex_location = GetOdexDir() + "/DexOdexNoOat.odex";
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700502 std::string app_image_file = GetScratchDir() + "/Test.art";
Andreas Gampe67f02822016-06-24 21:05:23 -0700503
504 Copy(GetDexSrc1(), dex_location);
505
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700506 std::vector<std::string> new_args(extra_args);
507 new_args.push_back("--app-image-file=" + app_image_file);
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800508 ASSERT_TRUE(GenerateOdexForTest(dex_location, odex_location, filter, new_args));
Andreas Gampe67f02822016-06-24 21:05:23 -0700509
510 CheckValidity();
511 ASSERT_TRUE(success_);
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700512 CheckResult(dex_location,
513 odex_location,
514 app_image_file,
515 filter,
516 expect_large,
517 expect_downgrade);
Andreas Gampe67f02822016-06-24 21:05:23 -0700518 }
519
520 void CheckResult(const std::string& dex_location,
521 const std::string& odex_location,
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700522 const std::string& app_image_file,
Andreas Gampe67f02822016-06-24 21:05:23 -0700523 CompilerFilter::Filter filter,
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700524 bool expect_large,
525 bool expect_downgrade) {
526 if (expect_downgrade) {
527 EXPECT_TRUE(expect_large);
528 }
Andreas Gampe67f02822016-06-24 21:05:23 -0700529 // Host/target independent checks.
530 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100531 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +0100532 odex_location.c_str(),
Andreas Gampe67f02822016-06-24 21:05:23 -0700533 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100534 /*executable=*/ false,
535 /*low_4gb=*/ false,
Andreas Gampe67f02822016-06-24 21:05:23 -0700536 dex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100537 /*reservation=*/ nullptr,
Andreas Gampe67f02822016-06-24 21:05:23 -0700538 &error_msg));
539 ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700540 EXPECT_GT(app_image_file.length(), 0u);
541 std::unique_ptr<File> file(OS::OpenFileForReading(app_image_file.c_str()));
Andreas Gampe67f02822016-06-24 21:05:23 -0700542 if (expect_large) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700543 // Note: we cannot check the following
544 // EXPECT_FALSE(CompilerFilter::IsAotCompilationEnabled(odex_file->GetCompilerFilter()));
Andreas Gampe67f02822016-06-24 21:05:23 -0700545 // The reason is that the filter override currently happens when the dex files are
546 // loaded in dex2oat, which is after the oat file has been started. Thus, the header
547 // store cannot be changed, and the original filter is set in stone.
548
549 for (const OatDexFile* oat_dex_file : odex_file->GetOatDexFiles()) {
550 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
551 ASSERT_TRUE(dex_file != nullptr);
552 uint32_t class_def_count = dex_file->NumClassDefs();
553 ASSERT_LT(class_def_count, std::numeric_limits<uint16_t>::max());
554 for (uint16_t class_def_index = 0; class_def_index < class_def_count; ++class_def_index) {
555 OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
556 EXPECT_EQ(oat_class.GetType(), OatClassType::kOatClassNoneCompiled);
557 }
558 }
559
560 // If the input filter was "below," it should have been used.
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100561 if (!CompilerFilter::IsAsGoodAs(CompilerFilter::kExtract, filter)) {
Andreas Gampe67f02822016-06-24 21:05:23 -0700562 EXPECT_EQ(odex_file->GetCompilerFilter(), filter);
563 }
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700564
565 // If expect large, make sure the app image isn't generated or is empty.
566 if (file != nullptr) {
567 EXPECT_EQ(file->GetLength(), 0u);
568 }
Andreas Gampe67f02822016-06-24 21:05:23 -0700569 } else {
570 EXPECT_EQ(odex_file->GetCompilerFilter(), filter);
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700571 ASSERT_TRUE(file != nullptr) << app_image_file;
572 EXPECT_GT(file->GetLength(), 0u);
Andreas Gampe67f02822016-06-24 21:05:23 -0700573 }
574
575 // Host/target dependent checks.
576 if (kIsTargetBuild) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700577 CheckTargetResult(expect_downgrade);
Andreas Gampe67f02822016-06-24 21:05:23 -0700578 } else {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700579 CheckHostResult(expect_downgrade);
Andreas Gampe67f02822016-06-24 21:05:23 -0700580 }
581 }
582
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700583 void CheckTargetResult(bool expect_downgrade ATTRIBUTE_UNUSED) {
Andreas Gampe67f02822016-06-24 21:05:23 -0700584 // TODO: Ignore for now. May do something for fd things.
585 }
586
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700587 void CheckHostResult(bool expect_downgrade) {
Andreas Gampe67f02822016-06-24 21:05:23 -0700588 if (!kIsTargetBuild) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700589 if (expect_downgrade) {
590 EXPECT_NE(output_.find("Very large app, downgrading to"), std::string::npos) << output_;
Andreas Gampe67f02822016-06-24 21:05:23 -0700591 } else {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700592 EXPECT_EQ(output_.find("Very large app, downgrading to"), std::string::npos) << output_;
Andreas Gampe67f02822016-06-24 21:05:23 -0700593 }
594 }
595 }
596
597 // Check whether the dex2oat run was really successful.
598 void CheckValidity() {
599 if (kIsTargetBuild) {
600 CheckTargetValidity();
601 } else {
602 CheckHostValidity();
603 }
604 }
605
606 void CheckTargetValidity() {
607 // TODO: Ignore for now.
608 }
609
610 // On the host, we can get the dex2oat output. Here, look for "dex2oat took."
611 void CheckHostValidity() {
612 EXPECT_NE(output_.find("dex2oat took"), std::string::npos) << output_;
613 }
614};
615
616TEST_F(Dex2oatVeryLargeTest, DontUseVeryLarge) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700617 RunTest(CompilerFilter::kAssumeVerified, false, false);
618 RunTest(CompilerFilter::kExtract, false, false);
619 RunTest(CompilerFilter::kQuicken, false, false);
620 RunTest(CompilerFilter::kSpeed, false, false);
Andreas Gampe67f02822016-06-24 21:05:23 -0700621
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700622 RunTest(CompilerFilter::kAssumeVerified, false, false, { "--very-large-app-threshold=10000000" });
623 RunTest(CompilerFilter::kExtract, false, false, { "--very-large-app-threshold=10000000" });
624 RunTest(CompilerFilter::kQuicken, false, false, { "--very-large-app-threshold=10000000" });
625 RunTest(CompilerFilter::kSpeed, false, false, { "--very-large-app-threshold=10000000" });
Andreas Gampe67f02822016-06-24 21:05:23 -0700626}
627
628TEST_F(Dex2oatVeryLargeTest, UseVeryLarge) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700629 RunTest(CompilerFilter::kAssumeVerified, true, false, { "--very-large-app-threshold=100" });
630 RunTest(CompilerFilter::kExtract, true, false, { "--very-large-app-threshold=100" });
631 RunTest(CompilerFilter::kQuicken, true, true, { "--very-large-app-threshold=100" });
632 RunTest(CompilerFilter::kSpeed, true, true, { "--very-large-app-threshold=100" });
Andreas Gampe67f02822016-06-24 21:05:23 -0700633}
634
Mathieu Chartier97ab5e32017-02-22 13:35:44 -0800635// Regressin test for b/35665292.
636TEST_F(Dex2oatVeryLargeTest, SpeedProfileNoProfile) {
637 // Test that dex2oat doesn't crash with speed-profile but no input profile.
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700638 RunTest(CompilerFilter::kSpeedProfile, false, false);
Mathieu Chartier97ab5e32017-02-22 13:35:44 -0800639}
640
Jeff Hao608f2ce2016-10-19 11:17:11 -0700641class Dex2oatLayoutTest : public Dex2oatTest {
642 protected:
643 void CheckFilter(CompilerFilter::Filter input ATTRIBUTE_UNUSED,
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100644 CompilerFilter::Filter result ATTRIBUTE_UNUSED) override {
Jeff Hao608f2ce2016-10-19 11:17:11 -0700645 // Ignore, we'll do our own checks.
646 }
647
Jeff Hao41fba6a2016-11-28 11:53:33 -0800648 // Emits a profile with a single dex file with the given location and a single class index of 1.
649 void GenerateProfile(const std::string& test_profile,
650 const std::string& dex_location,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800651 size_t num_classes,
Jeff Hao41fba6a2016-11-28 11:53:33 -0800652 uint32_t checksum) {
Andreas Gampedfcd82c2018-10-16 20:22:37 -0700653 int profile_test_fd = open(test_profile.c_str(),
654 O_CREAT | O_TRUNC | O_WRONLY | O_CLOEXEC,
655 0644);
Jeff Hao41fba6a2016-11-28 11:53:33 -0800656 CHECK_GE(profile_test_fd, 0);
657
658 ProfileCompilationInfo info;
659 std::string profile_key = ProfileCompilationInfo::GetProfileDexFileKey(dex_location);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800660 for (size_t i = 0; i < num_classes; ++i) {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700661 info.AddClassIndex(profile_key, checksum, dex::TypeIndex(1 + i), kMaxMethodIds);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800662 }
Jeff Hao41fba6a2016-11-28 11:53:33 -0800663 bool result = info.Save(profile_test_fd);
664 close(profile_test_fd);
665 ASSERT_TRUE(result);
666 }
667
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800668 void CompileProfileOdex(const std::string& dex_location,
669 const std::string& odex_location,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800670 const std::string& app_image_file_name,
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800671 bool use_fd,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800672 size_t num_profile_classes,
Nicolas Geoffray97fa9922017-03-09 13:13:25 +0000673 const std::vector<std::string>& extra_args = {},
674 bool expect_success = true) {
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800675 const std::string profile_location = GetScratchDir() + "/primary.prof";
Jeff Hao41fba6a2016-11-28 11:53:33 -0800676 const char* location = dex_location.c_str();
677 std::string error_msg;
678 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Sehr013fd802018-01-11 22:55:24 -0800679 const ArtDexFileLoader dex_file_loader;
680 ASSERT_TRUE(dex_file_loader.Open(
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100681 location, location, /*verify=*/ true, /*verify_checksum=*/ true, &error_msg, &dex_files));
Jeff Hao41fba6a2016-11-28 11:53:33 -0800682 EXPECT_EQ(dex_files.size(), 1U);
683 std::unique_ptr<const DexFile>& dex_file = dex_files[0];
Mathieu Chartier046854b2017-03-01 17:16:22 -0800684 GenerateProfile(profile_location,
685 dex_location,
686 num_profile_classes,
687 dex_file->GetLocationChecksum());
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800688 std::vector<std::string> copy(extra_args);
689 copy.push_back("--profile-file=" + profile_location);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800690 std::unique_ptr<File> app_image_file;
691 if (!app_image_file_name.empty()) {
692 if (use_fd) {
693 app_image_file.reset(OS::CreateEmptyFile(app_image_file_name.c_str()));
694 copy.push_back("--app-image-fd=" + std::to_string(app_image_file->Fd()));
695 } else {
696 copy.push_back("--app-image-file=" + app_image_file_name);
697 }
698 }
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800699 ASSERT_TRUE(GenerateOdexForTest(dex_location,
700 odex_location,
701 CompilerFilter::kSpeedProfile,
702 copy,
703 expect_success,
704 use_fd));
Mathieu Chartier046854b2017-03-01 17:16:22 -0800705 if (app_image_file != nullptr) {
706 ASSERT_EQ(app_image_file->FlushCloseOrErase(), 0) << "Could not flush and close art file";
707 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800708 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700709
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100710 uint64_t GetImageObjectSectionSize(const std::string& image_file_name) {
Mathieu Chartier046854b2017-03-01 17:16:22 -0800711 EXPECT_FALSE(image_file_name.empty());
712 std::unique_ptr<File> file(OS::OpenFileForReading(image_file_name.c_str()));
713 CHECK(file != nullptr);
714 ImageHeader image_header;
715 const bool success = file->ReadFully(&image_header, sizeof(image_header));
716 CHECK(success);
717 CHECK(image_header.IsValid());
718 ReaderMutexLock mu(Thread::Current(), *Locks::mutator_lock_);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100719 return image_header.GetObjectsSection().Size();
Mathieu Chartier046854b2017-03-01 17:16:22 -0800720 }
721
722 void RunTest(bool app_image) {
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800723 std::string dex_location = GetScratchDir() + "/DexNoOat.jar";
724 std::string odex_location = GetOdexDir() + "/DexOdexNoOat.odex";
Mathieu Chartier046854b2017-03-01 17:16:22 -0800725 std::string app_image_file = app_image ? (GetOdexDir() + "/DexOdexNoOat.art"): "";
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800726 Copy(GetDexSrc2(), dex_location);
727
Mathieu Chartier046854b2017-03-01 17:16:22 -0800728 uint64_t image_file_empty_profile = 0;
729 if (app_image) {
730 CompileProfileOdex(dex_location,
731 odex_location,
732 app_image_file,
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100733 /*use_fd=*/ false,
734 /*num_profile_classes=*/ 0);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800735 CheckValidity();
736 ASSERT_TRUE(success_);
737 // Don't check the result since CheckResult relies on the class being in the profile.
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100738 image_file_empty_profile = GetImageObjectSectionSize(app_image_file);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800739 EXPECT_GT(image_file_empty_profile, 0u);
740 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700741
Mathieu Chartier046854b2017-03-01 17:16:22 -0800742 // Small profile.
743 CompileProfileOdex(dex_location,
744 odex_location,
745 app_image_file,
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100746 /*use_fd=*/ false,
747 /*num_profile_classes=*/ 1);
Jeff Hao608f2ce2016-10-19 11:17:11 -0700748 CheckValidity();
749 ASSERT_TRUE(success_);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800750 CheckResult(dex_location, odex_location, app_image_file);
751
752 if (app_image) {
753 // Test that the profile made a difference by adding more classes.
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100754 const uint64_t image_file_small_profile = GetImageObjectSectionSize(app_image_file);
755 ASSERT_LT(image_file_empty_profile, image_file_small_profile);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800756 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700757 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800758
759 void RunTestVDex() {
760 std::string dex_location = GetScratchDir() + "/DexNoOat.jar";
761 std::string odex_location = GetOdexDir() + "/DexOdexNoOat.odex";
762 std::string vdex_location = GetOdexDir() + "/DexOdexNoOat.vdex";
Mathieu Chartier046854b2017-03-01 17:16:22 -0800763 std::string app_image_file_name = GetOdexDir() + "/DexOdexNoOat.art";
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800764 Copy(GetDexSrc2(), dex_location);
765
766 std::unique_ptr<File> vdex_file1(OS::CreateEmptyFile(vdex_location.c_str()));
767 CHECK(vdex_file1 != nullptr) << vdex_location;
768 ScratchFile vdex_file2;
769 {
770 std::string input_vdex = "--input-vdex-fd=-1";
771 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file1->Fd());
772 CompileProfileOdex(dex_location,
773 odex_location,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800774 app_image_file_name,
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100775 /*use_fd=*/ true,
776 /*num_profile_classes=*/ 1,
Mathieu Chartierf1609832018-01-31 03:09:56 -0800777 { input_vdex, output_vdex });
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800778 EXPECT_GT(vdex_file1->GetLength(), 0u);
779 }
780 {
Nicolas Geoffray97fa9922017-03-09 13:13:25 +0000781 // Test that vdex and dexlayout fail gracefully.
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800782 std::string input_vdex = StringPrintf("--input-vdex-fd=%d", vdex_file1->Fd());
783 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file2.GetFd());
784 CompileProfileOdex(dex_location,
785 odex_location,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800786 app_image_file_name,
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100787 /*use_fd=*/ true,
788 /*num_profile_classes=*/ 1,
Mathieu Chartierd27923c2018-02-08 21:00:03 -0800789 { input_vdex, output_vdex },
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100790 /*expect_success=*/ true);
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +0100791 EXPECT_GT(vdex_file2.GetFile()->GetLength(), 0u);
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800792 }
793 ASSERT_EQ(vdex_file1->FlushCloseOrErase(), 0) << "Could not flush and close vdex file";
794 CheckValidity();
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +0100795 ASSERT_TRUE(success_);
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800796 }
797
Mathieu Chartier046854b2017-03-01 17:16:22 -0800798 void CheckResult(const std::string& dex_location,
799 const std::string& odex_location,
800 const std::string& app_image_file_name) {
Jeff Hao608f2ce2016-10-19 11:17:11 -0700801 // Host/target independent checks.
802 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100803 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +0100804 odex_location.c_str(),
Jeff Hao608f2ce2016-10-19 11:17:11 -0700805 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100806 /*executable=*/ false,
807 /*low_4gb=*/ false,
Jeff Hao608f2ce2016-10-19 11:17:11 -0700808 dex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100809 /*reservation=*/ nullptr,
Jeff Hao608f2ce2016-10-19 11:17:11 -0700810 &error_msg));
811 ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
812
Jeff Hao042e8982016-10-19 11:17:11 -0700813 const char* location = dex_location.c_str();
814 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Sehr013fd802018-01-11 22:55:24 -0800815 const ArtDexFileLoader dex_file_loader;
816 ASSERT_TRUE(dex_file_loader.Open(
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100817 location, location, /*verify=*/ true, /*verify_checksum=*/ true, &error_msg, &dex_files));
Jeff Hao042e8982016-10-19 11:17:11 -0700818 EXPECT_EQ(dex_files.size(), 1U);
819 std::unique_ptr<const DexFile>& old_dex_file = dex_files[0];
820
Jeff Hao608f2ce2016-10-19 11:17:11 -0700821 for (const OatDexFile* oat_dex_file : odex_file->GetOatDexFiles()) {
Jeff Hao042e8982016-10-19 11:17:11 -0700822 std::unique_ptr<const DexFile> new_dex_file = oat_dex_file->OpenDexFile(&error_msg);
823 ASSERT_TRUE(new_dex_file != nullptr);
824 uint32_t class_def_count = new_dex_file->NumClassDefs();
Jeff Hao608f2ce2016-10-19 11:17:11 -0700825 ASSERT_LT(class_def_count, std::numeric_limits<uint16_t>::max());
Jeff Hao042e8982016-10-19 11:17:11 -0700826 ASSERT_GE(class_def_count, 2U);
827
Mathieu Chartier24066ec2017-10-21 16:01:08 -0700828 // Make sure the indexes stay the same.
Jeff Hao042e8982016-10-19 11:17:11 -0700829 std::string old_class0 = old_dex_file->PrettyType(old_dex_file->GetClassDef(0).class_idx_);
830 std::string old_class1 = old_dex_file->PrettyType(old_dex_file->GetClassDef(1).class_idx_);
831 std::string new_class0 = new_dex_file->PrettyType(new_dex_file->GetClassDef(0).class_idx_);
832 std::string new_class1 = new_dex_file->PrettyType(new_dex_file->GetClassDef(1).class_idx_);
Mathieu Chartier24066ec2017-10-21 16:01:08 -0700833 EXPECT_EQ(old_class0, new_class0);
834 EXPECT_EQ(old_class1, new_class1);
Jeff Hao608f2ce2016-10-19 11:17:11 -0700835 }
836
Jeff Haoc155b052017-01-17 17:43:29 -0800837 EXPECT_EQ(odex_file->GetCompilerFilter(), CompilerFilter::kSpeedProfile);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800838
839 if (!app_image_file_name.empty()) {
840 // Go peek at the image header to make sure it was large enough to contain the class.
841 std::unique_ptr<File> file(OS::OpenFileForReading(app_image_file_name.c_str()));
842 ImageHeader image_header;
843 bool success = file->ReadFully(&image_header, sizeof(image_header));
844 ASSERT_TRUE(success);
845 ASSERT_TRUE(image_header.IsValid());
Vladimir Markocd87c3e2017-09-05 13:11:57 +0100846 EXPECT_GT(image_header.GetObjectsSection().Size(), 0u);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800847 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700848 }
849
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800850 // Check whether the dex2oat run was really successful.
851 void CheckValidity() {
852 if (kIsTargetBuild) {
853 CheckTargetValidity();
854 } else {
855 CheckHostValidity();
Jeff Hao608f2ce2016-10-19 11:17:11 -0700856 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800857 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700858
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800859 void CheckTargetValidity() {
860 // TODO: Ignore for now.
861 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700862
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800863 // On the host, we can get the dex2oat output. Here, look for "dex2oat took."
864 void CheckHostValidity() {
865 EXPECT_NE(output_.find("dex2oat took"), std::string::npos) << output_;
866 }
867};
Jeff Hao608f2ce2016-10-19 11:17:11 -0700868
869TEST_F(Dex2oatLayoutTest, TestLayout) {
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100870 RunTest(/*app_image=*/ false);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800871}
872
873TEST_F(Dex2oatLayoutTest, TestLayoutAppImage) {
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100874 RunTest(/*app_image=*/ true);
Jeff Hao608f2ce2016-10-19 11:17:11 -0700875}
876
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800877TEST_F(Dex2oatLayoutTest, TestVdexLayout) {
878 RunTestVDex();
879}
880
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100881class Dex2oatUnquickenTest : public Dex2oatTest {
882 protected:
883 void RunUnquickenMultiDex() {
884 std::string dex_location = GetScratchDir() + "/UnquickenMultiDex.jar";
885 std::string odex_location = GetOdexDir() + "/UnquickenMultiDex.odex";
886 std::string vdex_location = GetOdexDir() + "/UnquickenMultiDex.vdex";
887 Copy(GetTestDexFileName("MultiDex"), dex_location);
888
889 std::unique_ptr<File> vdex_file1(OS::CreateEmptyFile(vdex_location.c_str()));
890 CHECK(vdex_file1 != nullptr) << vdex_location;
891 // Quicken the dex file into a vdex file.
892 {
893 std::string input_vdex = "--input-vdex-fd=-1";
894 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file1->Fd());
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800895 ASSERT_TRUE(GenerateOdexForTest(dex_location,
896 odex_location,
897 CompilerFilter::kQuicken,
898 { input_vdex, output_vdex },
899 /* expect_success= */ true,
900 /* use_fd= */ true));
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100901 EXPECT_GT(vdex_file1->GetLength(), 0u);
902 }
903 // Unquicken by running the verify compiler filter on the vdex file.
904 {
905 std::string input_vdex = StringPrintf("--input-vdex-fd=%d", vdex_file1->Fd());
906 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file1->Fd());
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800907 ASSERT_TRUE(GenerateOdexForTest(dex_location,
908 odex_location,
909 CompilerFilter::kVerify,
910 { input_vdex, output_vdex, kDisableCompactDex },
911 /* expect_success= */ true,
912 /* use_fd= */ true));
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100913 }
914 ASSERT_EQ(vdex_file1->FlushCloseOrErase(), 0) << "Could not flush and close vdex file";
915 CheckResult(dex_location, odex_location);
916 ASSERT_TRUE(success_);
917 }
918
Mathieu Chartierd27923c2018-02-08 21:00:03 -0800919 void RunUnquickenMultiDexCDex() {
920 std::string dex_location = GetScratchDir() + "/UnquickenMultiDex.jar";
921 std::string odex_location = GetOdexDir() + "/UnquickenMultiDex.odex";
922 std::string odex_location2 = GetOdexDir() + "/UnquickenMultiDex2.odex";
923 std::string vdex_location = GetOdexDir() + "/UnquickenMultiDex.vdex";
924 std::string vdex_location2 = GetOdexDir() + "/UnquickenMultiDex2.vdex";
925 Copy(GetTestDexFileName("MultiDex"), dex_location);
926
927 std::unique_ptr<File> vdex_file1(OS::CreateEmptyFile(vdex_location.c_str()));
928 std::unique_ptr<File> vdex_file2(OS::CreateEmptyFile(vdex_location2.c_str()));
929 CHECK(vdex_file1 != nullptr) << vdex_location;
930 CHECK(vdex_file2 != nullptr) << vdex_location2;
931
932 // Quicken the dex file into a vdex file.
933 {
934 std::string input_vdex = "--input-vdex-fd=-1";
935 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file1->Fd());
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800936 ASSERT_TRUE(GenerateOdexForTest(dex_location,
937 odex_location,
938 CompilerFilter::kQuicken,
939 { input_vdex, output_vdex, "--compact-dex-level=fast"},
940 /* expect_success= */ true,
941 /* use_fd= */ true));
Mathieu Chartierd27923c2018-02-08 21:00:03 -0800942 EXPECT_GT(vdex_file1->GetLength(), 0u);
943 }
944
945 // Unquicken by running the verify compiler filter on the vdex file.
946 {
947 std::string input_vdex = StringPrintf("--input-vdex-fd=%d", vdex_file1->Fd());
948 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file2->Fd());
Andreas Gampe50f9dc22018-11-05 10:29:43 -0800949 ASSERT_TRUE(GenerateOdexForTest(dex_location,
950 odex_location2,
951 CompilerFilter::kVerify,
952 { input_vdex, output_vdex, "--compact-dex-level=none"},
953 /* expect_success= */ true,
954 /* use_fd= */ true));
Mathieu Chartierd27923c2018-02-08 21:00:03 -0800955 }
956 ASSERT_EQ(vdex_file1->FlushCloseOrErase(), 0) << "Could not flush and close vdex file";
957 ASSERT_EQ(vdex_file2->FlushCloseOrErase(), 0) << "Could not flush and close vdex file";
958 CheckResult(dex_location, odex_location2);
959 ASSERT_TRUE(success_);
960 }
961
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100962 void CheckResult(const std::string& dex_location, const std::string& odex_location) {
963 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100964 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +0100965 odex_location.c_str(),
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100966 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100967 /*executable=*/ false,
968 /*low_4gb=*/ false,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100969 dex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100970 /*reservation=*/ nullptr,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100971 &error_msg));
972 ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
973 ASSERT_GE(odex_file->GetOatDexFiles().size(), 1u);
974
975 // Iterate over the dex files and ensure there is no quickened instruction.
976 for (const OatDexFile* oat_dex_file : odex_file->GetOatDexFiles()) {
977 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
Mathieu Chartier2242ef12018-07-23 18:14:13 -0700978 for (ClassAccessor accessor : dex_file->GetClasses()) {
979 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
980 for (const DexInstructionPcPair& inst : method.GetInstructions()) {
981 ASSERT_FALSE(inst->IsQuickened()) << inst->Opcode() << " " << output_;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100982 }
983 }
984 }
985 }
986 }
987};
988
989TEST_F(Dex2oatUnquickenTest, UnquickenMultiDex) {
990 RunUnquickenMultiDex();
991}
992
Mathieu Chartierd27923c2018-02-08 21:00:03 -0800993TEST_F(Dex2oatUnquickenTest, UnquickenMultiDexCDex) {
994 RunUnquickenMultiDexCDex();
995}
996
Andreas Gampe2e8a2562017-01-18 20:39:02 -0800997class Dex2oatWatchdogTest : public Dex2oatTest {
998 protected:
999 void RunTest(bool expect_success, const std::vector<std::string>& extra_args = {}) {
1000 std::string dex_location = GetScratchDir() + "/Dex2OatSwapTest.jar";
1001 std::string odex_location = GetOdexDir() + "/Dex2OatSwapTest.odex";
1002
1003 Copy(GetTestDexFileName(), dex_location);
1004
1005 std::vector<std::string> copy(extra_args);
1006
1007 std::string swap_location = GetOdexDir() + "/Dex2OatSwapTest.odex.swap";
1008 copy.push_back("--swap-file=" + swap_location);
Andreas Gampe22fa3762017-10-23 20:58:12 -07001009 copy.push_back("-j512"); // Excessive idle threads just slow down dex2oat.
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001010 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1011 odex_location,
1012 CompilerFilter::kSpeed,
1013 copy,
1014 expect_success));
Andreas Gampe2e8a2562017-01-18 20:39:02 -08001015 }
1016
1017 std::string GetTestDexFileName() {
1018 return GetDexSrc1();
1019 }
1020};
1021
1022TEST_F(Dex2oatWatchdogTest, TestWatchdogOK) {
1023 // Check with default.
1024 RunTest(true);
1025
1026 // Check with ten minutes.
1027 RunTest(true, { "--watchdog-timeout=600000" });
1028}
1029
1030TEST_F(Dex2oatWatchdogTest, TestWatchdogTrigger) {
Andreas Gampe80ddf272018-01-11 09:41:00 -08001031 // The watchdog is independent of dex2oat and will not delete intermediates. It is possible
1032 // that the compilation succeeds and the file is completely written by the time the watchdog
1033 // kills dex2oat (but the dex2oat threads must have been scheduled pretty badly).
1034 test_accepts_odex_file_on_failure = true;
1035
Andreas Gampe2e8a2562017-01-18 20:39:02 -08001036 // Check with ten milliseconds.
1037 RunTest(false, { "--watchdog-timeout=10" });
1038}
1039
Andreas Gampef7882972017-03-20 16:35:24 -07001040class Dex2oatReturnCodeTest : public Dex2oatTest {
1041 protected:
1042 int RunTest(const std::vector<std::string>& extra_args = {}) {
1043 std::string dex_location = GetScratchDir() + "/Dex2OatSwapTest.jar";
1044 std::string odex_location = GetOdexDir() + "/Dex2OatSwapTest.odex";
1045
1046 Copy(GetTestDexFileName(), dex_location);
1047
1048 std::string error_msg;
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001049 return GenerateOdexForTestWithStatus({dex_location},
Andreas Gampef7882972017-03-20 16:35:24 -07001050 odex_location,
1051 CompilerFilter::kSpeed,
1052 &error_msg,
1053 extra_args);
1054 }
1055
1056 std::string GetTestDexFileName() {
1057 return GetDexSrc1();
1058 }
1059};
1060
1061TEST_F(Dex2oatReturnCodeTest, TestCreateRuntime) {
Andreas Gampefd80b172017-04-26 22:25:31 -07001062 TEST_DISABLED_FOR_MEMORY_TOOL(); // b/19100793
Andreas Gampef7882972017-03-20 16:35:24 -07001063 int status = RunTest({ "--boot-image=/this/does/not/exist/yolo.oat" });
1064 EXPECT_EQ(static_cast<int>(dex2oat::ReturnCode::kCreateRuntime), WEXITSTATUS(status)) << output_;
1065}
1066
Calin Juravle1ce70852017-06-28 10:59:03 -07001067class Dex2oatClassLoaderContextTest : public Dex2oatTest {
1068 protected:
1069 void RunTest(const char* class_loader_context,
1070 const char* expected_classpath_key,
1071 bool expected_success,
1072 bool use_second_source = false) {
1073 std::string dex_location = GetUsedDexLocation();
1074 std::string odex_location = GetUsedOatLocation();
1075
1076 Copy(use_second_source ? GetDexSrc2() : GetDexSrc1(), dex_location);
1077
1078 std::string error_msg;
1079 std::vector<std::string> extra_args;
1080 if (class_loader_context != nullptr) {
1081 extra_args.push_back(std::string("--class-loader-context=") + class_loader_context);
1082 }
1083 auto check_oat = [expected_classpath_key](const OatFile& oat_file) {
1084 ASSERT_TRUE(expected_classpath_key != nullptr);
1085 const char* classpath = oat_file.GetOatHeader().GetStoreValueByKey(OatHeader::kClassPathKey);
1086 ASSERT_TRUE(classpath != nullptr);
1087 ASSERT_STREQ(expected_classpath_key, classpath);
1088 };
1089
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001090 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1091 odex_location,
1092 CompilerFilter::kQuicken,
1093 extra_args,
1094 expected_success,
1095 /*use_fd*/ false,
1096 check_oat));
Calin Juravle1ce70852017-06-28 10:59:03 -07001097 }
1098
1099 std::string GetUsedDexLocation() {
1100 return GetScratchDir() + "/Context.jar";
1101 }
1102
1103 std::string GetUsedOatLocation() {
1104 return GetOdexDir() + "/Context.odex";
1105 }
1106
Calin Juravle7b0648a2017-07-07 18:40:50 -07001107 const char* kEmptyClassPathKey = "PCL[]";
Calin Juravle1ce70852017-06-28 10:59:03 -07001108};
1109
1110TEST_F(Dex2oatClassLoaderContextTest, InvalidContext) {
1111 RunTest("Invalid[]", /*expected_classpath_key*/ nullptr, /*expected_success*/ false);
1112}
1113
1114TEST_F(Dex2oatClassLoaderContextTest, EmptyContext) {
1115 RunTest("PCL[]", kEmptyClassPathKey, /*expected_success*/ true);
1116}
1117
1118TEST_F(Dex2oatClassLoaderContextTest, SpecialContext) {
1119 RunTest(OatFile::kSpecialSharedLibrary,
1120 OatFile::kSpecialSharedLibrary,
1121 /*expected_success*/ true);
1122}
1123
1124TEST_F(Dex2oatClassLoaderContextTest, ContextWithTheSourceDexFiles) {
1125 std::string context = "PCL[" + GetUsedDexLocation() + "]";
1126 RunTest(context.c_str(), kEmptyClassPathKey, /*expected_success*/ true);
1127}
1128
1129TEST_F(Dex2oatClassLoaderContextTest, ContextWithOtherDexFiles) {
1130 std::vector<std::unique_ptr<const DexFile>> dex_files = OpenTestDexFiles("Nested");
Calin Juravle1ce70852017-06-28 10:59:03 -07001131
1132 std::string context = "PCL[" + dex_files[0]->GetLocation() + "]";
Calin Juravle7b0648a2017-07-07 18:40:50 -07001133 std::string expected_classpath_key = "PCL[" +
1134 dex_files[0]->GetLocation() + "*" + std::to_string(dex_files[0]->GetLocationChecksum()) + "]";
Calin Juravle1ce70852017-06-28 10:59:03 -07001135 RunTest(context.c_str(), expected_classpath_key.c_str(), true);
1136}
1137
1138TEST_F(Dex2oatClassLoaderContextTest, ContextWithStrippedDexFiles) {
1139 std::string stripped_classpath = GetScratchDir() + "/stripped_classpath.jar";
1140 Copy(GetStrippedDexSrc1(), stripped_classpath);
1141
1142 std::string context = "PCL[" + stripped_classpath + "]";
1143 // Expect an empty context because stripped dex files cannot be open.
Calin Juravle7b0648a2017-07-07 18:40:50 -07001144 RunTest(context.c_str(), kEmptyClassPathKey , /*expected_success*/ true);
Calin Juravle1ce70852017-06-28 10:59:03 -07001145}
1146
1147TEST_F(Dex2oatClassLoaderContextTest, ContextWithStrippedDexFilesBackedByOdex) {
1148 std::string stripped_classpath = GetScratchDir() + "/stripped_classpath.jar";
1149 std::string odex_for_classpath = GetOdexDir() + "/stripped_classpath.odex";
1150
1151 Copy(GetDexSrc1(), stripped_classpath);
1152
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001153 ASSERT_TRUE(GenerateOdexForTest(stripped_classpath,
1154 odex_for_classpath,
1155 CompilerFilter::kQuicken,
1156 {},
1157 true));
Calin Juravle1ce70852017-06-28 10:59:03 -07001158
1159 // Strip the dex file
1160 Copy(GetStrippedDexSrc1(), stripped_classpath);
1161
1162 std::string context = "PCL[" + stripped_classpath + "]";
Calin Juravle7b0648a2017-07-07 18:40:50 -07001163 std::string expected_classpath_key;
Calin Juravle1ce70852017-06-28 10:59:03 -07001164 {
1165 // Open the oat file to get the expected classpath.
Nicolas Geoffray29742602017-12-14 10:09:03 +00001166 OatFileAssistant oat_file_assistant(stripped_classpath.c_str(), kRuntimeISA, false, false);
Calin Juravle1ce70852017-06-28 10:59:03 -07001167 std::unique_ptr<OatFile> oat_file(oat_file_assistant.GetBestOatFile());
1168 std::vector<std::unique_ptr<const DexFile>> oat_dex_files =
1169 OatFileAssistant::LoadDexFiles(*oat_file, stripped_classpath.c_str());
Calin Juravle7b0648a2017-07-07 18:40:50 -07001170 expected_classpath_key = "PCL[";
1171 for (size_t i = 0; i < oat_dex_files.size(); i++) {
1172 if (i > 0) {
1173 expected_classpath_key + ":";
1174 }
1175 expected_classpath_key += oat_dex_files[i]->GetLocation() + "*" +
1176 std::to_string(oat_dex_files[i]->GetLocationChecksum());
1177 }
1178 expected_classpath_key += "]";
Calin Juravle1ce70852017-06-28 10:59:03 -07001179 }
1180
1181 RunTest(context.c_str(),
Calin Juravle7b0648a2017-07-07 18:40:50 -07001182 expected_classpath_key.c_str(),
Calin Juravle1ce70852017-06-28 10:59:03 -07001183 /*expected_success*/ true,
1184 /*use_second_source*/ true);
1185}
1186
1187TEST_F(Dex2oatClassLoaderContextTest, ContextWithNotExistentDexFiles) {
1188 std::string context = "PCL[does_not_exists.dex]";
1189 // Expect an empty context because stripped dex files cannot be open.
1190 RunTest(context.c_str(), kEmptyClassPathKey, /*expected_success*/ true);
1191}
1192
Calin Juravlec79470d2017-07-12 17:37:42 -07001193TEST_F(Dex2oatClassLoaderContextTest, ChainContext) {
1194 std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested");
1195 std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex");
1196
1197 std::string context = "PCL[" + GetTestDexFileName("Nested") + "];" +
1198 "DLC[" + GetTestDexFileName("MultiDex") + "]";
1199 std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "];" +
1200 "DLC[" + CreateClassPathWithChecksums(dex_files2) + "]";
1201
1202 RunTest(context.c_str(), expected_classpath_key.c_str(), true);
1203}
1204
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00001205TEST_F(Dex2oatClassLoaderContextTest, ContextWithSharedLibrary) {
1206 std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested");
1207 std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex");
1208
1209 std::string context = "PCL[" + GetTestDexFileName("Nested") + "]" +
1210 "{PCL[" + GetTestDexFileName("MultiDex") + "]}";
1211 std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "]" +
1212 "{PCL[" + CreateClassPathWithChecksums(dex_files2) + "]}";
1213 RunTest(context.c_str(), expected_classpath_key.c_str(), true);
1214}
1215
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001216class Dex2oatDeterminism : public Dex2oatTest {};
1217
1218TEST_F(Dex2oatDeterminism, UnloadCompile) {
1219 if (!kUseReadBarrier &&
1220 gc::kCollectorTypeDefault != gc::kCollectorTypeCMS &&
1221 gc::kCollectorTypeDefault != gc::kCollectorTypeMS) {
1222 LOG(INFO) << "Test requires determinism support.";
1223 return;
1224 }
1225 Runtime* const runtime = Runtime::Current();
1226 std::string out_dir = GetScratchDir();
1227 const std::string base_oat_name = out_dir + "/base.oat";
1228 const std::string base_vdex_name = out_dir + "/base.vdex";
1229 const std::string unload_oat_name = out_dir + "/unload.oat";
1230 const std::string unload_vdex_name = out_dir + "/unload.vdex";
1231 const std::string no_unload_oat_name = out_dir + "/nounload.oat";
1232 const std::string no_unload_vdex_name = out_dir + "/nounload.vdex";
1233 const std::string app_image_name = out_dir + "/unload.art";
1234 std::string error_msg;
1235 const std::vector<gc::space::ImageSpace*>& spaces = runtime->GetHeap()->GetBootImageSpaces();
1236 ASSERT_GT(spaces.size(), 0u);
1237 const std::string image_location = spaces[0]->GetImageLocation();
1238 // Without passing in an app image, it will unload in between compilations.
1239 const int res = GenerateOdexForTestWithStatus(
1240 GetLibCoreDexFileNames(),
1241 base_oat_name,
1242 CompilerFilter::Filter::kQuicken,
1243 &error_msg,
1244 {"--force-determinism", "--avoid-storing-invocation"});
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001245 ASSERT_EQ(res, 0);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001246 Copy(base_oat_name, unload_oat_name);
1247 Copy(base_vdex_name, unload_vdex_name);
1248 std::unique_ptr<File> unload_oat(OS::OpenFileForReading(unload_oat_name.c_str()));
1249 std::unique_ptr<File> unload_vdex(OS::OpenFileForReading(unload_vdex_name.c_str()));
1250 ASSERT_TRUE(unload_oat != nullptr);
1251 ASSERT_TRUE(unload_vdex != nullptr);
1252 EXPECT_GT(unload_oat->GetLength(), 0u);
1253 EXPECT_GT(unload_vdex->GetLength(), 0u);
1254 // Regenerate with an app image to disable the dex2oat unloading and verify that the output is
1255 // the same.
1256 const int res2 = GenerateOdexForTestWithStatus(
1257 GetLibCoreDexFileNames(),
1258 base_oat_name,
1259 CompilerFilter::Filter::kQuicken,
1260 &error_msg,
1261 {"--force-determinism", "--avoid-storing-invocation", "--app-image-file=" + app_image_name});
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001262 ASSERT_EQ(res2, 0);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001263 Copy(base_oat_name, no_unload_oat_name);
1264 Copy(base_vdex_name, no_unload_vdex_name);
1265 std::unique_ptr<File> no_unload_oat(OS::OpenFileForReading(no_unload_oat_name.c_str()));
1266 std::unique_ptr<File> no_unload_vdex(OS::OpenFileForReading(no_unload_vdex_name.c_str()));
1267 ASSERT_TRUE(no_unload_oat != nullptr);
1268 ASSERT_TRUE(no_unload_vdex != nullptr);
1269 EXPECT_GT(no_unload_oat->GetLength(), 0u);
1270 EXPECT_GT(no_unload_vdex->GetLength(), 0u);
1271 // Verify that both of the files are the same (odex and vdex).
1272 EXPECT_EQ(unload_oat->GetLength(), no_unload_oat->GetLength());
1273 EXPECT_EQ(unload_vdex->GetLength(), no_unload_vdex->GetLength());
1274 EXPECT_EQ(unload_oat->Compare(no_unload_oat.get()), 0)
1275 << unload_oat_name << " " << no_unload_oat_name;
1276 EXPECT_EQ(unload_vdex->Compare(no_unload_vdex.get()), 0)
1277 << unload_vdex_name << " " << no_unload_vdex_name;
1278 // App image file.
1279 std::unique_ptr<File> app_image_file(OS::OpenFileForReading(app_image_name.c_str()));
1280 ASSERT_TRUE(app_image_file != nullptr);
1281 EXPECT_GT(app_image_file->GetLength(), 0u);
1282}
1283
Mathieu Chartier120aa282017-08-05 16:03:03 -07001284// Test that dexlayout section info is correctly written to the oat file for profile based
1285// compilation.
1286TEST_F(Dex2oatTest, LayoutSections) {
1287 using Hotness = ProfileCompilationInfo::MethodHotness;
1288 std::unique_ptr<const DexFile> dex(OpenTestDexFile("ManyMethods"));
1289 ScratchFile profile_file;
1290 // We can only layout method indices with code items, figure out which ones have this property
1291 // first.
1292 std::vector<uint16_t> methods;
1293 {
1294 const DexFile::TypeId* type_id = dex->FindTypeId("LManyMethods;");
1295 dex::TypeIndex type_idx = dex->GetIndexForTypeId(*type_id);
Mathieu Chartier2242ef12018-07-23 18:14:13 -07001296 ClassAccessor accessor(*dex, *dex->FindClassDef(type_idx));
Mathieu Chartier120aa282017-08-05 16:03:03 -07001297 std::set<size_t> code_item_offsets;
Mathieu Chartier2242ef12018-07-23 18:14:13 -07001298 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
1299 const uint16_t method_idx = method.GetIndex();
1300 const size_t code_item_offset = method.GetCodeItemOffset();
Mathieu Chartier120aa282017-08-05 16:03:03 -07001301 if (code_item_offsets.insert(code_item_offset).second) {
1302 // Unique code item, add the method index.
1303 methods.push_back(method_idx);
1304 }
1305 }
Mathieu Chartier120aa282017-08-05 16:03:03 -07001306 }
1307 ASSERT_GE(methods.size(), 8u);
1308 std::vector<uint16_t> hot_methods = {methods[1], methods[3], methods[5]};
1309 std::vector<uint16_t> startup_methods = {methods[1], methods[2], methods[7]};
1310 std::vector<uint16_t> post_methods = {methods[0], methods[2], methods[6]};
1311 // Here, we build the profile from the method lists.
1312 ProfileCompilationInfo info;
1313 info.AddMethodsForDex(
1314 static_cast<Hotness::Flag>(Hotness::kFlagHot | Hotness::kFlagStartup),
1315 dex.get(),
1316 hot_methods.begin(),
1317 hot_methods.end());
1318 info.AddMethodsForDex(
1319 Hotness::kFlagStartup,
1320 dex.get(),
1321 startup_methods.begin(),
1322 startup_methods.end());
1323 info.AddMethodsForDex(
1324 Hotness::kFlagPostStartup,
1325 dex.get(),
1326 post_methods.begin(),
1327 post_methods.end());
1328 for (uint16_t id : hot_methods) {
1329 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsHot());
1330 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsStartup());
1331 }
1332 for (uint16_t id : startup_methods) {
1333 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsStartup());
1334 }
1335 for (uint16_t id : post_methods) {
1336 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsPostStartup());
1337 }
1338 // Save the profile since we want to use it with dex2oat to produce an oat file.
1339 ASSERT_TRUE(info.Save(profile_file.GetFd()));
1340 // Generate a profile based odex.
1341 const std::string dir = GetScratchDir();
1342 const std::string oat_filename = dir + "/base.oat";
1343 const std::string vdex_filename = dir + "/base.vdex";
1344 std::string error_msg;
1345 const int res = GenerateOdexForTestWithStatus(
1346 {dex->GetLocation()},
1347 oat_filename,
1348 CompilerFilter::Filter::kQuicken,
1349 &error_msg,
1350 {"--profile-file=" + profile_file.GetFilename()});
1351 EXPECT_EQ(res, 0);
1352
1353 // Open our generated oat file.
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001354 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01001355 oat_filename.c_str(),
Mathieu Chartier120aa282017-08-05 16:03:03 -07001356 oat_filename.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001357 /*executable=*/ false,
1358 /*low_4gb=*/ false,
Mathieu Chartier120aa282017-08-05 16:03:03 -07001359 dex->GetLocation().c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001360 /*reservation=*/ nullptr,
Mathieu Chartier120aa282017-08-05 16:03:03 -07001361 &error_msg));
1362 ASSERT_TRUE(odex_file != nullptr);
1363 std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
1364 ASSERT_EQ(oat_dex_files.size(), 1u);
1365 // Check that the code sections match what we expect.
1366 for (const OatDexFile* oat_dex : oat_dex_files) {
1367 const DexLayoutSections* const sections = oat_dex->GetDexLayoutSections();
1368 // Testing of logging the sections.
1369 ASSERT_TRUE(sections != nullptr);
1370 LOG(INFO) << *sections;
1371
1372 // Load the sections into temporary variables for convenience.
1373 const DexLayoutSection& code_section =
1374 sections->sections_[static_cast<size_t>(DexLayoutSections::SectionType::kSectionTypeCode)];
1375 const DexLayoutSection::Subsection& section_hot_code =
1376 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeHot)];
1377 const DexLayoutSection::Subsection& section_sometimes_used =
1378 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeSometimesUsed)];
1379 const DexLayoutSection::Subsection& section_startup_only =
1380 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeStartupOnly)];
1381 const DexLayoutSection::Subsection& section_unused =
1382 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeUnused)];
1383
1384 // All the sections should be non-empty.
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001385 EXPECT_GT(section_hot_code.Size(), 0u);
1386 EXPECT_GT(section_sometimes_used.Size(), 0u);
1387 EXPECT_GT(section_startup_only.Size(), 0u);
1388 EXPECT_GT(section_unused.Size(), 0u);
Mathieu Chartier120aa282017-08-05 16:03:03 -07001389
1390 // Open the dex file since we need to peek at the code items to verify the layout matches what
1391 // we expect.
1392 std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1393 ASSERT_TRUE(dex_file != nullptr) << error_msg;
1394 const DexFile::TypeId* type_id = dex_file->FindTypeId("LManyMethods;");
1395 ASSERT_TRUE(type_id != nullptr);
1396 dex::TypeIndex type_idx = dex_file->GetIndexForTypeId(*type_id);
1397 const DexFile::ClassDef* class_def = dex_file->FindClassDef(type_idx);
1398 ASSERT_TRUE(class_def != nullptr);
1399
1400 // Count how many code items are for each category, there should be at least one per category.
1401 size_t hot_count = 0;
1402 size_t post_startup_count = 0;
1403 size_t startup_count = 0;
1404 size_t unused_count = 0;
1405 // Visit all of the methdos of the main class and cross reference the method indices to their
1406 // corresponding code item offsets to verify the layout.
Mathieu Chartier2242ef12018-07-23 18:14:13 -07001407 ClassAccessor accessor(*dex_file, *class_def);
1408 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
1409 const size_t method_idx = method.GetIndex();
1410 const size_t code_item_offset = method.GetCodeItemOffset();
Mathieu Chartier120aa282017-08-05 16:03:03 -07001411 const bool is_hot = ContainsElement(hot_methods, method_idx);
1412 const bool is_startup = ContainsElement(startup_methods, method_idx);
1413 const bool is_post_startup = ContainsElement(post_methods, method_idx);
1414 if (is_hot) {
1415 // Hot is highest precedence, check that the hot methods are in the hot section.
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001416 EXPECT_TRUE(section_hot_code.Contains(code_item_offset));
Mathieu Chartier120aa282017-08-05 16:03:03 -07001417 ++hot_count;
1418 } else if (is_post_startup) {
1419 // Post startup is sometimes used section.
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001420 EXPECT_TRUE(section_sometimes_used.Contains(code_item_offset));
Mathieu Chartier120aa282017-08-05 16:03:03 -07001421 ++post_startup_count;
1422 } else if (is_startup) {
1423 // Startup at this point means not hot or post startup, these must be startup only then.
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001424 EXPECT_TRUE(section_startup_only.Contains(code_item_offset));
Mathieu Chartier120aa282017-08-05 16:03:03 -07001425 ++startup_count;
1426 } else {
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001427 if (section_unused.Contains(code_item_offset)) {
Alan Leung9595fd32017-10-17 17:08:19 -07001428 // If no flags are set, the method should be unused ...
1429 ++unused_count;
1430 } else {
1431 // or this method is part of the last code item and the end is 4 byte aligned.
Mathieu Chartier2242ef12018-07-23 18:14:13 -07001432 for (const ClassAccessor::Method& method2 : accessor.GetMethods()) {
1433 EXPECT_LE(method2.GetCodeItemOffset(), code_item_offset);
Alan Leung9595fd32017-10-17 17:08:19 -07001434 }
1435 uint32_t code_item_size = dex_file->FindCodeItemOffset(*class_def, method_idx);
1436 EXPECT_EQ((code_item_offset + code_item_size) % 4, 0u);
1437 }
Mathieu Chartier120aa282017-08-05 16:03:03 -07001438 }
1439 }
Mathieu Chartier120aa282017-08-05 16:03:03 -07001440 EXPECT_GT(hot_count, 0u);
1441 EXPECT_GT(post_startup_count, 0u);
1442 EXPECT_GT(startup_count, 0u);
1443 EXPECT_GT(unused_count, 0u);
1444 }
1445}
1446
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001447// Test that generating compact dex works.
1448TEST_F(Dex2oatTest, GenerateCompactDex) {
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001449 // Generate a compact dex based odex.
1450 const std::string dir = GetScratchDir();
1451 const std::string oat_filename = dir + "/base.oat";
1452 const std::string vdex_filename = dir + "/base.vdex";
Mathieu Chartierc17b7d82018-03-14 14:00:04 -07001453 const std::string dex_location = GetTestDexFileName("MultiDex");
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001454 std::string error_msg;
1455 const int res = GenerateOdexForTestWithStatus(
Mathieu Chartierc17b7d82018-03-14 14:00:04 -07001456 { dex_location },
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001457 oat_filename,
1458 CompilerFilter::Filter::kQuicken,
1459 &error_msg,
1460 {"--compact-dex-level=fast"});
1461 EXPECT_EQ(res, 0);
1462 // Open our generated oat file.
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001463 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01001464 oat_filename.c_str(),
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001465 oat_filename.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001466 /*executable=*/ false,
1467 /*low_4gb=*/ false,
Mathieu Chartierc17b7d82018-03-14 14:00:04 -07001468 dex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001469 /*reservation=*/ nullptr,
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001470 &error_msg));
1471 ASSERT_TRUE(odex_file != nullptr);
1472 std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
Mathieu Chartierc17b7d82018-03-14 14:00:04 -07001473 ASSERT_GT(oat_dex_files.size(), 1u);
1474 // Check that each dex is a compact dex file.
1475 std::vector<std::unique_ptr<const CompactDexFile>> compact_dex_files;
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001476 for (const OatDexFile* oat_dex : oat_dex_files) {
1477 std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1478 ASSERT_TRUE(dex_file != nullptr) << error_msg;
1479 ASSERT_TRUE(dex_file->IsCompactDexFile());
Mathieu Chartierc17b7d82018-03-14 14:00:04 -07001480 compact_dex_files.push_back(
1481 std::unique_ptr<const CompactDexFile>(dex_file.release()->AsCompactDexFile()));
1482 }
1483 for (const std::unique_ptr<const CompactDexFile>& dex_file : compact_dex_files) {
1484 // Test that every code item is in the owned section.
1485 const CompactDexFile::Header& header = dex_file->GetHeader();
1486 EXPECT_LE(header.OwnedDataBegin(), header.OwnedDataEnd());
1487 EXPECT_LE(header.OwnedDataBegin(), header.data_size_);
1488 EXPECT_LE(header.OwnedDataEnd(), header.data_size_);
Mathieu Chartier2242ef12018-07-23 18:14:13 -07001489 for (ClassAccessor accessor : dex_file->GetClasses()) {
1490 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
1491 if (method.GetCodeItemOffset() != 0u) {
1492 ASSERT_GE(method.GetCodeItemOffset(), header.OwnedDataBegin());
1493 ASSERT_LT(method.GetCodeItemOffset(), header.OwnedDataEnd());
Mathieu Chartierc17b7d82018-03-14 14:00:04 -07001494 }
Mathieu Chartier2242ef12018-07-23 18:14:13 -07001495 }
Mathieu Chartierc17b7d82018-03-14 14:00:04 -07001496 }
1497 // Test that the owned sections don't overlap.
1498 for (const std::unique_ptr<const CompactDexFile>& other_dex : compact_dex_files) {
1499 if (dex_file != other_dex) {
1500 ASSERT_TRUE(
1501 (dex_file->GetHeader().OwnedDataBegin() >= other_dex->GetHeader().OwnedDataEnd()) ||
1502 (dex_file->GetHeader().OwnedDataEnd() <= other_dex->GetHeader().OwnedDataBegin()));
1503 }
1504 }
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001505 }
1506}
1507
Andreas Gampef39208f2017-10-19 15:06:59 -07001508class Dex2oatVerifierAbort : public Dex2oatTest {};
1509
1510TEST_F(Dex2oatVerifierAbort, HardFail) {
1511 // Use VerifierDeps as it has hard-failing classes.
1512 std::unique_ptr<const DexFile> dex(OpenTestDexFile("VerifierDeps"));
1513 std::string out_dir = GetScratchDir();
1514 const std::string base_oat_name = out_dir + "/base.oat";
1515 std::string error_msg;
1516 const int res_fail = GenerateOdexForTestWithStatus(
1517 {dex->GetLocation()},
1518 base_oat_name,
1519 CompilerFilter::Filter::kQuicken,
1520 &error_msg,
1521 {"--abort-on-hard-verifier-error"});
1522 EXPECT_NE(0, res_fail);
1523
1524 const int res_no_fail = GenerateOdexForTestWithStatus(
1525 {dex->GetLocation()},
1526 base_oat_name,
1527 CompilerFilter::Filter::kQuicken,
1528 &error_msg,
1529 {"--no-abort-on-hard-verifier-error"});
1530 EXPECT_EQ(0, res_no_fail);
1531}
1532
1533TEST_F(Dex2oatVerifierAbort, SoftFail) {
1534 // Use VerifierDepsMulti as it has hard-failing classes.
1535 std::unique_ptr<const DexFile> dex(OpenTestDexFile("VerifierDepsMulti"));
1536 std::string out_dir = GetScratchDir();
1537 const std::string base_oat_name = out_dir + "/base.oat";
1538 std::string error_msg;
1539 const int res_fail = GenerateOdexForTestWithStatus(
1540 {dex->GetLocation()},
1541 base_oat_name,
1542 CompilerFilter::Filter::kQuicken,
1543 &error_msg,
1544 {"--abort-on-soft-verifier-error"});
1545 EXPECT_NE(0, res_fail);
1546
1547 const int res_no_fail = GenerateOdexForTestWithStatus(
1548 {dex->GetLocation()},
1549 base_oat_name,
1550 CompilerFilter::Filter::kQuicken,
1551 &error_msg,
1552 {"--no-abort-on-soft-verifier-error"});
1553 EXPECT_EQ(0, res_no_fail);
1554}
1555
Andreas Gampecac31ad2017-11-06 20:01:17 -08001556class Dex2oatDedupeCode : public Dex2oatTest {};
1557
1558TEST_F(Dex2oatDedupeCode, DedupeTest) {
1559 // Use MyClassNatives. It has lots of native methods that will produce deduplicate-able code.
1560 std::unique_ptr<const DexFile> dex(OpenTestDexFile("MyClassNatives"));
1561 std::string out_dir = GetScratchDir();
1562 const std::string base_oat_name = out_dir + "/base.oat";
1563 size_t no_dedupe_size = 0;
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001564 ASSERT_TRUE(GenerateOdexForTest(dex->GetLocation(),
1565 base_oat_name,
1566 CompilerFilter::Filter::kSpeed,
1567 { "--deduplicate-code=false" },
1568 true, // expect_success
1569 false, // use_fd
1570 [&no_dedupe_size](const OatFile& o) {
1571 no_dedupe_size = o.Size();
1572 }));
Andreas Gampecac31ad2017-11-06 20:01:17 -08001573
1574 size_t dedupe_size = 0;
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001575 ASSERT_TRUE(GenerateOdexForTest(dex->GetLocation(),
1576 base_oat_name,
1577 CompilerFilter::Filter::kSpeed,
1578 { "--deduplicate-code=true" },
1579 true, // expect_success
1580 false, // use_fd
1581 [&dedupe_size](const OatFile& o) {
1582 dedupe_size = o.Size();
1583 }));
Andreas Gampecac31ad2017-11-06 20:01:17 -08001584
1585 EXPECT_LT(dedupe_size, no_dedupe_size);
1586}
1587
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00001588TEST_F(Dex2oatTest, UncompressedTest) {
1589 std::unique_ptr<const DexFile> dex(OpenTestDexFile("MainUncompressed"));
1590 std::string out_dir = GetScratchDir();
1591 const std::string base_oat_name = out_dir + "/base.oat";
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001592 ASSERT_TRUE(GenerateOdexForTest(dex->GetLocation(),
1593 base_oat_name,
1594 CompilerFilter::Filter::kQuicken,
1595 { },
1596 true, // expect_success
1597 false, // use_fd
1598 [](const OatFile& o) {
1599 CHECK(!o.ContainsDexCode());
1600 }));
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00001601}
1602
Mathieu Chartier700a9852018-02-06 18:27:38 -08001603TEST_F(Dex2oatTest, EmptyUncompressedDexTest) {
1604 std::string out_dir = GetScratchDir();
1605 const std::string base_oat_name = out_dir + "/base.oat";
1606 std::string error_msg;
1607 int status = GenerateOdexForTestWithStatus(
1608 { GetTestDexFileName("MainEmptyUncompressed") },
1609 base_oat_name,
1610 CompilerFilter::Filter::kQuicken,
1611 &error_msg,
1612 { },
1613 /*use_fd*/ false);
1614 // Expect to fail with code 1 and not SIGSEGV or SIGABRT.
1615 ASSERT_TRUE(WIFEXITED(status));
1616 ASSERT_EQ(WEXITSTATUS(status), 1) << error_msg;
1617}
1618
Mathieu Chartier05f90d12018-02-07 13:47:17 -08001619// Dex file that has duplicate methods have different code items and debug info.
1620static const char kDuplicateMethodInputDex[] =
1621 "ZGV4CjAzOQDEy8VPdj4qHpgPYFWtLCtOykfFP4kB8tGYDAAAcAAAAHhWNBIAAAAAAAAAANALAABI"
1622 "AAAAcAAAAA4AAACQAQAABQAAAMgBAAANAAAABAIAABkAAABsAgAABAAAADQDAADgCAAAuAMAADgI"
1623 "AABCCAAASggAAE8IAABcCAAAaggAAHkIAACICAAAlggAAKQIAACyCAAAwAgAAM4IAADcCAAA6ggA"
1624 "APgIAAD7CAAA/wgAABcJAAAuCQAARQkAAFQJAAB4CQAAmAkAALsJAADSCQAA5gkAAPoJAAAVCgAA"
1625 "KQoAADsKAABCCgAASgoAAFIKAABbCgAAZAoAAGwKAAB0CgAAfAoAAIQKAACMCgAAlAoAAJwKAACk"
1626 "CgAArQoAALcKAADACgAAwwoAAMcKAADcCgAA6QoAAPEKAAD3CgAA/QoAAAMLAAAJCwAAEAsAABcL"
1627 "AAAdCwAAIwsAACkLAAAvCwAANQsAADsLAABBCwAARwsAAE0LAABSCwAAWwsAAF4LAABoCwAAbwsA"
1628 "ABEAAAASAAAAEwAAABQAAAAVAAAAFgAAABcAAAAYAAAAGQAAABoAAAAbAAAAHAAAAC4AAAAwAAAA"
1629 "DwAAAAkAAAAAAAAAEAAAAAoAAACoBwAALgAAAAwAAAAAAAAALwAAAAwAAACoBwAALwAAAAwAAACw"
1630 "BwAAAgAJADUAAAACAAkANgAAAAIACQA3AAAAAgAJADgAAAACAAkAOQAAAAIACQA6AAAAAgAJADsA"
1631 "AAACAAkAPAAAAAIACQA9AAAAAgAJAD4AAAACAAkAPwAAAAIACQBAAAAACwAHAEIAAAAAAAIAAQAA"
1632 "AAAAAwAeAAAAAQACAAEAAAABAAMAHgAAAAIAAgAAAAAAAgACAAEAAAADAAIAAQAAAAMAAgAfAAAA"
1633 "AwACACAAAAADAAIAIQAAAAMAAgAiAAAAAwACACMAAAADAAIAJAAAAAMAAgAlAAAAAwACACYAAAAD"
1634 "AAIAJwAAAAMAAgAoAAAAAwACACkAAAADAAIAKgAAAAMABAA0AAAABwADAEMAAAAIAAIAAQAAAAoA"
1635 "AgABAAAACgABADIAAAAKAAAARQAAAAAAAAAAAAAACAAAAAAAAAAdAAAAaAcAALYHAAAAAAAAAQAA"
1636 "AAAAAAAIAAAAAAAAAB0AAAB4BwAAxAcAAAAAAAACAAAAAAAAAAgAAAAAAAAAHQAAAIgHAADSBwAA"
1637 "AAAAAAMAAAAAAAAACAAAAAAAAAAdAAAAmAcAAPoHAAAAAAAAAAAAAAEAAAAAAAAArAYAADEAAAAa"
1638 "AAMAaQAAABoABABpAAEAGgAHAGkABAAaAAgAaQAFABoACQBpAAYAGgAKAGkABwAaAAsAaQAIABoA"
1639 "DABpAAkAGgANAGkACgAaAA4AaQALABoABQBpAAIAGgAGAGkAAwAOAAAAAQABAAEAAACSBgAABAAA"
1640 "AHAQFQAAAA4ABAABAAIAAACWBgAAFwAAAGIADAAiAQoAcBAWAAEAGgICAG4gFwAhAG4gFwAxAG4Q"
1641 "GAABAAwBbiAUABAADgAAAAEAAQABAAAAngYAAAQAAABwEBUAAAAOAAIAAQACAAAAogYAAAYAAABi"
1642 "AAwAbiAUABAADgABAAEAAQAAAKgGAAAEAAAAcBAVAAAADgABAAEAAQAAALsGAAAEAAAAcBAVAAAA"
1643 "DgABAAAAAQAAAL8GAAAGAAAAYgAAAHEQAwAAAA4AAQAAAAEAAADEBgAABgAAAGIAAQBxEAMAAAAO"
1644 "AAEAAAABAAAA8QYAAAYAAABiAAIAcRABAAAADgABAAAAAQAAAPYGAAAGAAAAYgADAHEQAwAAAA4A"
1645 "AQAAAAEAAADJBgAABgAAAGIABABxEAMAAAAOAAEAAAABAAAAzgYAAAYAAABiAAEAcRADAAAADgAB"
1646 "AAAAAQAAANMGAAAGAAAAYgAGAHEQAwAAAA4AAQAAAAEAAADYBgAABgAAAGIABwBxEAMAAAAOAAEA"
1647 "AAABAAAA3QYAAAYAAABiAAgAcRABAAAADgABAAAAAQAAAOIGAAAGAAAAYgAJAHEQAwAAAA4AAQAA"
1648 "AAEAAADnBgAABgAAAGIACgBxEAMAAAAOAAEAAAABAAAA7AYAAAYAAABiAAsAcRABAAAADgABAAEA"
1649 "AAAAAPsGAAAlAAAAcQAHAAAAcQAIAAAAcQALAAAAcQAMAAAAcQANAAAAcQAOAAAAcQAPAAAAcQAQ"
1650 "AAAAcQARAAAAcQASAAAAcQAJAAAAcQAKAAAADgAnAA4AKQFFDgEWDwAhAA4AIwFFDloAEgAOABMA"
1651 "DktLS0tLS0tLS0tLABEADgAuAA5aADIADloANgAOWgA6AA5aAD4ADloAQgAOWgBGAA5aAEoADloA"
1652 "TgAOWgBSAA5aAFYADloAWgAOWgBeATQOPDw8PDw8PDw8PDw8AAIEAUYYAwIFAjEECEEXLAIFAjEE"
1653 "CEEXKwIFAjEECEEXLQIGAUYcAxgAGAEYAgAAAAIAAAAMBwAAEgcAAAIAAAAMBwAAGwcAAAIAAAAM"
1654 "BwAAJAcAAAEAAAAtBwAAPAcAAAAAAAAAAAAAAAAAAEgHAAAAAAAAAAAAAAAAAABUBwAAAAAAAAAA"
1655 "AAAAAAAAYAcAAAAAAAAAAAAAAAAAAAEAAAAJAAAAAQAAAA0AAAACAACAgASsCAEIxAgAAAIAAoCA"
1656 "BIQJAQicCQwAAgAACQEJAQkBCQEJAQkBCQEJAQkBCQEJAQkEiIAEuAcBgIAEuAkAAA4ABoCABNAJ"
1657 "AQnoCQAJhAoACaAKAAm8CgAJ2AoACfQKAAmQCwAJrAsACcgLAAnkCwAJgAwACZwMAAm4DAg8Y2xp"
1658 "bml0PgAGPGluaXQ+AANBQUEAC0hlbGxvIFdvcmxkAAxIZWxsbyBXb3JsZDEADUhlbGxvIFdvcmxk"
1659 "MTAADUhlbGxvIFdvcmxkMTEADEhlbGxvIFdvcmxkMgAMSGVsbG8gV29ybGQzAAxIZWxsbyBXb3Js"
1660 "ZDQADEhlbGxvIFdvcmxkNQAMSGVsbG8gV29ybGQ2AAxIZWxsbyBXb3JsZDcADEhlbGxvIFdvcmxk"
1661 "OAAMSGVsbG8gV29ybGQ5AAFMAAJMTAAWTE1hbnlNZXRob2RzJFByaW50ZXIyOwAVTE1hbnlNZXRo"
1662 "b2RzJFByaW50ZXI7ABVMTWFueU1ldGhvZHMkU3RyaW5nczsADUxNYW55TWV0aG9kczsAIkxkYWx2"
1663 "aWsvYW5ub3RhdGlvbi9FbmNsb3NpbmdDbGFzczsAHkxkYWx2aWsvYW5ub3RhdGlvbi9Jbm5lckNs"
1664 "YXNzOwAhTGRhbHZpay9hbm5vdGF0aW9uL01lbWJlckNsYXNzZXM7ABVMamF2YS9pby9QcmludFN0"
1665 "cmVhbTsAEkxqYXZhL2xhbmcvT2JqZWN0OwASTGphdmEvbGFuZy9TdHJpbmc7ABlMamF2YS9sYW5n"
1666 "L1N0cmluZ0J1aWxkZXI7ABJMamF2YS9sYW5nL1N5c3RlbTsAEE1hbnlNZXRob2RzLmphdmEABVBy"
1667 "aW50AAZQcmludDAABlByaW50MQAHUHJpbnQxMAAHUHJpbnQxMQAGUHJpbnQyAAZQcmludDMABlBy"
1668 "aW50NAAGUHJpbnQ1AAZQcmludDYABlByaW50NwAGUHJpbnQ4AAZQcmludDkAB1ByaW50ZXIACFBy"
1669 "aW50ZXIyAAdTdHJpbmdzAAFWAAJWTAATW0xqYXZhL2xhbmcvU3RyaW5nOwALYWNjZXNzRmxhZ3MA"
1670 "BmFwcGVuZAAEYXJncwAEbWFpbgAEbXNnMAAEbXNnMQAFbXNnMTAABW1zZzExAARtc2cyAARtc2cz"
1671 "AARtc2c0AARtc2c1AARtc2c2AARtc2c3AARtc2c4AARtc2c5AARuYW1lAANvdXQAB3ByaW50bG4A"
1672 "AXMACHRvU3RyaW5nAAV2YWx1ZQBffn5EOHsibWluLWFwaSI6MTAwMDAsInNoYS0xIjoiZmViODZj"
1673 "MDA2ZWZhY2YxZDc5ODRiODVlMTc5MGZlZjdhNzY3YWViYyIsInZlcnNpb24iOiJ2MS4xLjUtZGV2"
1674 "In0AEAAAAAAAAAABAAAAAAAAAAEAAABIAAAAcAAAAAIAAAAOAAAAkAEAAAMAAAAFAAAAyAEAAAQA"
1675 "AAANAAAABAIAAAUAAAAZAAAAbAIAAAYAAAAEAAAANAMAAAEgAAAUAAAAuAMAAAMgAAAUAAAAkgYA"
1676 "AAQgAAAFAAAADAcAAAMQAAAEAAAAOQcAAAYgAAAEAAAAaAcAAAEQAAACAAAAqAcAAAAgAAAEAAAA"
1677 "tgcAAAIgAABIAAAAOAgAAAAQAAABAAAA0AsAAAAAAAA=";
1678
1679static void WriteBase64ToFile(const char* base64, File* file) {
1680 // Decode base64.
1681 CHECK(base64 != nullptr);
1682 size_t length;
1683 std::unique_ptr<uint8_t[]> bytes(DecodeBase64(base64, &length));
1684 CHECK(bytes != nullptr);
1685 if (!file->WriteFully(bytes.get(), length)) {
1686 PLOG(FATAL) << "Failed to write base64 as file";
1687 }
1688}
1689
1690TEST_F(Dex2oatTest, CompactDexGenerationFailure) {
1691 ScratchFile temp_dex;
1692 WriteBase64ToFile(kDuplicateMethodInputDex, temp_dex.GetFile());
1693 std::string out_dir = GetScratchDir();
1694 const std::string oat_filename = out_dir + "/base.oat";
1695 // The dex won't pass the method verifier, only use the verify filter.
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001696 ASSERT_TRUE(GenerateOdexForTest(temp_dex.GetFilename(),
1697 oat_filename,
1698 CompilerFilter::Filter::kVerify,
1699 { },
1700 true, // expect_success
1701 false, // use_fd
1702 [](const OatFile& o) {
1703 CHECK(o.ContainsDexCode());
1704 }));
Mathieu Chartier05f90d12018-02-07 13:47:17 -08001705 // Open our generated oat file.
1706 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001707 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01001708 oat_filename.c_str(),
Mathieu Chartier05f90d12018-02-07 13:47:17 -08001709 oat_filename.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001710 /*executable=*/ false,
1711 /*low_4gb=*/ false,
Mathieu Chartier05f90d12018-02-07 13:47:17 -08001712 temp_dex.GetFilename().c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001713 /*reservation=*/ nullptr,
Mathieu Chartier05f90d12018-02-07 13:47:17 -08001714 &error_msg));
1715 ASSERT_TRUE(odex_file != nullptr);
1716 std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
1717 ASSERT_EQ(oat_dex_files.size(), 1u);
1718 // The dexes should have failed to convert to compact dex.
1719 for (const OatDexFile* oat_dex : oat_dex_files) {
1720 std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1721 ASSERT_TRUE(dex_file != nullptr) << error_msg;
1722 ASSERT_TRUE(!dex_file->IsCompactDexFile());
1723 }
1724}
1725
Mathieu Chartiercda83be2018-03-01 23:55:55 -08001726TEST_F(Dex2oatTest, CompactDexGenerationFailureMultiDex) {
1727 // Create a multidex file with only one dex that gets rejected for cdex conversion.
1728 ScratchFile apk_file;
1729 {
Andreas Gampedfcd82c2018-10-16 20:22:37 -07001730 FILE* file = fdopen(DupCloexec(apk_file.GetFd()), "w+b");
Mathieu Chartiercda83be2018-03-01 23:55:55 -08001731 ZipWriter writer(file);
1732 // Add vdex to zip.
1733 writer.StartEntry("classes.dex", ZipWriter::kCompress);
1734 size_t length = 0u;
1735 std::unique_ptr<uint8_t[]> bytes(DecodeBase64(kDuplicateMethodInputDex, &length));
1736 ASSERT_GE(writer.WriteBytes(&bytes[0], length), 0);
1737 writer.FinishEntry();
1738 writer.StartEntry("classes2.dex", ZipWriter::kCompress);
1739 std::unique_ptr<const DexFile> dex(OpenTestDexFile("ManyMethods"));
1740 ASSERT_GE(writer.WriteBytes(dex->Begin(), dex->Size()), 0);
1741 writer.FinishEntry();
1742 writer.Finish();
1743 ASSERT_EQ(apk_file.GetFile()->Flush(), 0);
1744 }
Andreas Gampebc802de2018-06-20 17:24:11 -07001745 const std::string& dex_location = apk_file.GetFilename();
Mathieu Chartiercda83be2018-03-01 23:55:55 -08001746 const std::string odex_location = GetOdexDir() + "/output.odex";
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001747 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1748 odex_location,
1749 CompilerFilter::kQuicken,
1750 { "--compact-dex-level=fast" },
1751 true));
Mathieu Chartiercda83be2018-03-01 23:55:55 -08001752}
1753
Andreas Gampe25419b52018-02-08 21:30:26 -08001754TEST_F(Dex2oatTest, StderrLoggerOutput) {
1755 std::string dex_location = GetScratchDir() + "/Dex2OatStderrLoggerTest.jar";
1756 std::string odex_location = GetOdexDir() + "/Dex2OatStderrLoggerTest.odex";
1757
1758 // Test file doesn't matter.
1759 Copy(GetDexSrc1(), dex_location);
1760
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001761 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1762 odex_location,
1763 CompilerFilter::kQuicken,
1764 { "--runtime-arg", "-Xuse-stderr-logger" },
1765 true));
Andreas Gampe25419b52018-02-08 21:30:26 -08001766 // Look for some random part of dex2oat logging. With the stderr logger this should be captured,
1767 // even on device.
1768 EXPECT_NE(std::string::npos, output_.find("dex2oat took"));
1769}
1770
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001771TEST_F(Dex2oatTest, VerifyCompilationReason) {
1772 std::string dex_location = GetScratchDir() + "/Dex2OatCompilationReason.jar";
1773 std::string odex_location = GetOdexDir() + "/Dex2OatCompilationReason.odex";
1774
1775 // Test file doesn't matter.
1776 Copy(GetDexSrc1(), dex_location);
1777
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001778 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1779 odex_location,
1780 CompilerFilter::kVerify,
1781 { "--compilation-reason=install" },
1782 true));
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001783 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001784 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01001785 odex_location.c_str(),
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001786 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001787 /*executable=*/ false,
1788 /*low_4gb=*/ false,
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001789 dex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001790 /*reservation=*/ nullptr,
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001791 &error_msg));
1792 ASSERT_TRUE(odex_file != nullptr);
1793 ASSERT_STREQ("install", odex_file->GetCompilationReason());
1794}
1795
1796TEST_F(Dex2oatTest, VerifyNoCompilationReason) {
1797 std::string dex_location = GetScratchDir() + "/Dex2OatNoCompilationReason.jar";
1798 std::string odex_location = GetOdexDir() + "/Dex2OatNoCompilationReason.odex";
1799
1800 // Test file doesn't matter.
1801 Copy(GetDexSrc1(), dex_location);
1802
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001803 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1804 odex_location,
1805 CompilerFilter::kVerify,
1806 {},
1807 true));
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001808 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001809 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01001810 odex_location.c_str(),
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001811 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001812 /*executable=*/ false,
1813 /*low_4gb=*/ false,
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001814 dex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001815 /*reservation=*/ nullptr,
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001816 &error_msg));
1817 ASSERT_TRUE(odex_file != nullptr);
1818 ASSERT_EQ(nullptr, odex_file->GetCompilationReason());
1819}
1820
Mathieu Chartier792111c2018-02-15 13:02:15 -08001821TEST_F(Dex2oatTest, DontExtract) {
1822 std::unique_ptr<const DexFile> dex(OpenTestDexFile("ManyMethods"));
1823 std::string error_msg;
1824 const std::string out_dir = GetScratchDir();
1825 const std::string dex_location = dex->GetLocation();
1826 const std::string odex_location = out_dir + "/base.oat";
1827 const std::string vdex_location = out_dir + "/base.vdex";
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001828 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1829 odex_location,
1830 CompilerFilter::Filter::kVerify,
1831 { "--copy-dex-files=false" },
1832 true, // expect_success
1833 false, // use_fd
1834 [](const OatFile&) {}));
Mathieu Chartier792111c2018-02-15 13:02:15 -08001835 {
1836 // Check the vdex doesn't have dex.
1837 std::unique_ptr<VdexFile> vdex(VdexFile::Open(vdex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001838 /*writable=*/ false,
1839 /*low_4gb=*/ false,
1840 /*unquicken=*/ false,
Mathieu Chartier792111c2018-02-15 13:02:15 -08001841 &error_msg));
1842 ASSERT_TRUE(vdex != nullptr);
Nicolas Geoffray3a293552018-03-02 10:52:16 +00001843 EXPECT_FALSE(vdex->HasDexSection()) << output_;
Mathieu Chartier792111c2018-02-15 13:02:15 -08001844 }
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001845 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01001846 odex_location.c_str(),
Mathieu Chartier792111c2018-02-15 13:02:15 -08001847 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001848 /*executable=*/ false,
1849 /*low_4gb=*/ false,
Mathieu Chartier792111c2018-02-15 13:02:15 -08001850 dex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001851 /*reservation=*/ nullptr,
Mathieu Chartier792111c2018-02-15 13:02:15 -08001852 &error_msg));
1853 ASSERT_TRUE(odex_file != nullptr) << dex_location;
1854 std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
1855 ASSERT_EQ(oat_dex_files.size(), 1u);
1856 // Verify that the oat file can still open the dex files.
1857 for (const OatDexFile* oat_dex : oat_dex_files) {
1858 std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1859 ASSERT_TRUE(dex_file != nullptr) << error_msg;
1860 }
1861 // Create a dm file and use it to verify.
1862 // Add produced artifacts to a zip file that doesn't contain the classes.dex.
1863 ScratchFile dm_file;
1864 {
1865 std::unique_ptr<File> vdex_file(OS::OpenFileForReading(vdex_location.c_str()));
1866 ASSERT_TRUE(vdex_file != nullptr);
1867 ASSERT_GT(vdex_file->GetLength(), 0u);
Andreas Gampedfcd82c2018-10-16 20:22:37 -07001868 FILE* file = fdopen(DupCloexec(dm_file.GetFd()), "w+b");
Mathieu Chartier792111c2018-02-15 13:02:15 -08001869 ZipWriter writer(file);
1870 auto write_all_bytes = [&](File* file) {
1871 std::unique_ptr<uint8_t[]> bytes(new uint8_t[file->GetLength()]);
1872 ASSERT_TRUE(file->ReadFully(&bytes[0], file->GetLength()));
1873 ASSERT_GE(writer.WriteBytes(&bytes[0], file->GetLength()), 0);
1874 };
1875 // Add vdex to zip.
1876 writer.StartEntry(VdexFile::kVdexNameInDmFile, ZipWriter::kCompress);
1877 write_all_bytes(vdex_file.get());
1878 writer.FinishEntry();
1879 writer.Finish();
1880 ASSERT_EQ(dm_file.GetFile()->Flush(), 0);
1881 }
1882
Mathieu Chartier2eabc612018-05-25 14:31:16 -07001883 auto generate_and_check = [&](CompilerFilter::Filter filter) {
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001884 output_.clear();
1885 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1886 odex_location,
1887 filter,
1888 { "--dump-timings",
1889 "--dm-file=" + dm_file.GetFilename(),
1890 // Pass -Xuse-stderr-logger have dex2oat output in output_ on
1891 // target.
1892 "--runtime-arg",
1893 "-Xuse-stderr-logger" },
1894 true, // expect_success
1895 false, // use_fd
1896 [](const OatFile& o) {
1897 CHECK(o.ContainsDexCode());
1898 }));
Mathieu Chartier2eabc612018-05-25 14:31:16 -07001899 // Check the output for "Fast verify", this is printed from --dump-timings.
1900 std::istringstream iss(output_);
1901 std::string line;
1902 bool found_fast_verify = false;
1903 const std::string kFastVerifyString = "Fast Verify";
1904 while (std::getline(iss, line) && !found_fast_verify) {
1905 found_fast_verify = found_fast_verify || line.find(kFastVerifyString) != std::string::npos;
1906 }
1907 EXPECT_TRUE(found_fast_verify) << "Expected to find " << kFastVerifyString << "\n" << output_;
1908 };
1909
Mathieu Chartier792111c2018-02-15 13:02:15 -08001910 // Generate a quickened dex by using the input dm file to verify.
Mathieu Chartier2eabc612018-05-25 14:31:16 -07001911 generate_and_check(CompilerFilter::Filter::kQuicken);
1912 // Use verify compiler filter to sanity check that FastVerify works for that filter too.
1913 generate_and_check(CompilerFilter::Filter::kVerify);
Mathieu Chartier792111c2018-02-15 13:02:15 -08001914}
1915
Mathieu Chartier2daa1342018-02-20 16:19:28 -08001916// Test that dex files with quickened opcodes aren't dequickened.
1917TEST_F(Dex2oatTest, QuickenedInput) {
1918 std::string error_msg;
1919 ScratchFile temp_dex;
1920 MutateDexFile(temp_dex.GetFile(), GetTestDexFileName("ManyMethods"), [] (DexFile* dex) {
1921 bool mutated_successfully = false;
1922 // Change the dex instructions to make an opcode that spans past the end of the code item.
Mathieu Chartier2242ef12018-07-23 18:14:13 -07001923 for (ClassAccessor accessor : dex->GetClasses()) {
1924 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
1925 CodeItemInstructionAccessor instructions = method.GetInstructions();
1926 // Make a quickened instruction that doesn't run past the end of the code item.
1927 if (instructions.InsnsSizeInCodeUnits() > 2) {
1928 const_cast<Instruction&>(instructions.InstructionAt(0)).SetOpcode(
1929 Instruction::IGET_BYTE_QUICK);
1930 mutated_successfully = true;
Mathieu Chartier2daa1342018-02-20 16:19:28 -08001931 }
Mathieu Chartier2daa1342018-02-20 16:19:28 -08001932 }
1933 }
1934 CHECK(mutated_successfully)
1935 << "Failed to find candidate code item with only one code unit in last instruction.";
1936 });
1937
Andreas Gampebc802de2018-06-20 17:24:11 -07001938 const std::string& dex_location = temp_dex.GetFilename();
Mathieu Chartier2daa1342018-02-20 16:19:28 -08001939 std::string odex_location = GetOdexDir() + "/quickened.odex";
1940 std::string vdex_location = GetOdexDir() + "/quickened.vdex";
1941 std::unique_ptr<File> vdex_output(OS::CreateEmptyFile(vdex_location.c_str()));
1942 // Quicken the dex
1943 {
1944 std::string input_vdex = "--input-vdex-fd=-1";
1945 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_output->Fd());
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001946 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1947 odex_location,
1948 CompilerFilter::kQuicken,
1949 // Disable cdex since we want to compare against the original
1950 // dex file after unquickening.
1951 { input_vdex, output_vdex, kDisableCompactDex },
1952 /* expect_success= */ true,
1953 /* use_fd= */ true));
Mathieu Chartier2daa1342018-02-20 16:19:28 -08001954 }
1955 // Unquicken by running the verify compiler filter on the vdex file and verify it matches.
1956 std::string odex_location2 = GetOdexDir() + "/unquickened.odex";
1957 std::string vdex_location2 = GetOdexDir() + "/unquickened.vdex";
1958 std::unique_ptr<File> vdex_unquickened(OS::CreateEmptyFile(vdex_location2.c_str()));
1959 {
1960 std::string input_vdex = StringPrintf("--input-vdex-fd=%d", vdex_output->Fd());
1961 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_unquickened->Fd());
Andreas Gampe50f9dc22018-11-05 10:29:43 -08001962 ASSERT_TRUE(GenerateOdexForTest(dex_location,
1963 odex_location2,
1964 CompilerFilter::kVerify,
1965 // Disable cdex to avoid needing to write out the shared
1966 // section.
1967 { input_vdex, output_vdex, kDisableCompactDex },
1968 /* expect_success= */ true,
1969 /* use_fd= */ true));
Mathieu Chartier2daa1342018-02-20 16:19:28 -08001970 }
1971 ASSERT_EQ(vdex_unquickened->Flush(), 0) << "Could not flush and close vdex file";
1972 ASSERT_TRUE(success_);
1973 {
1974 // Check that hte vdex has one dex and compare it to the original one.
1975 std::unique_ptr<VdexFile> vdex(VdexFile::Open(vdex_location2.c_str(),
1976 /*writable*/ false,
1977 /*low_4gb*/ false,
1978 /*unquicken*/ false,
1979 &error_msg));
1980 std::vector<std::unique_ptr<const DexFile>> dex_files;
1981 bool result = vdex->OpenAllDexFiles(&dex_files, &error_msg);
1982 ASSERT_TRUE(result) << error_msg;
1983 ASSERT_EQ(dex_files.size(), 1u) << error_msg;
1984 ScratchFile temp;
1985 ASSERT_TRUE(temp.GetFile()->WriteFully(dex_files[0]->Begin(), dex_files[0]->Size()));
1986 ASSERT_EQ(temp.GetFile()->Flush(), 0) << "Could not flush extracted dex";
1987 EXPECT_EQ(temp.GetFile()->Compare(temp_dex.GetFile()), 0);
1988 }
1989 ASSERT_EQ(vdex_output->FlushCloseOrErase(), 0) << "Could not flush and close";
1990 ASSERT_EQ(vdex_unquickened->FlushCloseOrErase(), 0) << "Could not flush and close";
1991}
1992
Mathieu Chartierd45863a2018-03-21 18:16:36 -07001993// Test that compact dex generation with invalid dex files doesn't crash dex2oat. b/75970654
1994TEST_F(Dex2oatTest, CompactDexInvalidSource) {
1995 ScratchFile invalid_dex;
1996 {
Andreas Gampedfcd82c2018-10-16 20:22:37 -07001997 FILE* file = fdopen(DupCloexec(invalid_dex.GetFd()), "w+b");
Mathieu Chartierd45863a2018-03-21 18:16:36 -07001998 ZipWriter writer(file);
1999 writer.StartEntry("classes.dex", ZipWriter::kAlign32);
2000 DexFile::Header header = {};
2001 StandardDexFile::WriteMagic(header.magic_);
2002 StandardDexFile::WriteCurrentVersion(header.magic_);
2003 header.file_size_ = 4 * KB;
2004 header.data_size_ = 4 * KB;
2005 header.data_off_ = 10 * MB;
2006 header.map_off_ = 10 * MB;
2007 header.class_defs_off_ = 10 * MB;
2008 header.class_defs_size_ = 10000;
2009 ASSERT_GE(writer.WriteBytes(&header, sizeof(header)), 0);
2010 writer.FinishEntry();
2011 writer.Finish();
2012 ASSERT_EQ(invalid_dex.GetFile()->Flush(), 0);
2013 }
Andreas Gampebc802de2018-06-20 17:24:11 -07002014 const std::string& dex_location = invalid_dex.GetFilename();
Mathieu Chartierd45863a2018-03-21 18:16:36 -07002015 const std::string odex_location = GetOdexDir() + "/output.odex";
2016 std::string error_msg;
2017 int status = GenerateOdexForTestWithStatus(
2018 {dex_location},
2019 odex_location,
2020 CompilerFilter::kQuicken,
2021 &error_msg,
2022 { "--compact-dex-level=fast" });
2023 ASSERT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) != 0) << status << " " << output_;
2024}
2025
Mathieu Chartier14e7bad2018-03-22 14:33:20 -07002026// Test that dex2oat with a CompactDex file in the APK fails.
2027TEST_F(Dex2oatTest, CompactDexInZip) {
2028 CompactDexFile::Header header = {};
2029 CompactDexFile::WriteMagic(header.magic_);
2030 CompactDexFile::WriteCurrentVersion(header.magic_);
2031 header.file_size_ = sizeof(CompactDexFile::Header);
2032 header.data_off_ = 10 * MB;
2033 header.map_off_ = 10 * MB;
2034 header.class_defs_off_ = 10 * MB;
2035 header.class_defs_size_ = 10000;
2036 // Create a zip containing the invalid dex.
2037 ScratchFile invalid_dex_zip;
2038 {
Andreas Gampedfcd82c2018-10-16 20:22:37 -07002039 FILE* file = fdopen(DupCloexec(invalid_dex_zip.GetFd()), "w+b");
Mathieu Chartier14e7bad2018-03-22 14:33:20 -07002040 ZipWriter writer(file);
2041 writer.StartEntry("classes.dex", ZipWriter::kCompress);
2042 ASSERT_GE(writer.WriteBytes(&header, sizeof(header)), 0);
2043 writer.FinishEntry();
2044 writer.Finish();
2045 ASSERT_EQ(invalid_dex_zip.GetFile()->Flush(), 0);
2046 }
2047 // Create the dex file directly.
2048 ScratchFile invalid_dex;
2049 {
2050 ASSERT_GE(invalid_dex.GetFile()->WriteFully(&header, sizeof(header)), 0);
2051 ASSERT_EQ(invalid_dex.GetFile()->Flush(), 0);
2052 }
2053 std::string error_msg;
2054 int status = 0u;
2055
2056 status = GenerateOdexForTestWithStatus(
2057 { invalid_dex_zip.GetFilename() },
2058 GetOdexDir() + "/output_apk.odex",
2059 CompilerFilter::kQuicken,
2060 &error_msg,
2061 { "--compact-dex-level=fast" });
2062 ASSERT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) != 0) << status << " " << output_;
2063
2064 status = GenerateOdexForTestWithStatus(
2065 { invalid_dex.GetFilename() },
2066 GetOdexDir() + "/output.odex",
2067 CompilerFilter::kQuicken,
2068 &error_msg,
2069 { "--compact-dex-level=fast" });
2070 ASSERT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) != 0) << status << " " << output_;
2071}
2072
Mathieu Chartierf85b3db2018-04-02 18:16:21 -07002073TEST_F(Dex2oatTest, AppImageNoProfile) {
2074 ScratchFile app_image_file;
2075 const std::string out_dir = GetScratchDir();
2076 const std::string odex_location = out_dir + "/base.odex";
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002077 ASSERT_TRUE(GenerateOdexForTest(GetTestDexFileName("ManyMethods"),
2078 odex_location,
2079 CompilerFilter::Filter::kSpeedProfile,
2080 { "--app-image-fd=" + std::to_string(app_image_file.GetFd()) },
2081 true, // expect_success
2082 false, // use_fd
2083 [](const OatFile&) {}));
Mathieu Chartierf85b3db2018-04-02 18:16:21 -07002084 // Open our generated oat file.
2085 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002086 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Nicolas Geoffray30025092018-04-19 14:43:29 +01002087 odex_location.c_str(),
Mathieu Chartierf85b3db2018-04-02 18:16:21 -07002088 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002089 /*executable=*/ false,
2090 /*low_4gb=*/ false,
Mathieu Chartierf85b3db2018-04-02 18:16:21 -07002091 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002092 /*reservation=*/ nullptr,
Mathieu Chartierf85b3db2018-04-02 18:16:21 -07002093 &error_msg));
2094 ASSERT_TRUE(odex_file != nullptr);
2095 ImageHeader header = {};
2096 ASSERT_TRUE(app_image_file.GetFile()->PreadFully(
2097 reinterpret_cast<void*>(&header),
2098 sizeof(header),
2099 /*offset*/ 0u)) << app_image_file.GetFile()->GetLength();
2100 EXPECT_GT(header.GetImageSection(ImageHeader::kSectionObjects).Size(), 0u);
2101 EXPECT_EQ(header.GetImageSection(ImageHeader::kSectionArtMethods).Size(), 0u);
2102 EXPECT_EQ(header.GetImageSection(ImageHeader::kSectionArtFields).Size(), 0u);
2103}
2104
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002105TEST_F(Dex2oatTest, AppImageResolveStrings) {
2106 using Hotness = ProfileCompilationInfo::MethodHotness;
2107 // Create a profile with the startup method marked.
2108 ScratchFile profile_file;
2109 std::vector<uint16_t> methods;
Mathieu Chartier22752772018-10-18 14:18:59 -07002110 std::vector<dex::TypeIndex> classes;
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07002111 std::unique_ptr<const DexFile> dex(OpenTestDexFile("StringLiterals"));
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002112 {
Mathieu Chartier22752772018-10-18 14:18:59 -07002113 for (ClassAccessor accessor : dex->GetClasses()) {
2114 if (accessor.GetDescriptor() == std::string("LStringLiterals$StartupClass;")) {
2115 classes.push_back(accessor.GetClassIdx());
2116 }
2117 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
2118 std::string method_name(dex->GetMethodName(dex->GetMethodId(method.GetIndex())));
2119 if (method_name == "startUpMethod") {
2120 methods.push_back(method.GetIndex());
2121 }
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002122 }
2123 }
Mathieu Chartier22752772018-10-18 14:18:59 -07002124 ASSERT_GT(classes.size(), 0u);
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002125 ASSERT_GT(methods.size(), 0u);
2126 // Here, we build the profile from the method lists.
2127 ProfileCompilationInfo info;
Mathieu Chartier22752772018-10-18 14:18:59 -07002128 info.AddClassesForDex(dex.get(), classes.begin(), classes.end());
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002129 info.AddMethodsForDex(Hotness::kFlagStartup, dex.get(), methods.begin(), methods.end());
2130 // Save the profile since we want to use it with dex2oat to produce an oat file.
2131 ASSERT_TRUE(info.Save(profile_file.GetFd()));
2132 }
2133 const std::string out_dir = GetScratchDir();
2134 const std::string odex_location = out_dir + "/base.odex";
2135 const std::string app_image_location = out_dir + "/base.art";
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002136 ASSERT_TRUE(GenerateOdexForTest(GetTestDexFileName("StringLiterals"),
2137 odex_location,
2138 CompilerFilter::Filter::kSpeedProfile,
2139 { "--app-image-file=" + app_image_location,
2140 "--resolve-startup-const-strings=true",
2141 "--profile-file=" + profile_file.GetFilename()},
2142 /* expect_success= */ true,
2143 /* use_fd= */ false,
2144 [](const OatFile&) {}));
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002145 // Open our generated oat file.
2146 std::string error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002147 std::unique_ptr<OatFile> odex_file(OatFile::Open(/*zip_fd=*/ -1,
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002148 odex_location.c_str(),
2149 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002150 /*executable=*/ false,
2151 /*low_4gb=*/ false,
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002152 odex_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002153 /*reservation=*/ nullptr,
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002154 &error_msg));
2155 ASSERT_TRUE(odex_file != nullptr);
2156 // Check the strings in the app image intern table only contain the "startup" strigs.
2157 {
2158 ScopedObjectAccess soa(Thread::Current());
2159 std::unique_ptr<gc::space::ImageSpace> space =
2160 gc::space::ImageSpace::CreateFromAppImage(app_image_location.c_str(),
2161 odex_file.get(),
2162 &error_msg);
2163 ASSERT_TRUE(space != nullptr) << error_msg;
2164 std::set<std::string> seen;
2165 InternTable intern_table;
2166 intern_table.AddImageStringsToTable(space.get(), [&](InternTable::UnorderedSet& interns)
2167 REQUIRES_SHARED(Locks::mutator_lock_) {
2168 for (const GcRoot<mirror::String>& str : interns) {
2169 seen.insert(str.Read()->ToModifiedUtf8());
2170 }
2171 });
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07002172 // Ensure that the dex cache has a preresolved string array.
2173 std::set<std::string> preresolved_seen;
2174 bool saw_dexcache = false;
2175 space->GetLiveBitmap()->VisitAllMarked(
2176 [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
2177 if (obj->IsDexCache<kVerifyNone>()) {
2178 ObjPtr<mirror::DexCache> dex_cache = obj->AsDexCache();
2179 GcRoot<mirror::String>* preresolved_strings = dex_cache->GetPreResolvedStrings();
2180 ASSERT_EQ(dex->NumStringIds(), dex_cache->NumPreResolvedStrings());
2181 for (size_t i = 0; i < dex_cache->NumPreResolvedStrings(); ++i) {
2182 ObjPtr<mirror::String> string = preresolved_strings[i].Read<kWithoutReadBarrier>();
2183 if (string != nullptr) {
2184 preresolved_seen.insert(string->ToModifiedUtf8());
2185 }
2186 }
2187 saw_dexcache = true;
2188 }
2189 });
2190 ASSERT_TRUE(saw_dexcache);
2191 // Everything in the preresolved array should also be in the intern table.
2192 for (const std::string& str : preresolved_seen) {
2193 EXPECT_TRUE(seen.find(str) != seen.end());
2194 }
Mathieu Chartier22752772018-10-18 14:18:59 -07002195 // Normal methods
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07002196 EXPECT_TRUE(preresolved_seen.find("Loading ") != preresolved_seen.end());
2197 EXPECT_TRUE(preresolved_seen.find("Starting up") != preresolved_seen.end());
2198 EXPECT_TRUE(preresolved_seen.find("abcd.apk") != preresolved_seen.end());
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002199 EXPECT_TRUE(seen.find("Unexpected error") == seen.end());
2200 EXPECT_TRUE(seen.find("Shutting down!") == seen.end());
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07002201 EXPECT_TRUE(preresolved_seen.find("Unexpected error") == preresolved_seen.end());
2202 EXPECT_TRUE(preresolved_seen.find("Shutting down!") == preresolved_seen.end());
Mathieu Chartier22752772018-10-18 14:18:59 -07002203 // Classes initializers
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07002204 EXPECT_TRUE(preresolved_seen.find("Startup init") != preresolved_seen.end());
Mathieu Chartier22752772018-10-18 14:18:59 -07002205 EXPECT_TRUE(seen.find("Other class init") == seen.end());
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07002206 EXPECT_TRUE(preresolved_seen.find("Other class init") == preresolved_seen.end());
2207 // Expect the sets match.
2208 EXPECT_GE(seen.size(), preresolved_seen.size());
Mathieu Chartier8cc418e2018-10-31 10:54:30 -07002209
2210 // Verify what strings are marked as boot image.
2211 std::set<std::string> boot_image_strings;
2212 std::set<std::string> app_image_strings;
2213
2214 MutexLock mu(Thread::Current(), *Locks::intern_table_lock_);
2215 intern_table.VisitInterns([&](const GcRoot<mirror::String>& root)
2216 REQUIRES_SHARED(Locks::mutator_lock_) {
2217 boot_image_strings.insert(root.Read()->ToModifiedUtf8());
2218 }, /*visit_boot_images=*/true, /*visit_non_boot_images=*/false);
2219 intern_table.VisitInterns([&](const GcRoot<mirror::String>& root)
2220 REQUIRES_SHARED(Locks::mutator_lock_) {
2221 app_image_strings.insert(root.Read()->ToModifiedUtf8());
2222 }, /*visit_boot_images=*/false, /*visit_non_boot_images=*/true);
2223 EXPECT_EQ(boot_image_strings.size(), 0u);
2224 EXPECT_TRUE(app_image_strings == seen);
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -07002225 }
2226}
2227
2228
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002229TEST_F(Dex2oatClassLoaderContextTest, StoredClassLoaderContext) {
Mathieu Chartierc4440772018-04-16 14:40:56 -07002230 std::vector<std::unique_ptr<const DexFile>> dex_files = OpenTestDexFiles("MultiDex");
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002231 const std::string out_dir = GetScratchDir();
2232 const std::string odex_location = out_dir + "/base.odex";
Mathieu Chartierc4440772018-04-16 14:40:56 -07002233 const std::string valid_context = "PCL[" + dex_files[0]->GetLocation() + "]";
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002234 const std::string stored_context = "PCL[/system/not_real_lib.jar]";
Mathieu Chartierc4440772018-04-16 14:40:56 -07002235 std::string expected_stored_context = "PCL[";
2236 size_t index = 1;
2237 for (const std::unique_ptr<const DexFile>& dex_file : dex_files) {
2238 const bool is_first = index == 1u;
2239 if (!is_first) {
2240 expected_stored_context += ":";
2241 }
2242 expected_stored_context += "/system/not_real_lib.jar";
2243 if (!is_first) {
2244 expected_stored_context += "!classes" + std::to_string(index) + ".dex";
2245 }
2246 expected_stored_context += "*" + std::to_string(dex_file->GetLocationChecksum());
2247 ++index;
2248 }
2249 expected_stored_context += + "]";
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002250 // The class path should not be valid and should fail being stored.
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002251 EXPECT_TRUE(GenerateOdexForTest(GetTestDexFileName("ManyMethods"),
2252 odex_location,
2253 CompilerFilter::Filter::kQuicken,
2254 { "--class-loader-context=" + stored_context },
2255 true, // expect_success
2256 false, // use_fd
2257 [&](const OatFile& oat_file) {
Mathieu Chartierc4440772018-04-16 14:40:56 -07002258 EXPECT_NE(oat_file.GetClassLoaderContext(), stored_context) << output_;
2259 EXPECT_NE(oat_file.GetClassLoaderContext(), valid_context) << output_;
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002260 }));
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002261 // The stored context should match what we expect even though it's invalid.
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002262 EXPECT_TRUE(GenerateOdexForTest(GetTestDexFileName("ManyMethods"),
2263 odex_location,
2264 CompilerFilter::Filter::kQuicken,
2265 { "--class-loader-context=" + valid_context,
2266 "--stored-class-loader-context=" + stored_context },
2267 true, // expect_success
2268 false, // use_fd
2269 [&](const OatFile& oat_file) {
Mathieu Chartierc4440772018-04-16 14:40:56 -07002270 EXPECT_EQ(oat_file.GetClassLoaderContext(), expected_stored_context) << output_;
Andreas Gampe50f9dc22018-11-05 10:29:43 -08002271 }));
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002272}
2273
Andreas Gampee1459ae2016-06-29 09:36:30 -07002274} // namespace art