blob: 21768d312618b9c2e5f774dc7ba990834b7b1d56 [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
Andreas Gampe7adeda82016-07-25 08:27:35 -070017#include <regex>
18#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
25#include "android-base/stringprintf.h"
26
Andreas Gampee1459ae2016-06-29 09:36:30 -070027#include "common_runtime_test.h"
28
29#include "base/logging.h"
30#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"
Andreas Gampee1459ae2016-06-29 09:36:30 -070033#include "dex2oat_environment_test.h"
Andreas Gampef7882972017-03-20 16:35:24 -070034#include "dex2oat_return_codes.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070035#include "dex_file-inl.h"
Mathieu Chartier79c87da2017-10-10 11:54:29 -070036#include "dex_file_loader.h"
Calin Juravle33083d62017-01-18 15:29:12 -080037#include "jit/profile_compilation_info.h"
Andreas Gampe67f02822016-06-24 21:05:23 -070038#include "oat.h"
39#include "oat_file.h"
Andreas Gampee1459ae2016-06-29 09:36:30 -070040#include "utils.h"
41
Andreas Gampee1459ae2016-06-29 09:36:30 -070042namespace art {
43
Mathieu Chartierea650f32017-05-24 12:04:13 -070044static constexpr size_t kMaxMethodIds = 65535;
Mathieu Chartier9e050df2017-08-09 10:05:47 -070045static constexpr bool kDebugArgs = false;
Mathieu Chartierea650f32017-05-24 12:04:13 -070046
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080047using android::base::StringPrintf;
48
Andreas Gampee1459ae2016-06-29 09:36:30 -070049class Dex2oatTest : public Dex2oatEnvironmentTest {
50 public:
51 virtual void TearDown() OVERRIDE {
52 Dex2oatEnvironmentTest::TearDown();
53
54 output_ = "";
55 error_msg_ = "";
56 success_ = false;
57 }
58
59 protected:
Mathieu Chartier9e050df2017-08-09 10:05:47 -070060 int GenerateOdexForTestWithStatus(const std::vector<std::string>& dex_locations,
Andreas Gampef7882972017-03-20 16:35:24 -070061 const std::string& odex_location,
62 CompilerFilter::Filter filter,
63 std::string* error_msg,
64 const std::vector<std::string>& extra_args = {},
65 bool use_fd = false) {
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080066 std::unique_ptr<File> oat_file;
Andreas Gampee1459ae2016-06-29 09:36:30 -070067 std::vector<std::string> args;
Mathieu Chartier9e050df2017-08-09 10:05:47 -070068 // Add dex file args.
69 for (const std::string& dex_location : dex_locations) {
70 args.push_back("--dex-file=" + dex_location);
71 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080072 if (use_fd) {
73 oat_file.reset(OS::CreateEmptyFile(odex_location.c_str()));
74 CHECK(oat_file != nullptr) << odex_location;
75 args.push_back("--oat-fd=" + std::to_string(oat_file->Fd()));
Mathieu Chartier046854b2017-03-01 17:16:22 -080076 args.push_back("--oat-location=" + odex_location);
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080077 } else {
78 args.push_back("--oat-file=" + odex_location);
79 }
Andreas Gampee1459ae2016-06-29 09:36:30 -070080 args.push_back("--compiler-filter=" + CompilerFilter::NameOfFilter(filter));
81 args.push_back("--runtime-arg");
82 args.push_back("-Xnorelocate");
83
84 args.insert(args.end(), extra_args.begin(), extra_args.end());
85
Andreas Gampef7882972017-03-20 16:35:24 -070086 int status = Dex2Oat(args, error_msg);
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080087 if (oat_file != nullptr) {
Andreas Gampef7882972017-03-20 16:35:24 -070088 CHECK_EQ(oat_file->FlushClose(), 0) << "Could not flush and close oat file";
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080089 }
Andreas Gampef7882972017-03-20 16:35:24 -070090 return status;
91 }
Andreas Gampee1459ae2016-06-29 09:36:30 -070092
Andreas Gampe641a4732017-08-24 13:21:35 -070093 void GenerateOdexForTest(
94 const std::string& dex_location,
95 const std::string& odex_location,
96 CompilerFilter::Filter filter,
97 const std::vector<std::string>& extra_args = {},
98 bool expect_success = true,
99 bool use_fd = false) {
100 GenerateOdexForTest(dex_location,
101 odex_location,
102 filter,
103 extra_args,
104 expect_success,
105 use_fd,
106 [](const OatFile&) {});
107 }
108
109 template <typename T>
110 void GenerateOdexForTest(
111 const std::string& dex_location,
112 const std::string& odex_location,
113 CompilerFilter::Filter filter,
114 const std::vector<std::string>& extra_args,
115 bool expect_success,
116 bool use_fd,
117 T check_oat) {
Andreas Gampef7882972017-03-20 16:35:24 -0700118 std::string error_msg;
Mathieu Chartier9e050df2017-08-09 10:05:47 -0700119 int status = GenerateOdexForTestWithStatus({dex_location},
Andreas Gampef7882972017-03-20 16:35:24 -0700120 odex_location,
121 filter,
122 &error_msg,
123 extra_args,
124 use_fd);
125 bool success = (status == 0);
Andreas Gampee1459ae2016-06-29 09:36:30 -0700126 if (expect_success) {
Andreas Gampe2e8a2562017-01-18 20:39:02 -0800127 ASSERT_TRUE(success) << error_msg << std::endl << output_;
Andreas Gampee1459ae2016-06-29 09:36:30 -0700128
129 // Verify the odex file was generated as expected.
130 std::unique_ptr<OatFile> odex_file(OatFile::Open(odex_location.c_str(),
131 odex_location.c_str(),
132 nullptr,
133 nullptr,
134 false,
135 /*low_4gb*/false,
136 dex_location.c_str(),
137 &error_msg));
138 ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
139
140 CheckFilter(filter, odex_file->GetCompilerFilter());
Calin Juravle1ce70852017-06-28 10:59:03 -0700141 check_oat(*(odex_file.get()));
Andreas Gampee1459ae2016-06-29 09:36:30 -0700142 } else {
143 ASSERT_FALSE(success) << output_;
144
145 error_msg_ = error_msg;
146
147 // Verify there's no loadable odex file.
148 std::unique_ptr<OatFile> odex_file(OatFile::Open(odex_location.c_str(),
149 odex_location.c_str(),
150 nullptr,
151 nullptr,
152 false,
153 /*low_4gb*/false,
154 dex_location.c_str(),
155 &error_msg));
156 ASSERT_TRUE(odex_file.get() == nullptr);
157 }
158 }
159
Calin Juravle1ccf6132017-08-02 17:46:53 -0700160 // Check the input compiler filter against the generated oat file's filter. May be overridden
Andreas Gampee1459ae2016-06-29 09:36:30 -0700161 // in subclasses when equality is not expected.
162 virtual void CheckFilter(CompilerFilter::Filter expected, CompilerFilter::Filter actual) {
163 EXPECT_EQ(expected, actual);
164 }
165
Andreas Gampef7882972017-03-20 16:35:24 -0700166 int Dex2Oat(const std::vector<std::string>& dex2oat_args, std::string* error_msg) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700167 Runtime* runtime = Runtime::Current();
168
169 const std::vector<gc::space::ImageSpace*>& image_spaces =
170 runtime->GetHeap()->GetBootImageSpaces();
171 if (image_spaces.empty()) {
172 *error_msg = "No image location found for Dex2Oat.";
173 return false;
174 }
175 std::string image_location = image_spaces[0]->GetImageLocation();
176
177 std::vector<std::string> argv;
178 argv.push_back(runtime->GetCompilerExecutable());
Calin Juravle1ccf6132017-08-02 17:46:53 -0700179
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000180 if (runtime->IsJavaDebuggable()) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700181 argv.push_back("--debuggable");
182 }
183 runtime->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv);
184
185 if (!runtime->IsVerificationEnabled()) {
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100186 argv.push_back("--compiler-filter=assume-verified");
Andreas Gampee1459ae2016-06-29 09:36:30 -0700187 }
188
189 if (runtime->MustRelocateIfPossible()) {
190 argv.push_back("--runtime-arg");
191 argv.push_back("-Xrelocate");
192 } else {
193 argv.push_back("--runtime-arg");
194 argv.push_back("-Xnorelocate");
195 }
196
197 if (!kIsTargetBuild) {
198 argv.push_back("--host");
199 }
200
201 argv.push_back("--boot-image=" + image_location);
202
203 std::vector<std::string> compiler_options = runtime->GetCompilerOptions();
204 argv.insert(argv.end(), compiler_options.begin(), compiler_options.end());
205
206 argv.insert(argv.end(), dex2oat_args.begin(), dex2oat_args.end());
207
208 // We must set --android-root.
209 const char* android_root = getenv("ANDROID_ROOT");
210 CHECK(android_root != nullptr);
211 argv.push_back("--android-root=" + std::string(android_root));
212
Mathieu Chartier9e050df2017-08-09 10:05:47 -0700213 if (kDebugArgs) {
214 std::string all_args;
215 for (const std::string& arg : argv) {
216 all_args += arg + " ";
217 }
218 LOG(ERROR) << all_args;
219 }
220
Nicolas Geoffray56fe0f02016-06-30 15:07:46 +0100221 int link[2];
Andreas Gampee1459ae2016-06-29 09:36:30 -0700222
Nicolas Geoffray56fe0f02016-06-30 15:07:46 +0100223 if (pipe(link) == -1) {
224 return false;
225 }
Andreas Gampee1459ae2016-06-29 09:36:30 -0700226
Nicolas Geoffray56fe0f02016-06-30 15:07:46 +0100227 pid_t pid = fork();
228 if (pid == -1) {
229 return false;
230 }
Andreas Gampee1459ae2016-06-29 09:36:30 -0700231
Nicolas Geoffray56fe0f02016-06-30 15:07:46 +0100232 if (pid == 0) {
233 // We need dex2oat to actually log things.
234 setenv("ANDROID_LOG_TAGS", "*:d", 1);
235 dup2(link[1], STDERR_FILENO);
236 close(link[0]);
237 close(link[1]);
238 std::vector<const char*> c_args;
239 for (const std::string& str : argv) {
240 c_args.push_back(str.c_str());
Andreas Gampee1459ae2016-06-29 09:36:30 -0700241 }
Nicolas Geoffray56fe0f02016-06-30 15:07:46 +0100242 c_args.push_back(nullptr);
243 execv(c_args[0], const_cast<char* const*>(c_args.data()));
244 exit(1);
Andreas Gampef7882972017-03-20 16:35:24 -0700245 UNREACHABLE();
Nicolas Geoffray56fe0f02016-06-30 15:07:46 +0100246 } else {
247 close(link[1]);
248 char buffer[128];
249 memset(buffer, 0, 128);
250 ssize_t bytes_read = 0;
Andreas Gampee1459ae2016-06-29 09:36:30 -0700251
Nicolas Geoffray56fe0f02016-06-30 15:07:46 +0100252 while (TEMP_FAILURE_RETRY(bytes_read = read(link[0], buffer, 128)) > 0) {
253 output_ += std::string(buffer, bytes_read);
254 }
255 close(link[0]);
Andreas Gampef7882972017-03-20 16:35:24 -0700256 int status = -1;
Nicolas Geoffray56fe0f02016-06-30 15:07:46 +0100257 if (waitpid(pid, &status, 0) != -1) {
258 success_ = (status == 0);
259 }
Andreas Gampef7882972017-03-20 16:35:24 -0700260 return status;
Andreas Gampee1459ae2016-06-29 09:36:30 -0700261 }
Andreas Gampee1459ae2016-06-29 09:36:30 -0700262 }
263
264 std::string output_ = "";
265 std::string error_msg_ = "";
266 bool success_ = false;
267};
268
269class Dex2oatSwapTest : public Dex2oatTest {
270 protected:
271 void RunTest(bool use_fd, bool expect_use, const std::vector<std::string>& extra_args = {}) {
272 std::string dex_location = GetScratchDir() + "/Dex2OatSwapTest.jar";
273 std::string odex_location = GetOdexDir() + "/Dex2OatSwapTest.odex";
274
Andreas Gampe7adeda82016-07-25 08:27:35 -0700275 Copy(GetTestDexFileName(), dex_location);
Andreas Gampee1459ae2016-06-29 09:36:30 -0700276
277 std::vector<std::string> copy(extra_args);
278
279 std::unique_ptr<ScratchFile> sf;
280 if (use_fd) {
281 sf.reset(new ScratchFile());
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800282 copy.push_back(android::base::StringPrintf("--swap-fd=%d", sf->GetFd()));
Andreas Gampee1459ae2016-06-29 09:36:30 -0700283 } else {
284 std::string swap_location = GetOdexDir() + "/Dex2OatSwapTest.odex.swap";
285 copy.push_back("--swap-file=" + swap_location);
286 }
287 GenerateOdexForTest(dex_location, odex_location, CompilerFilter::kSpeed, copy);
288
289 CheckValidity();
290 ASSERT_TRUE(success_);
291 CheckResult(expect_use);
292 }
293
Andreas Gampe7adeda82016-07-25 08:27:35 -0700294 virtual std::string GetTestDexFileName() {
Vladimir Marko15357702017-02-09 10:37:31 +0000295 return Dex2oatEnvironmentTest::GetTestDexFileName("VerifierDeps");
Andreas Gampe7adeda82016-07-25 08:27:35 -0700296 }
297
298 virtual void CheckResult(bool expect_use) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700299 if (kIsTargetBuild) {
300 CheckTargetResult(expect_use);
301 } else {
302 CheckHostResult(expect_use);
303 }
304 }
305
Andreas Gampe7adeda82016-07-25 08:27:35 -0700306 virtual void CheckTargetResult(bool expect_use ATTRIBUTE_UNUSED) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700307 // TODO: Ignore for now, as we won't capture any output (it goes to the logcat). We may do
308 // something for variants with file descriptor where we can control the lifetime of
309 // the swap file and thus take a look at it.
310 }
311
Andreas Gampe7adeda82016-07-25 08:27:35 -0700312 virtual void CheckHostResult(bool expect_use) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700313 if (!kIsTargetBuild) {
314 if (expect_use) {
315 EXPECT_NE(output_.find("Large app, accepted running with swap."), std::string::npos)
316 << output_;
317 } else {
318 EXPECT_EQ(output_.find("Large app, accepted running with swap."), std::string::npos)
319 << output_;
320 }
321 }
322 }
323
324 // Check whether the dex2oat run was really successful.
Andreas Gampe7adeda82016-07-25 08:27:35 -0700325 virtual void CheckValidity() {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700326 if (kIsTargetBuild) {
327 CheckTargetValidity();
328 } else {
329 CheckHostValidity();
330 }
331 }
332
Andreas Gampe7adeda82016-07-25 08:27:35 -0700333 virtual void CheckTargetValidity() {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700334 // TODO: Ignore for now, as we won't capture any output (it goes to the logcat). We may do
335 // something for variants with file descriptor where we can control the lifetime of
336 // the swap file and thus take a look at it.
337 }
338
339 // On the host, we can get the dex2oat output. Here, look for "dex2oat took."
Andreas Gampe7adeda82016-07-25 08:27:35 -0700340 virtual void CheckHostValidity() {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700341 EXPECT_NE(output_.find("dex2oat took"), std::string::npos) << output_;
342 }
343};
344
345TEST_F(Dex2oatSwapTest, DoNotUseSwapDefaultSingleSmall) {
346 RunTest(false /* use_fd */, false /* expect_use */);
347 RunTest(true /* use_fd */, false /* expect_use */);
348}
349
350TEST_F(Dex2oatSwapTest, DoNotUseSwapSingle) {
351 RunTest(false /* use_fd */, false /* expect_use */, { "--swap-dex-size-threshold=0" });
352 RunTest(true /* use_fd */, false /* expect_use */, { "--swap-dex-size-threshold=0" });
353}
354
355TEST_F(Dex2oatSwapTest, DoNotUseSwapSmall) {
356 RunTest(false /* use_fd */, false /* expect_use */, { "--swap-dex-count-threshold=0" });
357 RunTest(true /* use_fd */, false /* expect_use */, { "--swap-dex-count-threshold=0" });
358}
359
360TEST_F(Dex2oatSwapTest, DoUseSwapSingleSmall) {
361 RunTest(false /* use_fd */,
362 true /* expect_use */,
363 { "--swap-dex-size-threshold=0", "--swap-dex-count-threshold=0" });
364 RunTest(true /* use_fd */,
365 true /* expect_use */,
366 { "--swap-dex-size-threshold=0", "--swap-dex-count-threshold=0" });
367}
368
Andreas Gampe7adeda82016-07-25 08:27:35 -0700369class Dex2oatSwapUseTest : public Dex2oatSwapTest {
370 protected:
371 void CheckHostResult(bool expect_use) OVERRIDE {
372 if (!kIsTargetBuild) {
373 if (expect_use) {
374 EXPECT_NE(output_.find("Large app, accepted running with swap."), std::string::npos)
375 << output_;
376 } else {
377 EXPECT_EQ(output_.find("Large app, accepted running with swap."), std::string::npos)
378 << output_;
379 }
380 }
381 }
382
383 std::string GetTestDexFileName() OVERRIDE {
384 // Use Statics as it has a handful of functions.
385 return CommonRuntimeTest::GetTestDexFileName("Statics");
386 }
387
388 void GrabResult1() {
389 if (!kIsTargetBuild) {
390 native_alloc_1_ = ParseNativeAlloc();
391 swap_1_ = ParseSwap(false /* expected */);
392 } else {
393 native_alloc_1_ = std::numeric_limits<size_t>::max();
394 swap_1_ = 0;
395 }
396 }
397
398 void GrabResult2() {
399 if (!kIsTargetBuild) {
400 native_alloc_2_ = ParseNativeAlloc();
401 swap_2_ = ParseSwap(true /* expected */);
402 } else {
403 native_alloc_2_ = 0;
404 swap_2_ = std::numeric_limits<size_t>::max();
405 }
406 }
407
408 private:
409 size_t ParseNativeAlloc() {
410 std::regex native_alloc_regex("dex2oat took.*native alloc=[^ ]+ \\(([0-9]+)B\\)");
411 std::smatch native_alloc_match;
412 bool found = std::regex_search(output_, native_alloc_match, native_alloc_regex);
413 if (!found) {
414 EXPECT_TRUE(found);
415 return 0;
416 }
417 if (native_alloc_match.size() != 2U) {
418 EXPECT_EQ(native_alloc_match.size(), 2U);
419 return 0;
420 }
421
422 std::istringstream stream(native_alloc_match[1].str());
423 size_t value;
424 stream >> value;
425
426 return value;
427 }
428
429 size_t ParseSwap(bool expected) {
430 std::regex swap_regex("dex2oat took[^\\n]+swap=[^ ]+ \\(([0-9]+)B\\)");
431 std::smatch swap_match;
432 bool found = std::regex_search(output_, swap_match, swap_regex);
433 if (found != expected) {
434 EXPECT_EQ(expected, found);
435 return 0;
436 }
437
438 if (!found) {
439 return 0;
440 }
441
442 if (swap_match.size() != 2U) {
443 EXPECT_EQ(swap_match.size(), 2U);
444 return 0;
445 }
446
447 std::istringstream stream(swap_match[1].str());
448 size_t value;
449 stream >> value;
450
451 return value;
452 }
453
454 protected:
455 size_t native_alloc_1_;
456 size_t native_alloc_2_;
457
458 size_t swap_1_;
459 size_t swap_2_;
460};
461
462TEST_F(Dex2oatSwapUseTest, CheckSwapUsage) {
Andreas Gampef4a67fd2017-05-04 09:55:36 -0700463 // Native memory usage isn't correctly tracked under sanitization.
464 TEST_DISABLED_FOR_MEMORY_TOOL_ASAN();
465
Vladimir Marko57070da2017-02-14 16:16:30 +0000466 // The `native_alloc_2_ >= native_alloc_1_` assertion below may not
Roland Levillain19772bf2017-02-16 11:28:10 +0000467 // hold true on some x86 systems; disable this test while we
468 // investigate (b/29259363).
469 TEST_DISABLED_FOR_X86();
Vladimir Marko57070da2017-02-14 16:16:30 +0000470
Andreas Gampe7adeda82016-07-25 08:27:35 -0700471 RunTest(false /* use_fd */,
472 false /* expect_use */);
473 GrabResult1();
474 std::string output_1 = output_;
475
476 output_ = "";
477
478 RunTest(false /* use_fd */,
479 true /* expect_use */,
480 { "--swap-dex-size-threshold=0", "--swap-dex-count-threshold=0" });
481 GrabResult2();
482 std::string output_2 = output_;
483
484 if (native_alloc_2_ >= native_alloc_1_ || swap_1_ >= swap_2_) {
485 EXPECT_LT(native_alloc_2_, native_alloc_1_);
486 EXPECT_LT(swap_1_, swap_2_);
487
488 LOG(ERROR) << output_1;
489 LOG(ERROR) << output_2;
490 }
491}
492
Andreas Gampe67f02822016-06-24 21:05:23 -0700493class Dex2oatVeryLargeTest : public Dex2oatTest {
494 protected:
495 void CheckFilter(CompilerFilter::Filter input ATTRIBUTE_UNUSED,
496 CompilerFilter::Filter result ATTRIBUTE_UNUSED) OVERRIDE {
497 // Ignore, we'll do our own checks.
498 }
499
500 void RunTest(CompilerFilter::Filter filter,
501 bool expect_large,
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700502 bool expect_downgrade,
Andreas Gampe67f02822016-06-24 21:05:23 -0700503 const std::vector<std::string>& extra_args = {}) {
504 std::string dex_location = GetScratchDir() + "/DexNoOat.jar";
505 std::string odex_location = GetOdexDir() + "/DexOdexNoOat.odex";
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700506 std::string app_image_file = GetScratchDir() + "/Test.art";
Andreas Gampe67f02822016-06-24 21:05:23 -0700507
508 Copy(GetDexSrc1(), dex_location);
509
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700510 std::vector<std::string> new_args(extra_args);
511 new_args.push_back("--app-image-file=" + app_image_file);
512 GenerateOdexForTest(dex_location, odex_location, filter, new_args);
Andreas Gampe67f02822016-06-24 21:05:23 -0700513
514 CheckValidity();
515 ASSERT_TRUE(success_);
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700516 CheckResult(dex_location,
517 odex_location,
518 app_image_file,
519 filter,
520 expect_large,
521 expect_downgrade);
Andreas Gampe67f02822016-06-24 21:05:23 -0700522 }
523
524 void CheckResult(const std::string& dex_location,
525 const std::string& odex_location,
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700526 const std::string& app_image_file,
Andreas Gampe67f02822016-06-24 21:05:23 -0700527 CompilerFilter::Filter filter,
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700528 bool expect_large,
529 bool expect_downgrade) {
530 if (expect_downgrade) {
531 EXPECT_TRUE(expect_large);
532 }
Andreas Gampe67f02822016-06-24 21:05:23 -0700533 // Host/target independent checks.
534 std::string error_msg;
535 std::unique_ptr<OatFile> odex_file(OatFile::Open(odex_location.c_str(),
536 odex_location.c_str(),
537 nullptr,
538 nullptr,
539 false,
540 /*low_4gb*/false,
541 dex_location.c_str(),
542 &error_msg));
543 ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700544 EXPECT_GT(app_image_file.length(), 0u);
545 std::unique_ptr<File> file(OS::OpenFileForReading(app_image_file.c_str()));
Andreas Gampe67f02822016-06-24 21:05:23 -0700546 if (expect_large) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700547 // Note: we cannot check the following
548 // EXPECT_FALSE(CompilerFilter::IsAotCompilationEnabled(odex_file->GetCompilerFilter()));
Andreas Gampe67f02822016-06-24 21:05:23 -0700549 // The reason is that the filter override currently happens when the dex files are
550 // loaded in dex2oat, which is after the oat file has been started. Thus, the header
551 // store cannot be changed, and the original filter is set in stone.
552
553 for (const OatDexFile* oat_dex_file : odex_file->GetOatDexFiles()) {
554 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
555 ASSERT_TRUE(dex_file != nullptr);
556 uint32_t class_def_count = dex_file->NumClassDefs();
557 ASSERT_LT(class_def_count, std::numeric_limits<uint16_t>::max());
558 for (uint16_t class_def_index = 0; class_def_index < class_def_count; ++class_def_index) {
559 OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
560 EXPECT_EQ(oat_class.GetType(), OatClassType::kOatClassNoneCompiled);
561 }
562 }
563
564 // If the input filter was "below," it should have been used.
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100565 if (!CompilerFilter::IsAsGoodAs(CompilerFilter::kExtract, filter)) {
Andreas Gampe67f02822016-06-24 21:05:23 -0700566 EXPECT_EQ(odex_file->GetCompilerFilter(), filter);
567 }
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700568
569 // If expect large, make sure the app image isn't generated or is empty.
570 if (file != nullptr) {
571 EXPECT_EQ(file->GetLength(), 0u);
572 }
Andreas Gampe67f02822016-06-24 21:05:23 -0700573 } else {
574 EXPECT_EQ(odex_file->GetCompilerFilter(), filter);
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700575 ASSERT_TRUE(file != nullptr) << app_image_file;
576 EXPECT_GT(file->GetLength(), 0u);
Andreas Gampe67f02822016-06-24 21:05:23 -0700577 }
578
579 // Host/target dependent checks.
580 if (kIsTargetBuild) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700581 CheckTargetResult(expect_downgrade);
Andreas Gampe67f02822016-06-24 21:05:23 -0700582 } else {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700583 CheckHostResult(expect_downgrade);
Andreas Gampe67f02822016-06-24 21:05:23 -0700584 }
585 }
586
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700587 void CheckTargetResult(bool expect_downgrade ATTRIBUTE_UNUSED) {
Andreas Gampe67f02822016-06-24 21:05:23 -0700588 // TODO: Ignore for now. May do something for fd things.
589 }
590
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700591 void CheckHostResult(bool expect_downgrade) {
Andreas Gampe67f02822016-06-24 21:05:23 -0700592 if (!kIsTargetBuild) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700593 if (expect_downgrade) {
594 EXPECT_NE(output_.find("Very large app, downgrading to"), std::string::npos) << output_;
Andreas Gampe67f02822016-06-24 21:05:23 -0700595 } else {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700596 EXPECT_EQ(output_.find("Very large app, downgrading to"), std::string::npos) << output_;
Andreas Gampe67f02822016-06-24 21:05:23 -0700597 }
598 }
599 }
600
601 // Check whether the dex2oat run was really successful.
602 void CheckValidity() {
603 if (kIsTargetBuild) {
604 CheckTargetValidity();
605 } else {
606 CheckHostValidity();
607 }
608 }
609
610 void CheckTargetValidity() {
611 // TODO: Ignore for now.
612 }
613
614 // On the host, we can get the dex2oat output. Here, look for "dex2oat took."
615 void CheckHostValidity() {
616 EXPECT_NE(output_.find("dex2oat took"), std::string::npos) << output_;
617 }
618};
619
620TEST_F(Dex2oatVeryLargeTest, DontUseVeryLarge) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700621 RunTest(CompilerFilter::kAssumeVerified, false, false);
622 RunTest(CompilerFilter::kExtract, false, false);
623 RunTest(CompilerFilter::kQuicken, false, false);
624 RunTest(CompilerFilter::kSpeed, false, false);
Andreas Gampe67f02822016-06-24 21:05:23 -0700625
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700626 RunTest(CompilerFilter::kAssumeVerified, false, false, { "--very-large-app-threshold=10000000" });
627 RunTest(CompilerFilter::kExtract, false, false, { "--very-large-app-threshold=10000000" });
628 RunTest(CompilerFilter::kQuicken, false, false, { "--very-large-app-threshold=10000000" });
629 RunTest(CompilerFilter::kSpeed, false, false, { "--very-large-app-threshold=10000000" });
Andreas Gampe67f02822016-06-24 21:05:23 -0700630}
631
632TEST_F(Dex2oatVeryLargeTest, UseVeryLarge) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700633 RunTest(CompilerFilter::kAssumeVerified, true, false, { "--very-large-app-threshold=100" });
634 RunTest(CompilerFilter::kExtract, true, false, { "--very-large-app-threshold=100" });
635 RunTest(CompilerFilter::kQuicken, true, true, { "--very-large-app-threshold=100" });
636 RunTest(CompilerFilter::kSpeed, true, true, { "--very-large-app-threshold=100" });
Andreas Gampe67f02822016-06-24 21:05:23 -0700637}
638
Mathieu Chartier97ab5e32017-02-22 13:35:44 -0800639// Regressin test for b/35665292.
640TEST_F(Dex2oatVeryLargeTest, SpeedProfileNoProfile) {
641 // Test that dex2oat doesn't crash with speed-profile but no input profile.
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700642 RunTest(CompilerFilter::kSpeedProfile, false, false);
Mathieu Chartier97ab5e32017-02-22 13:35:44 -0800643}
644
Jeff Hao608f2ce2016-10-19 11:17:11 -0700645class Dex2oatLayoutTest : public Dex2oatTest {
646 protected:
647 void CheckFilter(CompilerFilter::Filter input ATTRIBUTE_UNUSED,
648 CompilerFilter::Filter result ATTRIBUTE_UNUSED) OVERRIDE {
649 // Ignore, we'll do our own checks.
650 }
651
Jeff Hao41fba6a2016-11-28 11:53:33 -0800652 // Emits a profile with a single dex file with the given location and a single class index of 1.
653 void GenerateProfile(const std::string& test_profile,
654 const std::string& dex_location,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800655 size_t num_classes,
Jeff Hao41fba6a2016-11-28 11:53:33 -0800656 uint32_t checksum) {
657 int profile_test_fd = open(test_profile.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644);
658 CHECK_GE(profile_test_fd, 0);
659
660 ProfileCompilationInfo info;
661 std::string profile_key = ProfileCompilationInfo::GetProfileDexFileKey(dex_location);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800662 for (size_t i = 0; i < num_classes; ++i) {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700663 info.AddClassIndex(profile_key, checksum, dex::TypeIndex(1 + i), kMaxMethodIds);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800664 }
Jeff Hao41fba6a2016-11-28 11:53:33 -0800665 bool result = info.Save(profile_test_fd);
666 close(profile_test_fd);
667 ASSERT_TRUE(result);
668 }
669
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800670 void CompileProfileOdex(const std::string& dex_location,
671 const std::string& odex_location,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800672 const std::string& app_image_file_name,
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800673 bool use_fd,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800674 size_t num_profile_classes,
Nicolas Geoffray97fa9922017-03-09 13:13:25 +0000675 const std::vector<std::string>& extra_args = {},
676 bool expect_success = true) {
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800677 const std::string profile_location = GetScratchDir() + "/primary.prof";
Jeff Hao41fba6a2016-11-28 11:53:33 -0800678 const char* location = dex_location.c_str();
679 std::string error_msg;
680 std::vector<std::unique_ptr<const DexFile>> dex_files;
Nicolas Geoffray095c6c92017-10-19 13:59:55 +0100681 ASSERT_TRUE(DexFileLoader::Open(
682 location, location, /* verify */ true, /* verify_checksum */ true, &error_msg, &dex_files));
Jeff Hao41fba6a2016-11-28 11:53:33 -0800683 EXPECT_EQ(dex_files.size(), 1U);
684 std::unique_ptr<const DexFile>& dex_file = dex_files[0];
Mathieu Chartier046854b2017-03-01 17:16:22 -0800685 GenerateProfile(profile_location,
686 dex_location,
687 num_profile_classes,
688 dex_file->GetLocationChecksum());
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800689 std::vector<std::string> copy(extra_args);
690 copy.push_back("--profile-file=" + profile_location);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800691 std::unique_ptr<File> app_image_file;
692 if (!app_image_file_name.empty()) {
693 if (use_fd) {
694 app_image_file.reset(OS::CreateEmptyFile(app_image_file_name.c_str()));
695 copy.push_back("--app-image-fd=" + std::to_string(app_image_file->Fd()));
696 } else {
697 copy.push_back("--app-image-file=" + app_image_file_name);
698 }
699 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800700 GenerateOdexForTest(dex_location,
701 odex_location,
702 CompilerFilter::kSpeedProfile,
703 copy,
Nicolas Geoffray97fa9922017-03-09 13:13:25 +0000704 expect_success,
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800705 use_fd);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800706 if (app_image_file != nullptr) {
707 ASSERT_EQ(app_image_file->FlushCloseOrErase(), 0) << "Could not flush and close art file";
708 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800709 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700710
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100711 uint64_t GetImageObjectSectionSize(const std::string& image_file_name) {
Mathieu Chartier046854b2017-03-01 17:16:22 -0800712 EXPECT_FALSE(image_file_name.empty());
713 std::unique_ptr<File> file(OS::OpenFileForReading(image_file_name.c_str()));
714 CHECK(file != nullptr);
715 ImageHeader image_header;
716 const bool success = file->ReadFully(&image_header, sizeof(image_header));
717 CHECK(success);
718 CHECK(image_header.IsValid());
719 ReaderMutexLock mu(Thread::Current(), *Locks::mutator_lock_);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100720 return image_header.GetObjectsSection().Size();
Mathieu Chartier046854b2017-03-01 17:16:22 -0800721 }
722
723 void RunTest(bool app_image) {
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800724 std::string dex_location = GetScratchDir() + "/DexNoOat.jar";
725 std::string odex_location = GetOdexDir() + "/DexOdexNoOat.odex";
Mathieu Chartier046854b2017-03-01 17:16:22 -0800726 std::string app_image_file = app_image ? (GetOdexDir() + "/DexOdexNoOat.art"): "";
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800727 Copy(GetDexSrc2(), dex_location);
728
Mathieu Chartier046854b2017-03-01 17:16:22 -0800729 uint64_t image_file_empty_profile = 0;
730 if (app_image) {
731 CompileProfileOdex(dex_location,
732 odex_location,
733 app_image_file,
734 /* use_fd */ false,
735 /* num_profile_classes */ 0);
736 CheckValidity();
737 ASSERT_TRUE(success_);
738 // Don't check the result since CheckResult relies on the class being in the profile.
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100739 image_file_empty_profile = GetImageObjectSectionSize(app_image_file);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800740 EXPECT_GT(image_file_empty_profile, 0u);
741 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700742
Mathieu Chartier046854b2017-03-01 17:16:22 -0800743 // Small profile.
744 CompileProfileOdex(dex_location,
745 odex_location,
746 app_image_file,
747 /* use_fd */ false,
748 /* num_profile_classes */ 1);
Jeff Hao608f2ce2016-10-19 11:17:11 -0700749 CheckValidity();
750 ASSERT_TRUE(success_);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800751 CheckResult(dex_location, odex_location, app_image_file);
752
753 if (app_image) {
754 // Test that the profile made a difference by adding more classes.
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100755 const uint64_t image_file_small_profile = GetImageObjectSectionSize(app_image_file);
756 ASSERT_LT(image_file_empty_profile, image_file_small_profile);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800757 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700758 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800759
760 void RunTestVDex() {
761 std::string dex_location = GetScratchDir() + "/DexNoOat.jar";
762 std::string odex_location = GetOdexDir() + "/DexOdexNoOat.odex";
763 std::string vdex_location = GetOdexDir() + "/DexOdexNoOat.vdex";
Mathieu Chartier046854b2017-03-01 17:16:22 -0800764 std::string app_image_file_name = GetOdexDir() + "/DexOdexNoOat.art";
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800765 Copy(GetDexSrc2(), dex_location);
766
767 std::unique_ptr<File> vdex_file1(OS::CreateEmptyFile(vdex_location.c_str()));
768 CHECK(vdex_file1 != nullptr) << vdex_location;
769 ScratchFile vdex_file2;
770 {
771 std::string input_vdex = "--input-vdex-fd=-1";
772 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file1->Fd());
773 CompileProfileOdex(dex_location,
774 odex_location,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800775 app_image_file_name,
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800776 /* use_fd */ true,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800777 /* num_profile_classes */ 1,
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800778 { input_vdex, output_vdex });
779 EXPECT_GT(vdex_file1->GetLength(), 0u);
780 }
781 {
Nicolas Geoffray97fa9922017-03-09 13:13:25 +0000782 // Test that vdex and dexlayout fail gracefully.
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800783 std::string input_vdex = StringPrintf("--input-vdex-fd=%d", vdex_file1->Fd());
784 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file2.GetFd());
785 CompileProfileOdex(dex_location,
786 odex_location,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800787 app_image_file_name,
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800788 /* use_fd */ true,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800789 /* num_profile_classes */ 1,
Nicolas Geoffray97fa9922017-03-09 13:13:25 +0000790 { input_vdex, output_vdex },
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +0100791 /* expect_success */ true);
792 EXPECT_GT(vdex_file2.GetFile()->GetLength(), 0u);
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800793 }
794 ASSERT_EQ(vdex_file1->FlushCloseOrErase(), 0) << "Could not flush and close vdex file";
795 CheckValidity();
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +0100796 ASSERT_TRUE(success_);
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800797 }
798
Mathieu Chartier046854b2017-03-01 17:16:22 -0800799 void CheckResult(const std::string& dex_location,
800 const std::string& odex_location,
801 const std::string& app_image_file_name) {
Jeff Hao608f2ce2016-10-19 11:17:11 -0700802 // Host/target independent checks.
803 std::string error_msg;
804 std::unique_ptr<OatFile> odex_file(OatFile::Open(odex_location.c_str(),
805 odex_location.c_str(),
806 nullptr,
807 nullptr,
808 false,
809 /*low_4gb*/false,
810 dex_location.c_str(),
811 &error_msg));
812 ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
813
Jeff Hao042e8982016-10-19 11:17:11 -0700814 const char* location = dex_location.c_str();
815 std::vector<std::unique_ptr<const DexFile>> dex_files;
Nicolas Geoffray095c6c92017-10-19 13:59:55 +0100816 ASSERT_TRUE(DexFileLoader::Open(
817 location, location, /* verify */ true, /* verify_checksum */ true, &error_msg, &dex_files));
Jeff Hao042e8982016-10-19 11:17:11 -0700818 EXPECT_EQ(dex_files.size(), 1U);
819 std::unique_ptr<const DexFile>& old_dex_file = dex_files[0];
820
Jeff Hao608f2ce2016-10-19 11:17:11 -0700821 for (const OatDexFile* oat_dex_file : odex_file->GetOatDexFiles()) {
Jeff Hao042e8982016-10-19 11:17:11 -0700822 std::unique_ptr<const DexFile> new_dex_file = oat_dex_file->OpenDexFile(&error_msg);
823 ASSERT_TRUE(new_dex_file != nullptr);
824 uint32_t class_def_count = new_dex_file->NumClassDefs();
Jeff Hao608f2ce2016-10-19 11:17:11 -0700825 ASSERT_LT(class_def_count, std::numeric_limits<uint16_t>::max());
Jeff Hao042e8982016-10-19 11:17:11 -0700826 ASSERT_GE(class_def_count, 2U);
827
828 // The new layout swaps the classes at indexes 0 and 1.
829 std::string old_class0 = old_dex_file->PrettyType(old_dex_file->GetClassDef(0).class_idx_);
830 std::string old_class1 = old_dex_file->PrettyType(old_dex_file->GetClassDef(1).class_idx_);
831 std::string new_class0 = new_dex_file->PrettyType(new_dex_file->GetClassDef(0).class_idx_);
832 std::string new_class1 = new_dex_file->PrettyType(new_dex_file->GetClassDef(1).class_idx_);
833 EXPECT_EQ(old_class0, new_class1);
834 EXPECT_EQ(old_class1, new_class0);
Jeff Hao608f2ce2016-10-19 11:17:11 -0700835 }
836
Jeff Haoc155b052017-01-17 17:43:29 -0800837 EXPECT_EQ(odex_file->GetCompilerFilter(), CompilerFilter::kSpeedProfile);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800838
839 if (!app_image_file_name.empty()) {
840 // Go peek at the image header to make sure it was large enough to contain the class.
841 std::unique_ptr<File> file(OS::OpenFileForReading(app_image_file_name.c_str()));
842 ImageHeader image_header;
843 bool success = file->ReadFully(&image_header, sizeof(image_header));
844 ASSERT_TRUE(success);
845 ASSERT_TRUE(image_header.IsValid());
Vladimir Markocd87c3e2017-09-05 13:11:57 +0100846 EXPECT_GT(image_header.GetObjectsSection().Size(), 0u);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800847 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700848 }
849
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800850 // Check whether the dex2oat run was really successful.
851 void CheckValidity() {
852 if (kIsTargetBuild) {
853 CheckTargetValidity();
854 } else {
855 CheckHostValidity();
Jeff Hao608f2ce2016-10-19 11:17:11 -0700856 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800857 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700858
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800859 void CheckTargetValidity() {
860 // TODO: Ignore for now.
861 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700862
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800863 // On the host, we can get the dex2oat output. Here, look for "dex2oat took."
864 void CheckHostValidity() {
865 EXPECT_NE(output_.find("dex2oat took"), std::string::npos) << output_;
866 }
867};
Jeff Hao608f2ce2016-10-19 11:17:11 -0700868
869TEST_F(Dex2oatLayoutTest, TestLayout) {
Mathieu Chartier046854b2017-03-01 17:16:22 -0800870 RunTest(/* app-image */ false);
871}
872
873TEST_F(Dex2oatLayoutTest, TestLayoutAppImage) {
874 RunTest(/* app-image */ true);
Jeff Hao608f2ce2016-10-19 11:17:11 -0700875}
876
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800877TEST_F(Dex2oatLayoutTest, TestVdexLayout) {
878 RunTestVDex();
879}
880
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100881class Dex2oatUnquickenTest : public Dex2oatTest {
882 protected:
883 void RunUnquickenMultiDex() {
884 std::string dex_location = GetScratchDir() + "/UnquickenMultiDex.jar";
885 std::string odex_location = GetOdexDir() + "/UnquickenMultiDex.odex";
886 std::string vdex_location = GetOdexDir() + "/UnquickenMultiDex.vdex";
887 Copy(GetTestDexFileName("MultiDex"), dex_location);
888
889 std::unique_ptr<File> vdex_file1(OS::CreateEmptyFile(vdex_location.c_str()));
890 CHECK(vdex_file1 != nullptr) << vdex_location;
891 // Quicken the dex file into a vdex file.
892 {
893 std::string input_vdex = "--input-vdex-fd=-1";
894 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file1->Fd());
895 GenerateOdexForTest(dex_location,
896 odex_location,
897 CompilerFilter::kQuicken,
898 { input_vdex, output_vdex },
899 /* expect_success */ true,
900 /* use_fd */ true);
901 EXPECT_GT(vdex_file1->GetLength(), 0u);
902 }
903 // Unquicken by running the verify compiler filter on the vdex file.
904 {
905 std::string input_vdex = StringPrintf("--input-vdex-fd=%d", vdex_file1->Fd());
906 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file1->Fd());
907 GenerateOdexForTest(dex_location,
908 odex_location,
909 CompilerFilter::kVerify,
910 { input_vdex, output_vdex },
911 /* expect_success */ true,
912 /* use_fd */ true);
913 }
914 ASSERT_EQ(vdex_file1->FlushCloseOrErase(), 0) << "Could not flush and close vdex file";
915 CheckResult(dex_location, odex_location);
916 ASSERT_TRUE(success_);
917 }
918
919 void CheckResult(const std::string& dex_location, const std::string& odex_location) {
920 std::string error_msg;
921 std::unique_ptr<OatFile> odex_file(OatFile::Open(odex_location.c_str(),
922 odex_location.c_str(),
923 nullptr,
924 nullptr,
925 false,
926 /*low_4gb*/false,
927 dex_location.c_str(),
928 &error_msg));
929 ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
930 ASSERT_GE(odex_file->GetOatDexFiles().size(), 1u);
931
932 // Iterate over the dex files and ensure there is no quickened instruction.
933 for (const OatDexFile* oat_dex_file : odex_file->GetOatDexFiles()) {
934 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
935 for (uint32_t i = 0; i < dex_file->NumClassDefs(); ++i) {
936 const DexFile::ClassDef& class_def = dex_file->GetClassDef(i);
937 const uint8_t* class_data = dex_file->GetClassData(class_def);
938 if (class_data != nullptr) {
939 for (ClassDataItemIterator class_it(*dex_file, class_data);
940 class_it.HasNext();
941 class_it.Next()) {
942 if (class_it.IsAtMethod() && class_it.GetMethodCodeItem() != nullptr) {
943 for (CodeItemIterator it(*class_it.GetMethodCodeItem()); !it.Done(); it.Advance()) {
944 Instruction* inst = const_cast<Instruction*>(&it.CurrentInstruction());
945 ASSERT_FALSE(inst->IsQuickened());
946 }
947 }
948 }
949 }
950 }
951 }
952 }
953};
954
955TEST_F(Dex2oatUnquickenTest, UnquickenMultiDex) {
956 RunUnquickenMultiDex();
957}
958
Andreas Gampe2e8a2562017-01-18 20:39:02 -0800959class Dex2oatWatchdogTest : public Dex2oatTest {
960 protected:
961 void RunTest(bool expect_success, const std::vector<std::string>& extra_args = {}) {
962 std::string dex_location = GetScratchDir() + "/Dex2OatSwapTest.jar";
963 std::string odex_location = GetOdexDir() + "/Dex2OatSwapTest.odex";
964
965 Copy(GetTestDexFileName(), dex_location);
966
967 std::vector<std::string> copy(extra_args);
968
969 std::string swap_location = GetOdexDir() + "/Dex2OatSwapTest.odex.swap";
970 copy.push_back("--swap-file=" + swap_location);
Andreas Gampe22fa3762017-10-23 20:58:12 -0700971 copy.push_back("-j512"); // Excessive idle threads just slow down dex2oat.
Andreas Gampe2e8a2562017-01-18 20:39:02 -0800972 GenerateOdexForTest(dex_location,
973 odex_location,
974 CompilerFilter::kSpeed,
975 copy,
976 expect_success);
977 }
978
979 std::string GetTestDexFileName() {
980 return GetDexSrc1();
981 }
982};
983
984TEST_F(Dex2oatWatchdogTest, TestWatchdogOK) {
985 // Check with default.
986 RunTest(true);
987
988 // Check with ten minutes.
989 RunTest(true, { "--watchdog-timeout=600000" });
990}
991
992TEST_F(Dex2oatWatchdogTest, TestWatchdogTrigger) {
Roland Levillain68db2252017-08-14 12:48:47 +0100993 TEST_DISABLED_FOR_MEMORY_TOOL_VALGRIND(); // b/63052624
Andreas Gampe2e8a2562017-01-18 20:39:02 -0800994 // Check with ten milliseconds.
995 RunTest(false, { "--watchdog-timeout=10" });
996}
997
Andreas Gampef7882972017-03-20 16:35:24 -0700998class Dex2oatReturnCodeTest : public Dex2oatTest {
999 protected:
1000 int RunTest(const std::vector<std::string>& extra_args = {}) {
1001 std::string dex_location = GetScratchDir() + "/Dex2OatSwapTest.jar";
1002 std::string odex_location = GetOdexDir() + "/Dex2OatSwapTest.odex";
1003
1004 Copy(GetTestDexFileName(), dex_location);
1005
1006 std::string error_msg;
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001007 return GenerateOdexForTestWithStatus({dex_location},
Andreas Gampef7882972017-03-20 16:35:24 -07001008 odex_location,
1009 CompilerFilter::kSpeed,
1010 &error_msg,
1011 extra_args);
1012 }
1013
1014 std::string GetTestDexFileName() {
1015 return GetDexSrc1();
1016 }
1017};
1018
1019TEST_F(Dex2oatReturnCodeTest, TestCreateRuntime) {
Andreas Gampefd80b172017-04-26 22:25:31 -07001020 TEST_DISABLED_FOR_MEMORY_TOOL(); // b/19100793
Andreas Gampef7882972017-03-20 16:35:24 -07001021 int status = RunTest({ "--boot-image=/this/does/not/exist/yolo.oat" });
1022 EXPECT_EQ(static_cast<int>(dex2oat::ReturnCode::kCreateRuntime), WEXITSTATUS(status)) << output_;
1023}
1024
Calin Juravle1ce70852017-06-28 10:59:03 -07001025class Dex2oatClassLoaderContextTest : public Dex2oatTest {
1026 protected:
1027 void RunTest(const char* class_loader_context,
1028 const char* expected_classpath_key,
1029 bool expected_success,
1030 bool use_second_source = false) {
1031 std::string dex_location = GetUsedDexLocation();
1032 std::string odex_location = GetUsedOatLocation();
1033
1034 Copy(use_second_source ? GetDexSrc2() : GetDexSrc1(), dex_location);
1035
1036 std::string error_msg;
1037 std::vector<std::string> extra_args;
1038 if (class_loader_context != nullptr) {
1039 extra_args.push_back(std::string("--class-loader-context=") + class_loader_context);
1040 }
1041 auto check_oat = [expected_classpath_key](const OatFile& oat_file) {
1042 ASSERT_TRUE(expected_classpath_key != nullptr);
1043 const char* classpath = oat_file.GetOatHeader().GetStoreValueByKey(OatHeader::kClassPathKey);
1044 ASSERT_TRUE(classpath != nullptr);
1045 ASSERT_STREQ(expected_classpath_key, classpath);
1046 };
1047
1048 GenerateOdexForTest(dex_location,
1049 odex_location,
1050 CompilerFilter::kQuicken,
1051 extra_args,
1052 expected_success,
1053 /*use_fd*/ false,
1054 check_oat);
1055 }
1056
1057 std::string GetUsedDexLocation() {
1058 return GetScratchDir() + "/Context.jar";
1059 }
1060
1061 std::string GetUsedOatLocation() {
1062 return GetOdexDir() + "/Context.odex";
1063 }
1064
Calin Juravle7b0648a2017-07-07 18:40:50 -07001065 const char* kEmptyClassPathKey = "PCL[]";
Calin Juravle1ce70852017-06-28 10:59:03 -07001066};
1067
1068TEST_F(Dex2oatClassLoaderContextTest, InvalidContext) {
1069 RunTest("Invalid[]", /*expected_classpath_key*/ nullptr, /*expected_success*/ false);
1070}
1071
1072TEST_F(Dex2oatClassLoaderContextTest, EmptyContext) {
1073 RunTest("PCL[]", kEmptyClassPathKey, /*expected_success*/ true);
1074}
1075
1076TEST_F(Dex2oatClassLoaderContextTest, SpecialContext) {
1077 RunTest(OatFile::kSpecialSharedLibrary,
1078 OatFile::kSpecialSharedLibrary,
1079 /*expected_success*/ true);
1080}
1081
1082TEST_F(Dex2oatClassLoaderContextTest, ContextWithTheSourceDexFiles) {
1083 std::string context = "PCL[" + GetUsedDexLocation() + "]";
1084 RunTest(context.c_str(), kEmptyClassPathKey, /*expected_success*/ true);
1085}
1086
1087TEST_F(Dex2oatClassLoaderContextTest, ContextWithOtherDexFiles) {
1088 std::vector<std::unique_ptr<const DexFile>> dex_files = OpenTestDexFiles("Nested");
Calin Juravle1ce70852017-06-28 10:59:03 -07001089
1090 std::string context = "PCL[" + dex_files[0]->GetLocation() + "]";
Calin Juravle7b0648a2017-07-07 18:40:50 -07001091 std::string expected_classpath_key = "PCL[" +
1092 dex_files[0]->GetLocation() + "*" + std::to_string(dex_files[0]->GetLocationChecksum()) + "]";
Calin Juravle1ce70852017-06-28 10:59:03 -07001093 RunTest(context.c_str(), expected_classpath_key.c_str(), true);
1094}
1095
1096TEST_F(Dex2oatClassLoaderContextTest, ContextWithStrippedDexFiles) {
1097 std::string stripped_classpath = GetScratchDir() + "/stripped_classpath.jar";
1098 Copy(GetStrippedDexSrc1(), stripped_classpath);
1099
1100 std::string context = "PCL[" + stripped_classpath + "]";
1101 // Expect an empty context because stripped dex files cannot be open.
Calin Juravle7b0648a2017-07-07 18:40:50 -07001102 RunTest(context.c_str(), kEmptyClassPathKey , /*expected_success*/ true);
Calin Juravle1ce70852017-06-28 10:59:03 -07001103}
1104
1105TEST_F(Dex2oatClassLoaderContextTest, ContextWithStrippedDexFilesBackedByOdex) {
1106 std::string stripped_classpath = GetScratchDir() + "/stripped_classpath.jar";
1107 std::string odex_for_classpath = GetOdexDir() + "/stripped_classpath.odex";
1108
1109 Copy(GetDexSrc1(), stripped_classpath);
1110
1111 GenerateOdexForTest(stripped_classpath,
1112 odex_for_classpath,
1113 CompilerFilter::kQuicken,
1114 {},
1115 true);
1116
1117 // Strip the dex file
1118 Copy(GetStrippedDexSrc1(), stripped_classpath);
1119
1120 std::string context = "PCL[" + stripped_classpath + "]";
Calin Juravle7b0648a2017-07-07 18:40:50 -07001121 std::string expected_classpath_key;
Calin Juravle1ce70852017-06-28 10:59:03 -07001122 {
1123 // Open the oat file to get the expected classpath.
1124 OatFileAssistant oat_file_assistant(stripped_classpath.c_str(), kRuntimeISA, false);
1125 std::unique_ptr<OatFile> oat_file(oat_file_assistant.GetBestOatFile());
1126 std::vector<std::unique_ptr<const DexFile>> oat_dex_files =
1127 OatFileAssistant::LoadDexFiles(*oat_file, stripped_classpath.c_str());
Calin Juravle7b0648a2017-07-07 18:40:50 -07001128 expected_classpath_key = "PCL[";
1129 for (size_t i = 0; i < oat_dex_files.size(); i++) {
1130 if (i > 0) {
1131 expected_classpath_key + ":";
1132 }
1133 expected_classpath_key += oat_dex_files[i]->GetLocation() + "*" +
1134 std::to_string(oat_dex_files[i]->GetLocationChecksum());
1135 }
1136 expected_classpath_key += "]";
Calin Juravle1ce70852017-06-28 10:59:03 -07001137 }
1138
1139 RunTest(context.c_str(),
Calin Juravle7b0648a2017-07-07 18:40:50 -07001140 expected_classpath_key.c_str(),
Calin Juravle1ce70852017-06-28 10:59:03 -07001141 /*expected_success*/ true,
1142 /*use_second_source*/ true);
1143}
1144
1145TEST_F(Dex2oatClassLoaderContextTest, ContextWithNotExistentDexFiles) {
1146 std::string context = "PCL[does_not_exists.dex]";
1147 // Expect an empty context because stripped dex files cannot be open.
1148 RunTest(context.c_str(), kEmptyClassPathKey, /*expected_success*/ true);
1149}
1150
Calin Juravlec79470d2017-07-12 17:37:42 -07001151TEST_F(Dex2oatClassLoaderContextTest, ChainContext) {
1152 std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested");
1153 std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex");
1154
1155 std::string context = "PCL[" + GetTestDexFileName("Nested") + "];" +
1156 "DLC[" + GetTestDexFileName("MultiDex") + "]";
1157 std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "];" +
1158 "DLC[" + CreateClassPathWithChecksums(dex_files2) + "]";
1159
1160 RunTest(context.c_str(), expected_classpath_key.c_str(), true);
1161}
1162
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001163class Dex2oatDeterminism : public Dex2oatTest {};
1164
1165TEST_F(Dex2oatDeterminism, UnloadCompile) {
1166 if (!kUseReadBarrier &&
1167 gc::kCollectorTypeDefault != gc::kCollectorTypeCMS &&
1168 gc::kCollectorTypeDefault != gc::kCollectorTypeMS) {
1169 LOG(INFO) << "Test requires determinism support.";
1170 return;
1171 }
1172 Runtime* const runtime = Runtime::Current();
1173 std::string out_dir = GetScratchDir();
1174 const std::string base_oat_name = out_dir + "/base.oat";
1175 const std::string base_vdex_name = out_dir + "/base.vdex";
1176 const std::string unload_oat_name = out_dir + "/unload.oat";
1177 const std::string unload_vdex_name = out_dir + "/unload.vdex";
1178 const std::string no_unload_oat_name = out_dir + "/nounload.oat";
1179 const std::string no_unload_vdex_name = out_dir + "/nounload.vdex";
1180 const std::string app_image_name = out_dir + "/unload.art";
1181 std::string error_msg;
1182 const std::vector<gc::space::ImageSpace*>& spaces = runtime->GetHeap()->GetBootImageSpaces();
1183 ASSERT_GT(spaces.size(), 0u);
1184 const std::string image_location = spaces[0]->GetImageLocation();
1185 // Without passing in an app image, it will unload in between compilations.
1186 const int res = GenerateOdexForTestWithStatus(
1187 GetLibCoreDexFileNames(),
1188 base_oat_name,
1189 CompilerFilter::Filter::kQuicken,
1190 &error_msg,
1191 {"--force-determinism", "--avoid-storing-invocation"});
1192 EXPECT_EQ(res, 0);
1193 Copy(base_oat_name, unload_oat_name);
1194 Copy(base_vdex_name, unload_vdex_name);
1195 std::unique_ptr<File> unload_oat(OS::OpenFileForReading(unload_oat_name.c_str()));
1196 std::unique_ptr<File> unload_vdex(OS::OpenFileForReading(unload_vdex_name.c_str()));
1197 ASSERT_TRUE(unload_oat != nullptr);
1198 ASSERT_TRUE(unload_vdex != nullptr);
1199 EXPECT_GT(unload_oat->GetLength(), 0u);
1200 EXPECT_GT(unload_vdex->GetLength(), 0u);
1201 // Regenerate with an app image to disable the dex2oat unloading and verify that the output is
1202 // the same.
1203 const int res2 = GenerateOdexForTestWithStatus(
1204 GetLibCoreDexFileNames(),
1205 base_oat_name,
1206 CompilerFilter::Filter::kQuicken,
1207 &error_msg,
1208 {"--force-determinism", "--avoid-storing-invocation", "--app-image-file=" + app_image_name});
1209 EXPECT_EQ(res2, 0);
1210 Copy(base_oat_name, no_unload_oat_name);
1211 Copy(base_vdex_name, no_unload_vdex_name);
1212 std::unique_ptr<File> no_unload_oat(OS::OpenFileForReading(no_unload_oat_name.c_str()));
1213 std::unique_ptr<File> no_unload_vdex(OS::OpenFileForReading(no_unload_vdex_name.c_str()));
1214 ASSERT_TRUE(no_unload_oat != nullptr);
1215 ASSERT_TRUE(no_unload_vdex != nullptr);
1216 EXPECT_GT(no_unload_oat->GetLength(), 0u);
1217 EXPECT_GT(no_unload_vdex->GetLength(), 0u);
1218 // Verify that both of the files are the same (odex and vdex).
1219 EXPECT_EQ(unload_oat->GetLength(), no_unload_oat->GetLength());
1220 EXPECT_EQ(unload_vdex->GetLength(), no_unload_vdex->GetLength());
1221 EXPECT_EQ(unload_oat->Compare(no_unload_oat.get()), 0)
1222 << unload_oat_name << " " << no_unload_oat_name;
1223 EXPECT_EQ(unload_vdex->Compare(no_unload_vdex.get()), 0)
1224 << unload_vdex_name << " " << no_unload_vdex_name;
1225 // App image file.
1226 std::unique_ptr<File> app_image_file(OS::OpenFileForReading(app_image_name.c_str()));
1227 ASSERT_TRUE(app_image_file != nullptr);
1228 EXPECT_GT(app_image_file->GetLength(), 0u);
1229}
1230
Mathieu Chartier120aa282017-08-05 16:03:03 -07001231// Test that dexlayout section info is correctly written to the oat file for profile based
1232// compilation.
1233TEST_F(Dex2oatTest, LayoutSections) {
1234 using Hotness = ProfileCompilationInfo::MethodHotness;
1235 std::unique_ptr<const DexFile> dex(OpenTestDexFile("ManyMethods"));
1236 ScratchFile profile_file;
1237 // We can only layout method indices with code items, figure out which ones have this property
1238 // first.
1239 std::vector<uint16_t> methods;
1240 {
1241 const DexFile::TypeId* type_id = dex->FindTypeId("LManyMethods;");
1242 dex::TypeIndex type_idx = dex->GetIndexForTypeId(*type_id);
1243 const DexFile::ClassDef* class_def = dex->FindClassDef(type_idx);
1244 ClassDataItemIterator it(*dex, dex->GetClassData(*class_def));
1245 it.SkipAllFields();
1246 std::set<size_t> code_item_offsets;
1247 for (; it.HasNextDirectMethod() || it.HasNextVirtualMethod(); it.Next()) {
1248 const uint16_t method_idx = it.GetMemberIndex();
1249 const size_t code_item_offset = it.GetMethodCodeItemOffset();
1250 if (code_item_offsets.insert(code_item_offset).second) {
1251 // Unique code item, add the method index.
1252 methods.push_back(method_idx);
1253 }
1254 }
1255 DCHECK(!it.HasNext());
1256 }
1257 ASSERT_GE(methods.size(), 8u);
1258 std::vector<uint16_t> hot_methods = {methods[1], methods[3], methods[5]};
1259 std::vector<uint16_t> startup_methods = {methods[1], methods[2], methods[7]};
1260 std::vector<uint16_t> post_methods = {methods[0], methods[2], methods[6]};
1261 // Here, we build the profile from the method lists.
1262 ProfileCompilationInfo info;
1263 info.AddMethodsForDex(
1264 static_cast<Hotness::Flag>(Hotness::kFlagHot | Hotness::kFlagStartup),
1265 dex.get(),
1266 hot_methods.begin(),
1267 hot_methods.end());
1268 info.AddMethodsForDex(
1269 Hotness::kFlagStartup,
1270 dex.get(),
1271 startup_methods.begin(),
1272 startup_methods.end());
1273 info.AddMethodsForDex(
1274 Hotness::kFlagPostStartup,
1275 dex.get(),
1276 post_methods.begin(),
1277 post_methods.end());
1278 for (uint16_t id : hot_methods) {
1279 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsHot());
1280 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsStartup());
1281 }
1282 for (uint16_t id : startup_methods) {
1283 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsStartup());
1284 }
1285 for (uint16_t id : post_methods) {
1286 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsPostStartup());
1287 }
1288 // Save the profile since we want to use it with dex2oat to produce an oat file.
1289 ASSERT_TRUE(info.Save(profile_file.GetFd()));
1290 // Generate a profile based odex.
1291 const std::string dir = GetScratchDir();
1292 const std::string oat_filename = dir + "/base.oat";
1293 const std::string vdex_filename = dir + "/base.vdex";
1294 std::string error_msg;
1295 const int res = GenerateOdexForTestWithStatus(
1296 {dex->GetLocation()},
1297 oat_filename,
1298 CompilerFilter::Filter::kQuicken,
1299 &error_msg,
1300 {"--profile-file=" + profile_file.GetFilename()});
1301 EXPECT_EQ(res, 0);
1302
1303 // Open our generated oat file.
1304 std::unique_ptr<OatFile> odex_file(OatFile::Open(oat_filename.c_str(),
1305 oat_filename.c_str(),
1306 nullptr,
1307 nullptr,
1308 false,
1309 /*low_4gb*/false,
1310 dex->GetLocation().c_str(),
1311 &error_msg));
1312 ASSERT_TRUE(odex_file != nullptr);
1313 std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
1314 ASSERT_EQ(oat_dex_files.size(), 1u);
1315 // Check that the code sections match what we expect.
1316 for (const OatDexFile* oat_dex : oat_dex_files) {
1317 const DexLayoutSections* const sections = oat_dex->GetDexLayoutSections();
1318 // Testing of logging the sections.
1319 ASSERT_TRUE(sections != nullptr);
1320 LOG(INFO) << *sections;
1321
1322 // Load the sections into temporary variables for convenience.
1323 const DexLayoutSection& code_section =
1324 sections->sections_[static_cast<size_t>(DexLayoutSections::SectionType::kSectionTypeCode)];
1325 const DexLayoutSection::Subsection& section_hot_code =
1326 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeHot)];
1327 const DexLayoutSection::Subsection& section_sometimes_used =
1328 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeSometimesUsed)];
1329 const DexLayoutSection::Subsection& section_startup_only =
1330 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeStartupOnly)];
1331 const DexLayoutSection::Subsection& section_unused =
1332 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeUnused)];
1333
1334 // All the sections should be non-empty.
1335 EXPECT_GT(section_hot_code.size_, 0u);
1336 EXPECT_GT(section_sometimes_used.size_, 0u);
1337 EXPECT_GT(section_startup_only.size_, 0u);
1338 EXPECT_GT(section_unused.size_, 0u);
1339
1340 // Open the dex file since we need to peek at the code items to verify the layout matches what
1341 // we expect.
1342 std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1343 ASSERT_TRUE(dex_file != nullptr) << error_msg;
1344 const DexFile::TypeId* type_id = dex_file->FindTypeId("LManyMethods;");
1345 ASSERT_TRUE(type_id != nullptr);
1346 dex::TypeIndex type_idx = dex_file->GetIndexForTypeId(*type_id);
1347 const DexFile::ClassDef* class_def = dex_file->FindClassDef(type_idx);
1348 ASSERT_TRUE(class_def != nullptr);
1349
1350 // Count how many code items are for each category, there should be at least one per category.
1351 size_t hot_count = 0;
1352 size_t post_startup_count = 0;
1353 size_t startup_count = 0;
1354 size_t unused_count = 0;
1355 // Visit all of the methdos of the main class and cross reference the method indices to their
1356 // corresponding code item offsets to verify the layout.
1357 ClassDataItemIterator it(*dex_file, dex_file->GetClassData(*class_def));
1358 it.SkipAllFields();
1359 for (; it.HasNextDirectMethod() || it.HasNextVirtualMethod(); it.Next()) {
1360 const size_t method_idx = it.GetMemberIndex();
1361 const size_t code_item_offset = it.GetMethodCodeItemOffset();
1362 const bool is_hot = ContainsElement(hot_methods, method_idx);
1363 const bool is_startup = ContainsElement(startup_methods, method_idx);
1364 const bool is_post_startup = ContainsElement(post_methods, method_idx);
1365 if (is_hot) {
1366 // Hot is highest precedence, check that the hot methods are in the hot section.
1367 EXPECT_LT(code_item_offset - section_hot_code.offset_, section_hot_code.size_);
1368 ++hot_count;
1369 } else if (is_post_startup) {
1370 // Post startup is sometimes used section.
1371 EXPECT_LT(code_item_offset - section_sometimes_used.offset_, section_sometimes_used.size_);
1372 ++post_startup_count;
1373 } else if (is_startup) {
1374 // Startup at this point means not hot or post startup, these must be startup only then.
1375 EXPECT_LT(code_item_offset - section_startup_only.offset_, section_startup_only.size_);
1376 ++startup_count;
1377 } else {
Alan Leung9595fd32017-10-17 17:08:19 -07001378 if (code_item_offset - section_unused.offset_ < section_unused.size_) {
1379 // If no flags are set, the method should be unused ...
1380 ++unused_count;
1381 } else {
1382 // or this method is part of the last code item and the end is 4 byte aligned.
1383 ClassDataItemIterator it2(*dex_file, dex_file->GetClassData(*class_def));
1384 it2.SkipAllFields();
1385 for (; it2.HasNextDirectMethod() || it2.HasNextVirtualMethod(); it2.Next()) {
1386 EXPECT_LE(it2.GetMethodCodeItemOffset(), code_item_offset);
1387 }
1388 uint32_t code_item_size = dex_file->FindCodeItemOffset(*class_def, method_idx);
1389 EXPECT_EQ((code_item_offset + code_item_size) % 4, 0u);
1390 }
Mathieu Chartier120aa282017-08-05 16:03:03 -07001391 }
1392 }
1393 DCHECK(!it.HasNext());
1394 EXPECT_GT(hot_count, 0u);
1395 EXPECT_GT(post_startup_count, 0u);
1396 EXPECT_GT(startup_count, 0u);
1397 EXPECT_GT(unused_count, 0u);
1398 }
1399}
1400
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001401// Test that generating compact dex works.
1402TEST_F(Dex2oatTest, GenerateCompactDex) {
1403 std::unique_ptr<const DexFile> dex(OpenTestDexFile("ManyMethods"));
1404 // Generate a compact dex based odex.
1405 const std::string dir = GetScratchDir();
1406 const std::string oat_filename = dir + "/base.oat";
1407 const std::string vdex_filename = dir + "/base.vdex";
1408 std::string error_msg;
1409 const int res = GenerateOdexForTestWithStatus(
1410 {dex->GetLocation()},
1411 oat_filename,
1412 CompilerFilter::Filter::kQuicken,
1413 &error_msg,
1414 {"--compact-dex-level=fast"});
1415 EXPECT_EQ(res, 0);
1416 // Open our generated oat file.
1417 std::unique_ptr<OatFile> odex_file(OatFile::Open(oat_filename.c_str(),
1418 oat_filename.c_str(),
1419 nullptr,
1420 nullptr,
1421 false,
1422 /*low_4gb*/false,
1423 dex->GetLocation().c_str(),
1424 &error_msg));
1425 ASSERT_TRUE(odex_file != nullptr);
1426 std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
1427 ASSERT_EQ(oat_dex_files.size(), 1u);
1428 // Check that each dex is a compact dex.
1429 for (const OatDexFile* oat_dex : oat_dex_files) {
1430 std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1431 ASSERT_TRUE(dex_file != nullptr) << error_msg;
1432 ASSERT_TRUE(dex_file->IsCompactDexFile());
1433 }
1434}
1435
Andreas Gampef39208f2017-10-19 15:06:59 -07001436class Dex2oatVerifierAbort : public Dex2oatTest {};
1437
1438TEST_F(Dex2oatVerifierAbort, HardFail) {
1439 // Use VerifierDeps as it has hard-failing classes.
1440 std::unique_ptr<const DexFile> dex(OpenTestDexFile("VerifierDeps"));
1441 std::string out_dir = GetScratchDir();
1442 const std::string base_oat_name = out_dir + "/base.oat";
1443 std::string error_msg;
1444 const int res_fail = GenerateOdexForTestWithStatus(
1445 {dex->GetLocation()},
1446 base_oat_name,
1447 CompilerFilter::Filter::kQuicken,
1448 &error_msg,
1449 {"--abort-on-hard-verifier-error"});
1450 EXPECT_NE(0, res_fail);
1451
1452 const int res_no_fail = GenerateOdexForTestWithStatus(
1453 {dex->GetLocation()},
1454 base_oat_name,
1455 CompilerFilter::Filter::kQuicken,
1456 &error_msg,
1457 {"--no-abort-on-hard-verifier-error"});
1458 EXPECT_EQ(0, res_no_fail);
1459}
1460
1461TEST_F(Dex2oatVerifierAbort, SoftFail) {
1462 // Use VerifierDepsMulti as it has hard-failing classes.
1463 std::unique_ptr<const DexFile> dex(OpenTestDexFile("VerifierDepsMulti"));
1464 std::string out_dir = GetScratchDir();
1465 const std::string base_oat_name = out_dir + "/base.oat";
1466 std::string error_msg;
1467 const int res_fail = GenerateOdexForTestWithStatus(
1468 {dex->GetLocation()},
1469 base_oat_name,
1470 CompilerFilter::Filter::kQuicken,
1471 &error_msg,
1472 {"--abort-on-soft-verifier-error"});
1473 EXPECT_NE(0, res_fail);
1474
1475 const int res_no_fail = GenerateOdexForTestWithStatus(
1476 {dex->GetLocation()},
1477 base_oat_name,
1478 CompilerFilter::Filter::kQuicken,
1479 &error_msg,
1480 {"--no-abort-on-soft-verifier-error"});
1481 EXPECT_EQ(0, res_no_fail);
1482}
1483
Andreas Gampee1459ae2016-06-29 09:36:30 -07001484} // namespace art