blob: f176cc2839236d9494b6908b1964045cd5423b0d [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"
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +010032#include "bytecode_utils.h"
David Sehr9e734c72018-01-04 17:56:19 -080033#include "dex/code_item_accessors-inl.h"
34#include "dex/dex_file-inl.h"
35#include "dex/dex_file_loader.h"
Andreas Gampee1459ae2016-06-29 09:36:30 -070036#include "dex2oat_environment_test.h"
Andreas Gampef7882972017-03-20 16:35:24 -070037#include "dex2oat_return_codes.h"
Calin Juravle33083d62017-01-18 15:29:12 -080038#include "jit/profile_compilation_info.h"
Andreas Gampe67f02822016-06-24 21:05:23 -070039#include "oat.h"
40#include "oat_file.h"
Andreas Gampee1459ae2016-06-29 09:36:30 -070041#include "utils.h"
42
Andreas Gampee1459ae2016-06-29 09:36:30 -070043namespace art {
44
Mathieu Chartierea650f32017-05-24 12:04:13 -070045static constexpr size_t kMaxMethodIds = 65535;
Mathieu Chartier9e050df2017-08-09 10:05:47 -070046static constexpr bool kDebugArgs = false;
Mathieu Chartier02129102017-12-22 11:04:01 -080047static const char* kDisableCompactDex = "--compact-dex-level=none";
Mathieu Chartierea650f32017-05-24 12:04:13 -070048
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080049using android::base::StringPrintf;
50
Andreas Gampee1459ae2016-06-29 09:36:30 -070051class Dex2oatTest : public Dex2oatEnvironmentTest {
52 public:
53 virtual void TearDown() OVERRIDE {
54 Dex2oatEnvironmentTest::TearDown();
55
56 output_ = "";
57 error_msg_ = "";
58 success_ = false;
59 }
60
61 protected:
Mathieu Chartier9e050df2017-08-09 10:05:47 -070062 int GenerateOdexForTestWithStatus(const std::vector<std::string>& dex_locations,
Andreas Gampef7882972017-03-20 16:35:24 -070063 const std::string& odex_location,
64 CompilerFilter::Filter filter,
65 std::string* error_msg,
66 const std::vector<std::string>& extra_args = {},
67 bool use_fd = false) {
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080068 std::unique_ptr<File> oat_file;
Andreas Gampee1459ae2016-06-29 09:36:30 -070069 std::vector<std::string> args;
Mathieu Chartier9e050df2017-08-09 10:05:47 -070070 // Add dex file args.
71 for (const std::string& dex_location : dex_locations) {
72 args.push_back("--dex-file=" + dex_location);
73 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080074 if (use_fd) {
75 oat_file.reset(OS::CreateEmptyFile(odex_location.c_str()));
76 CHECK(oat_file != nullptr) << odex_location;
77 args.push_back("--oat-fd=" + std::to_string(oat_file->Fd()));
Mathieu Chartier046854b2017-03-01 17:16:22 -080078 args.push_back("--oat-location=" + odex_location);
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080079 } else {
80 args.push_back("--oat-file=" + odex_location);
81 }
Andreas Gampee1459ae2016-06-29 09:36:30 -070082 args.push_back("--compiler-filter=" + CompilerFilter::NameOfFilter(filter));
83 args.push_back("--runtime-arg");
84 args.push_back("-Xnorelocate");
85
86 args.insert(args.end(), extra_args.begin(), extra_args.end());
87
Andreas Gampef7882972017-03-20 16:35:24 -070088 int status = Dex2Oat(args, error_msg);
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080089 if (oat_file != nullptr) {
Andreas Gampef7882972017-03-20 16:35:24 -070090 CHECK_EQ(oat_file->FlushClose(), 0) << "Could not flush and close oat file";
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080091 }
Andreas Gampef7882972017-03-20 16:35:24 -070092 return status;
93 }
Andreas Gampee1459ae2016-06-29 09:36:30 -070094
Andreas Gampe641a4732017-08-24 13:21:35 -070095 void GenerateOdexForTest(
96 const std::string& dex_location,
97 const std::string& odex_location,
98 CompilerFilter::Filter filter,
99 const std::vector<std::string>& extra_args = {},
100 bool expect_success = true,
101 bool use_fd = false) {
102 GenerateOdexForTest(dex_location,
103 odex_location,
104 filter,
105 extra_args,
106 expect_success,
107 use_fd,
108 [](const OatFile&) {});
109 }
110
111 template <typename T>
112 void GenerateOdexForTest(
113 const std::string& dex_location,
114 const std::string& odex_location,
115 CompilerFilter::Filter filter,
116 const std::vector<std::string>& extra_args,
117 bool expect_success,
118 bool use_fd,
119 T check_oat) {
Andreas Gampef7882972017-03-20 16:35:24 -0700120 std::string error_msg;
Mathieu Chartier9e050df2017-08-09 10:05:47 -0700121 int status = GenerateOdexForTestWithStatus({dex_location},
Andreas Gampef7882972017-03-20 16:35:24 -0700122 odex_location,
123 filter,
124 &error_msg,
125 extra_args,
126 use_fd);
127 bool success = (status == 0);
Andreas Gampee1459ae2016-06-29 09:36:30 -0700128 if (expect_success) {
Andreas Gampe2e8a2562017-01-18 20:39:02 -0800129 ASSERT_TRUE(success) << error_msg << std::endl << output_;
Andreas Gampee1459ae2016-06-29 09:36:30 -0700130
131 // Verify the odex file was generated as expected.
132 std::unique_ptr<OatFile> odex_file(OatFile::Open(odex_location.c_str(),
133 odex_location.c_str(),
134 nullptr,
135 nullptr,
136 false,
137 /*low_4gb*/false,
138 dex_location.c_str(),
139 &error_msg));
140 ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
141
142 CheckFilter(filter, odex_file->GetCompilerFilter());
Calin Juravle1ce70852017-06-28 10:59:03 -0700143 check_oat(*(odex_file.get()));
Andreas Gampee1459ae2016-06-29 09:36:30 -0700144 } else {
145 ASSERT_FALSE(success) << output_;
146
147 error_msg_ = error_msg;
148
149 // Verify there's no loadable odex file.
150 std::unique_ptr<OatFile> odex_file(OatFile::Open(odex_location.c_str(),
151 odex_location.c_str(),
152 nullptr,
153 nullptr,
154 false,
155 /*low_4gb*/false,
156 dex_location.c_str(),
157 &error_msg));
158 ASSERT_TRUE(odex_file.get() == nullptr);
159 }
160 }
161
Calin Juravle1ccf6132017-08-02 17:46:53 -0700162 // Check the input compiler filter against the generated oat file's filter. May be overridden
Andreas Gampee1459ae2016-06-29 09:36:30 -0700163 // in subclasses when equality is not expected.
164 virtual void CheckFilter(CompilerFilter::Filter expected, CompilerFilter::Filter actual) {
165 EXPECT_EQ(expected, actual);
166 }
167
Andreas Gampef7882972017-03-20 16:35:24 -0700168 int Dex2Oat(const std::vector<std::string>& dex2oat_args, std::string* error_msg) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700169 Runtime* runtime = Runtime::Current();
170
171 const std::vector<gc::space::ImageSpace*>& image_spaces =
172 runtime->GetHeap()->GetBootImageSpaces();
173 if (image_spaces.empty()) {
174 *error_msg = "No image location found for Dex2Oat.";
175 return false;
176 }
177 std::string image_location = image_spaces[0]->GetImageLocation();
178
179 std::vector<std::string> argv;
180 argv.push_back(runtime->GetCompilerExecutable());
Calin Juravle1ccf6132017-08-02 17:46:53 -0700181
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000182 if (runtime->IsJavaDebuggable()) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700183 argv.push_back("--debuggable");
184 }
185 runtime->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv);
186
187 if (!runtime->IsVerificationEnabled()) {
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100188 argv.push_back("--compiler-filter=assume-verified");
Andreas Gampee1459ae2016-06-29 09:36:30 -0700189 }
190
191 if (runtime->MustRelocateIfPossible()) {
192 argv.push_back("--runtime-arg");
193 argv.push_back("-Xrelocate");
194 } else {
195 argv.push_back("--runtime-arg");
196 argv.push_back("-Xnorelocate");
197 }
198
199 if (!kIsTargetBuild) {
200 argv.push_back("--host");
201 }
202
203 argv.push_back("--boot-image=" + image_location);
204
205 std::vector<std::string> compiler_options = runtime->GetCompilerOptions();
206 argv.insert(argv.end(), compiler_options.begin(), compiler_options.end());
207
208 argv.insert(argv.end(), dex2oat_args.begin(), dex2oat_args.end());
209
210 // We must set --android-root.
211 const char* android_root = getenv("ANDROID_ROOT");
212 CHECK(android_root != nullptr);
213 argv.push_back("--android-root=" + std::string(android_root));
214
Mathieu Chartier9e050df2017-08-09 10:05:47 -0700215 if (kDebugArgs) {
216 std::string all_args;
217 for (const std::string& arg : argv) {
218 all_args += arg + " ";
219 }
220 LOG(ERROR) << all_args;
221 }
222
Nicolas Geoffray56fe0f02016-06-30 15:07:46 +0100223 int link[2];
Andreas Gampee1459ae2016-06-29 09:36:30 -0700224
Nicolas Geoffray56fe0f02016-06-30 15:07:46 +0100225 if (pipe(link) == -1) {
226 return false;
227 }
Andreas Gampee1459ae2016-06-29 09:36:30 -0700228
Nicolas Geoffray56fe0f02016-06-30 15:07:46 +0100229 pid_t pid = fork();
230 if (pid == -1) {
231 return false;
232 }
Andreas Gampee1459ae2016-06-29 09:36:30 -0700233
Nicolas Geoffray56fe0f02016-06-30 15:07:46 +0100234 if (pid == 0) {
235 // We need dex2oat to actually log things.
236 setenv("ANDROID_LOG_TAGS", "*:d", 1);
237 dup2(link[1], STDERR_FILENO);
238 close(link[0]);
239 close(link[1]);
240 std::vector<const char*> c_args;
241 for (const std::string& str : argv) {
242 c_args.push_back(str.c_str());
Andreas Gampee1459ae2016-06-29 09:36:30 -0700243 }
Nicolas Geoffray56fe0f02016-06-30 15:07:46 +0100244 c_args.push_back(nullptr);
245 execv(c_args[0], const_cast<char* const*>(c_args.data()));
246 exit(1);
Andreas Gampef7882972017-03-20 16:35:24 -0700247 UNREACHABLE();
Nicolas Geoffray56fe0f02016-06-30 15:07:46 +0100248 } else {
249 close(link[1]);
250 char buffer[128];
251 memset(buffer, 0, 128);
252 ssize_t bytes_read = 0;
Andreas Gampee1459ae2016-06-29 09:36:30 -0700253
Nicolas Geoffray56fe0f02016-06-30 15:07:46 +0100254 while (TEMP_FAILURE_RETRY(bytes_read = read(link[0], buffer, 128)) > 0) {
255 output_ += std::string(buffer, bytes_read);
256 }
257 close(link[0]);
Andreas Gampef7882972017-03-20 16:35:24 -0700258 int status = -1;
Nicolas Geoffray56fe0f02016-06-30 15:07:46 +0100259 if (waitpid(pid, &status, 0) != -1) {
260 success_ = (status == 0);
261 }
Andreas Gampef7882972017-03-20 16:35:24 -0700262 return status;
Andreas Gampee1459ae2016-06-29 09:36:30 -0700263 }
Andreas Gampee1459ae2016-06-29 09:36:30 -0700264 }
265
266 std::string output_ = "";
267 std::string error_msg_ = "";
268 bool success_ = false;
269};
270
271class Dex2oatSwapTest : public Dex2oatTest {
272 protected:
273 void RunTest(bool use_fd, bool expect_use, const std::vector<std::string>& extra_args = {}) {
274 std::string dex_location = GetScratchDir() + "/Dex2OatSwapTest.jar";
275 std::string odex_location = GetOdexDir() + "/Dex2OatSwapTest.odex";
276
Andreas Gampe7adeda82016-07-25 08:27:35 -0700277 Copy(GetTestDexFileName(), dex_location);
Andreas Gampee1459ae2016-06-29 09:36:30 -0700278
279 std::vector<std::string> copy(extra_args);
280
281 std::unique_ptr<ScratchFile> sf;
282 if (use_fd) {
283 sf.reset(new ScratchFile());
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800284 copy.push_back(android::base::StringPrintf("--swap-fd=%d", sf->GetFd()));
Andreas Gampee1459ae2016-06-29 09:36:30 -0700285 } else {
286 std::string swap_location = GetOdexDir() + "/Dex2OatSwapTest.odex.swap";
287 copy.push_back("--swap-file=" + swap_location);
288 }
289 GenerateOdexForTest(dex_location, odex_location, CompilerFilter::kSpeed, copy);
290
291 CheckValidity();
292 ASSERT_TRUE(success_);
293 CheckResult(expect_use);
294 }
295
Andreas Gampe7adeda82016-07-25 08:27:35 -0700296 virtual std::string GetTestDexFileName() {
Vladimir Marko15357702017-02-09 10:37:31 +0000297 return Dex2oatEnvironmentTest::GetTestDexFileName("VerifierDeps");
Andreas Gampe7adeda82016-07-25 08:27:35 -0700298 }
299
300 virtual void CheckResult(bool expect_use) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700301 if (kIsTargetBuild) {
302 CheckTargetResult(expect_use);
303 } else {
304 CheckHostResult(expect_use);
305 }
306 }
307
Andreas Gampe7adeda82016-07-25 08:27:35 -0700308 virtual void CheckTargetResult(bool expect_use ATTRIBUTE_UNUSED) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700309 // TODO: Ignore for now, as we won't capture any output (it goes to the logcat). We may do
310 // something for variants with file descriptor where we can control the lifetime of
311 // the swap file and thus take a look at it.
312 }
313
Andreas Gampe7adeda82016-07-25 08:27:35 -0700314 virtual void CheckHostResult(bool expect_use) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700315 if (!kIsTargetBuild) {
316 if (expect_use) {
317 EXPECT_NE(output_.find("Large app, accepted running with swap."), std::string::npos)
318 << output_;
319 } else {
320 EXPECT_EQ(output_.find("Large app, accepted running with swap."), std::string::npos)
321 << output_;
322 }
323 }
324 }
325
326 // Check whether the dex2oat run was really successful.
Andreas Gampe7adeda82016-07-25 08:27:35 -0700327 virtual void CheckValidity() {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700328 if (kIsTargetBuild) {
329 CheckTargetValidity();
330 } else {
331 CheckHostValidity();
332 }
333 }
334
Andreas Gampe7adeda82016-07-25 08:27:35 -0700335 virtual void CheckTargetValidity() {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700336 // TODO: Ignore for now, as we won't capture any output (it goes to the logcat). We may do
337 // something for variants with file descriptor where we can control the lifetime of
338 // the swap file and thus take a look at it.
339 }
340
341 // On the host, we can get the dex2oat output. Here, look for "dex2oat took."
Andreas Gampe7adeda82016-07-25 08:27:35 -0700342 virtual void CheckHostValidity() {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700343 EXPECT_NE(output_.find("dex2oat took"), std::string::npos) << output_;
344 }
345};
346
347TEST_F(Dex2oatSwapTest, DoNotUseSwapDefaultSingleSmall) {
348 RunTest(false /* use_fd */, false /* expect_use */);
349 RunTest(true /* use_fd */, false /* expect_use */);
350}
351
352TEST_F(Dex2oatSwapTest, DoNotUseSwapSingle) {
353 RunTest(false /* use_fd */, false /* expect_use */, { "--swap-dex-size-threshold=0" });
354 RunTest(true /* use_fd */, false /* expect_use */, { "--swap-dex-size-threshold=0" });
355}
356
357TEST_F(Dex2oatSwapTest, DoNotUseSwapSmall) {
358 RunTest(false /* use_fd */, false /* expect_use */, { "--swap-dex-count-threshold=0" });
359 RunTest(true /* use_fd */, false /* expect_use */, { "--swap-dex-count-threshold=0" });
360}
361
362TEST_F(Dex2oatSwapTest, DoUseSwapSingleSmall) {
363 RunTest(false /* use_fd */,
364 true /* expect_use */,
365 { "--swap-dex-size-threshold=0", "--swap-dex-count-threshold=0" });
366 RunTest(true /* use_fd */,
367 true /* expect_use */,
368 { "--swap-dex-size-threshold=0", "--swap-dex-count-threshold=0" });
369}
370
Andreas Gampe7adeda82016-07-25 08:27:35 -0700371class Dex2oatSwapUseTest : public Dex2oatSwapTest {
372 protected:
373 void CheckHostResult(bool expect_use) OVERRIDE {
374 if (!kIsTargetBuild) {
375 if (expect_use) {
376 EXPECT_NE(output_.find("Large app, accepted running with swap."), std::string::npos)
377 << output_;
378 } else {
379 EXPECT_EQ(output_.find("Large app, accepted running with swap."), std::string::npos)
380 << output_;
381 }
382 }
383 }
384
385 std::string GetTestDexFileName() OVERRIDE {
386 // Use Statics as it has a handful of functions.
387 return CommonRuntimeTest::GetTestDexFileName("Statics");
388 }
389
390 void GrabResult1() {
391 if (!kIsTargetBuild) {
392 native_alloc_1_ = ParseNativeAlloc();
393 swap_1_ = ParseSwap(false /* expected */);
394 } else {
395 native_alloc_1_ = std::numeric_limits<size_t>::max();
396 swap_1_ = 0;
397 }
398 }
399
400 void GrabResult2() {
401 if (!kIsTargetBuild) {
402 native_alloc_2_ = ParseNativeAlloc();
403 swap_2_ = ParseSwap(true /* expected */);
404 } else {
405 native_alloc_2_ = 0;
406 swap_2_ = std::numeric_limits<size_t>::max();
407 }
408 }
409
410 private:
411 size_t ParseNativeAlloc() {
412 std::regex native_alloc_regex("dex2oat took.*native alloc=[^ ]+ \\(([0-9]+)B\\)");
413 std::smatch native_alloc_match;
414 bool found = std::regex_search(output_, native_alloc_match, native_alloc_regex);
415 if (!found) {
416 EXPECT_TRUE(found);
417 return 0;
418 }
419 if (native_alloc_match.size() != 2U) {
420 EXPECT_EQ(native_alloc_match.size(), 2U);
421 return 0;
422 }
423
424 std::istringstream stream(native_alloc_match[1].str());
425 size_t value;
426 stream >> value;
427
428 return value;
429 }
430
431 size_t ParseSwap(bool expected) {
432 std::regex swap_regex("dex2oat took[^\\n]+swap=[^ ]+ \\(([0-9]+)B\\)");
433 std::smatch swap_match;
434 bool found = std::regex_search(output_, swap_match, swap_regex);
435 if (found != expected) {
436 EXPECT_EQ(expected, found);
437 return 0;
438 }
439
440 if (!found) {
441 return 0;
442 }
443
444 if (swap_match.size() != 2U) {
445 EXPECT_EQ(swap_match.size(), 2U);
446 return 0;
447 }
448
449 std::istringstream stream(swap_match[1].str());
450 size_t value;
451 stream >> value;
452
453 return value;
454 }
455
456 protected:
457 size_t native_alloc_1_;
458 size_t native_alloc_2_;
459
460 size_t swap_1_;
461 size_t swap_2_;
462};
463
464TEST_F(Dex2oatSwapUseTest, CheckSwapUsage) {
Andreas Gampef4a67fd2017-05-04 09:55:36 -0700465 // Native memory usage isn't correctly tracked under sanitization.
466 TEST_DISABLED_FOR_MEMORY_TOOL_ASAN();
467
Vladimir Marko57070da2017-02-14 16:16:30 +0000468 // The `native_alloc_2_ >= native_alloc_1_` assertion below may not
Roland Levillain19772bf2017-02-16 11:28:10 +0000469 // hold true on some x86 systems; disable this test while we
470 // investigate (b/29259363).
471 TEST_DISABLED_FOR_X86();
Vladimir Marko57070da2017-02-14 16:16:30 +0000472
Andreas Gampe7adeda82016-07-25 08:27:35 -0700473 RunTest(false /* use_fd */,
474 false /* expect_use */);
475 GrabResult1();
476 std::string output_1 = output_;
477
478 output_ = "";
479
480 RunTest(false /* use_fd */,
481 true /* expect_use */,
482 { "--swap-dex-size-threshold=0", "--swap-dex-count-threshold=0" });
483 GrabResult2();
484 std::string output_2 = output_;
485
486 if (native_alloc_2_ >= native_alloc_1_ || swap_1_ >= swap_2_) {
487 EXPECT_LT(native_alloc_2_, native_alloc_1_);
488 EXPECT_LT(swap_1_, swap_2_);
489
490 LOG(ERROR) << output_1;
491 LOG(ERROR) << output_2;
492 }
493}
494
Andreas Gampe67f02822016-06-24 21:05:23 -0700495class Dex2oatVeryLargeTest : public Dex2oatTest {
496 protected:
497 void CheckFilter(CompilerFilter::Filter input ATTRIBUTE_UNUSED,
498 CompilerFilter::Filter result ATTRIBUTE_UNUSED) OVERRIDE {
499 // Ignore, we'll do our own checks.
500 }
501
502 void RunTest(CompilerFilter::Filter filter,
503 bool expect_large,
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700504 bool expect_downgrade,
Andreas Gampe67f02822016-06-24 21:05:23 -0700505 const std::vector<std::string>& extra_args = {}) {
506 std::string dex_location = GetScratchDir() + "/DexNoOat.jar";
507 std::string odex_location = GetOdexDir() + "/DexOdexNoOat.odex";
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700508 std::string app_image_file = GetScratchDir() + "/Test.art";
Andreas Gampe67f02822016-06-24 21:05:23 -0700509
510 Copy(GetDexSrc1(), dex_location);
511
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700512 std::vector<std::string> new_args(extra_args);
513 new_args.push_back("--app-image-file=" + app_image_file);
514 GenerateOdexForTest(dex_location, odex_location, filter, new_args);
Andreas Gampe67f02822016-06-24 21:05:23 -0700515
516 CheckValidity();
517 ASSERT_TRUE(success_);
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700518 CheckResult(dex_location,
519 odex_location,
520 app_image_file,
521 filter,
522 expect_large,
523 expect_downgrade);
Andreas Gampe67f02822016-06-24 21:05:23 -0700524 }
525
526 void CheckResult(const std::string& dex_location,
527 const std::string& odex_location,
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700528 const std::string& app_image_file,
Andreas Gampe67f02822016-06-24 21:05:23 -0700529 CompilerFilter::Filter filter,
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700530 bool expect_large,
531 bool expect_downgrade) {
532 if (expect_downgrade) {
533 EXPECT_TRUE(expect_large);
534 }
Andreas Gampe67f02822016-06-24 21:05:23 -0700535 // Host/target independent checks.
536 std::string error_msg;
537 std::unique_ptr<OatFile> odex_file(OatFile::Open(odex_location.c_str(),
538 odex_location.c_str(),
539 nullptr,
540 nullptr,
541 false,
542 /*low_4gb*/false,
543 dex_location.c_str(),
544 &error_msg));
545 ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700546 EXPECT_GT(app_image_file.length(), 0u);
547 std::unique_ptr<File> file(OS::OpenFileForReading(app_image_file.c_str()));
Andreas Gampe67f02822016-06-24 21:05:23 -0700548 if (expect_large) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700549 // Note: we cannot check the following
550 // EXPECT_FALSE(CompilerFilter::IsAotCompilationEnabled(odex_file->GetCompilerFilter()));
Andreas Gampe67f02822016-06-24 21:05:23 -0700551 // The reason is that the filter override currently happens when the dex files are
552 // loaded in dex2oat, which is after the oat file has been started. Thus, the header
553 // store cannot be changed, and the original filter is set in stone.
554
555 for (const OatDexFile* oat_dex_file : odex_file->GetOatDexFiles()) {
556 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
557 ASSERT_TRUE(dex_file != nullptr);
558 uint32_t class_def_count = dex_file->NumClassDefs();
559 ASSERT_LT(class_def_count, std::numeric_limits<uint16_t>::max());
560 for (uint16_t class_def_index = 0; class_def_index < class_def_count; ++class_def_index) {
561 OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
562 EXPECT_EQ(oat_class.GetType(), OatClassType::kOatClassNoneCompiled);
563 }
564 }
565
566 // If the input filter was "below," it should have been used.
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100567 if (!CompilerFilter::IsAsGoodAs(CompilerFilter::kExtract, filter)) {
Andreas Gampe67f02822016-06-24 21:05:23 -0700568 EXPECT_EQ(odex_file->GetCompilerFilter(), filter);
569 }
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700570
571 // If expect large, make sure the app image isn't generated or is empty.
572 if (file != nullptr) {
573 EXPECT_EQ(file->GetLength(), 0u);
574 }
Andreas Gampe67f02822016-06-24 21:05:23 -0700575 } else {
576 EXPECT_EQ(odex_file->GetCompilerFilter(), filter);
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700577 ASSERT_TRUE(file != nullptr) << app_image_file;
578 EXPECT_GT(file->GetLength(), 0u);
Andreas Gampe67f02822016-06-24 21:05:23 -0700579 }
580
581 // Host/target dependent checks.
582 if (kIsTargetBuild) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700583 CheckTargetResult(expect_downgrade);
Andreas Gampe67f02822016-06-24 21:05:23 -0700584 } else {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700585 CheckHostResult(expect_downgrade);
Andreas Gampe67f02822016-06-24 21:05:23 -0700586 }
587 }
588
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700589 void CheckTargetResult(bool expect_downgrade ATTRIBUTE_UNUSED) {
Andreas Gampe67f02822016-06-24 21:05:23 -0700590 // TODO: Ignore for now. May do something for fd things.
591 }
592
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700593 void CheckHostResult(bool expect_downgrade) {
Andreas Gampe67f02822016-06-24 21:05:23 -0700594 if (!kIsTargetBuild) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700595 if (expect_downgrade) {
596 EXPECT_NE(output_.find("Very large app, downgrading to"), std::string::npos) << output_;
Andreas Gampe67f02822016-06-24 21:05:23 -0700597 } else {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700598 EXPECT_EQ(output_.find("Very large app, downgrading to"), std::string::npos) << output_;
Andreas Gampe67f02822016-06-24 21:05:23 -0700599 }
600 }
601 }
602
603 // Check whether the dex2oat run was really successful.
604 void CheckValidity() {
605 if (kIsTargetBuild) {
606 CheckTargetValidity();
607 } else {
608 CheckHostValidity();
609 }
610 }
611
612 void CheckTargetValidity() {
613 // TODO: Ignore for now.
614 }
615
616 // On the host, we can get the dex2oat output. Here, look for "dex2oat took."
617 void CheckHostValidity() {
618 EXPECT_NE(output_.find("dex2oat took"), std::string::npos) << output_;
619 }
620};
621
622TEST_F(Dex2oatVeryLargeTest, DontUseVeryLarge) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700623 RunTest(CompilerFilter::kAssumeVerified, false, false);
624 RunTest(CompilerFilter::kExtract, false, false);
625 RunTest(CompilerFilter::kQuicken, false, false);
626 RunTest(CompilerFilter::kSpeed, false, false);
Andreas Gampe67f02822016-06-24 21:05:23 -0700627
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700628 RunTest(CompilerFilter::kAssumeVerified, false, false, { "--very-large-app-threshold=10000000" });
629 RunTest(CompilerFilter::kExtract, false, false, { "--very-large-app-threshold=10000000" });
630 RunTest(CompilerFilter::kQuicken, false, false, { "--very-large-app-threshold=10000000" });
631 RunTest(CompilerFilter::kSpeed, false, false, { "--very-large-app-threshold=10000000" });
Andreas Gampe67f02822016-06-24 21:05:23 -0700632}
633
634TEST_F(Dex2oatVeryLargeTest, UseVeryLarge) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700635 RunTest(CompilerFilter::kAssumeVerified, true, false, { "--very-large-app-threshold=100" });
636 RunTest(CompilerFilter::kExtract, true, false, { "--very-large-app-threshold=100" });
637 RunTest(CompilerFilter::kQuicken, true, true, { "--very-large-app-threshold=100" });
638 RunTest(CompilerFilter::kSpeed, true, true, { "--very-large-app-threshold=100" });
Andreas Gampe67f02822016-06-24 21:05:23 -0700639}
640
Mathieu Chartier97ab5e32017-02-22 13:35:44 -0800641// Regressin test for b/35665292.
642TEST_F(Dex2oatVeryLargeTest, SpeedProfileNoProfile) {
643 // Test that dex2oat doesn't crash with speed-profile but no input profile.
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700644 RunTest(CompilerFilter::kSpeedProfile, false, false);
Mathieu Chartier97ab5e32017-02-22 13:35:44 -0800645}
646
Jeff Hao608f2ce2016-10-19 11:17:11 -0700647class Dex2oatLayoutTest : public Dex2oatTest {
648 protected:
649 void CheckFilter(CompilerFilter::Filter input ATTRIBUTE_UNUSED,
650 CompilerFilter::Filter result ATTRIBUTE_UNUSED) OVERRIDE {
651 // Ignore, we'll do our own checks.
652 }
653
Jeff Hao41fba6a2016-11-28 11:53:33 -0800654 // Emits a profile with a single dex file with the given location and a single class index of 1.
655 void GenerateProfile(const std::string& test_profile,
656 const std::string& dex_location,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800657 size_t num_classes,
Jeff Hao41fba6a2016-11-28 11:53:33 -0800658 uint32_t checksum) {
659 int profile_test_fd = open(test_profile.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644);
660 CHECK_GE(profile_test_fd, 0);
661
662 ProfileCompilationInfo info;
663 std::string profile_key = ProfileCompilationInfo::GetProfileDexFileKey(dex_location);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800664 for (size_t i = 0; i < num_classes; ++i) {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700665 info.AddClassIndex(profile_key, checksum, dex::TypeIndex(1 + i), kMaxMethodIds);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800666 }
Jeff Hao41fba6a2016-11-28 11:53:33 -0800667 bool result = info.Save(profile_test_fd);
668 close(profile_test_fd);
669 ASSERT_TRUE(result);
670 }
671
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800672 void CompileProfileOdex(const std::string& dex_location,
673 const std::string& odex_location,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800674 const std::string& app_image_file_name,
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800675 bool use_fd,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800676 size_t num_profile_classes,
Nicolas Geoffray97fa9922017-03-09 13:13:25 +0000677 const std::vector<std::string>& extra_args = {},
678 bool expect_success = true) {
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800679 const std::string profile_location = GetScratchDir() + "/primary.prof";
Jeff Hao41fba6a2016-11-28 11:53:33 -0800680 const char* location = dex_location.c_str();
681 std::string error_msg;
682 std::vector<std::unique_ptr<const DexFile>> dex_files;
Nicolas Geoffray095c6c92017-10-19 13:59:55 +0100683 ASSERT_TRUE(DexFileLoader::Open(
684 location, location, /* verify */ true, /* verify_checksum */ true, &error_msg, &dex_files));
Jeff Hao41fba6a2016-11-28 11:53:33 -0800685 EXPECT_EQ(dex_files.size(), 1U);
686 std::unique_ptr<const DexFile>& dex_file = dex_files[0];
Mathieu Chartier046854b2017-03-01 17:16:22 -0800687 GenerateProfile(profile_location,
688 dex_location,
689 num_profile_classes,
690 dex_file->GetLocationChecksum());
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800691 std::vector<std::string> copy(extra_args);
692 copy.push_back("--profile-file=" + profile_location);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800693 std::unique_ptr<File> app_image_file;
694 if (!app_image_file_name.empty()) {
695 if (use_fd) {
696 app_image_file.reset(OS::CreateEmptyFile(app_image_file_name.c_str()));
697 copy.push_back("--app-image-fd=" + std::to_string(app_image_file->Fd()));
698 } else {
699 copy.push_back("--app-image-file=" + app_image_file_name);
700 }
701 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800702 GenerateOdexForTest(dex_location,
703 odex_location,
704 CompilerFilter::kSpeedProfile,
705 copy,
Nicolas Geoffray97fa9922017-03-09 13:13:25 +0000706 expect_success,
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800707 use_fd);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800708 if (app_image_file != nullptr) {
709 ASSERT_EQ(app_image_file->FlushCloseOrErase(), 0) << "Could not flush and close art file";
710 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800711 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700712
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100713 uint64_t GetImageObjectSectionSize(const std::string& image_file_name) {
Mathieu Chartier046854b2017-03-01 17:16:22 -0800714 EXPECT_FALSE(image_file_name.empty());
715 std::unique_ptr<File> file(OS::OpenFileForReading(image_file_name.c_str()));
716 CHECK(file != nullptr);
717 ImageHeader image_header;
718 const bool success = file->ReadFully(&image_header, sizeof(image_header));
719 CHECK(success);
720 CHECK(image_header.IsValid());
721 ReaderMutexLock mu(Thread::Current(), *Locks::mutator_lock_);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100722 return image_header.GetObjectsSection().Size();
Mathieu Chartier046854b2017-03-01 17:16:22 -0800723 }
724
725 void RunTest(bool app_image) {
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800726 std::string dex_location = GetScratchDir() + "/DexNoOat.jar";
727 std::string odex_location = GetOdexDir() + "/DexOdexNoOat.odex";
Mathieu Chartier046854b2017-03-01 17:16:22 -0800728 std::string app_image_file = app_image ? (GetOdexDir() + "/DexOdexNoOat.art"): "";
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800729 Copy(GetDexSrc2(), dex_location);
730
Mathieu Chartier046854b2017-03-01 17:16:22 -0800731 uint64_t image_file_empty_profile = 0;
732 if (app_image) {
733 CompileProfileOdex(dex_location,
734 odex_location,
735 app_image_file,
736 /* use_fd */ false,
737 /* num_profile_classes */ 0);
738 CheckValidity();
739 ASSERT_TRUE(success_);
740 // Don't check the result since CheckResult relies on the class being in the profile.
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100741 image_file_empty_profile = GetImageObjectSectionSize(app_image_file);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800742 EXPECT_GT(image_file_empty_profile, 0u);
743 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700744
Mathieu Chartier046854b2017-03-01 17:16:22 -0800745 // Small profile.
746 CompileProfileOdex(dex_location,
747 odex_location,
748 app_image_file,
749 /* use_fd */ false,
750 /* num_profile_classes */ 1);
Jeff Hao608f2ce2016-10-19 11:17:11 -0700751 CheckValidity();
752 ASSERT_TRUE(success_);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800753 CheckResult(dex_location, odex_location, app_image_file);
754
755 if (app_image) {
756 // Test that the profile made a difference by adding more classes.
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100757 const uint64_t image_file_small_profile = GetImageObjectSectionSize(app_image_file);
758 ASSERT_LT(image_file_empty_profile, image_file_small_profile);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800759 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700760 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800761
762 void RunTestVDex() {
763 std::string dex_location = GetScratchDir() + "/DexNoOat.jar";
764 std::string odex_location = GetOdexDir() + "/DexOdexNoOat.odex";
765 std::string vdex_location = GetOdexDir() + "/DexOdexNoOat.vdex";
Mathieu Chartier046854b2017-03-01 17:16:22 -0800766 std::string app_image_file_name = GetOdexDir() + "/DexOdexNoOat.art";
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800767 Copy(GetDexSrc2(), dex_location);
768
769 std::unique_ptr<File> vdex_file1(OS::CreateEmptyFile(vdex_location.c_str()));
770 CHECK(vdex_file1 != nullptr) << vdex_location;
771 ScratchFile vdex_file2;
772 {
773 std::string input_vdex = "--input-vdex-fd=-1";
774 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file1->Fd());
775 CompileProfileOdex(dex_location,
776 odex_location,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800777 app_image_file_name,
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800778 /* use_fd */ true,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800779 /* num_profile_classes */ 1,
Mathieu Chartier02129102017-12-22 11:04:01 -0800780 { input_vdex, output_vdex, kDisableCompactDex });
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800781 EXPECT_GT(vdex_file1->GetLength(), 0u);
782 }
783 {
Nicolas Geoffray97fa9922017-03-09 13:13:25 +0000784 // Test that vdex and dexlayout fail gracefully.
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800785 std::string input_vdex = StringPrintf("--input-vdex-fd=%d", vdex_file1->Fd());
786 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file2.GetFd());
787 CompileProfileOdex(dex_location,
788 odex_location,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800789 app_image_file_name,
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800790 /* use_fd */ true,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800791 /* num_profile_classes */ 1,
Mathieu Chartier02129102017-12-22 11:04:01 -0800792 { input_vdex, output_vdex, kDisableCompactDex },
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +0100793 /* expect_success */ true);
794 EXPECT_GT(vdex_file2.GetFile()->GetLength(), 0u);
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800795 }
796 ASSERT_EQ(vdex_file1->FlushCloseOrErase(), 0) << "Could not flush and close vdex file";
797 CheckValidity();
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +0100798 ASSERT_TRUE(success_);
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800799 }
800
Mathieu Chartier046854b2017-03-01 17:16:22 -0800801 void CheckResult(const std::string& dex_location,
802 const std::string& odex_location,
803 const std::string& app_image_file_name) {
Jeff Hao608f2ce2016-10-19 11:17:11 -0700804 // Host/target independent checks.
805 std::string error_msg;
806 std::unique_ptr<OatFile> odex_file(OatFile::Open(odex_location.c_str(),
807 odex_location.c_str(),
808 nullptr,
809 nullptr,
810 false,
811 /*low_4gb*/false,
812 dex_location.c_str(),
813 &error_msg));
814 ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
815
Jeff Hao042e8982016-10-19 11:17:11 -0700816 const char* location = dex_location.c_str();
817 std::vector<std::unique_ptr<const DexFile>> dex_files;
Nicolas Geoffray095c6c92017-10-19 13:59:55 +0100818 ASSERT_TRUE(DexFileLoader::Open(
819 location, location, /* verify */ true, /* verify_checksum */ true, &error_msg, &dex_files));
Jeff Hao042e8982016-10-19 11:17:11 -0700820 EXPECT_EQ(dex_files.size(), 1U);
821 std::unique_ptr<const DexFile>& old_dex_file = dex_files[0];
822
Jeff Hao608f2ce2016-10-19 11:17:11 -0700823 for (const OatDexFile* oat_dex_file : odex_file->GetOatDexFiles()) {
Jeff Hao042e8982016-10-19 11:17:11 -0700824 std::unique_ptr<const DexFile> new_dex_file = oat_dex_file->OpenDexFile(&error_msg);
825 ASSERT_TRUE(new_dex_file != nullptr);
826 uint32_t class_def_count = new_dex_file->NumClassDefs();
Jeff Hao608f2ce2016-10-19 11:17:11 -0700827 ASSERT_LT(class_def_count, std::numeric_limits<uint16_t>::max());
Jeff Hao042e8982016-10-19 11:17:11 -0700828 ASSERT_GE(class_def_count, 2U);
829
Mathieu Chartier24066ec2017-10-21 16:01:08 -0700830 // Make sure the indexes stay the same.
Jeff Hao042e8982016-10-19 11:17:11 -0700831 std::string old_class0 = old_dex_file->PrettyType(old_dex_file->GetClassDef(0).class_idx_);
832 std::string old_class1 = old_dex_file->PrettyType(old_dex_file->GetClassDef(1).class_idx_);
833 std::string new_class0 = new_dex_file->PrettyType(new_dex_file->GetClassDef(0).class_idx_);
834 std::string new_class1 = new_dex_file->PrettyType(new_dex_file->GetClassDef(1).class_idx_);
Mathieu Chartier24066ec2017-10-21 16:01:08 -0700835 EXPECT_EQ(old_class0, new_class0);
836 EXPECT_EQ(old_class1, new_class1);
Jeff Hao608f2ce2016-10-19 11:17:11 -0700837 }
838
Jeff Haoc155b052017-01-17 17:43:29 -0800839 EXPECT_EQ(odex_file->GetCompilerFilter(), CompilerFilter::kSpeedProfile);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800840
841 if (!app_image_file_name.empty()) {
842 // Go peek at the image header to make sure it was large enough to contain the class.
843 std::unique_ptr<File> file(OS::OpenFileForReading(app_image_file_name.c_str()));
844 ImageHeader image_header;
845 bool success = file->ReadFully(&image_header, sizeof(image_header));
846 ASSERT_TRUE(success);
847 ASSERT_TRUE(image_header.IsValid());
Vladimir Markocd87c3e2017-09-05 13:11:57 +0100848 EXPECT_GT(image_header.GetObjectsSection().Size(), 0u);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800849 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700850 }
851
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800852 // Check whether the dex2oat run was really successful.
853 void CheckValidity() {
854 if (kIsTargetBuild) {
855 CheckTargetValidity();
856 } else {
857 CheckHostValidity();
Jeff Hao608f2ce2016-10-19 11:17:11 -0700858 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800859 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700860
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800861 void CheckTargetValidity() {
862 // TODO: Ignore for now.
863 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700864
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800865 // On the host, we can get the dex2oat output. Here, look for "dex2oat took."
866 void CheckHostValidity() {
867 EXPECT_NE(output_.find("dex2oat took"), std::string::npos) << output_;
868 }
869};
Jeff Hao608f2ce2016-10-19 11:17:11 -0700870
871TEST_F(Dex2oatLayoutTest, TestLayout) {
Mathieu Chartier046854b2017-03-01 17:16:22 -0800872 RunTest(/* app-image */ false);
873}
874
875TEST_F(Dex2oatLayoutTest, TestLayoutAppImage) {
876 RunTest(/* app-image */ true);
Jeff Hao608f2ce2016-10-19 11:17:11 -0700877}
878
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800879TEST_F(Dex2oatLayoutTest, TestVdexLayout) {
880 RunTestVDex();
881}
882
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100883class Dex2oatUnquickenTest : public Dex2oatTest {
884 protected:
885 void RunUnquickenMultiDex() {
886 std::string dex_location = GetScratchDir() + "/UnquickenMultiDex.jar";
887 std::string odex_location = GetOdexDir() + "/UnquickenMultiDex.odex";
888 std::string vdex_location = GetOdexDir() + "/UnquickenMultiDex.vdex";
889 Copy(GetTestDexFileName("MultiDex"), dex_location);
890
891 std::unique_ptr<File> vdex_file1(OS::CreateEmptyFile(vdex_location.c_str()));
892 CHECK(vdex_file1 != nullptr) << vdex_location;
893 // Quicken the dex file into a vdex file.
894 {
895 std::string input_vdex = "--input-vdex-fd=-1";
896 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file1->Fd());
897 GenerateOdexForTest(dex_location,
898 odex_location,
899 CompilerFilter::kQuicken,
Mathieu Chartier02129102017-12-22 11:04:01 -0800900 { input_vdex, output_vdex, kDisableCompactDex },
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100901 /* expect_success */ true,
902 /* use_fd */ true);
903 EXPECT_GT(vdex_file1->GetLength(), 0u);
904 }
905 // Unquicken by running the verify compiler filter on the vdex file.
906 {
907 std::string input_vdex = StringPrintf("--input-vdex-fd=%d", vdex_file1->Fd());
908 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file1->Fd());
909 GenerateOdexForTest(dex_location,
910 odex_location,
911 CompilerFilter::kVerify,
Mathieu Chartier02129102017-12-22 11:04:01 -0800912 { input_vdex, output_vdex, kDisableCompactDex },
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100913 /* expect_success */ true,
914 /* use_fd */ true);
915 }
916 ASSERT_EQ(vdex_file1->FlushCloseOrErase(), 0) << "Could not flush and close vdex file";
917 CheckResult(dex_location, odex_location);
918 ASSERT_TRUE(success_);
919 }
920
921 void CheckResult(const std::string& dex_location, const std::string& odex_location) {
922 std::string error_msg;
923 std::unique_ptr<OatFile> odex_file(OatFile::Open(odex_location.c_str(),
924 odex_location.c_str(),
925 nullptr,
926 nullptr,
927 false,
928 /*low_4gb*/false,
929 dex_location.c_str(),
930 &error_msg));
931 ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
932 ASSERT_GE(odex_file->GetOatDexFiles().size(), 1u);
933
934 // Iterate over the dex files and ensure there is no quickened instruction.
935 for (const OatDexFile* oat_dex_file : odex_file->GetOatDexFiles()) {
936 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
937 for (uint32_t i = 0; i < dex_file->NumClassDefs(); ++i) {
938 const DexFile::ClassDef& class_def = dex_file->GetClassDef(i);
939 const uint8_t* class_data = dex_file->GetClassData(class_def);
940 if (class_data != nullptr) {
941 for (ClassDataItemIterator class_it(*dex_file, class_data);
942 class_it.HasNext();
943 class_it.Next()) {
944 if (class_it.IsAtMethod() && class_it.GetMethodCodeItem() != nullptr) {
Mathieu Chartier0021feb2017-11-07 00:08:52 -0800945 for (const DexInstructionPcPair& inst :
Mathieu Chartier698ebbc2018-01-05 11:00:42 -0800946 CodeItemInstructionAccessor(*dex_file, class_it.GetMethodCodeItem())) {
Mathieu Chartier02129102017-12-22 11:04:01 -0800947 ASSERT_FALSE(inst->IsQuickened()) << output_;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100948 }
949 }
950 }
951 }
952 }
953 }
954 }
955};
956
957TEST_F(Dex2oatUnquickenTest, UnquickenMultiDex) {
958 RunUnquickenMultiDex();
959}
960
Andreas Gampe2e8a2562017-01-18 20:39:02 -0800961class Dex2oatWatchdogTest : public Dex2oatTest {
962 protected:
963 void RunTest(bool expect_success, const std::vector<std::string>& extra_args = {}) {
964 std::string dex_location = GetScratchDir() + "/Dex2OatSwapTest.jar";
965 std::string odex_location = GetOdexDir() + "/Dex2OatSwapTest.odex";
966
967 Copy(GetTestDexFileName(), dex_location);
968
969 std::vector<std::string> copy(extra_args);
970
971 std::string swap_location = GetOdexDir() + "/Dex2OatSwapTest.odex.swap";
972 copy.push_back("--swap-file=" + swap_location);
Andreas Gampe22fa3762017-10-23 20:58:12 -0700973 copy.push_back("-j512"); // Excessive idle threads just slow down dex2oat.
Andreas Gampe2e8a2562017-01-18 20:39:02 -0800974 GenerateOdexForTest(dex_location,
975 odex_location,
976 CompilerFilter::kSpeed,
977 copy,
978 expect_success);
979 }
980
981 std::string GetTestDexFileName() {
982 return GetDexSrc1();
983 }
984};
985
986TEST_F(Dex2oatWatchdogTest, TestWatchdogOK) {
987 // Check with default.
988 RunTest(true);
989
990 // Check with ten minutes.
991 RunTest(true, { "--watchdog-timeout=600000" });
992}
993
994TEST_F(Dex2oatWatchdogTest, TestWatchdogTrigger) {
Roland Levillain68db2252017-08-14 12:48:47 +0100995 TEST_DISABLED_FOR_MEMORY_TOOL_VALGRIND(); // b/63052624
Andreas Gampe21f9cb82017-12-27 08:43:08 -0800996 TEST_DISABLED_WITHOUT_BAKER_READ_BARRIERS(); // b/63052624
Andreas Gampe2e8a2562017-01-18 20:39:02 -0800997 // Check with ten milliseconds.
998 RunTest(false, { "--watchdog-timeout=10" });
999}
1000
Andreas Gampef7882972017-03-20 16:35:24 -07001001class Dex2oatReturnCodeTest : public Dex2oatTest {
1002 protected:
1003 int RunTest(const std::vector<std::string>& extra_args = {}) {
1004 std::string dex_location = GetScratchDir() + "/Dex2OatSwapTest.jar";
1005 std::string odex_location = GetOdexDir() + "/Dex2OatSwapTest.odex";
1006
1007 Copy(GetTestDexFileName(), dex_location);
1008
1009 std::string error_msg;
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001010 return GenerateOdexForTestWithStatus({dex_location},
Andreas Gampef7882972017-03-20 16:35:24 -07001011 odex_location,
1012 CompilerFilter::kSpeed,
1013 &error_msg,
1014 extra_args);
1015 }
1016
1017 std::string GetTestDexFileName() {
1018 return GetDexSrc1();
1019 }
1020};
1021
1022TEST_F(Dex2oatReturnCodeTest, TestCreateRuntime) {
Andreas Gampefd80b172017-04-26 22:25:31 -07001023 TEST_DISABLED_FOR_MEMORY_TOOL(); // b/19100793
Andreas Gampef7882972017-03-20 16:35:24 -07001024 int status = RunTest({ "--boot-image=/this/does/not/exist/yolo.oat" });
1025 EXPECT_EQ(static_cast<int>(dex2oat::ReturnCode::kCreateRuntime), WEXITSTATUS(status)) << output_;
1026}
1027
Calin Juravle1ce70852017-06-28 10:59:03 -07001028class Dex2oatClassLoaderContextTest : public Dex2oatTest {
1029 protected:
1030 void RunTest(const char* class_loader_context,
1031 const char* expected_classpath_key,
1032 bool expected_success,
1033 bool use_second_source = false) {
1034 std::string dex_location = GetUsedDexLocation();
1035 std::string odex_location = GetUsedOatLocation();
1036
1037 Copy(use_second_source ? GetDexSrc2() : GetDexSrc1(), dex_location);
1038
1039 std::string error_msg;
1040 std::vector<std::string> extra_args;
1041 if (class_loader_context != nullptr) {
1042 extra_args.push_back(std::string("--class-loader-context=") + class_loader_context);
1043 }
1044 auto check_oat = [expected_classpath_key](const OatFile& oat_file) {
1045 ASSERT_TRUE(expected_classpath_key != nullptr);
1046 const char* classpath = oat_file.GetOatHeader().GetStoreValueByKey(OatHeader::kClassPathKey);
1047 ASSERT_TRUE(classpath != nullptr);
1048 ASSERT_STREQ(expected_classpath_key, classpath);
1049 };
1050
1051 GenerateOdexForTest(dex_location,
1052 odex_location,
1053 CompilerFilter::kQuicken,
1054 extra_args,
1055 expected_success,
1056 /*use_fd*/ false,
1057 check_oat);
1058 }
1059
1060 std::string GetUsedDexLocation() {
1061 return GetScratchDir() + "/Context.jar";
1062 }
1063
1064 std::string GetUsedOatLocation() {
1065 return GetOdexDir() + "/Context.odex";
1066 }
1067
Calin Juravle7b0648a2017-07-07 18:40:50 -07001068 const char* kEmptyClassPathKey = "PCL[]";
Calin Juravle1ce70852017-06-28 10:59:03 -07001069};
1070
1071TEST_F(Dex2oatClassLoaderContextTest, InvalidContext) {
1072 RunTest("Invalid[]", /*expected_classpath_key*/ nullptr, /*expected_success*/ false);
1073}
1074
1075TEST_F(Dex2oatClassLoaderContextTest, EmptyContext) {
1076 RunTest("PCL[]", kEmptyClassPathKey, /*expected_success*/ true);
1077}
1078
1079TEST_F(Dex2oatClassLoaderContextTest, SpecialContext) {
1080 RunTest(OatFile::kSpecialSharedLibrary,
1081 OatFile::kSpecialSharedLibrary,
1082 /*expected_success*/ true);
1083}
1084
1085TEST_F(Dex2oatClassLoaderContextTest, ContextWithTheSourceDexFiles) {
1086 std::string context = "PCL[" + GetUsedDexLocation() + "]";
1087 RunTest(context.c_str(), kEmptyClassPathKey, /*expected_success*/ true);
1088}
1089
1090TEST_F(Dex2oatClassLoaderContextTest, ContextWithOtherDexFiles) {
1091 std::vector<std::unique_ptr<const DexFile>> dex_files = OpenTestDexFiles("Nested");
Calin Juravle1ce70852017-06-28 10:59:03 -07001092
1093 std::string context = "PCL[" + dex_files[0]->GetLocation() + "]";
Calin Juravle7b0648a2017-07-07 18:40:50 -07001094 std::string expected_classpath_key = "PCL[" +
1095 dex_files[0]->GetLocation() + "*" + std::to_string(dex_files[0]->GetLocationChecksum()) + "]";
Calin Juravle1ce70852017-06-28 10:59:03 -07001096 RunTest(context.c_str(), expected_classpath_key.c_str(), true);
1097}
1098
1099TEST_F(Dex2oatClassLoaderContextTest, ContextWithStrippedDexFiles) {
1100 std::string stripped_classpath = GetScratchDir() + "/stripped_classpath.jar";
1101 Copy(GetStrippedDexSrc1(), stripped_classpath);
1102
1103 std::string context = "PCL[" + stripped_classpath + "]";
1104 // Expect an empty context because stripped dex files cannot be open.
Calin Juravle7b0648a2017-07-07 18:40:50 -07001105 RunTest(context.c_str(), kEmptyClassPathKey , /*expected_success*/ true);
Calin Juravle1ce70852017-06-28 10:59:03 -07001106}
1107
1108TEST_F(Dex2oatClassLoaderContextTest, ContextWithStrippedDexFilesBackedByOdex) {
1109 std::string stripped_classpath = GetScratchDir() + "/stripped_classpath.jar";
1110 std::string odex_for_classpath = GetOdexDir() + "/stripped_classpath.odex";
1111
1112 Copy(GetDexSrc1(), stripped_classpath);
1113
1114 GenerateOdexForTest(stripped_classpath,
1115 odex_for_classpath,
1116 CompilerFilter::kQuicken,
1117 {},
1118 true);
1119
1120 // Strip the dex file
1121 Copy(GetStrippedDexSrc1(), stripped_classpath);
1122
1123 std::string context = "PCL[" + stripped_classpath + "]";
Calin Juravle7b0648a2017-07-07 18:40:50 -07001124 std::string expected_classpath_key;
Calin Juravle1ce70852017-06-28 10:59:03 -07001125 {
1126 // Open the oat file to get the expected classpath.
1127 OatFileAssistant oat_file_assistant(stripped_classpath.c_str(), kRuntimeISA, false);
1128 std::unique_ptr<OatFile> oat_file(oat_file_assistant.GetBestOatFile());
1129 std::vector<std::unique_ptr<const DexFile>> oat_dex_files =
1130 OatFileAssistant::LoadDexFiles(*oat_file, stripped_classpath.c_str());
Calin Juravle7b0648a2017-07-07 18:40:50 -07001131 expected_classpath_key = "PCL[";
1132 for (size_t i = 0; i < oat_dex_files.size(); i++) {
1133 if (i > 0) {
1134 expected_classpath_key + ":";
1135 }
1136 expected_classpath_key += oat_dex_files[i]->GetLocation() + "*" +
1137 std::to_string(oat_dex_files[i]->GetLocationChecksum());
1138 }
1139 expected_classpath_key += "]";
Calin Juravle1ce70852017-06-28 10:59:03 -07001140 }
1141
1142 RunTest(context.c_str(),
Calin Juravle7b0648a2017-07-07 18:40:50 -07001143 expected_classpath_key.c_str(),
Calin Juravle1ce70852017-06-28 10:59:03 -07001144 /*expected_success*/ true,
1145 /*use_second_source*/ true);
1146}
1147
1148TEST_F(Dex2oatClassLoaderContextTest, ContextWithNotExistentDexFiles) {
1149 std::string context = "PCL[does_not_exists.dex]";
1150 // Expect an empty context because stripped dex files cannot be open.
1151 RunTest(context.c_str(), kEmptyClassPathKey, /*expected_success*/ true);
1152}
1153
Calin Juravlec79470d2017-07-12 17:37:42 -07001154TEST_F(Dex2oatClassLoaderContextTest, ChainContext) {
1155 std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested");
1156 std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex");
1157
1158 std::string context = "PCL[" + GetTestDexFileName("Nested") + "];" +
1159 "DLC[" + GetTestDexFileName("MultiDex") + "]";
1160 std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "];" +
1161 "DLC[" + CreateClassPathWithChecksums(dex_files2) + "]";
1162
1163 RunTest(context.c_str(), expected_classpath_key.c_str(), true);
1164}
1165
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001166class Dex2oatDeterminism : public Dex2oatTest {};
1167
1168TEST_F(Dex2oatDeterminism, UnloadCompile) {
1169 if (!kUseReadBarrier &&
1170 gc::kCollectorTypeDefault != gc::kCollectorTypeCMS &&
1171 gc::kCollectorTypeDefault != gc::kCollectorTypeMS) {
1172 LOG(INFO) << "Test requires determinism support.";
1173 return;
1174 }
1175 Runtime* const runtime = Runtime::Current();
1176 std::string out_dir = GetScratchDir();
1177 const std::string base_oat_name = out_dir + "/base.oat";
1178 const std::string base_vdex_name = out_dir + "/base.vdex";
1179 const std::string unload_oat_name = out_dir + "/unload.oat";
1180 const std::string unload_vdex_name = out_dir + "/unload.vdex";
1181 const std::string no_unload_oat_name = out_dir + "/nounload.oat";
1182 const std::string no_unload_vdex_name = out_dir + "/nounload.vdex";
1183 const std::string app_image_name = out_dir + "/unload.art";
1184 std::string error_msg;
1185 const std::vector<gc::space::ImageSpace*>& spaces = runtime->GetHeap()->GetBootImageSpaces();
1186 ASSERT_GT(spaces.size(), 0u);
1187 const std::string image_location = spaces[0]->GetImageLocation();
1188 // Without passing in an app image, it will unload in between compilations.
1189 const int res = GenerateOdexForTestWithStatus(
1190 GetLibCoreDexFileNames(),
1191 base_oat_name,
1192 CompilerFilter::Filter::kQuicken,
1193 &error_msg,
1194 {"--force-determinism", "--avoid-storing-invocation"});
1195 EXPECT_EQ(res, 0);
1196 Copy(base_oat_name, unload_oat_name);
1197 Copy(base_vdex_name, unload_vdex_name);
1198 std::unique_ptr<File> unload_oat(OS::OpenFileForReading(unload_oat_name.c_str()));
1199 std::unique_ptr<File> unload_vdex(OS::OpenFileForReading(unload_vdex_name.c_str()));
1200 ASSERT_TRUE(unload_oat != nullptr);
1201 ASSERT_TRUE(unload_vdex != nullptr);
1202 EXPECT_GT(unload_oat->GetLength(), 0u);
1203 EXPECT_GT(unload_vdex->GetLength(), 0u);
1204 // Regenerate with an app image to disable the dex2oat unloading and verify that the output is
1205 // the same.
1206 const int res2 = GenerateOdexForTestWithStatus(
1207 GetLibCoreDexFileNames(),
1208 base_oat_name,
1209 CompilerFilter::Filter::kQuicken,
1210 &error_msg,
1211 {"--force-determinism", "--avoid-storing-invocation", "--app-image-file=" + app_image_name});
1212 EXPECT_EQ(res2, 0);
1213 Copy(base_oat_name, no_unload_oat_name);
1214 Copy(base_vdex_name, no_unload_vdex_name);
1215 std::unique_ptr<File> no_unload_oat(OS::OpenFileForReading(no_unload_oat_name.c_str()));
1216 std::unique_ptr<File> no_unload_vdex(OS::OpenFileForReading(no_unload_vdex_name.c_str()));
1217 ASSERT_TRUE(no_unload_oat != nullptr);
1218 ASSERT_TRUE(no_unload_vdex != nullptr);
1219 EXPECT_GT(no_unload_oat->GetLength(), 0u);
1220 EXPECT_GT(no_unload_vdex->GetLength(), 0u);
1221 // Verify that both of the files are the same (odex and vdex).
1222 EXPECT_EQ(unload_oat->GetLength(), no_unload_oat->GetLength());
1223 EXPECT_EQ(unload_vdex->GetLength(), no_unload_vdex->GetLength());
1224 EXPECT_EQ(unload_oat->Compare(no_unload_oat.get()), 0)
1225 << unload_oat_name << " " << no_unload_oat_name;
1226 EXPECT_EQ(unload_vdex->Compare(no_unload_vdex.get()), 0)
1227 << unload_vdex_name << " " << no_unload_vdex_name;
1228 // App image file.
1229 std::unique_ptr<File> app_image_file(OS::OpenFileForReading(app_image_name.c_str()));
1230 ASSERT_TRUE(app_image_file != nullptr);
1231 EXPECT_GT(app_image_file->GetLength(), 0u);
1232}
1233
Mathieu Chartier120aa282017-08-05 16:03:03 -07001234// Test that dexlayout section info is correctly written to the oat file for profile based
1235// compilation.
1236TEST_F(Dex2oatTest, LayoutSections) {
1237 using Hotness = ProfileCompilationInfo::MethodHotness;
1238 std::unique_ptr<const DexFile> dex(OpenTestDexFile("ManyMethods"));
1239 ScratchFile profile_file;
1240 // We can only layout method indices with code items, figure out which ones have this property
1241 // first.
1242 std::vector<uint16_t> methods;
1243 {
1244 const DexFile::TypeId* type_id = dex->FindTypeId("LManyMethods;");
1245 dex::TypeIndex type_idx = dex->GetIndexForTypeId(*type_id);
1246 const DexFile::ClassDef* class_def = dex->FindClassDef(type_idx);
1247 ClassDataItemIterator it(*dex, dex->GetClassData(*class_def));
1248 it.SkipAllFields();
1249 std::set<size_t> code_item_offsets;
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08001250 for (; it.HasNextMethod(); it.Next()) {
Mathieu Chartier120aa282017-08-05 16:03:03 -07001251 const uint16_t method_idx = it.GetMemberIndex();
1252 const size_t code_item_offset = it.GetMethodCodeItemOffset();
1253 if (code_item_offsets.insert(code_item_offset).second) {
1254 // Unique code item, add the method index.
1255 methods.push_back(method_idx);
1256 }
1257 }
1258 DCHECK(!it.HasNext());
1259 }
1260 ASSERT_GE(methods.size(), 8u);
1261 std::vector<uint16_t> hot_methods = {methods[1], methods[3], methods[5]};
1262 std::vector<uint16_t> startup_methods = {methods[1], methods[2], methods[7]};
1263 std::vector<uint16_t> post_methods = {methods[0], methods[2], methods[6]};
1264 // Here, we build the profile from the method lists.
1265 ProfileCompilationInfo info;
1266 info.AddMethodsForDex(
1267 static_cast<Hotness::Flag>(Hotness::kFlagHot | Hotness::kFlagStartup),
1268 dex.get(),
1269 hot_methods.begin(),
1270 hot_methods.end());
1271 info.AddMethodsForDex(
1272 Hotness::kFlagStartup,
1273 dex.get(),
1274 startup_methods.begin(),
1275 startup_methods.end());
1276 info.AddMethodsForDex(
1277 Hotness::kFlagPostStartup,
1278 dex.get(),
1279 post_methods.begin(),
1280 post_methods.end());
1281 for (uint16_t id : hot_methods) {
1282 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsHot());
1283 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsStartup());
1284 }
1285 for (uint16_t id : startup_methods) {
1286 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsStartup());
1287 }
1288 for (uint16_t id : post_methods) {
1289 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsPostStartup());
1290 }
1291 // Save the profile since we want to use it with dex2oat to produce an oat file.
1292 ASSERT_TRUE(info.Save(profile_file.GetFd()));
1293 // Generate a profile based odex.
1294 const std::string dir = GetScratchDir();
1295 const std::string oat_filename = dir + "/base.oat";
1296 const std::string vdex_filename = dir + "/base.vdex";
1297 std::string error_msg;
1298 const int res = GenerateOdexForTestWithStatus(
1299 {dex->GetLocation()},
1300 oat_filename,
1301 CompilerFilter::Filter::kQuicken,
1302 &error_msg,
1303 {"--profile-file=" + profile_file.GetFilename()});
1304 EXPECT_EQ(res, 0);
1305
1306 // Open our generated oat file.
1307 std::unique_ptr<OatFile> odex_file(OatFile::Open(oat_filename.c_str(),
1308 oat_filename.c_str(),
1309 nullptr,
1310 nullptr,
1311 false,
1312 /*low_4gb*/false,
1313 dex->GetLocation().c_str(),
1314 &error_msg));
1315 ASSERT_TRUE(odex_file != nullptr);
1316 std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
1317 ASSERT_EQ(oat_dex_files.size(), 1u);
1318 // Check that the code sections match what we expect.
1319 for (const OatDexFile* oat_dex : oat_dex_files) {
1320 const DexLayoutSections* const sections = oat_dex->GetDexLayoutSections();
1321 // Testing of logging the sections.
1322 ASSERT_TRUE(sections != nullptr);
1323 LOG(INFO) << *sections;
1324
1325 // Load the sections into temporary variables for convenience.
1326 const DexLayoutSection& code_section =
1327 sections->sections_[static_cast<size_t>(DexLayoutSections::SectionType::kSectionTypeCode)];
1328 const DexLayoutSection::Subsection& section_hot_code =
1329 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeHot)];
1330 const DexLayoutSection::Subsection& section_sometimes_used =
1331 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeSometimesUsed)];
1332 const DexLayoutSection::Subsection& section_startup_only =
1333 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeStartupOnly)];
1334 const DexLayoutSection::Subsection& section_unused =
1335 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeUnused)];
1336
1337 // All the sections should be non-empty.
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001338 EXPECT_GT(section_hot_code.Size(), 0u);
1339 EXPECT_GT(section_sometimes_used.Size(), 0u);
1340 EXPECT_GT(section_startup_only.Size(), 0u);
1341 EXPECT_GT(section_unused.Size(), 0u);
Mathieu Chartier120aa282017-08-05 16:03:03 -07001342
1343 // Open the dex file since we need to peek at the code items to verify the layout matches what
1344 // we expect.
1345 std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1346 ASSERT_TRUE(dex_file != nullptr) << error_msg;
1347 const DexFile::TypeId* type_id = dex_file->FindTypeId("LManyMethods;");
1348 ASSERT_TRUE(type_id != nullptr);
1349 dex::TypeIndex type_idx = dex_file->GetIndexForTypeId(*type_id);
1350 const DexFile::ClassDef* class_def = dex_file->FindClassDef(type_idx);
1351 ASSERT_TRUE(class_def != nullptr);
1352
1353 // Count how many code items are for each category, there should be at least one per category.
1354 size_t hot_count = 0;
1355 size_t post_startup_count = 0;
1356 size_t startup_count = 0;
1357 size_t unused_count = 0;
1358 // Visit all of the methdos of the main class and cross reference the method indices to their
1359 // corresponding code item offsets to verify the layout.
1360 ClassDataItemIterator it(*dex_file, dex_file->GetClassData(*class_def));
1361 it.SkipAllFields();
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08001362 for (; it.HasNextMethod(); it.Next()) {
Mathieu Chartier120aa282017-08-05 16:03:03 -07001363 const size_t method_idx = it.GetMemberIndex();
1364 const size_t code_item_offset = it.GetMethodCodeItemOffset();
1365 const bool is_hot = ContainsElement(hot_methods, method_idx);
1366 const bool is_startup = ContainsElement(startup_methods, method_idx);
1367 const bool is_post_startup = ContainsElement(post_methods, method_idx);
1368 if (is_hot) {
1369 // Hot is highest precedence, check that the hot methods are in the hot section.
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001370 EXPECT_TRUE(section_hot_code.Contains(code_item_offset));
Mathieu Chartier120aa282017-08-05 16:03:03 -07001371 ++hot_count;
1372 } else if (is_post_startup) {
1373 // Post startup is sometimes used section.
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001374 EXPECT_TRUE(section_sometimes_used.Contains(code_item_offset));
Mathieu Chartier120aa282017-08-05 16:03:03 -07001375 ++post_startup_count;
1376 } else if (is_startup) {
1377 // Startup at this point means not hot or post startup, these must be startup only then.
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001378 EXPECT_TRUE(section_startup_only.Contains(code_item_offset));
Mathieu Chartier120aa282017-08-05 16:03:03 -07001379 ++startup_count;
1380 } else {
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001381 if (section_unused.Contains(code_item_offset)) {
Alan Leung9595fd32017-10-17 17:08:19 -07001382 // If no flags are set, the method should be unused ...
1383 ++unused_count;
1384 } else {
1385 // or this method is part of the last code item and the end is 4 byte aligned.
1386 ClassDataItemIterator it2(*dex_file, dex_file->GetClassData(*class_def));
1387 it2.SkipAllFields();
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08001388 for (; it2.HasNextMethod(); it2.Next()) {
Alan Leung9595fd32017-10-17 17:08:19 -07001389 EXPECT_LE(it2.GetMethodCodeItemOffset(), code_item_offset);
1390 }
1391 uint32_t code_item_size = dex_file->FindCodeItemOffset(*class_def, method_idx);
1392 EXPECT_EQ((code_item_offset + code_item_size) % 4, 0u);
1393 }
Mathieu Chartier120aa282017-08-05 16:03:03 -07001394 }
1395 }
1396 DCHECK(!it.HasNext());
1397 EXPECT_GT(hot_count, 0u);
1398 EXPECT_GT(post_startup_count, 0u);
1399 EXPECT_GT(startup_count, 0u);
1400 EXPECT_GT(unused_count, 0u);
1401 }
1402}
1403
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001404// Test that generating compact dex works.
1405TEST_F(Dex2oatTest, GenerateCompactDex) {
1406 std::unique_ptr<const DexFile> dex(OpenTestDexFile("ManyMethods"));
1407 // Generate a compact dex based odex.
1408 const std::string dir = GetScratchDir();
1409 const std::string oat_filename = dir + "/base.oat";
1410 const std::string vdex_filename = dir + "/base.vdex";
1411 std::string error_msg;
1412 const int res = GenerateOdexForTestWithStatus(
1413 {dex->GetLocation()},
1414 oat_filename,
1415 CompilerFilter::Filter::kQuicken,
1416 &error_msg,
1417 {"--compact-dex-level=fast"});
1418 EXPECT_EQ(res, 0);
1419 // Open our generated oat file.
1420 std::unique_ptr<OatFile> odex_file(OatFile::Open(oat_filename.c_str(),
1421 oat_filename.c_str(),
1422 nullptr,
1423 nullptr,
1424 false,
1425 /*low_4gb*/false,
1426 dex->GetLocation().c_str(),
1427 &error_msg));
1428 ASSERT_TRUE(odex_file != nullptr);
1429 std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
1430 ASSERT_EQ(oat_dex_files.size(), 1u);
1431 // Check that each dex is a compact dex.
1432 for (const OatDexFile* oat_dex : oat_dex_files) {
1433 std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1434 ASSERT_TRUE(dex_file != nullptr) << error_msg;
1435 ASSERT_TRUE(dex_file->IsCompactDexFile());
1436 }
1437}
1438
Andreas Gampef39208f2017-10-19 15:06:59 -07001439class Dex2oatVerifierAbort : public Dex2oatTest {};
1440
1441TEST_F(Dex2oatVerifierAbort, HardFail) {
1442 // Use VerifierDeps as it has hard-failing classes.
1443 std::unique_ptr<const DexFile> dex(OpenTestDexFile("VerifierDeps"));
1444 std::string out_dir = GetScratchDir();
1445 const std::string base_oat_name = out_dir + "/base.oat";
1446 std::string error_msg;
1447 const int res_fail = GenerateOdexForTestWithStatus(
1448 {dex->GetLocation()},
1449 base_oat_name,
1450 CompilerFilter::Filter::kQuicken,
1451 &error_msg,
1452 {"--abort-on-hard-verifier-error"});
1453 EXPECT_NE(0, res_fail);
1454
1455 const int res_no_fail = GenerateOdexForTestWithStatus(
1456 {dex->GetLocation()},
1457 base_oat_name,
1458 CompilerFilter::Filter::kQuicken,
1459 &error_msg,
1460 {"--no-abort-on-hard-verifier-error"});
1461 EXPECT_EQ(0, res_no_fail);
1462}
1463
1464TEST_F(Dex2oatVerifierAbort, SoftFail) {
1465 // Use VerifierDepsMulti as it has hard-failing classes.
1466 std::unique_ptr<const DexFile> dex(OpenTestDexFile("VerifierDepsMulti"));
1467 std::string out_dir = GetScratchDir();
1468 const std::string base_oat_name = out_dir + "/base.oat";
1469 std::string error_msg;
1470 const int res_fail = GenerateOdexForTestWithStatus(
1471 {dex->GetLocation()},
1472 base_oat_name,
1473 CompilerFilter::Filter::kQuicken,
1474 &error_msg,
1475 {"--abort-on-soft-verifier-error"});
1476 EXPECT_NE(0, res_fail);
1477
1478 const int res_no_fail = GenerateOdexForTestWithStatus(
1479 {dex->GetLocation()},
1480 base_oat_name,
1481 CompilerFilter::Filter::kQuicken,
1482 &error_msg,
1483 {"--no-abort-on-soft-verifier-error"});
1484 EXPECT_EQ(0, res_no_fail);
1485}
1486
Andreas Gampecac31ad2017-11-06 20:01:17 -08001487class Dex2oatDedupeCode : public Dex2oatTest {};
1488
1489TEST_F(Dex2oatDedupeCode, DedupeTest) {
1490 // Use MyClassNatives. It has lots of native methods that will produce deduplicate-able code.
1491 std::unique_ptr<const DexFile> dex(OpenTestDexFile("MyClassNatives"));
1492 std::string out_dir = GetScratchDir();
1493 const std::string base_oat_name = out_dir + "/base.oat";
1494 size_t no_dedupe_size = 0;
1495 GenerateOdexForTest(dex->GetLocation(),
1496 base_oat_name,
1497 CompilerFilter::Filter::kSpeed,
1498 { "--deduplicate-code=false" },
1499 true, // expect_success
1500 false, // use_fd
1501 [&no_dedupe_size](const OatFile& o) {
1502 no_dedupe_size = o.Size();
1503 });
1504
1505 size_t dedupe_size = 0;
1506 GenerateOdexForTest(dex->GetLocation(),
1507 base_oat_name,
1508 CompilerFilter::Filter::kSpeed,
1509 { "--deduplicate-code=true" },
1510 true, // expect_success
1511 false, // use_fd
1512 [&dedupe_size](const OatFile& o) {
1513 dedupe_size = o.Size();
1514 });
1515
1516 EXPECT_LT(dedupe_size, no_dedupe_size);
1517}
1518
Andreas Gampee1459ae2016-06-29 09:36:30 -07001519} // namespace art