blob: 1196d113d4c066d8067c8356bb5c9c5393b5d99f [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>
26#include <android-base/stringprintf.h>
Andreas Gampe46ee31b2016-12-14 10:11:49 -080027
Andreas Gampee1459ae2016-06-29 09:36:30 -070028#include "common_runtime_test.h"
29
Andreas Gampee1459ae2016-06-29 09:36:30 -070030#include "base/macros.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070031#include "base/mutex-inl.h"
David Sehrc431b9d2018-03-02 12:01:51 -080032#include "base/utils.h"
David Sehr013fd802018-01-11 22:55:24 -080033#include "dex/art_dex_file_loader.h"
Mathieu Chartier05f90d12018-02-07 13:47:17 -080034#include "dex/base64_test_util.h"
David Sehr312f3b22018-03-19 08:39:26 -070035#include "dex/bytecode_utils.h"
David Sehr9e734c72018-01-04 17:56:19 -080036#include "dex/code_item_accessors-inl.h"
37#include "dex/dex_file-inl.h"
38#include "dex/dex_file_loader.h"
Andreas Gampee1459ae2016-06-29 09:36:30 -070039#include "dex2oat_environment_test.h"
Andreas Gampef7882972017-03-20 16:35:24 -070040#include "dex2oat_return_codes.h"
Andreas Gampe67f02822016-06-24 21:05:23 -070041#include "oat.h"
42#include "oat_file.h"
David Sehr82d046e2018-04-23 08:14:19 -070043#include "profile/profile_compilation_info.h"
Mathieu Chartier792111c2018-02-15 13:02:15 -080044#include "vdex_file.h"
45#include "ziparchive/zip_writer.h"
Andreas Gampee1459ae2016-06-29 09:36:30 -070046
Andreas Gampee1459ae2016-06-29 09:36:30 -070047namespace art {
48
Mathieu Chartierea650f32017-05-24 12:04:13 -070049static constexpr size_t kMaxMethodIds = 65535;
Mathieu Chartier9e050df2017-08-09 10:05:47 -070050static constexpr bool kDebugArgs = false;
Mathieu Chartier02129102017-12-22 11:04:01 -080051static const char* kDisableCompactDex = "--compact-dex-level=none";
Mathieu Chartierea650f32017-05-24 12:04:13 -070052
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080053using android::base::StringPrintf;
54
Andreas Gampee1459ae2016-06-29 09:36:30 -070055class Dex2oatTest : public Dex2oatEnvironmentTest {
56 public:
57 virtual void TearDown() OVERRIDE {
58 Dex2oatEnvironmentTest::TearDown();
59
60 output_ = "";
61 error_msg_ = "";
62 success_ = false;
63 }
64
65 protected:
Mathieu Chartier9e050df2017-08-09 10:05:47 -070066 int GenerateOdexForTestWithStatus(const std::vector<std::string>& dex_locations,
Andreas Gampef7882972017-03-20 16:35:24 -070067 const std::string& odex_location,
68 CompilerFilter::Filter filter,
69 std::string* error_msg,
70 const std::vector<std::string>& extra_args = {},
71 bool use_fd = false) {
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080072 std::unique_ptr<File> oat_file;
Andreas Gampee1459ae2016-06-29 09:36:30 -070073 std::vector<std::string> args;
Mathieu Chartier9e050df2017-08-09 10:05:47 -070074 // Add dex file args.
75 for (const std::string& dex_location : dex_locations) {
76 args.push_back("--dex-file=" + dex_location);
77 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080078 if (use_fd) {
79 oat_file.reset(OS::CreateEmptyFile(odex_location.c_str()));
80 CHECK(oat_file != nullptr) << odex_location;
81 args.push_back("--oat-fd=" + std::to_string(oat_file->Fd()));
Mathieu Chartier046854b2017-03-01 17:16:22 -080082 args.push_back("--oat-location=" + odex_location);
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080083 } else {
84 args.push_back("--oat-file=" + odex_location);
85 }
Andreas Gampee1459ae2016-06-29 09:36:30 -070086 args.push_back("--compiler-filter=" + CompilerFilter::NameOfFilter(filter));
87 args.push_back("--runtime-arg");
88 args.push_back("-Xnorelocate");
89
90 args.insert(args.end(), extra_args.begin(), extra_args.end());
91
Andreas Gampef7882972017-03-20 16:35:24 -070092 int status = Dex2Oat(args, error_msg);
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080093 if (oat_file != nullptr) {
Andreas Gampef7882972017-03-20 16:35:24 -070094 CHECK_EQ(oat_file->FlushClose(), 0) << "Could not flush and close oat file";
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080095 }
Andreas Gampef7882972017-03-20 16:35:24 -070096 return status;
97 }
Andreas Gampee1459ae2016-06-29 09:36:30 -070098
Andreas Gampe641a4732017-08-24 13:21:35 -070099 void GenerateOdexForTest(
100 const std::string& dex_location,
101 const std::string& odex_location,
102 CompilerFilter::Filter filter,
103 const std::vector<std::string>& extra_args = {},
104 bool expect_success = true,
105 bool use_fd = false) {
106 GenerateOdexForTest(dex_location,
107 odex_location,
108 filter,
109 extra_args,
110 expect_success,
111 use_fd,
112 [](const OatFile&) {});
113 }
114
Andreas Gampe80ddf272018-01-11 09:41:00 -0800115 bool test_accepts_odex_file_on_failure = false;
116
Andreas Gampe641a4732017-08-24 13:21:35 -0700117 template <typename T>
118 void GenerateOdexForTest(
119 const std::string& dex_location,
120 const std::string& odex_location,
121 CompilerFilter::Filter filter,
122 const std::vector<std::string>& extra_args,
123 bool expect_success,
124 bool use_fd,
125 T check_oat) {
Andreas Gampef7882972017-03-20 16:35:24 -0700126 std::string error_msg;
Mathieu Chartier9e050df2017-08-09 10:05:47 -0700127 int status = GenerateOdexForTestWithStatus({dex_location},
Andreas Gampef7882972017-03-20 16:35:24 -0700128 odex_location,
129 filter,
130 &error_msg,
131 extra_args,
132 use_fd);
Andreas Gampe80ddf272018-01-11 09:41:00 -0800133 bool success = (WIFEXITED(status) && WEXITSTATUS(status) == 0);
Andreas Gampee1459ae2016-06-29 09:36:30 -0700134 if (expect_success) {
Andreas Gampe2e8a2562017-01-18 20:39:02 -0800135 ASSERT_TRUE(success) << error_msg << std::endl << output_;
Andreas Gampee1459ae2016-06-29 09:36:30 -0700136
137 // Verify the odex file was generated as expected.
Nicolas Geoffray30025092018-04-19 14:43:29 +0100138 std::unique_ptr<OatFile> odex_file(OatFile::Open(/* zip_fd */ -1,
139 odex_location.c_str(),
Andreas Gampee1459ae2016-06-29 09:36:30 -0700140 odex_location.c_str(),
141 nullptr,
142 nullptr,
143 false,
144 /*low_4gb*/false,
145 dex_location.c_str(),
146 &error_msg));
147 ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
148
149 CheckFilter(filter, odex_file->GetCompilerFilter());
Calin Juravle1ce70852017-06-28 10:59:03 -0700150 check_oat(*(odex_file.get()));
Andreas Gampee1459ae2016-06-29 09:36:30 -0700151 } else {
152 ASSERT_FALSE(success) << output_;
153
154 error_msg_ = error_msg;
155
Andreas Gampe80ddf272018-01-11 09:41:00 -0800156 if (!test_accepts_odex_file_on_failure) {
157 // Verify there's no loadable odex file.
Nicolas Geoffray30025092018-04-19 14:43:29 +0100158 std::unique_ptr<OatFile> odex_file(OatFile::Open(/* zip_fd */ -1,
159 odex_location.c_str(),
Andreas Gampe80ddf272018-01-11 09:41:00 -0800160 odex_location.c_str(),
161 nullptr,
162 nullptr,
163 false,
164 /*low_4gb*/false,
165 dex_location.c_str(),
166 &error_msg));
167 ASSERT_TRUE(odex_file.get() == nullptr);
168 }
Andreas Gampee1459ae2016-06-29 09:36:30 -0700169 }
170 }
171
Calin Juravle1ccf6132017-08-02 17:46:53 -0700172 // Check the input compiler filter against the generated oat file's filter. May be overridden
Andreas Gampee1459ae2016-06-29 09:36:30 -0700173 // in subclasses when equality is not expected.
174 virtual void CheckFilter(CompilerFilter::Filter expected, CompilerFilter::Filter actual) {
175 EXPECT_EQ(expected, actual);
176 }
177
Andreas Gampef7882972017-03-20 16:35:24 -0700178 int Dex2Oat(const std::vector<std::string>& dex2oat_args, std::string* error_msg) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700179 Runtime* runtime = Runtime::Current();
180
181 const std::vector<gc::space::ImageSpace*>& image_spaces =
182 runtime->GetHeap()->GetBootImageSpaces();
183 if (image_spaces.empty()) {
184 *error_msg = "No image location found for Dex2Oat.";
185 return false;
186 }
187 std::string image_location = image_spaces[0]->GetImageLocation();
188
189 std::vector<std::string> argv;
190 argv.push_back(runtime->GetCompilerExecutable());
Calin Juravle1ccf6132017-08-02 17:46:53 -0700191
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000192 if (runtime->IsJavaDebuggable()) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700193 argv.push_back("--debuggable");
194 }
195 runtime->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv);
196
197 if (!runtime->IsVerificationEnabled()) {
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100198 argv.push_back("--compiler-filter=assume-verified");
Andreas Gampee1459ae2016-06-29 09:36:30 -0700199 }
200
201 if (runtime->MustRelocateIfPossible()) {
202 argv.push_back("--runtime-arg");
203 argv.push_back("-Xrelocate");
204 } else {
205 argv.push_back("--runtime-arg");
206 argv.push_back("-Xnorelocate");
207 }
208
209 if (!kIsTargetBuild) {
210 argv.push_back("--host");
211 }
212
213 argv.push_back("--boot-image=" + image_location);
214
215 std::vector<std::string> compiler_options = runtime->GetCompilerOptions();
216 argv.insert(argv.end(), compiler_options.begin(), compiler_options.end());
217
218 argv.insert(argv.end(), dex2oat_args.begin(), dex2oat_args.end());
219
220 // We must set --android-root.
221 const char* android_root = getenv("ANDROID_ROOT");
222 CHECK(android_root != nullptr);
223 argv.push_back("--android-root=" + std::string(android_root));
224
Mathieu Chartier9e050df2017-08-09 10:05:47 -0700225 if (kDebugArgs) {
226 std::string all_args;
227 for (const std::string& arg : argv) {
228 all_args += arg + " ";
229 }
230 LOG(ERROR) << all_args;
231 }
232
Andreas Gampe38aa0b52018-07-10 23:26:55 -0700233 // We need dex2oat to actually log things.
234 auto post_fork_fn = []() { return setenv("ANDROID_LOG_TAGS", "*:d", 1) == 0; };
235 ForkAndExecResult res = ForkAndExec(argv, post_fork_fn, &output_);
236 if (res.stage != ForkAndExecResult::kFinished) {
237 *error_msg = strerror(errno);
238 return -1;
Nicolas Geoffray56fe0f02016-06-30 15:07:46 +0100239 }
Andreas Gampe38aa0b52018-07-10 23:26:55 -0700240 success_ = res.StandardSuccess();
241 return res.status_code;
Andreas Gampee1459ae2016-06-29 09:36:30 -0700242 }
243
244 std::string output_ = "";
245 std::string error_msg_ = "";
246 bool success_ = false;
247};
248
249class Dex2oatSwapTest : public Dex2oatTest {
250 protected:
251 void RunTest(bool use_fd, bool expect_use, const std::vector<std::string>& extra_args = {}) {
252 std::string dex_location = GetScratchDir() + "/Dex2OatSwapTest.jar";
253 std::string odex_location = GetOdexDir() + "/Dex2OatSwapTest.odex";
254
Andreas Gampe7adeda82016-07-25 08:27:35 -0700255 Copy(GetTestDexFileName(), dex_location);
Andreas Gampee1459ae2016-06-29 09:36:30 -0700256
257 std::vector<std::string> copy(extra_args);
258
259 std::unique_ptr<ScratchFile> sf;
260 if (use_fd) {
261 sf.reset(new ScratchFile());
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800262 copy.push_back(android::base::StringPrintf("--swap-fd=%d", sf->GetFd()));
Andreas Gampee1459ae2016-06-29 09:36:30 -0700263 } else {
264 std::string swap_location = GetOdexDir() + "/Dex2OatSwapTest.odex.swap";
265 copy.push_back("--swap-file=" + swap_location);
266 }
267 GenerateOdexForTest(dex_location, odex_location, CompilerFilter::kSpeed, copy);
268
269 CheckValidity();
270 ASSERT_TRUE(success_);
271 CheckResult(expect_use);
272 }
273
Andreas Gampe7adeda82016-07-25 08:27:35 -0700274 virtual std::string GetTestDexFileName() {
Vladimir Marko15357702017-02-09 10:37:31 +0000275 return Dex2oatEnvironmentTest::GetTestDexFileName("VerifierDeps");
Andreas Gampe7adeda82016-07-25 08:27:35 -0700276 }
277
278 virtual void CheckResult(bool expect_use) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700279 if (kIsTargetBuild) {
280 CheckTargetResult(expect_use);
281 } else {
282 CheckHostResult(expect_use);
283 }
284 }
285
Andreas Gampe7adeda82016-07-25 08:27:35 -0700286 virtual void CheckTargetResult(bool expect_use ATTRIBUTE_UNUSED) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700287 // TODO: Ignore for now, as we won't capture any output (it goes to the logcat). We may do
288 // something for variants with file descriptor where we can control the lifetime of
289 // the swap file and thus take a look at it.
290 }
291
Andreas Gampe7adeda82016-07-25 08:27:35 -0700292 virtual void CheckHostResult(bool expect_use) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700293 if (!kIsTargetBuild) {
294 if (expect_use) {
295 EXPECT_NE(output_.find("Large app, accepted running with swap."), std::string::npos)
296 << output_;
297 } else {
298 EXPECT_EQ(output_.find("Large app, accepted running with swap."), std::string::npos)
299 << output_;
300 }
301 }
302 }
303
304 // Check whether the dex2oat run was really successful.
Andreas Gampe7adeda82016-07-25 08:27:35 -0700305 virtual void CheckValidity() {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700306 if (kIsTargetBuild) {
307 CheckTargetValidity();
308 } else {
309 CheckHostValidity();
310 }
311 }
312
Andreas Gampe7adeda82016-07-25 08:27:35 -0700313 virtual void CheckTargetValidity() {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700314 // TODO: Ignore for now, as we won't capture any output (it goes to the logcat). We may do
315 // something for variants with file descriptor where we can control the lifetime of
316 // the swap file and thus take a look at it.
317 }
318
319 // On the host, we can get the dex2oat output. Here, look for "dex2oat took."
Andreas Gampe7adeda82016-07-25 08:27:35 -0700320 virtual void CheckHostValidity() {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700321 EXPECT_NE(output_.find("dex2oat took"), std::string::npos) << output_;
322 }
323};
324
325TEST_F(Dex2oatSwapTest, DoNotUseSwapDefaultSingleSmall) {
326 RunTest(false /* use_fd */, false /* expect_use */);
327 RunTest(true /* use_fd */, false /* expect_use */);
328}
329
330TEST_F(Dex2oatSwapTest, DoNotUseSwapSingle) {
331 RunTest(false /* use_fd */, false /* expect_use */, { "--swap-dex-size-threshold=0" });
332 RunTest(true /* use_fd */, false /* expect_use */, { "--swap-dex-size-threshold=0" });
333}
334
335TEST_F(Dex2oatSwapTest, DoNotUseSwapSmall) {
336 RunTest(false /* use_fd */, false /* expect_use */, { "--swap-dex-count-threshold=0" });
337 RunTest(true /* use_fd */, false /* expect_use */, { "--swap-dex-count-threshold=0" });
338}
339
340TEST_F(Dex2oatSwapTest, DoUseSwapSingleSmall) {
341 RunTest(false /* use_fd */,
342 true /* expect_use */,
343 { "--swap-dex-size-threshold=0", "--swap-dex-count-threshold=0" });
344 RunTest(true /* use_fd */,
345 true /* expect_use */,
346 { "--swap-dex-size-threshold=0", "--swap-dex-count-threshold=0" });
347}
348
Andreas Gampe7adeda82016-07-25 08:27:35 -0700349class Dex2oatSwapUseTest : public Dex2oatSwapTest {
350 protected:
351 void CheckHostResult(bool expect_use) OVERRIDE {
352 if (!kIsTargetBuild) {
353 if (expect_use) {
354 EXPECT_NE(output_.find("Large app, accepted running with swap."), std::string::npos)
355 << output_;
356 } else {
357 EXPECT_EQ(output_.find("Large app, accepted running with swap."), std::string::npos)
358 << output_;
359 }
360 }
361 }
362
363 std::string GetTestDexFileName() OVERRIDE {
364 // Use Statics as it has a handful of functions.
365 return CommonRuntimeTest::GetTestDexFileName("Statics");
366 }
367
368 void GrabResult1() {
369 if (!kIsTargetBuild) {
370 native_alloc_1_ = ParseNativeAlloc();
371 swap_1_ = ParseSwap(false /* expected */);
372 } else {
373 native_alloc_1_ = std::numeric_limits<size_t>::max();
374 swap_1_ = 0;
375 }
376 }
377
378 void GrabResult2() {
379 if (!kIsTargetBuild) {
380 native_alloc_2_ = ParseNativeAlloc();
381 swap_2_ = ParseSwap(true /* expected */);
382 } else {
383 native_alloc_2_ = 0;
384 swap_2_ = std::numeric_limits<size_t>::max();
385 }
386 }
387
388 private:
389 size_t ParseNativeAlloc() {
390 std::regex native_alloc_regex("dex2oat took.*native alloc=[^ ]+ \\(([0-9]+)B\\)");
391 std::smatch native_alloc_match;
392 bool found = std::regex_search(output_, native_alloc_match, native_alloc_regex);
393 if (!found) {
394 EXPECT_TRUE(found);
395 return 0;
396 }
397 if (native_alloc_match.size() != 2U) {
398 EXPECT_EQ(native_alloc_match.size(), 2U);
399 return 0;
400 }
401
402 std::istringstream stream(native_alloc_match[1].str());
403 size_t value;
404 stream >> value;
405
406 return value;
407 }
408
409 size_t ParseSwap(bool expected) {
410 std::regex swap_regex("dex2oat took[^\\n]+swap=[^ ]+ \\(([0-9]+)B\\)");
411 std::smatch swap_match;
412 bool found = std::regex_search(output_, swap_match, swap_regex);
413 if (found != expected) {
414 EXPECT_EQ(expected, found);
415 return 0;
416 }
417
418 if (!found) {
419 return 0;
420 }
421
422 if (swap_match.size() != 2U) {
423 EXPECT_EQ(swap_match.size(), 2U);
424 return 0;
425 }
426
427 std::istringstream stream(swap_match[1].str());
428 size_t value;
429 stream >> value;
430
431 return value;
432 }
433
434 protected:
435 size_t native_alloc_1_;
436 size_t native_alloc_2_;
437
438 size_t swap_1_;
439 size_t swap_2_;
440};
441
442TEST_F(Dex2oatSwapUseTest, CheckSwapUsage) {
Roland Levillain05e34f42018-05-24 13:19:05 +0000443 // Native memory usage isn't correctly tracked when running under ASan.
444 TEST_DISABLED_FOR_MEMORY_TOOL();
Andreas Gampef4a67fd2017-05-04 09:55:36 -0700445
Vladimir Marko57070da2017-02-14 16:16:30 +0000446 // The `native_alloc_2_ >= native_alloc_1_` assertion below may not
Roland Levillain19772bf2017-02-16 11:28:10 +0000447 // hold true on some x86 systems; disable this test while we
448 // investigate (b/29259363).
449 TEST_DISABLED_FOR_X86();
Vladimir Marko57070da2017-02-14 16:16:30 +0000450
Andreas Gampe7adeda82016-07-25 08:27:35 -0700451 RunTest(false /* use_fd */,
452 false /* expect_use */);
453 GrabResult1();
454 std::string output_1 = output_;
455
456 output_ = "";
457
458 RunTest(false /* use_fd */,
459 true /* expect_use */,
460 { "--swap-dex-size-threshold=0", "--swap-dex-count-threshold=0" });
461 GrabResult2();
462 std::string output_2 = output_;
463
464 if (native_alloc_2_ >= native_alloc_1_ || swap_1_ >= swap_2_) {
465 EXPECT_LT(native_alloc_2_, native_alloc_1_);
466 EXPECT_LT(swap_1_, swap_2_);
467
468 LOG(ERROR) << output_1;
469 LOG(ERROR) << output_2;
470 }
471}
472
Andreas Gampe67f02822016-06-24 21:05:23 -0700473class Dex2oatVeryLargeTest : public Dex2oatTest {
474 protected:
475 void CheckFilter(CompilerFilter::Filter input ATTRIBUTE_UNUSED,
476 CompilerFilter::Filter result ATTRIBUTE_UNUSED) OVERRIDE {
477 // Ignore, we'll do our own checks.
478 }
479
480 void RunTest(CompilerFilter::Filter filter,
481 bool expect_large,
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700482 bool expect_downgrade,
Andreas Gampe67f02822016-06-24 21:05:23 -0700483 const std::vector<std::string>& extra_args = {}) {
484 std::string dex_location = GetScratchDir() + "/DexNoOat.jar";
485 std::string odex_location = GetOdexDir() + "/DexOdexNoOat.odex";
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700486 std::string app_image_file = GetScratchDir() + "/Test.art";
Andreas Gampe67f02822016-06-24 21:05:23 -0700487
488 Copy(GetDexSrc1(), dex_location);
489
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700490 std::vector<std::string> new_args(extra_args);
491 new_args.push_back("--app-image-file=" + app_image_file);
492 GenerateOdexForTest(dex_location, odex_location, filter, new_args);
Andreas Gampe67f02822016-06-24 21:05:23 -0700493
494 CheckValidity();
495 ASSERT_TRUE(success_);
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700496 CheckResult(dex_location,
497 odex_location,
498 app_image_file,
499 filter,
500 expect_large,
501 expect_downgrade);
Andreas Gampe67f02822016-06-24 21:05:23 -0700502 }
503
504 void CheckResult(const std::string& dex_location,
505 const std::string& odex_location,
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700506 const std::string& app_image_file,
Andreas Gampe67f02822016-06-24 21:05:23 -0700507 CompilerFilter::Filter filter,
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700508 bool expect_large,
509 bool expect_downgrade) {
510 if (expect_downgrade) {
511 EXPECT_TRUE(expect_large);
512 }
Andreas Gampe67f02822016-06-24 21:05:23 -0700513 // Host/target independent checks.
514 std::string error_msg;
Nicolas Geoffray30025092018-04-19 14:43:29 +0100515 std::unique_ptr<OatFile> odex_file(OatFile::Open(/* zip_fd */ -1,
516 odex_location.c_str(),
Andreas Gampe67f02822016-06-24 21:05:23 -0700517 odex_location.c_str(),
518 nullptr,
519 nullptr,
520 false,
521 /*low_4gb*/false,
522 dex_location.c_str(),
523 &error_msg));
524 ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700525 EXPECT_GT(app_image_file.length(), 0u);
526 std::unique_ptr<File> file(OS::OpenFileForReading(app_image_file.c_str()));
Andreas Gampe67f02822016-06-24 21:05:23 -0700527 if (expect_large) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700528 // Note: we cannot check the following
529 // EXPECT_FALSE(CompilerFilter::IsAotCompilationEnabled(odex_file->GetCompilerFilter()));
Andreas Gampe67f02822016-06-24 21:05:23 -0700530 // The reason is that the filter override currently happens when the dex files are
531 // loaded in dex2oat, which is after the oat file has been started. Thus, the header
532 // store cannot be changed, and the original filter is set in stone.
533
534 for (const OatDexFile* oat_dex_file : odex_file->GetOatDexFiles()) {
535 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
536 ASSERT_TRUE(dex_file != nullptr);
537 uint32_t class_def_count = dex_file->NumClassDefs();
538 ASSERT_LT(class_def_count, std::numeric_limits<uint16_t>::max());
539 for (uint16_t class_def_index = 0; class_def_index < class_def_count; ++class_def_index) {
540 OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
541 EXPECT_EQ(oat_class.GetType(), OatClassType::kOatClassNoneCompiled);
542 }
543 }
544
545 // If the input filter was "below," it should have been used.
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100546 if (!CompilerFilter::IsAsGoodAs(CompilerFilter::kExtract, filter)) {
Andreas Gampe67f02822016-06-24 21:05:23 -0700547 EXPECT_EQ(odex_file->GetCompilerFilter(), filter);
548 }
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700549
550 // If expect large, make sure the app image isn't generated or is empty.
551 if (file != nullptr) {
552 EXPECT_EQ(file->GetLength(), 0u);
553 }
Andreas Gampe67f02822016-06-24 21:05:23 -0700554 } else {
555 EXPECT_EQ(odex_file->GetCompilerFilter(), filter);
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700556 ASSERT_TRUE(file != nullptr) << app_image_file;
557 EXPECT_GT(file->GetLength(), 0u);
Andreas Gampe67f02822016-06-24 21:05:23 -0700558 }
559
560 // Host/target dependent checks.
561 if (kIsTargetBuild) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700562 CheckTargetResult(expect_downgrade);
Andreas Gampe67f02822016-06-24 21:05:23 -0700563 } else {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700564 CheckHostResult(expect_downgrade);
Andreas Gampe67f02822016-06-24 21:05:23 -0700565 }
566 }
567
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700568 void CheckTargetResult(bool expect_downgrade ATTRIBUTE_UNUSED) {
Andreas Gampe67f02822016-06-24 21:05:23 -0700569 // TODO: Ignore for now. May do something for fd things.
570 }
571
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700572 void CheckHostResult(bool expect_downgrade) {
Andreas Gampe67f02822016-06-24 21:05:23 -0700573 if (!kIsTargetBuild) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700574 if (expect_downgrade) {
575 EXPECT_NE(output_.find("Very large app, downgrading to"), std::string::npos) << output_;
Andreas Gampe67f02822016-06-24 21:05:23 -0700576 } else {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700577 EXPECT_EQ(output_.find("Very large app, downgrading to"), std::string::npos) << output_;
Andreas Gampe67f02822016-06-24 21:05:23 -0700578 }
579 }
580 }
581
582 // Check whether the dex2oat run was really successful.
583 void CheckValidity() {
584 if (kIsTargetBuild) {
585 CheckTargetValidity();
586 } else {
587 CheckHostValidity();
588 }
589 }
590
591 void CheckTargetValidity() {
592 // TODO: Ignore for now.
593 }
594
595 // On the host, we can get the dex2oat output. Here, look for "dex2oat took."
596 void CheckHostValidity() {
597 EXPECT_NE(output_.find("dex2oat took"), std::string::npos) << output_;
598 }
599};
600
601TEST_F(Dex2oatVeryLargeTest, DontUseVeryLarge) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700602 RunTest(CompilerFilter::kAssumeVerified, false, false);
603 RunTest(CompilerFilter::kExtract, false, false);
604 RunTest(CompilerFilter::kQuicken, false, false);
605 RunTest(CompilerFilter::kSpeed, false, false);
Andreas Gampe67f02822016-06-24 21:05:23 -0700606
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700607 RunTest(CompilerFilter::kAssumeVerified, false, false, { "--very-large-app-threshold=10000000" });
608 RunTest(CompilerFilter::kExtract, false, false, { "--very-large-app-threshold=10000000" });
609 RunTest(CompilerFilter::kQuicken, false, false, { "--very-large-app-threshold=10000000" });
610 RunTest(CompilerFilter::kSpeed, false, false, { "--very-large-app-threshold=10000000" });
Andreas Gampe67f02822016-06-24 21:05:23 -0700611}
612
613TEST_F(Dex2oatVeryLargeTest, UseVeryLarge) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700614 RunTest(CompilerFilter::kAssumeVerified, true, false, { "--very-large-app-threshold=100" });
615 RunTest(CompilerFilter::kExtract, true, false, { "--very-large-app-threshold=100" });
616 RunTest(CompilerFilter::kQuicken, true, true, { "--very-large-app-threshold=100" });
617 RunTest(CompilerFilter::kSpeed, true, true, { "--very-large-app-threshold=100" });
Andreas Gampe67f02822016-06-24 21:05:23 -0700618}
619
Mathieu Chartier97ab5e32017-02-22 13:35:44 -0800620// Regressin test for b/35665292.
621TEST_F(Dex2oatVeryLargeTest, SpeedProfileNoProfile) {
622 // Test that dex2oat doesn't crash with speed-profile but no input profile.
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700623 RunTest(CompilerFilter::kSpeedProfile, false, false);
Mathieu Chartier97ab5e32017-02-22 13:35:44 -0800624}
625
Jeff Hao608f2ce2016-10-19 11:17:11 -0700626class Dex2oatLayoutTest : public Dex2oatTest {
627 protected:
628 void CheckFilter(CompilerFilter::Filter input ATTRIBUTE_UNUSED,
629 CompilerFilter::Filter result ATTRIBUTE_UNUSED) OVERRIDE {
630 // Ignore, we'll do our own checks.
631 }
632
Jeff Hao41fba6a2016-11-28 11:53:33 -0800633 // Emits a profile with a single dex file with the given location and a single class index of 1.
634 void GenerateProfile(const std::string& test_profile,
635 const std::string& dex_location,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800636 size_t num_classes,
Jeff Hao41fba6a2016-11-28 11:53:33 -0800637 uint32_t checksum) {
638 int profile_test_fd = open(test_profile.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644);
639 CHECK_GE(profile_test_fd, 0);
640
641 ProfileCompilationInfo info;
642 std::string profile_key = ProfileCompilationInfo::GetProfileDexFileKey(dex_location);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800643 for (size_t i = 0; i < num_classes; ++i) {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700644 info.AddClassIndex(profile_key, checksum, dex::TypeIndex(1 + i), kMaxMethodIds);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800645 }
Jeff Hao41fba6a2016-11-28 11:53:33 -0800646 bool result = info.Save(profile_test_fd);
647 close(profile_test_fd);
648 ASSERT_TRUE(result);
649 }
650
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800651 void CompileProfileOdex(const std::string& dex_location,
652 const std::string& odex_location,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800653 const std::string& app_image_file_name,
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800654 bool use_fd,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800655 size_t num_profile_classes,
Nicolas Geoffray97fa9922017-03-09 13:13:25 +0000656 const std::vector<std::string>& extra_args = {},
657 bool expect_success = true) {
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800658 const std::string profile_location = GetScratchDir() + "/primary.prof";
Jeff Hao41fba6a2016-11-28 11:53:33 -0800659 const char* location = dex_location.c_str();
660 std::string error_msg;
661 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Sehr013fd802018-01-11 22:55:24 -0800662 const ArtDexFileLoader dex_file_loader;
663 ASSERT_TRUE(dex_file_loader.Open(
Nicolas Geoffray095c6c92017-10-19 13:59:55 +0100664 location, location, /* verify */ true, /* verify_checksum */ true, &error_msg, &dex_files));
Jeff Hao41fba6a2016-11-28 11:53:33 -0800665 EXPECT_EQ(dex_files.size(), 1U);
666 std::unique_ptr<const DexFile>& dex_file = dex_files[0];
Mathieu Chartier046854b2017-03-01 17:16:22 -0800667 GenerateProfile(profile_location,
668 dex_location,
669 num_profile_classes,
670 dex_file->GetLocationChecksum());
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800671 std::vector<std::string> copy(extra_args);
672 copy.push_back("--profile-file=" + profile_location);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800673 std::unique_ptr<File> app_image_file;
674 if (!app_image_file_name.empty()) {
675 if (use_fd) {
676 app_image_file.reset(OS::CreateEmptyFile(app_image_file_name.c_str()));
677 copy.push_back("--app-image-fd=" + std::to_string(app_image_file->Fd()));
678 } else {
679 copy.push_back("--app-image-file=" + app_image_file_name);
680 }
681 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800682 GenerateOdexForTest(dex_location,
683 odex_location,
684 CompilerFilter::kSpeedProfile,
685 copy,
Nicolas Geoffray97fa9922017-03-09 13:13:25 +0000686 expect_success,
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800687 use_fd);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800688 if (app_image_file != nullptr) {
689 ASSERT_EQ(app_image_file->FlushCloseOrErase(), 0) << "Could not flush and close art file";
690 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800691 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700692
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100693 uint64_t GetImageObjectSectionSize(const std::string& image_file_name) {
Mathieu Chartier046854b2017-03-01 17:16:22 -0800694 EXPECT_FALSE(image_file_name.empty());
695 std::unique_ptr<File> file(OS::OpenFileForReading(image_file_name.c_str()));
696 CHECK(file != nullptr);
697 ImageHeader image_header;
698 const bool success = file->ReadFully(&image_header, sizeof(image_header));
699 CHECK(success);
700 CHECK(image_header.IsValid());
701 ReaderMutexLock mu(Thread::Current(), *Locks::mutator_lock_);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100702 return image_header.GetObjectsSection().Size();
Mathieu Chartier046854b2017-03-01 17:16:22 -0800703 }
704
705 void RunTest(bool app_image) {
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800706 std::string dex_location = GetScratchDir() + "/DexNoOat.jar";
707 std::string odex_location = GetOdexDir() + "/DexOdexNoOat.odex";
Mathieu Chartier046854b2017-03-01 17:16:22 -0800708 std::string app_image_file = app_image ? (GetOdexDir() + "/DexOdexNoOat.art"): "";
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800709 Copy(GetDexSrc2(), dex_location);
710
Mathieu Chartier046854b2017-03-01 17:16:22 -0800711 uint64_t image_file_empty_profile = 0;
712 if (app_image) {
713 CompileProfileOdex(dex_location,
714 odex_location,
715 app_image_file,
716 /* use_fd */ false,
717 /* num_profile_classes */ 0);
718 CheckValidity();
719 ASSERT_TRUE(success_);
720 // Don't check the result since CheckResult relies on the class being in the profile.
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100721 image_file_empty_profile = GetImageObjectSectionSize(app_image_file);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800722 EXPECT_GT(image_file_empty_profile, 0u);
723 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700724
Mathieu Chartier046854b2017-03-01 17:16:22 -0800725 // Small profile.
726 CompileProfileOdex(dex_location,
727 odex_location,
728 app_image_file,
729 /* use_fd */ false,
730 /* num_profile_classes */ 1);
Jeff Hao608f2ce2016-10-19 11:17:11 -0700731 CheckValidity();
732 ASSERT_TRUE(success_);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800733 CheckResult(dex_location, odex_location, app_image_file);
734
735 if (app_image) {
736 // Test that the profile made a difference by adding more classes.
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100737 const uint64_t image_file_small_profile = GetImageObjectSectionSize(app_image_file);
738 ASSERT_LT(image_file_empty_profile, image_file_small_profile);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800739 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700740 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800741
742 void RunTestVDex() {
743 std::string dex_location = GetScratchDir() + "/DexNoOat.jar";
744 std::string odex_location = GetOdexDir() + "/DexOdexNoOat.odex";
745 std::string vdex_location = GetOdexDir() + "/DexOdexNoOat.vdex";
Mathieu Chartier046854b2017-03-01 17:16:22 -0800746 std::string app_image_file_name = GetOdexDir() + "/DexOdexNoOat.art";
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800747 Copy(GetDexSrc2(), dex_location);
748
749 std::unique_ptr<File> vdex_file1(OS::CreateEmptyFile(vdex_location.c_str()));
750 CHECK(vdex_file1 != nullptr) << vdex_location;
751 ScratchFile vdex_file2;
752 {
753 std::string input_vdex = "--input-vdex-fd=-1";
754 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file1->Fd());
755 CompileProfileOdex(dex_location,
756 odex_location,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800757 app_image_file_name,
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800758 /* use_fd */ true,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800759 /* num_profile_classes */ 1,
Mathieu Chartierf1609832018-01-31 03:09:56 -0800760 { input_vdex, output_vdex });
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800761 EXPECT_GT(vdex_file1->GetLength(), 0u);
762 }
763 {
Nicolas Geoffray97fa9922017-03-09 13:13:25 +0000764 // Test that vdex and dexlayout fail gracefully.
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800765 std::string input_vdex = StringPrintf("--input-vdex-fd=%d", vdex_file1->Fd());
766 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file2.GetFd());
767 CompileProfileOdex(dex_location,
768 odex_location,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800769 app_image_file_name,
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800770 /* use_fd */ true,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800771 /* num_profile_classes */ 1,
Mathieu Chartierd27923c2018-02-08 21:00:03 -0800772 { input_vdex, output_vdex },
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +0100773 /* expect_success */ true);
774 EXPECT_GT(vdex_file2.GetFile()->GetLength(), 0u);
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800775 }
776 ASSERT_EQ(vdex_file1->FlushCloseOrErase(), 0) << "Could not flush and close vdex file";
777 CheckValidity();
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +0100778 ASSERT_TRUE(success_);
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800779 }
780
Mathieu Chartier046854b2017-03-01 17:16:22 -0800781 void CheckResult(const std::string& dex_location,
782 const std::string& odex_location,
783 const std::string& app_image_file_name) {
Jeff Hao608f2ce2016-10-19 11:17:11 -0700784 // Host/target independent checks.
785 std::string error_msg;
Nicolas Geoffray30025092018-04-19 14:43:29 +0100786 std::unique_ptr<OatFile> odex_file(OatFile::Open(/* zip_fd */ -1,
787 odex_location.c_str(),
Jeff Hao608f2ce2016-10-19 11:17:11 -0700788 odex_location.c_str(),
789 nullptr,
790 nullptr,
791 false,
792 /*low_4gb*/false,
793 dex_location.c_str(),
794 &error_msg));
795 ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
796
Jeff Hao042e8982016-10-19 11:17:11 -0700797 const char* location = dex_location.c_str();
798 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Sehr013fd802018-01-11 22:55:24 -0800799 const ArtDexFileLoader dex_file_loader;
800 ASSERT_TRUE(dex_file_loader.Open(
Nicolas Geoffray095c6c92017-10-19 13:59:55 +0100801 location, location, /* verify */ true, /* verify_checksum */ true, &error_msg, &dex_files));
Jeff Hao042e8982016-10-19 11:17:11 -0700802 EXPECT_EQ(dex_files.size(), 1U);
803 std::unique_ptr<const DexFile>& old_dex_file = dex_files[0];
804
Jeff Hao608f2ce2016-10-19 11:17:11 -0700805 for (const OatDexFile* oat_dex_file : odex_file->GetOatDexFiles()) {
Jeff Hao042e8982016-10-19 11:17:11 -0700806 std::unique_ptr<const DexFile> new_dex_file = oat_dex_file->OpenDexFile(&error_msg);
807 ASSERT_TRUE(new_dex_file != nullptr);
808 uint32_t class_def_count = new_dex_file->NumClassDefs();
Jeff Hao608f2ce2016-10-19 11:17:11 -0700809 ASSERT_LT(class_def_count, std::numeric_limits<uint16_t>::max());
Jeff Hao042e8982016-10-19 11:17:11 -0700810 ASSERT_GE(class_def_count, 2U);
811
Mathieu Chartier24066ec2017-10-21 16:01:08 -0700812 // Make sure the indexes stay the same.
Jeff Hao042e8982016-10-19 11:17:11 -0700813 std::string old_class0 = old_dex_file->PrettyType(old_dex_file->GetClassDef(0).class_idx_);
814 std::string old_class1 = old_dex_file->PrettyType(old_dex_file->GetClassDef(1).class_idx_);
815 std::string new_class0 = new_dex_file->PrettyType(new_dex_file->GetClassDef(0).class_idx_);
816 std::string new_class1 = new_dex_file->PrettyType(new_dex_file->GetClassDef(1).class_idx_);
Mathieu Chartier24066ec2017-10-21 16:01:08 -0700817 EXPECT_EQ(old_class0, new_class0);
818 EXPECT_EQ(old_class1, new_class1);
Jeff Hao608f2ce2016-10-19 11:17:11 -0700819 }
820
Jeff Haoc155b052017-01-17 17:43:29 -0800821 EXPECT_EQ(odex_file->GetCompilerFilter(), CompilerFilter::kSpeedProfile);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800822
823 if (!app_image_file_name.empty()) {
824 // Go peek at the image header to make sure it was large enough to contain the class.
825 std::unique_ptr<File> file(OS::OpenFileForReading(app_image_file_name.c_str()));
826 ImageHeader image_header;
827 bool success = file->ReadFully(&image_header, sizeof(image_header));
828 ASSERT_TRUE(success);
829 ASSERT_TRUE(image_header.IsValid());
Vladimir Markocd87c3e2017-09-05 13:11:57 +0100830 EXPECT_GT(image_header.GetObjectsSection().Size(), 0u);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800831 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700832 }
833
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800834 // Check whether the dex2oat run was really successful.
835 void CheckValidity() {
836 if (kIsTargetBuild) {
837 CheckTargetValidity();
838 } else {
839 CheckHostValidity();
Jeff Hao608f2ce2016-10-19 11:17:11 -0700840 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800841 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700842
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800843 void CheckTargetValidity() {
844 // TODO: Ignore for now.
845 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700846
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800847 // On the host, we can get the dex2oat output. Here, look for "dex2oat took."
848 void CheckHostValidity() {
849 EXPECT_NE(output_.find("dex2oat took"), std::string::npos) << output_;
850 }
851};
Jeff Hao608f2ce2016-10-19 11:17:11 -0700852
853TEST_F(Dex2oatLayoutTest, TestLayout) {
Mathieu Chartier046854b2017-03-01 17:16:22 -0800854 RunTest(/* app-image */ false);
855}
856
857TEST_F(Dex2oatLayoutTest, TestLayoutAppImage) {
858 RunTest(/* app-image */ true);
Jeff Hao608f2ce2016-10-19 11:17:11 -0700859}
860
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800861TEST_F(Dex2oatLayoutTest, TestVdexLayout) {
862 RunTestVDex();
863}
864
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100865class Dex2oatUnquickenTest : public Dex2oatTest {
866 protected:
867 void RunUnquickenMultiDex() {
868 std::string dex_location = GetScratchDir() + "/UnquickenMultiDex.jar";
869 std::string odex_location = GetOdexDir() + "/UnquickenMultiDex.odex";
870 std::string vdex_location = GetOdexDir() + "/UnquickenMultiDex.vdex";
871 Copy(GetTestDexFileName("MultiDex"), dex_location);
872
873 std::unique_ptr<File> vdex_file1(OS::CreateEmptyFile(vdex_location.c_str()));
874 CHECK(vdex_file1 != nullptr) << vdex_location;
875 // Quicken the dex file into a vdex file.
876 {
877 std::string input_vdex = "--input-vdex-fd=-1";
878 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file1->Fd());
879 GenerateOdexForTest(dex_location,
880 odex_location,
881 CompilerFilter::kQuicken,
Mathieu Chartierf1609832018-01-31 03:09:56 -0800882 { input_vdex, output_vdex },
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100883 /* expect_success */ true,
884 /* use_fd */ true);
885 EXPECT_GT(vdex_file1->GetLength(), 0u);
886 }
887 // Unquicken by running the verify compiler filter on the vdex file.
888 {
889 std::string input_vdex = StringPrintf("--input-vdex-fd=%d", vdex_file1->Fd());
890 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file1->Fd());
891 GenerateOdexForTest(dex_location,
892 odex_location,
893 CompilerFilter::kVerify,
Mathieu Chartier02129102017-12-22 11:04:01 -0800894 { input_vdex, output_vdex, kDisableCompactDex },
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100895 /* expect_success */ true,
896 /* use_fd */ true);
897 }
898 ASSERT_EQ(vdex_file1->FlushCloseOrErase(), 0) << "Could not flush and close vdex file";
899 CheckResult(dex_location, odex_location);
900 ASSERT_TRUE(success_);
901 }
902
Mathieu Chartierd27923c2018-02-08 21:00:03 -0800903 void RunUnquickenMultiDexCDex() {
904 std::string dex_location = GetScratchDir() + "/UnquickenMultiDex.jar";
905 std::string odex_location = GetOdexDir() + "/UnquickenMultiDex.odex";
906 std::string odex_location2 = GetOdexDir() + "/UnquickenMultiDex2.odex";
907 std::string vdex_location = GetOdexDir() + "/UnquickenMultiDex.vdex";
908 std::string vdex_location2 = GetOdexDir() + "/UnquickenMultiDex2.vdex";
909 Copy(GetTestDexFileName("MultiDex"), dex_location);
910
911 std::unique_ptr<File> vdex_file1(OS::CreateEmptyFile(vdex_location.c_str()));
912 std::unique_ptr<File> vdex_file2(OS::CreateEmptyFile(vdex_location2.c_str()));
913 CHECK(vdex_file1 != nullptr) << vdex_location;
914 CHECK(vdex_file2 != nullptr) << vdex_location2;
915
916 // Quicken the dex file into a vdex file.
917 {
918 std::string input_vdex = "--input-vdex-fd=-1";
919 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file1->Fd());
920 GenerateOdexForTest(dex_location,
921 odex_location,
922 CompilerFilter::kQuicken,
923 { input_vdex, output_vdex, "--compact-dex-level=fast"},
924 /* expect_success */ true,
925 /* use_fd */ true);
926 EXPECT_GT(vdex_file1->GetLength(), 0u);
927 }
928
929 // Unquicken by running the verify compiler filter on the vdex file.
930 {
931 std::string input_vdex = StringPrintf("--input-vdex-fd=%d", vdex_file1->Fd());
932 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file2->Fd());
933 GenerateOdexForTest(dex_location,
934 odex_location2,
935 CompilerFilter::kVerify,
936 { input_vdex, output_vdex, "--compact-dex-level=none"},
937 /* expect_success */ true,
938 /* use_fd */ true);
939 }
940 ASSERT_EQ(vdex_file1->FlushCloseOrErase(), 0) << "Could not flush and close vdex file";
941 ASSERT_EQ(vdex_file2->FlushCloseOrErase(), 0) << "Could not flush and close vdex file";
942 CheckResult(dex_location, odex_location2);
943 ASSERT_TRUE(success_);
944 }
945
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100946 void CheckResult(const std::string& dex_location, const std::string& odex_location) {
947 std::string error_msg;
Nicolas Geoffray30025092018-04-19 14:43:29 +0100948 std::unique_ptr<OatFile> odex_file(OatFile::Open(/* zip_fd */ -1,
949 odex_location.c_str(),
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100950 odex_location.c_str(),
951 nullptr,
952 nullptr,
953 false,
954 /*low_4gb*/false,
955 dex_location.c_str(),
956 &error_msg));
957 ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
958 ASSERT_GE(odex_file->GetOatDexFiles().size(), 1u);
959
960 // Iterate over the dex files and ensure there is no quickened instruction.
961 for (const OatDexFile* oat_dex_file : odex_file->GetOatDexFiles()) {
962 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
963 for (uint32_t i = 0; i < dex_file->NumClassDefs(); ++i) {
964 const DexFile::ClassDef& class_def = dex_file->GetClassDef(i);
965 const uint8_t* class_data = dex_file->GetClassData(class_def);
966 if (class_data != nullptr) {
967 for (ClassDataItemIterator class_it(*dex_file, class_data);
968 class_it.HasNext();
969 class_it.Next()) {
970 if (class_it.IsAtMethod() && class_it.GetMethodCodeItem() != nullptr) {
Mathieu Chartier0021feb2017-11-07 00:08:52 -0800971 for (const DexInstructionPcPair& inst :
Mathieu Chartier698ebbc2018-01-05 11:00:42 -0800972 CodeItemInstructionAccessor(*dex_file, class_it.GetMethodCodeItem())) {
Mathieu Chartier2daa1342018-02-20 16:19:28 -0800973 ASSERT_FALSE(inst->IsQuickened()) << inst->Opcode() << " " << output_;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100974 }
975 }
976 }
977 }
978 }
979 }
980 }
981};
982
983TEST_F(Dex2oatUnquickenTest, UnquickenMultiDex) {
984 RunUnquickenMultiDex();
985}
986
Mathieu Chartierd27923c2018-02-08 21:00:03 -0800987TEST_F(Dex2oatUnquickenTest, UnquickenMultiDexCDex) {
988 RunUnquickenMultiDexCDex();
989}
990
Andreas Gampe2e8a2562017-01-18 20:39:02 -0800991class Dex2oatWatchdogTest : public Dex2oatTest {
992 protected:
993 void RunTest(bool expect_success, const std::vector<std::string>& extra_args = {}) {
994 std::string dex_location = GetScratchDir() + "/Dex2OatSwapTest.jar";
995 std::string odex_location = GetOdexDir() + "/Dex2OatSwapTest.odex";
996
997 Copy(GetTestDexFileName(), dex_location);
998
999 std::vector<std::string> copy(extra_args);
1000
1001 std::string swap_location = GetOdexDir() + "/Dex2OatSwapTest.odex.swap";
1002 copy.push_back("--swap-file=" + swap_location);
Andreas Gampe22fa3762017-10-23 20:58:12 -07001003 copy.push_back("-j512"); // Excessive idle threads just slow down dex2oat.
Andreas Gampe2e8a2562017-01-18 20:39:02 -08001004 GenerateOdexForTest(dex_location,
1005 odex_location,
1006 CompilerFilter::kSpeed,
1007 copy,
1008 expect_success);
1009 }
1010
1011 std::string GetTestDexFileName() {
1012 return GetDexSrc1();
1013 }
1014};
1015
1016TEST_F(Dex2oatWatchdogTest, TestWatchdogOK) {
1017 // Check with default.
1018 RunTest(true);
1019
1020 // Check with ten minutes.
1021 RunTest(true, { "--watchdog-timeout=600000" });
1022}
1023
1024TEST_F(Dex2oatWatchdogTest, TestWatchdogTrigger) {
Andreas Gampe80ddf272018-01-11 09:41:00 -08001025 // The watchdog is independent of dex2oat and will not delete intermediates. It is possible
1026 // that the compilation succeeds and the file is completely written by the time the watchdog
1027 // kills dex2oat (but the dex2oat threads must have been scheduled pretty badly).
1028 test_accepts_odex_file_on_failure = true;
1029
Andreas Gampe2e8a2562017-01-18 20:39:02 -08001030 // Check with ten milliseconds.
1031 RunTest(false, { "--watchdog-timeout=10" });
1032}
1033
Andreas Gampef7882972017-03-20 16:35:24 -07001034class Dex2oatReturnCodeTest : public Dex2oatTest {
1035 protected:
1036 int RunTest(const std::vector<std::string>& extra_args = {}) {
1037 std::string dex_location = GetScratchDir() + "/Dex2OatSwapTest.jar";
1038 std::string odex_location = GetOdexDir() + "/Dex2OatSwapTest.odex";
1039
1040 Copy(GetTestDexFileName(), dex_location);
1041
1042 std::string error_msg;
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001043 return GenerateOdexForTestWithStatus({dex_location},
Andreas Gampef7882972017-03-20 16:35:24 -07001044 odex_location,
1045 CompilerFilter::kSpeed,
1046 &error_msg,
1047 extra_args);
1048 }
1049
1050 std::string GetTestDexFileName() {
1051 return GetDexSrc1();
1052 }
1053};
1054
1055TEST_F(Dex2oatReturnCodeTest, TestCreateRuntime) {
Andreas Gampefd80b172017-04-26 22:25:31 -07001056 TEST_DISABLED_FOR_MEMORY_TOOL(); // b/19100793
Andreas Gampef7882972017-03-20 16:35:24 -07001057 int status = RunTest({ "--boot-image=/this/does/not/exist/yolo.oat" });
1058 EXPECT_EQ(static_cast<int>(dex2oat::ReturnCode::kCreateRuntime), WEXITSTATUS(status)) << output_;
1059}
1060
Calin Juravle1ce70852017-06-28 10:59:03 -07001061class Dex2oatClassLoaderContextTest : public Dex2oatTest {
1062 protected:
1063 void RunTest(const char* class_loader_context,
1064 const char* expected_classpath_key,
1065 bool expected_success,
1066 bool use_second_source = false) {
1067 std::string dex_location = GetUsedDexLocation();
1068 std::string odex_location = GetUsedOatLocation();
1069
1070 Copy(use_second_source ? GetDexSrc2() : GetDexSrc1(), dex_location);
1071
1072 std::string error_msg;
1073 std::vector<std::string> extra_args;
1074 if (class_loader_context != nullptr) {
1075 extra_args.push_back(std::string("--class-loader-context=") + class_loader_context);
1076 }
1077 auto check_oat = [expected_classpath_key](const OatFile& oat_file) {
1078 ASSERT_TRUE(expected_classpath_key != nullptr);
1079 const char* classpath = oat_file.GetOatHeader().GetStoreValueByKey(OatHeader::kClassPathKey);
1080 ASSERT_TRUE(classpath != nullptr);
1081 ASSERT_STREQ(expected_classpath_key, classpath);
1082 };
1083
1084 GenerateOdexForTest(dex_location,
1085 odex_location,
1086 CompilerFilter::kQuicken,
1087 extra_args,
1088 expected_success,
1089 /*use_fd*/ false,
1090 check_oat);
1091 }
1092
1093 std::string GetUsedDexLocation() {
1094 return GetScratchDir() + "/Context.jar";
1095 }
1096
1097 std::string GetUsedOatLocation() {
1098 return GetOdexDir() + "/Context.odex";
1099 }
1100
Calin Juravle7b0648a2017-07-07 18:40:50 -07001101 const char* kEmptyClassPathKey = "PCL[]";
Calin Juravle1ce70852017-06-28 10:59:03 -07001102};
1103
1104TEST_F(Dex2oatClassLoaderContextTest, InvalidContext) {
1105 RunTest("Invalid[]", /*expected_classpath_key*/ nullptr, /*expected_success*/ false);
1106}
1107
1108TEST_F(Dex2oatClassLoaderContextTest, EmptyContext) {
1109 RunTest("PCL[]", kEmptyClassPathKey, /*expected_success*/ true);
1110}
1111
1112TEST_F(Dex2oatClassLoaderContextTest, SpecialContext) {
1113 RunTest(OatFile::kSpecialSharedLibrary,
1114 OatFile::kSpecialSharedLibrary,
1115 /*expected_success*/ true);
1116}
1117
1118TEST_F(Dex2oatClassLoaderContextTest, ContextWithTheSourceDexFiles) {
1119 std::string context = "PCL[" + GetUsedDexLocation() + "]";
1120 RunTest(context.c_str(), kEmptyClassPathKey, /*expected_success*/ true);
1121}
1122
1123TEST_F(Dex2oatClassLoaderContextTest, ContextWithOtherDexFiles) {
1124 std::vector<std::unique_ptr<const DexFile>> dex_files = OpenTestDexFiles("Nested");
Calin Juravle1ce70852017-06-28 10:59:03 -07001125
1126 std::string context = "PCL[" + dex_files[0]->GetLocation() + "]";
Calin Juravle7b0648a2017-07-07 18:40:50 -07001127 std::string expected_classpath_key = "PCL[" +
1128 dex_files[0]->GetLocation() + "*" + std::to_string(dex_files[0]->GetLocationChecksum()) + "]";
Calin Juravle1ce70852017-06-28 10:59:03 -07001129 RunTest(context.c_str(), expected_classpath_key.c_str(), true);
1130}
1131
1132TEST_F(Dex2oatClassLoaderContextTest, ContextWithStrippedDexFiles) {
1133 std::string stripped_classpath = GetScratchDir() + "/stripped_classpath.jar";
1134 Copy(GetStrippedDexSrc1(), stripped_classpath);
1135
1136 std::string context = "PCL[" + stripped_classpath + "]";
1137 // Expect an empty context because stripped dex files cannot be open.
Calin Juravle7b0648a2017-07-07 18:40:50 -07001138 RunTest(context.c_str(), kEmptyClassPathKey , /*expected_success*/ true);
Calin Juravle1ce70852017-06-28 10:59:03 -07001139}
1140
1141TEST_F(Dex2oatClassLoaderContextTest, ContextWithStrippedDexFilesBackedByOdex) {
1142 std::string stripped_classpath = GetScratchDir() + "/stripped_classpath.jar";
1143 std::string odex_for_classpath = GetOdexDir() + "/stripped_classpath.odex";
1144
1145 Copy(GetDexSrc1(), stripped_classpath);
1146
1147 GenerateOdexForTest(stripped_classpath,
1148 odex_for_classpath,
1149 CompilerFilter::kQuicken,
1150 {},
1151 true);
1152
1153 // Strip the dex file
1154 Copy(GetStrippedDexSrc1(), stripped_classpath);
1155
1156 std::string context = "PCL[" + stripped_classpath + "]";
Calin Juravle7b0648a2017-07-07 18:40:50 -07001157 std::string expected_classpath_key;
Calin Juravle1ce70852017-06-28 10:59:03 -07001158 {
1159 // Open the oat file to get the expected classpath.
Nicolas Geoffray29742602017-12-14 10:09:03 +00001160 OatFileAssistant oat_file_assistant(stripped_classpath.c_str(), kRuntimeISA, false, false);
Calin Juravle1ce70852017-06-28 10:59:03 -07001161 std::unique_ptr<OatFile> oat_file(oat_file_assistant.GetBestOatFile());
1162 std::vector<std::unique_ptr<const DexFile>> oat_dex_files =
1163 OatFileAssistant::LoadDexFiles(*oat_file, stripped_classpath.c_str());
Calin Juravle7b0648a2017-07-07 18:40:50 -07001164 expected_classpath_key = "PCL[";
1165 for (size_t i = 0; i < oat_dex_files.size(); i++) {
1166 if (i > 0) {
1167 expected_classpath_key + ":";
1168 }
1169 expected_classpath_key += oat_dex_files[i]->GetLocation() + "*" +
1170 std::to_string(oat_dex_files[i]->GetLocationChecksum());
1171 }
1172 expected_classpath_key += "]";
Calin Juravle1ce70852017-06-28 10:59:03 -07001173 }
1174
1175 RunTest(context.c_str(),
Calin Juravle7b0648a2017-07-07 18:40:50 -07001176 expected_classpath_key.c_str(),
Calin Juravle1ce70852017-06-28 10:59:03 -07001177 /*expected_success*/ true,
1178 /*use_second_source*/ true);
1179}
1180
1181TEST_F(Dex2oatClassLoaderContextTest, ContextWithNotExistentDexFiles) {
1182 std::string context = "PCL[does_not_exists.dex]";
1183 // Expect an empty context because stripped dex files cannot be open.
1184 RunTest(context.c_str(), kEmptyClassPathKey, /*expected_success*/ true);
1185}
1186
Calin Juravlec79470d2017-07-12 17:37:42 -07001187TEST_F(Dex2oatClassLoaderContextTest, ChainContext) {
1188 std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested");
1189 std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex");
1190
1191 std::string context = "PCL[" + GetTestDexFileName("Nested") + "];" +
1192 "DLC[" + GetTestDexFileName("MultiDex") + "]";
1193 std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "];" +
1194 "DLC[" + CreateClassPathWithChecksums(dex_files2) + "]";
1195
1196 RunTest(context.c_str(), expected_classpath_key.c_str(), true);
1197}
1198
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001199class Dex2oatDeterminism : public Dex2oatTest {};
1200
1201TEST_F(Dex2oatDeterminism, UnloadCompile) {
1202 if (!kUseReadBarrier &&
1203 gc::kCollectorTypeDefault != gc::kCollectorTypeCMS &&
1204 gc::kCollectorTypeDefault != gc::kCollectorTypeMS) {
1205 LOG(INFO) << "Test requires determinism support.";
1206 return;
1207 }
1208 Runtime* const runtime = Runtime::Current();
1209 std::string out_dir = GetScratchDir();
1210 const std::string base_oat_name = out_dir + "/base.oat";
1211 const std::string base_vdex_name = out_dir + "/base.vdex";
1212 const std::string unload_oat_name = out_dir + "/unload.oat";
1213 const std::string unload_vdex_name = out_dir + "/unload.vdex";
1214 const std::string no_unload_oat_name = out_dir + "/nounload.oat";
1215 const std::string no_unload_vdex_name = out_dir + "/nounload.vdex";
1216 const std::string app_image_name = out_dir + "/unload.art";
1217 std::string error_msg;
1218 const std::vector<gc::space::ImageSpace*>& spaces = runtime->GetHeap()->GetBootImageSpaces();
1219 ASSERT_GT(spaces.size(), 0u);
1220 const std::string image_location = spaces[0]->GetImageLocation();
1221 // Without passing in an app image, it will unload in between compilations.
1222 const int res = GenerateOdexForTestWithStatus(
1223 GetLibCoreDexFileNames(),
1224 base_oat_name,
1225 CompilerFilter::Filter::kQuicken,
1226 &error_msg,
1227 {"--force-determinism", "--avoid-storing-invocation"});
1228 EXPECT_EQ(res, 0);
1229 Copy(base_oat_name, unload_oat_name);
1230 Copy(base_vdex_name, unload_vdex_name);
1231 std::unique_ptr<File> unload_oat(OS::OpenFileForReading(unload_oat_name.c_str()));
1232 std::unique_ptr<File> unload_vdex(OS::OpenFileForReading(unload_vdex_name.c_str()));
1233 ASSERT_TRUE(unload_oat != nullptr);
1234 ASSERT_TRUE(unload_vdex != nullptr);
1235 EXPECT_GT(unload_oat->GetLength(), 0u);
1236 EXPECT_GT(unload_vdex->GetLength(), 0u);
1237 // Regenerate with an app image to disable the dex2oat unloading and verify that the output is
1238 // the same.
1239 const int res2 = GenerateOdexForTestWithStatus(
1240 GetLibCoreDexFileNames(),
1241 base_oat_name,
1242 CompilerFilter::Filter::kQuicken,
1243 &error_msg,
1244 {"--force-determinism", "--avoid-storing-invocation", "--app-image-file=" + app_image_name});
1245 EXPECT_EQ(res2, 0);
1246 Copy(base_oat_name, no_unload_oat_name);
1247 Copy(base_vdex_name, no_unload_vdex_name);
1248 std::unique_ptr<File> no_unload_oat(OS::OpenFileForReading(no_unload_oat_name.c_str()));
1249 std::unique_ptr<File> no_unload_vdex(OS::OpenFileForReading(no_unload_vdex_name.c_str()));
1250 ASSERT_TRUE(no_unload_oat != nullptr);
1251 ASSERT_TRUE(no_unload_vdex != nullptr);
1252 EXPECT_GT(no_unload_oat->GetLength(), 0u);
1253 EXPECT_GT(no_unload_vdex->GetLength(), 0u);
1254 // Verify that both of the files are the same (odex and vdex).
1255 EXPECT_EQ(unload_oat->GetLength(), no_unload_oat->GetLength());
1256 EXPECT_EQ(unload_vdex->GetLength(), no_unload_vdex->GetLength());
1257 EXPECT_EQ(unload_oat->Compare(no_unload_oat.get()), 0)
1258 << unload_oat_name << " " << no_unload_oat_name;
1259 EXPECT_EQ(unload_vdex->Compare(no_unload_vdex.get()), 0)
1260 << unload_vdex_name << " " << no_unload_vdex_name;
1261 // App image file.
1262 std::unique_ptr<File> app_image_file(OS::OpenFileForReading(app_image_name.c_str()));
1263 ASSERT_TRUE(app_image_file != nullptr);
1264 EXPECT_GT(app_image_file->GetLength(), 0u);
1265}
1266
Mathieu Chartier120aa282017-08-05 16:03:03 -07001267// Test that dexlayout section info is correctly written to the oat file for profile based
1268// compilation.
1269TEST_F(Dex2oatTest, LayoutSections) {
1270 using Hotness = ProfileCompilationInfo::MethodHotness;
1271 std::unique_ptr<const DexFile> dex(OpenTestDexFile("ManyMethods"));
1272 ScratchFile profile_file;
1273 // We can only layout method indices with code items, figure out which ones have this property
1274 // first.
1275 std::vector<uint16_t> methods;
1276 {
1277 const DexFile::TypeId* type_id = dex->FindTypeId("LManyMethods;");
1278 dex::TypeIndex type_idx = dex->GetIndexForTypeId(*type_id);
1279 const DexFile::ClassDef* class_def = dex->FindClassDef(type_idx);
1280 ClassDataItemIterator it(*dex, dex->GetClassData(*class_def));
1281 it.SkipAllFields();
1282 std::set<size_t> code_item_offsets;
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08001283 for (; it.HasNextMethod(); it.Next()) {
Mathieu Chartier120aa282017-08-05 16:03:03 -07001284 const uint16_t method_idx = it.GetMemberIndex();
1285 const size_t code_item_offset = it.GetMethodCodeItemOffset();
1286 if (code_item_offsets.insert(code_item_offset).second) {
1287 // Unique code item, add the method index.
1288 methods.push_back(method_idx);
1289 }
1290 }
1291 DCHECK(!it.HasNext());
1292 }
1293 ASSERT_GE(methods.size(), 8u);
1294 std::vector<uint16_t> hot_methods = {methods[1], methods[3], methods[5]};
1295 std::vector<uint16_t> startup_methods = {methods[1], methods[2], methods[7]};
1296 std::vector<uint16_t> post_methods = {methods[0], methods[2], methods[6]};
1297 // Here, we build the profile from the method lists.
1298 ProfileCompilationInfo info;
1299 info.AddMethodsForDex(
1300 static_cast<Hotness::Flag>(Hotness::kFlagHot | Hotness::kFlagStartup),
1301 dex.get(),
1302 hot_methods.begin(),
1303 hot_methods.end());
1304 info.AddMethodsForDex(
1305 Hotness::kFlagStartup,
1306 dex.get(),
1307 startup_methods.begin(),
1308 startup_methods.end());
1309 info.AddMethodsForDex(
1310 Hotness::kFlagPostStartup,
1311 dex.get(),
1312 post_methods.begin(),
1313 post_methods.end());
1314 for (uint16_t id : hot_methods) {
1315 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsHot());
1316 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsStartup());
1317 }
1318 for (uint16_t id : startup_methods) {
1319 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsStartup());
1320 }
1321 for (uint16_t id : post_methods) {
1322 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsPostStartup());
1323 }
1324 // Save the profile since we want to use it with dex2oat to produce an oat file.
1325 ASSERT_TRUE(info.Save(profile_file.GetFd()));
1326 // Generate a profile based odex.
1327 const std::string dir = GetScratchDir();
1328 const std::string oat_filename = dir + "/base.oat";
1329 const std::string vdex_filename = dir + "/base.vdex";
1330 std::string error_msg;
1331 const int res = GenerateOdexForTestWithStatus(
1332 {dex->GetLocation()},
1333 oat_filename,
1334 CompilerFilter::Filter::kQuicken,
1335 &error_msg,
1336 {"--profile-file=" + profile_file.GetFilename()});
1337 EXPECT_EQ(res, 0);
1338
1339 // Open our generated oat file.
Nicolas Geoffray30025092018-04-19 14:43:29 +01001340 std::unique_ptr<OatFile> odex_file(OatFile::Open(/* zip_fd */ -1,
1341 oat_filename.c_str(),
Mathieu Chartier120aa282017-08-05 16:03:03 -07001342 oat_filename.c_str(),
1343 nullptr,
1344 nullptr,
1345 false,
1346 /*low_4gb*/false,
1347 dex->GetLocation().c_str(),
1348 &error_msg));
1349 ASSERT_TRUE(odex_file != nullptr);
1350 std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
1351 ASSERT_EQ(oat_dex_files.size(), 1u);
1352 // Check that the code sections match what we expect.
1353 for (const OatDexFile* oat_dex : oat_dex_files) {
1354 const DexLayoutSections* const sections = oat_dex->GetDexLayoutSections();
1355 // Testing of logging the sections.
1356 ASSERT_TRUE(sections != nullptr);
1357 LOG(INFO) << *sections;
1358
1359 // Load the sections into temporary variables for convenience.
1360 const DexLayoutSection& code_section =
1361 sections->sections_[static_cast<size_t>(DexLayoutSections::SectionType::kSectionTypeCode)];
1362 const DexLayoutSection::Subsection& section_hot_code =
1363 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeHot)];
1364 const DexLayoutSection::Subsection& section_sometimes_used =
1365 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeSometimesUsed)];
1366 const DexLayoutSection::Subsection& section_startup_only =
1367 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeStartupOnly)];
1368 const DexLayoutSection::Subsection& section_unused =
1369 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeUnused)];
1370
1371 // All the sections should be non-empty.
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001372 EXPECT_GT(section_hot_code.Size(), 0u);
1373 EXPECT_GT(section_sometimes_used.Size(), 0u);
1374 EXPECT_GT(section_startup_only.Size(), 0u);
1375 EXPECT_GT(section_unused.Size(), 0u);
Mathieu Chartier120aa282017-08-05 16:03:03 -07001376
1377 // Open the dex file since we need to peek at the code items to verify the layout matches what
1378 // we expect.
1379 std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1380 ASSERT_TRUE(dex_file != nullptr) << error_msg;
1381 const DexFile::TypeId* type_id = dex_file->FindTypeId("LManyMethods;");
1382 ASSERT_TRUE(type_id != nullptr);
1383 dex::TypeIndex type_idx = dex_file->GetIndexForTypeId(*type_id);
1384 const DexFile::ClassDef* class_def = dex_file->FindClassDef(type_idx);
1385 ASSERT_TRUE(class_def != nullptr);
1386
1387 // Count how many code items are for each category, there should be at least one per category.
1388 size_t hot_count = 0;
1389 size_t post_startup_count = 0;
1390 size_t startup_count = 0;
1391 size_t unused_count = 0;
1392 // Visit all of the methdos of the main class and cross reference the method indices to their
1393 // corresponding code item offsets to verify the layout.
1394 ClassDataItemIterator it(*dex_file, dex_file->GetClassData(*class_def));
1395 it.SkipAllFields();
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08001396 for (; it.HasNextMethod(); it.Next()) {
Mathieu Chartier120aa282017-08-05 16:03:03 -07001397 const size_t method_idx = it.GetMemberIndex();
1398 const size_t code_item_offset = it.GetMethodCodeItemOffset();
1399 const bool is_hot = ContainsElement(hot_methods, method_idx);
1400 const bool is_startup = ContainsElement(startup_methods, method_idx);
1401 const bool is_post_startup = ContainsElement(post_methods, method_idx);
1402 if (is_hot) {
1403 // Hot is highest precedence, check that the hot methods are in the hot section.
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001404 EXPECT_TRUE(section_hot_code.Contains(code_item_offset));
Mathieu Chartier120aa282017-08-05 16:03:03 -07001405 ++hot_count;
1406 } else if (is_post_startup) {
1407 // Post startup is sometimes used section.
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001408 EXPECT_TRUE(section_sometimes_used.Contains(code_item_offset));
Mathieu Chartier120aa282017-08-05 16:03:03 -07001409 ++post_startup_count;
1410 } else if (is_startup) {
1411 // Startup at this point means not hot or post startup, these must be startup only then.
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001412 EXPECT_TRUE(section_startup_only.Contains(code_item_offset));
Mathieu Chartier120aa282017-08-05 16:03:03 -07001413 ++startup_count;
1414 } else {
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001415 if (section_unused.Contains(code_item_offset)) {
Alan Leung9595fd32017-10-17 17:08:19 -07001416 // If no flags are set, the method should be unused ...
1417 ++unused_count;
1418 } else {
1419 // or this method is part of the last code item and the end is 4 byte aligned.
1420 ClassDataItemIterator it2(*dex_file, dex_file->GetClassData(*class_def));
1421 it2.SkipAllFields();
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08001422 for (; it2.HasNextMethod(); it2.Next()) {
Alan Leung9595fd32017-10-17 17:08:19 -07001423 EXPECT_LE(it2.GetMethodCodeItemOffset(), code_item_offset);
1424 }
1425 uint32_t code_item_size = dex_file->FindCodeItemOffset(*class_def, method_idx);
1426 EXPECT_EQ((code_item_offset + code_item_size) % 4, 0u);
1427 }
Mathieu Chartier120aa282017-08-05 16:03:03 -07001428 }
1429 }
1430 DCHECK(!it.HasNext());
1431 EXPECT_GT(hot_count, 0u);
1432 EXPECT_GT(post_startup_count, 0u);
1433 EXPECT_GT(startup_count, 0u);
1434 EXPECT_GT(unused_count, 0u);
1435 }
1436}
1437
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001438// Test that generating compact dex works.
1439TEST_F(Dex2oatTest, GenerateCompactDex) {
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001440 // Generate a compact dex based odex.
1441 const std::string dir = GetScratchDir();
1442 const std::string oat_filename = dir + "/base.oat";
1443 const std::string vdex_filename = dir + "/base.vdex";
Mathieu Chartierc17b7d82018-03-14 14:00:04 -07001444 const std::string dex_location = GetTestDexFileName("MultiDex");
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001445 std::string error_msg;
1446 const int res = GenerateOdexForTestWithStatus(
Mathieu Chartierc17b7d82018-03-14 14:00:04 -07001447 { dex_location },
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001448 oat_filename,
1449 CompilerFilter::Filter::kQuicken,
1450 &error_msg,
1451 {"--compact-dex-level=fast"});
1452 EXPECT_EQ(res, 0);
1453 // Open our generated oat file.
Nicolas Geoffray30025092018-04-19 14:43:29 +01001454 std::unique_ptr<OatFile> odex_file(OatFile::Open(/* zip_fd */ -1,
1455 oat_filename.c_str(),
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001456 oat_filename.c_str(),
1457 nullptr,
1458 nullptr,
1459 false,
1460 /*low_4gb*/false,
Mathieu Chartierc17b7d82018-03-14 14:00:04 -07001461 dex_location.c_str(),
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001462 &error_msg));
1463 ASSERT_TRUE(odex_file != nullptr);
1464 std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
Mathieu Chartierc17b7d82018-03-14 14:00:04 -07001465 ASSERT_GT(oat_dex_files.size(), 1u);
1466 // Check that each dex is a compact dex file.
1467 std::vector<std::unique_ptr<const CompactDexFile>> compact_dex_files;
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001468 for (const OatDexFile* oat_dex : oat_dex_files) {
1469 std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1470 ASSERT_TRUE(dex_file != nullptr) << error_msg;
1471 ASSERT_TRUE(dex_file->IsCompactDexFile());
Mathieu Chartierc17b7d82018-03-14 14:00:04 -07001472 compact_dex_files.push_back(
1473 std::unique_ptr<const CompactDexFile>(dex_file.release()->AsCompactDexFile()));
1474 }
1475 for (const std::unique_ptr<const CompactDexFile>& dex_file : compact_dex_files) {
1476 // Test that every code item is in the owned section.
1477 const CompactDexFile::Header& header = dex_file->GetHeader();
1478 EXPECT_LE(header.OwnedDataBegin(), header.OwnedDataEnd());
1479 EXPECT_LE(header.OwnedDataBegin(), header.data_size_);
1480 EXPECT_LE(header.OwnedDataEnd(), header.data_size_);
1481 for (uint32_t i = 0; i < dex_file->NumClassDefs(); ++i) {
1482 const DexFile::ClassDef& class_def = dex_file->GetClassDef(i);
1483 class_def.VisitMethods(dex_file.get(), [&](const ClassDataItemIterator& it) {
1484 if (it.GetMethodCodeItemOffset() != 0u) {
1485 ASSERT_GE(it.GetMethodCodeItemOffset(), header.OwnedDataBegin());
1486 ASSERT_LT(it.GetMethodCodeItemOffset(), header.OwnedDataEnd());
1487 }
1488 });
1489 }
1490 // Test that the owned sections don't overlap.
1491 for (const std::unique_ptr<const CompactDexFile>& other_dex : compact_dex_files) {
1492 if (dex_file != other_dex) {
1493 ASSERT_TRUE(
1494 (dex_file->GetHeader().OwnedDataBegin() >= other_dex->GetHeader().OwnedDataEnd()) ||
1495 (dex_file->GetHeader().OwnedDataEnd() <= other_dex->GetHeader().OwnedDataBegin()));
1496 }
1497 }
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001498 }
1499}
1500
Andreas Gampef39208f2017-10-19 15:06:59 -07001501class Dex2oatVerifierAbort : public Dex2oatTest {};
1502
1503TEST_F(Dex2oatVerifierAbort, HardFail) {
1504 // Use VerifierDeps as it has hard-failing classes.
1505 std::unique_ptr<const DexFile> dex(OpenTestDexFile("VerifierDeps"));
1506 std::string out_dir = GetScratchDir();
1507 const std::string base_oat_name = out_dir + "/base.oat";
1508 std::string error_msg;
1509 const int res_fail = GenerateOdexForTestWithStatus(
1510 {dex->GetLocation()},
1511 base_oat_name,
1512 CompilerFilter::Filter::kQuicken,
1513 &error_msg,
1514 {"--abort-on-hard-verifier-error"});
1515 EXPECT_NE(0, res_fail);
1516
1517 const int res_no_fail = GenerateOdexForTestWithStatus(
1518 {dex->GetLocation()},
1519 base_oat_name,
1520 CompilerFilter::Filter::kQuicken,
1521 &error_msg,
1522 {"--no-abort-on-hard-verifier-error"});
1523 EXPECT_EQ(0, res_no_fail);
1524}
1525
1526TEST_F(Dex2oatVerifierAbort, SoftFail) {
1527 // Use VerifierDepsMulti as it has hard-failing classes.
1528 std::unique_ptr<const DexFile> dex(OpenTestDexFile("VerifierDepsMulti"));
1529 std::string out_dir = GetScratchDir();
1530 const std::string base_oat_name = out_dir + "/base.oat";
1531 std::string error_msg;
1532 const int res_fail = GenerateOdexForTestWithStatus(
1533 {dex->GetLocation()},
1534 base_oat_name,
1535 CompilerFilter::Filter::kQuicken,
1536 &error_msg,
1537 {"--abort-on-soft-verifier-error"});
1538 EXPECT_NE(0, res_fail);
1539
1540 const int res_no_fail = GenerateOdexForTestWithStatus(
1541 {dex->GetLocation()},
1542 base_oat_name,
1543 CompilerFilter::Filter::kQuicken,
1544 &error_msg,
1545 {"--no-abort-on-soft-verifier-error"});
1546 EXPECT_EQ(0, res_no_fail);
1547}
1548
Andreas Gampecac31ad2017-11-06 20:01:17 -08001549class Dex2oatDedupeCode : public Dex2oatTest {};
1550
1551TEST_F(Dex2oatDedupeCode, DedupeTest) {
1552 // Use MyClassNatives. It has lots of native methods that will produce deduplicate-able code.
1553 std::unique_ptr<const DexFile> dex(OpenTestDexFile("MyClassNatives"));
1554 std::string out_dir = GetScratchDir();
1555 const std::string base_oat_name = out_dir + "/base.oat";
1556 size_t no_dedupe_size = 0;
1557 GenerateOdexForTest(dex->GetLocation(),
1558 base_oat_name,
1559 CompilerFilter::Filter::kSpeed,
1560 { "--deduplicate-code=false" },
1561 true, // expect_success
1562 false, // use_fd
1563 [&no_dedupe_size](const OatFile& o) {
1564 no_dedupe_size = o.Size();
1565 });
1566
1567 size_t dedupe_size = 0;
1568 GenerateOdexForTest(dex->GetLocation(),
1569 base_oat_name,
1570 CompilerFilter::Filter::kSpeed,
1571 { "--deduplicate-code=true" },
1572 true, // expect_success
1573 false, // use_fd
1574 [&dedupe_size](const OatFile& o) {
1575 dedupe_size = o.Size();
1576 });
1577
1578 EXPECT_LT(dedupe_size, no_dedupe_size);
1579}
1580
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00001581TEST_F(Dex2oatTest, UncompressedTest) {
1582 std::unique_ptr<const DexFile> dex(OpenTestDexFile("MainUncompressed"));
1583 std::string out_dir = GetScratchDir();
1584 const std::string base_oat_name = out_dir + "/base.oat";
1585 GenerateOdexForTest(dex->GetLocation(),
1586 base_oat_name,
1587 CompilerFilter::Filter::kQuicken,
1588 { },
1589 true, // expect_success
1590 false, // use_fd
1591 [](const OatFile& o) {
1592 CHECK(!o.ContainsDexCode());
1593 });
1594}
1595
Mathieu Chartier700a9852018-02-06 18:27:38 -08001596TEST_F(Dex2oatTest, EmptyUncompressedDexTest) {
1597 std::string out_dir = GetScratchDir();
1598 const std::string base_oat_name = out_dir + "/base.oat";
1599 std::string error_msg;
1600 int status = GenerateOdexForTestWithStatus(
1601 { GetTestDexFileName("MainEmptyUncompressed") },
1602 base_oat_name,
1603 CompilerFilter::Filter::kQuicken,
1604 &error_msg,
1605 { },
1606 /*use_fd*/ false);
1607 // Expect to fail with code 1 and not SIGSEGV or SIGABRT.
1608 ASSERT_TRUE(WIFEXITED(status));
1609 ASSERT_EQ(WEXITSTATUS(status), 1) << error_msg;
1610}
1611
Mathieu Chartier05f90d12018-02-07 13:47:17 -08001612// Dex file that has duplicate methods have different code items and debug info.
1613static const char kDuplicateMethodInputDex[] =
1614 "ZGV4CjAzOQDEy8VPdj4qHpgPYFWtLCtOykfFP4kB8tGYDAAAcAAAAHhWNBIAAAAAAAAAANALAABI"
1615 "AAAAcAAAAA4AAACQAQAABQAAAMgBAAANAAAABAIAABkAAABsAgAABAAAADQDAADgCAAAuAMAADgI"
1616 "AABCCAAASggAAE8IAABcCAAAaggAAHkIAACICAAAlggAAKQIAACyCAAAwAgAAM4IAADcCAAA6ggA"
1617 "APgIAAD7CAAA/wgAABcJAAAuCQAARQkAAFQJAAB4CQAAmAkAALsJAADSCQAA5gkAAPoJAAAVCgAA"
1618 "KQoAADsKAABCCgAASgoAAFIKAABbCgAAZAoAAGwKAAB0CgAAfAoAAIQKAACMCgAAlAoAAJwKAACk"
1619 "CgAArQoAALcKAADACgAAwwoAAMcKAADcCgAA6QoAAPEKAAD3CgAA/QoAAAMLAAAJCwAAEAsAABcL"
1620 "AAAdCwAAIwsAACkLAAAvCwAANQsAADsLAABBCwAARwsAAE0LAABSCwAAWwsAAF4LAABoCwAAbwsA"
1621 "ABEAAAASAAAAEwAAABQAAAAVAAAAFgAAABcAAAAYAAAAGQAAABoAAAAbAAAAHAAAAC4AAAAwAAAA"
1622 "DwAAAAkAAAAAAAAAEAAAAAoAAACoBwAALgAAAAwAAAAAAAAALwAAAAwAAACoBwAALwAAAAwAAACw"
1623 "BwAAAgAJADUAAAACAAkANgAAAAIACQA3AAAAAgAJADgAAAACAAkAOQAAAAIACQA6AAAAAgAJADsA"
1624 "AAACAAkAPAAAAAIACQA9AAAAAgAJAD4AAAACAAkAPwAAAAIACQBAAAAACwAHAEIAAAAAAAIAAQAA"
1625 "AAAAAwAeAAAAAQACAAEAAAABAAMAHgAAAAIAAgAAAAAAAgACAAEAAAADAAIAAQAAAAMAAgAfAAAA"
1626 "AwACACAAAAADAAIAIQAAAAMAAgAiAAAAAwACACMAAAADAAIAJAAAAAMAAgAlAAAAAwACACYAAAAD"
1627 "AAIAJwAAAAMAAgAoAAAAAwACACkAAAADAAIAKgAAAAMABAA0AAAABwADAEMAAAAIAAIAAQAAAAoA"
1628 "AgABAAAACgABADIAAAAKAAAARQAAAAAAAAAAAAAACAAAAAAAAAAdAAAAaAcAALYHAAAAAAAAAQAA"
1629 "AAAAAAAIAAAAAAAAAB0AAAB4BwAAxAcAAAAAAAACAAAAAAAAAAgAAAAAAAAAHQAAAIgHAADSBwAA"
1630 "AAAAAAMAAAAAAAAACAAAAAAAAAAdAAAAmAcAAPoHAAAAAAAAAAAAAAEAAAAAAAAArAYAADEAAAAa"
1631 "AAMAaQAAABoABABpAAEAGgAHAGkABAAaAAgAaQAFABoACQBpAAYAGgAKAGkABwAaAAsAaQAIABoA"
1632 "DABpAAkAGgANAGkACgAaAA4AaQALABoABQBpAAIAGgAGAGkAAwAOAAAAAQABAAEAAACSBgAABAAA"
1633 "AHAQFQAAAA4ABAABAAIAAACWBgAAFwAAAGIADAAiAQoAcBAWAAEAGgICAG4gFwAhAG4gFwAxAG4Q"
1634 "GAABAAwBbiAUABAADgAAAAEAAQABAAAAngYAAAQAAABwEBUAAAAOAAIAAQACAAAAogYAAAYAAABi"
1635 "AAwAbiAUABAADgABAAEAAQAAAKgGAAAEAAAAcBAVAAAADgABAAEAAQAAALsGAAAEAAAAcBAVAAAA"
1636 "DgABAAAAAQAAAL8GAAAGAAAAYgAAAHEQAwAAAA4AAQAAAAEAAADEBgAABgAAAGIAAQBxEAMAAAAO"
1637 "AAEAAAABAAAA8QYAAAYAAABiAAIAcRABAAAADgABAAAAAQAAAPYGAAAGAAAAYgADAHEQAwAAAA4A"
1638 "AQAAAAEAAADJBgAABgAAAGIABABxEAMAAAAOAAEAAAABAAAAzgYAAAYAAABiAAEAcRADAAAADgAB"
1639 "AAAAAQAAANMGAAAGAAAAYgAGAHEQAwAAAA4AAQAAAAEAAADYBgAABgAAAGIABwBxEAMAAAAOAAEA"
1640 "AAABAAAA3QYAAAYAAABiAAgAcRABAAAADgABAAAAAQAAAOIGAAAGAAAAYgAJAHEQAwAAAA4AAQAA"
1641 "AAEAAADnBgAABgAAAGIACgBxEAMAAAAOAAEAAAABAAAA7AYAAAYAAABiAAsAcRABAAAADgABAAEA"
1642 "AAAAAPsGAAAlAAAAcQAHAAAAcQAIAAAAcQALAAAAcQAMAAAAcQANAAAAcQAOAAAAcQAPAAAAcQAQ"
1643 "AAAAcQARAAAAcQASAAAAcQAJAAAAcQAKAAAADgAnAA4AKQFFDgEWDwAhAA4AIwFFDloAEgAOABMA"
1644 "DktLS0tLS0tLS0tLABEADgAuAA5aADIADloANgAOWgA6AA5aAD4ADloAQgAOWgBGAA5aAEoADloA"
1645 "TgAOWgBSAA5aAFYADloAWgAOWgBeATQOPDw8PDw8PDw8PDw8AAIEAUYYAwIFAjEECEEXLAIFAjEE"
1646 "CEEXKwIFAjEECEEXLQIGAUYcAxgAGAEYAgAAAAIAAAAMBwAAEgcAAAIAAAAMBwAAGwcAAAIAAAAM"
1647 "BwAAJAcAAAEAAAAtBwAAPAcAAAAAAAAAAAAAAAAAAEgHAAAAAAAAAAAAAAAAAABUBwAAAAAAAAAA"
1648 "AAAAAAAAYAcAAAAAAAAAAAAAAAAAAAEAAAAJAAAAAQAAAA0AAAACAACAgASsCAEIxAgAAAIAAoCA"
1649 "BIQJAQicCQwAAgAACQEJAQkBCQEJAQkBCQEJAQkBCQEJAQkEiIAEuAcBgIAEuAkAAA4ABoCABNAJ"
1650 "AQnoCQAJhAoACaAKAAm8CgAJ2AoACfQKAAmQCwAJrAsACcgLAAnkCwAJgAwACZwMAAm4DAg8Y2xp"
1651 "bml0PgAGPGluaXQ+AANBQUEAC0hlbGxvIFdvcmxkAAxIZWxsbyBXb3JsZDEADUhlbGxvIFdvcmxk"
1652 "MTAADUhlbGxvIFdvcmxkMTEADEhlbGxvIFdvcmxkMgAMSGVsbG8gV29ybGQzAAxIZWxsbyBXb3Js"
1653 "ZDQADEhlbGxvIFdvcmxkNQAMSGVsbG8gV29ybGQ2AAxIZWxsbyBXb3JsZDcADEhlbGxvIFdvcmxk"
1654 "OAAMSGVsbG8gV29ybGQ5AAFMAAJMTAAWTE1hbnlNZXRob2RzJFByaW50ZXIyOwAVTE1hbnlNZXRo"
1655 "b2RzJFByaW50ZXI7ABVMTWFueU1ldGhvZHMkU3RyaW5nczsADUxNYW55TWV0aG9kczsAIkxkYWx2"
1656 "aWsvYW5ub3RhdGlvbi9FbmNsb3NpbmdDbGFzczsAHkxkYWx2aWsvYW5ub3RhdGlvbi9Jbm5lckNs"
1657 "YXNzOwAhTGRhbHZpay9hbm5vdGF0aW9uL01lbWJlckNsYXNzZXM7ABVMamF2YS9pby9QcmludFN0"
1658 "cmVhbTsAEkxqYXZhL2xhbmcvT2JqZWN0OwASTGphdmEvbGFuZy9TdHJpbmc7ABlMamF2YS9sYW5n"
1659 "L1N0cmluZ0J1aWxkZXI7ABJMamF2YS9sYW5nL1N5c3RlbTsAEE1hbnlNZXRob2RzLmphdmEABVBy"
1660 "aW50AAZQcmludDAABlByaW50MQAHUHJpbnQxMAAHUHJpbnQxMQAGUHJpbnQyAAZQcmludDMABlBy"
1661 "aW50NAAGUHJpbnQ1AAZQcmludDYABlByaW50NwAGUHJpbnQ4AAZQcmludDkAB1ByaW50ZXIACFBy"
1662 "aW50ZXIyAAdTdHJpbmdzAAFWAAJWTAATW0xqYXZhL2xhbmcvU3RyaW5nOwALYWNjZXNzRmxhZ3MA"
1663 "BmFwcGVuZAAEYXJncwAEbWFpbgAEbXNnMAAEbXNnMQAFbXNnMTAABW1zZzExAARtc2cyAARtc2cz"
1664 "AARtc2c0AARtc2c1AARtc2c2AARtc2c3AARtc2c4AARtc2c5AARuYW1lAANvdXQAB3ByaW50bG4A"
1665 "AXMACHRvU3RyaW5nAAV2YWx1ZQBffn5EOHsibWluLWFwaSI6MTAwMDAsInNoYS0xIjoiZmViODZj"
1666 "MDA2ZWZhY2YxZDc5ODRiODVlMTc5MGZlZjdhNzY3YWViYyIsInZlcnNpb24iOiJ2MS4xLjUtZGV2"
1667 "In0AEAAAAAAAAAABAAAAAAAAAAEAAABIAAAAcAAAAAIAAAAOAAAAkAEAAAMAAAAFAAAAyAEAAAQA"
1668 "AAANAAAABAIAAAUAAAAZAAAAbAIAAAYAAAAEAAAANAMAAAEgAAAUAAAAuAMAAAMgAAAUAAAAkgYA"
1669 "AAQgAAAFAAAADAcAAAMQAAAEAAAAOQcAAAYgAAAEAAAAaAcAAAEQAAACAAAAqAcAAAAgAAAEAAAA"
1670 "tgcAAAIgAABIAAAAOAgAAAAQAAABAAAA0AsAAAAAAAA=";
1671
1672static void WriteBase64ToFile(const char* base64, File* file) {
1673 // Decode base64.
1674 CHECK(base64 != nullptr);
1675 size_t length;
1676 std::unique_ptr<uint8_t[]> bytes(DecodeBase64(base64, &length));
1677 CHECK(bytes != nullptr);
1678 if (!file->WriteFully(bytes.get(), length)) {
1679 PLOG(FATAL) << "Failed to write base64 as file";
1680 }
1681}
1682
1683TEST_F(Dex2oatTest, CompactDexGenerationFailure) {
1684 ScratchFile temp_dex;
1685 WriteBase64ToFile(kDuplicateMethodInputDex, temp_dex.GetFile());
1686 std::string out_dir = GetScratchDir();
1687 const std::string oat_filename = out_dir + "/base.oat";
1688 // The dex won't pass the method verifier, only use the verify filter.
1689 GenerateOdexForTest(temp_dex.GetFilename(),
1690 oat_filename,
1691 CompilerFilter::Filter::kVerify,
1692 { },
1693 true, // expect_success
1694 false, // use_fd
1695 [](const OatFile& o) {
1696 CHECK(o.ContainsDexCode());
1697 });
1698 // Open our generated oat file.
1699 std::string error_msg;
Nicolas Geoffray30025092018-04-19 14:43:29 +01001700 std::unique_ptr<OatFile> odex_file(OatFile::Open(/* zip_fd */ -1,
1701 oat_filename.c_str(),
Mathieu Chartier05f90d12018-02-07 13:47:17 -08001702 oat_filename.c_str(),
1703 nullptr,
1704 nullptr,
1705 false,
1706 /*low_4gb*/false,
1707 temp_dex.GetFilename().c_str(),
1708 &error_msg));
1709 ASSERT_TRUE(odex_file != nullptr);
1710 std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
1711 ASSERT_EQ(oat_dex_files.size(), 1u);
1712 // The dexes should have failed to convert to compact dex.
1713 for (const OatDexFile* oat_dex : oat_dex_files) {
1714 std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1715 ASSERT_TRUE(dex_file != nullptr) << error_msg;
1716 ASSERT_TRUE(!dex_file->IsCompactDexFile());
1717 }
1718}
1719
Mathieu Chartiercda83be2018-03-01 23:55:55 -08001720TEST_F(Dex2oatTest, CompactDexGenerationFailureMultiDex) {
1721 // Create a multidex file with only one dex that gets rejected for cdex conversion.
1722 ScratchFile apk_file;
1723 {
1724 FILE* file = fdopen(apk_file.GetFd(), "w+b");
1725 ZipWriter writer(file);
1726 // Add vdex to zip.
1727 writer.StartEntry("classes.dex", ZipWriter::kCompress);
1728 size_t length = 0u;
1729 std::unique_ptr<uint8_t[]> bytes(DecodeBase64(kDuplicateMethodInputDex, &length));
1730 ASSERT_GE(writer.WriteBytes(&bytes[0], length), 0);
1731 writer.FinishEntry();
1732 writer.StartEntry("classes2.dex", ZipWriter::kCompress);
1733 std::unique_ptr<const DexFile> dex(OpenTestDexFile("ManyMethods"));
1734 ASSERT_GE(writer.WriteBytes(dex->Begin(), dex->Size()), 0);
1735 writer.FinishEntry();
1736 writer.Finish();
1737 ASSERT_EQ(apk_file.GetFile()->Flush(), 0);
1738 }
Andreas Gampebc802de2018-06-20 17:24:11 -07001739 const std::string& dex_location = apk_file.GetFilename();
Mathieu Chartiercda83be2018-03-01 23:55:55 -08001740 const std::string odex_location = GetOdexDir() + "/output.odex";
1741 GenerateOdexForTest(dex_location,
1742 odex_location,
1743 CompilerFilter::kQuicken,
1744 { "--compact-dex-level=fast" },
1745 true);
1746}
1747
Andreas Gampe25419b52018-02-08 21:30:26 -08001748TEST_F(Dex2oatTest, StderrLoggerOutput) {
1749 std::string dex_location = GetScratchDir() + "/Dex2OatStderrLoggerTest.jar";
1750 std::string odex_location = GetOdexDir() + "/Dex2OatStderrLoggerTest.odex";
1751
1752 // Test file doesn't matter.
1753 Copy(GetDexSrc1(), dex_location);
1754
1755 GenerateOdexForTest(dex_location,
1756 odex_location,
1757 CompilerFilter::kQuicken,
1758 { "--runtime-arg", "-Xuse-stderr-logger" },
1759 true);
1760 // Look for some random part of dex2oat logging. With the stderr logger this should be captured,
1761 // even on device.
1762 EXPECT_NE(std::string::npos, output_.find("dex2oat took"));
1763}
1764
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001765TEST_F(Dex2oatTest, VerifyCompilationReason) {
1766 std::string dex_location = GetScratchDir() + "/Dex2OatCompilationReason.jar";
1767 std::string odex_location = GetOdexDir() + "/Dex2OatCompilationReason.odex";
1768
1769 // Test file doesn't matter.
1770 Copy(GetDexSrc1(), dex_location);
1771
1772 GenerateOdexForTest(dex_location,
1773 odex_location,
1774 CompilerFilter::kVerify,
1775 { "--compilation-reason=install" },
1776 true);
1777 std::string error_msg;
Nicolas Geoffray30025092018-04-19 14:43:29 +01001778 std::unique_ptr<OatFile> odex_file(OatFile::Open(/* zip_fd */ -1,
1779 odex_location.c_str(),
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001780 odex_location.c_str(),
1781 nullptr,
1782 nullptr,
1783 false,
1784 /*low_4gb*/false,
1785 dex_location.c_str(),
1786 &error_msg));
1787 ASSERT_TRUE(odex_file != nullptr);
1788 ASSERT_STREQ("install", odex_file->GetCompilationReason());
1789}
1790
1791TEST_F(Dex2oatTest, VerifyNoCompilationReason) {
1792 std::string dex_location = GetScratchDir() + "/Dex2OatNoCompilationReason.jar";
1793 std::string odex_location = GetOdexDir() + "/Dex2OatNoCompilationReason.odex";
1794
1795 // Test file doesn't matter.
1796 Copy(GetDexSrc1(), dex_location);
1797
1798 GenerateOdexForTest(dex_location,
1799 odex_location,
1800 CompilerFilter::kVerify,
1801 {},
1802 true);
1803 std::string error_msg;
Nicolas Geoffray30025092018-04-19 14:43:29 +01001804 std::unique_ptr<OatFile> odex_file(OatFile::Open(/* zip_fd */ -1,
1805 odex_location.c_str(),
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001806 odex_location.c_str(),
1807 nullptr,
1808 nullptr,
1809 false,
1810 /*low_4gb*/false,
1811 dex_location.c_str(),
1812 &error_msg));
1813 ASSERT_TRUE(odex_file != nullptr);
1814 ASSERT_EQ(nullptr, odex_file->GetCompilationReason());
1815}
1816
Mathieu Chartier792111c2018-02-15 13:02:15 -08001817TEST_F(Dex2oatTest, DontExtract) {
1818 std::unique_ptr<const DexFile> dex(OpenTestDexFile("ManyMethods"));
1819 std::string error_msg;
1820 const std::string out_dir = GetScratchDir();
1821 const std::string dex_location = dex->GetLocation();
1822 const std::string odex_location = out_dir + "/base.oat";
1823 const std::string vdex_location = out_dir + "/base.vdex";
1824 GenerateOdexForTest(dex_location,
1825 odex_location,
1826 CompilerFilter::Filter::kVerify,
1827 { "--copy-dex-files=false" },
1828 true, // expect_success
1829 false, // use_fd
1830 [](const OatFile&) {
1831 });
1832 {
1833 // Check the vdex doesn't have dex.
1834 std::unique_ptr<VdexFile> vdex(VdexFile::Open(vdex_location.c_str(),
1835 /*writable*/ false,
1836 /*low_4gb*/ false,
1837 /*unquicken*/ false,
1838 &error_msg));
1839 ASSERT_TRUE(vdex != nullptr);
Nicolas Geoffray3a293552018-03-02 10:52:16 +00001840 EXPECT_FALSE(vdex->HasDexSection()) << output_;
Mathieu Chartier792111c2018-02-15 13:02:15 -08001841 }
Nicolas Geoffray30025092018-04-19 14:43:29 +01001842 std::unique_ptr<OatFile> odex_file(OatFile::Open(/* zip_fd */ -1,
1843 odex_location.c_str(),
Mathieu Chartier792111c2018-02-15 13:02:15 -08001844 odex_location.c_str(),
1845 nullptr,
1846 nullptr,
1847 false,
1848 /*low_4gb*/ false,
1849 dex_location.c_str(),
1850 &error_msg));
1851 ASSERT_TRUE(odex_file != nullptr) << dex_location;
1852 std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
1853 ASSERT_EQ(oat_dex_files.size(), 1u);
1854 // Verify that the oat file can still open the dex files.
1855 for (const OatDexFile* oat_dex : oat_dex_files) {
1856 std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1857 ASSERT_TRUE(dex_file != nullptr) << error_msg;
1858 }
1859 // Create a dm file and use it to verify.
1860 // Add produced artifacts to a zip file that doesn't contain the classes.dex.
1861 ScratchFile dm_file;
1862 {
1863 std::unique_ptr<File> vdex_file(OS::OpenFileForReading(vdex_location.c_str()));
1864 ASSERT_TRUE(vdex_file != nullptr);
1865 ASSERT_GT(vdex_file->GetLength(), 0u);
1866 FILE* file = fdopen(dm_file.GetFd(), "w+b");
1867 ZipWriter writer(file);
1868 auto write_all_bytes = [&](File* file) {
1869 std::unique_ptr<uint8_t[]> bytes(new uint8_t[file->GetLength()]);
1870 ASSERT_TRUE(file->ReadFully(&bytes[0], file->GetLength()));
1871 ASSERT_GE(writer.WriteBytes(&bytes[0], file->GetLength()), 0);
1872 };
1873 // Add vdex to zip.
1874 writer.StartEntry(VdexFile::kVdexNameInDmFile, ZipWriter::kCompress);
1875 write_all_bytes(vdex_file.get());
1876 writer.FinishEntry();
1877 writer.Finish();
1878 ASSERT_EQ(dm_file.GetFile()->Flush(), 0);
1879 }
1880
Mathieu Chartier2eabc612018-05-25 14:31:16 -07001881 auto generate_and_check = [&](CompilerFilter::Filter filter) {
1882 GenerateOdexForTest(dex_location,
1883 odex_location,
1884 filter,
1885 { "--dump-timings",
1886 "--dm-file=" + dm_file.GetFilename(),
1887 // Pass -Xuse-stderr-logger have dex2oat output in output_ on target.
1888 "--runtime-arg",
1889 "-Xuse-stderr-logger" },
1890 true, // expect_success
1891 false, // use_fd
1892 [](const OatFile& o) {
1893 CHECK(o.ContainsDexCode());
1894 });
1895 // Check the output for "Fast verify", this is printed from --dump-timings.
1896 std::istringstream iss(output_);
1897 std::string line;
1898 bool found_fast_verify = false;
1899 const std::string kFastVerifyString = "Fast Verify";
1900 while (std::getline(iss, line) && !found_fast_verify) {
1901 found_fast_verify = found_fast_verify || line.find(kFastVerifyString) != std::string::npos;
1902 }
1903 EXPECT_TRUE(found_fast_verify) << "Expected to find " << kFastVerifyString << "\n" << output_;
1904 };
1905
Mathieu Chartier792111c2018-02-15 13:02:15 -08001906 // Generate a quickened dex by using the input dm file to verify.
Mathieu Chartier2eabc612018-05-25 14:31:16 -07001907 generate_and_check(CompilerFilter::Filter::kQuicken);
1908 // Use verify compiler filter to sanity check that FastVerify works for that filter too.
1909 generate_and_check(CompilerFilter::Filter::kVerify);
Mathieu Chartier792111c2018-02-15 13:02:15 -08001910}
1911
Mathieu Chartier2daa1342018-02-20 16:19:28 -08001912// Test that dex files with quickened opcodes aren't dequickened.
1913TEST_F(Dex2oatTest, QuickenedInput) {
1914 std::string error_msg;
1915 ScratchFile temp_dex;
1916 MutateDexFile(temp_dex.GetFile(), GetTestDexFileName("ManyMethods"), [] (DexFile* dex) {
1917 bool mutated_successfully = false;
1918 // Change the dex instructions to make an opcode that spans past the end of the code item.
1919 for (size_t i = 0; i < dex->NumClassDefs(); ++i) {
1920 const DexFile::ClassDef& def = dex->GetClassDef(i);
1921 const uint8_t* data = dex->GetClassData(def);
1922 if (data == nullptr) {
1923 continue;
1924 }
1925 ClassDataItemIterator it(*dex, data);
1926 it.SkipAllFields();
1927 while (it.HasNextMethod()) {
1928 DexFile::CodeItem* item = const_cast<DexFile::CodeItem*>(it.GetMethodCodeItem());
1929 if (item != nullptr) {
1930 CodeItemInstructionAccessor instructions(*dex, item);
1931 // Make a quickened instruction that doesn't run past the end of the code item.
1932 if (instructions.InsnsSizeInCodeUnits() > 2) {
1933 const_cast<Instruction&>(instructions.InstructionAt(0)).SetOpcode(
1934 Instruction::IGET_BYTE_QUICK);
1935 mutated_successfully = true;
1936 }
1937 }
1938 it.Next();
1939 }
1940 }
1941 CHECK(mutated_successfully)
1942 << "Failed to find candidate code item with only one code unit in last instruction.";
1943 });
1944
Andreas Gampebc802de2018-06-20 17:24:11 -07001945 const std::string& dex_location = temp_dex.GetFilename();
Mathieu Chartier2daa1342018-02-20 16:19:28 -08001946 std::string odex_location = GetOdexDir() + "/quickened.odex";
1947 std::string vdex_location = GetOdexDir() + "/quickened.vdex";
1948 std::unique_ptr<File> vdex_output(OS::CreateEmptyFile(vdex_location.c_str()));
1949 // Quicken the dex
1950 {
1951 std::string input_vdex = "--input-vdex-fd=-1";
1952 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_output->Fd());
1953 GenerateOdexForTest(dex_location,
1954 odex_location,
1955 CompilerFilter::kQuicken,
1956 // Disable cdex since we want to compare against the original dex file
1957 // after unquickening.
1958 { input_vdex, output_vdex, kDisableCompactDex },
1959 /* expect_success */ true,
1960 /* use_fd */ true);
1961 }
1962 // Unquicken by running the verify compiler filter on the vdex file and verify it matches.
1963 std::string odex_location2 = GetOdexDir() + "/unquickened.odex";
1964 std::string vdex_location2 = GetOdexDir() + "/unquickened.vdex";
1965 std::unique_ptr<File> vdex_unquickened(OS::CreateEmptyFile(vdex_location2.c_str()));
1966 {
1967 std::string input_vdex = StringPrintf("--input-vdex-fd=%d", vdex_output->Fd());
1968 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_unquickened->Fd());
1969 GenerateOdexForTest(dex_location,
1970 odex_location2,
1971 CompilerFilter::kVerify,
1972 // Disable cdex to avoid needing to write out the shared section.
1973 { input_vdex, output_vdex, kDisableCompactDex },
1974 /* expect_success */ true,
1975 /* use_fd */ true);
1976 }
1977 ASSERT_EQ(vdex_unquickened->Flush(), 0) << "Could not flush and close vdex file";
1978 ASSERT_TRUE(success_);
1979 {
1980 // Check that hte vdex has one dex and compare it to the original one.
1981 std::unique_ptr<VdexFile> vdex(VdexFile::Open(vdex_location2.c_str(),
1982 /*writable*/ false,
1983 /*low_4gb*/ false,
1984 /*unquicken*/ false,
1985 &error_msg));
1986 std::vector<std::unique_ptr<const DexFile>> dex_files;
1987 bool result = vdex->OpenAllDexFiles(&dex_files, &error_msg);
1988 ASSERT_TRUE(result) << error_msg;
1989 ASSERT_EQ(dex_files.size(), 1u) << error_msg;
1990 ScratchFile temp;
1991 ASSERT_TRUE(temp.GetFile()->WriteFully(dex_files[0]->Begin(), dex_files[0]->Size()));
1992 ASSERT_EQ(temp.GetFile()->Flush(), 0) << "Could not flush extracted dex";
1993 EXPECT_EQ(temp.GetFile()->Compare(temp_dex.GetFile()), 0);
1994 }
1995 ASSERT_EQ(vdex_output->FlushCloseOrErase(), 0) << "Could not flush and close";
1996 ASSERT_EQ(vdex_unquickened->FlushCloseOrErase(), 0) << "Could not flush and close";
1997}
1998
Mathieu Chartierd45863a2018-03-21 18:16:36 -07001999// Test that compact dex generation with invalid dex files doesn't crash dex2oat. b/75970654
2000TEST_F(Dex2oatTest, CompactDexInvalidSource) {
2001 ScratchFile invalid_dex;
2002 {
2003 FILE* file = fdopen(invalid_dex.GetFd(), "w+b");
2004 ZipWriter writer(file);
2005 writer.StartEntry("classes.dex", ZipWriter::kAlign32);
2006 DexFile::Header header = {};
2007 StandardDexFile::WriteMagic(header.magic_);
2008 StandardDexFile::WriteCurrentVersion(header.magic_);
2009 header.file_size_ = 4 * KB;
2010 header.data_size_ = 4 * KB;
2011 header.data_off_ = 10 * MB;
2012 header.map_off_ = 10 * MB;
2013 header.class_defs_off_ = 10 * MB;
2014 header.class_defs_size_ = 10000;
2015 ASSERT_GE(writer.WriteBytes(&header, sizeof(header)), 0);
2016 writer.FinishEntry();
2017 writer.Finish();
2018 ASSERT_EQ(invalid_dex.GetFile()->Flush(), 0);
2019 }
Andreas Gampebc802de2018-06-20 17:24:11 -07002020 const std::string& dex_location = invalid_dex.GetFilename();
Mathieu Chartierd45863a2018-03-21 18:16:36 -07002021 const std::string odex_location = GetOdexDir() + "/output.odex";
2022 std::string error_msg;
2023 int status = GenerateOdexForTestWithStatus(
2024 {dex_location},
2025 odex_location,
2026 CompilerFilter::kQuicken,
2027 &error_msg,
2028 { "--compact-dex-level=fast" });
2029 ASSERT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) != 0) << status << " " << output_;
2030}
2031
Mathieu Chartier14e7bad2018-03-22 14:33:20 -07002032// Test that dex2oat with a CompactDex file in the APK fails.
2033TEST_F(Dex2oatTest, CompactDexInZip) {
2034 CompactDexFile::Header header = {};
2035 CompactDexFile::WriteMagic(header.magic_);
2036 CompactDexFile::WriteCurrentVersion(header.magic_);
2037 header.file_size_ = sizeof(CompactDexFile::Header);
2038 header.data_off_ = 10 * MB;
2039 header.map_off_ = 10 * MB;
2040 header.class_defs_off_ = 10 * MB;
2041 header.class_defs_size_ = 10000;
2042 // Create a zip containing the invalid dex.
2043 ScratchFile invalid_dex_zip;
2044 {
2045 FILE* file = fdopen(invalid_dex_zip.GetFd(), "w+b");
2046 ZipWriter writer(file);
2047 writer.StartEntry("classes.dex", ZipWriter::kCompress);
2048 ASSERT_GE(writer.WriteBytes(&header, sizeof(header)), 0);
2049 writer.FinishEntry();
2050 writer.Finish();
2051 ASSERT_EQ(invalid_dex_zip.GetFile()->Flush(), 0);
2052 }
2053 // Create the dex file directly.
2054 ScratchFile invalid_dex;
2055 {
2056 ASSERT_GE(invalid_dex.GetFile()->WriteFully(&header, sizeof(header)), 0);
2057 ASSERT_EQ(invalid_dex.GetFile()->Flush(), 0);
2058 }
2059 std::string error_msg;
2060 int status = 0u;
2061
2062 status = GenerateOdexForTestWithStatus(
2063 { invalid_dex_zip.GetFilename() },
2064 GetOdexDir() + "/output_apk.odex",
2065 CompilerFilter::kQuicken,
2066 &error_msg,
2067 { "--compact-dex-level=fast" });
2068 ASSERT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) != 0) << status << " " << output_;
2069
2070 status = GenerateOdexForTestWithStatus(
2071 { invalid_dex.GetFilename() },
2072 GetOdexDir() + "/output.odex",
2073 CompilerFilter::kQuicken,
2074 &error_msg,
2075 { "--compact-dex-level=fast" });
2076 ASSERT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) != 0) << status << " " << output_;
2077}
2078
Mathieu Chartierf85b3db2018-04-02 18:16:21 -07002079TEST_F(Dex2oatTest, AppImageNoProfile) {
2080 ScratchFile app_image_file;
2081 const std::string out_dir = GetScratchDir();
2082 const std::string odex_location = out_dir + "/base.odex";
2083 GenerateOdexForTest(GetTestDexFileName("ManyMethods"),
2084 odex_location,
2085 CompilerFilter::Filter::kSpeedProfile,
2086 { "--app-image-fd=" + std::to_string(app_image_file.GetFd()) },
2087 true, // expect_success
2088 false, // use_fd
2089 [](const OatFile&) {});
2090 // Open our generated oat file.
2091 std::string error_msg;
Nicolas Geoffray30025092018-04-19 14:43:29 +01002092 std::unique_ptr<OatFile> odex_file(OatFile::Open(/* zip_fd */ -1,
2093 odex_location.c_str(),
Mathieu Chartierf85b3db2018-04-02 18:16:21 -07002094 odex_location.c_str(),
2095 nullptr,
2096 nullptr,
2097 false,
2098 /*low_4gb*/false,
2099 odex_location.c_str(),
2100 &error_msg));
2101 ASSERT_TRUE(odex_file != nullptr);
2102 ImageHeader header = {};
2103 ASSERT_TRUE(app_image_file.GetFile()->PreadFully(
2104 reinterpret_cast<void*>(&header),
2105 sizeof(header),
2106 /*offset*/ 0u)) << app_image_file.GetFile()->GetLength();
2107 EXPECT_GT(header.GetImageSection(ImageHeader::kSectionObjects).Size(), 0u);
2108 EXPECT_EQ(header.GetImageSection(ImageHeader::kSectionArtMethods).Size(), 0u);
2109 EXPECT_EQ(header.GetImageSection(ImageHeader::kSectionArtFields).Size(), 0u);
2110}
2111
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002112TEST_F(Dex2oatClassLoaderContextTest, StoredClassLoaderContext) {
Mathieu Chartierc4440772018-04-16 14:40:56 -07002113 std::vector<std::unique_ptr<const DexFile>> dex_files = OpenTestDexFiles("MultiDex");
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002114 const std::string out_dir = GetScratchDir();
2115 const std::string odex_location = out_dir + "/base.odex";
Mathieu Chartierc4440772018-04-16 14:40:56 -07002116 const std::string valid_context = "PCL[" + dex_files[0]->GetLocation() + "]";
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002117 const std::string stored_context = "PCL[/system/not_real_lib.jar]";
Mathieu Chartierc4440772018-04-16 14:40:56 -07002118 std::string expected_stored_context = "PCL[";
2119 size_t index = 1;
2120 for (const std::unique_ptr<const DexFile>& dex_file : dex_files) {
2121 const bool is_first = index == 1u;
2122 if (!is_first) {
2123 expected_stored_context += ":";
2124 }
2125 expected_stored_context += "/system/not_real_lib.jar";
2126 if (!is_first) {
2127 expected_stored_context += "!classes" + std::to_string(index) + ".dex";
2128 }
2129 expected_stored_context += "*" + std::to_string(dex_file->GetLocationChecksum());
2130 ++index;
2131 }
2132 expected_stored_context += + "]";
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002133 // The class path should not be valid and should fail being stored.
2134 GenerateOdexForTest(GetTestDexFileName("ManyMethods"),
2135 odex_location,
2136 CompilerFilter::Filter::kQuicken,
2137 { "--class-loader-context=" + stored_context },
2138 true, // expect_success
2139 false, // use_fd
2140 [&](const OatFile& oat_file) {
Mathieu Chartierc4440772018-04-16 14:40:56 -07002141 EXPECT_NE(oat_file.GetClassLoaderContext(), stored_context) << output_;
2142 EXPECT_NE(oat_file.GetClassLoaderContext(), valid_context) << output_;
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002143 });
2144 // The stored context should match what we expect even though it's invalid.
2145 GenerateOdexForTest(GetTestDexFileName("ManyMethods"),
2146 odex_location,
2147 CompilerFilter::Filter::kQuicken,
2148 { "--class-loader-context=" + valid_context,
2149 "--stored-class-loader-context=" + stored_context },
2150 true, // expect_success
2151 false, // use_fd
2152 [&](const OatFile& oat_file) {
Mathieu Chartierc4440772018-04-16 14:40:56 -07002153 EXPECT_EQ(oat_file.GetClassLoaderContext(), expected_stored_context) << output_;
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002154 });
2155}
2156
Andreas Gampee1459ae2016-06-29 09:36:30 -07002157} // namespace art