blob: 8799540fd315cae56166792ad180197de44046ac [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 Sehr013fd802018-01-11 22:55:24 -080033#include "dex/art_dex_file_loader.h"
David Sehr9e734c72018-01-04 17:56:19 -080034#include "dex/code_item_accessors-inl.h"
35#include "dex/dex_file-inl.h"
36#include "dex/dex_file_loader.h"
Andreas Gampee1459ae2016-06-29 09:36:30 -070037#include "dex2oat_environment_test.h"
Andreas Gampef7882972017-03-20 16:35:24 -070038#include "dex2oat_return_codes.h"
Calin Juravle33083d62017-01-18 15:29:12 -080039#include "jit/profile_compilation_info.h"
Andreas Gampe67f02822016-06-24 21:05:23 -070040#include "oat.h"
41#include "oat_file.h"
Andreas Gampee1459ae2016-06-29 09:36:30 -070042#include "utils.h"
43
Andreas Gampee1459ae2016-06-29 09:36:30 -070044namespace art {
45
Mathieu Chartierea650f32017-05-24 12:04:13 -070046static constexpr size_t kMaxMethodIds = 65535;
Mathieu Chartier9e050df2017-08-09 10:05:47 -070047static constexpr bool kDebugArgs = false;
Mathieu Chartier02129102017-12-22 11:04:01 -080048static const char* kDisableCompactDex = "--compact-dex-level=none";
Mathieu Chartierea650f32017-05-24 12:04:13 -070049
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080050using android::base::StringPrintf;
51
Andreas Gampee1459ae2016-06-29 09:36:30 -070052class Dex2oatTest : public Dex2oatEnvironmentTest {
53 public:
54 virtual void TearDown() OVERRIDE {
55 Dex2oatEnvironmentTest::TearDown();
56
57 output_ = "";
58 error_msg_ = "";
59 success_ = false;
60 }
61
62 protected:
Mathieu Chartier9e050df2017-08-09 10:05:47 -070063 int GenerateOdexForTestWithStatus(const std::vector<std::string>& dex_locations,
Andreas Gampef7882972017-03-20 16:35:24 -070064 const std::string& odex_location,
65 CompilerFilter::Filter filter,
66 std::string* error_msg,
67 const std::vector<std::string>& extra_args = {},
68 bool use_fd = false) {
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080069 std::unique_ptr<File> oat_file;
Andreas Gampee1459ae2016-06-29 09:36:30 -070070 std::vector<std::string> args;
Mathieu Chartier9e050df2017-08-09 10:05:47 -070071 // Add dex file args.
72 for (const std::string& dex_location : dex_locations) {
73 args.push_back("--dex-file=" + dex_location);
74 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080075 if (use_fd) {
76 oat_file.reset(OS::CreateEmptyFile(odex_location.c_str()));
77 CHECK(oat_file != nullptr) << odex_location;
78 args.push_back("--oat-fd=" + std::to_string(oat_file->Fd()));
Mathieu Chartier046854b2017-03-01 17:16:22 -080079 args.push_back("--oat-location=" + odex_location);
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080080 } else {
81 args.push_back("--oat-file=" + odex_location);
82 }
Andreas Gampee1459ae2016-06-29 09:36:30 -070083 args.push_back("--compiler-filter=" + CompilerFilter::NameOfFilter(filter));
84 args.push_back("--runtime-arg");
85 args.push_back("-Xnorelocate");
86
87 args.insert(args.end(), extra_args.begin(), extra_args.end());
88
Andreas Gampef7882972017-03-20 16:35:24 -070089 int status = Dex2Oat(args, error_msg);
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080090 if (oat_file != nullptr) {
Andreas Gampef7882972017-03-20 16:35:24 -070091 CHECK_EQ(oat_file->FlushClose(), 0) << "Could not flush and close oat file";
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080092 }
Andreas Gampef7882972017-03-20 16:35:24 -070093 return status;
94 }
Andreas Gampee1459ae2016-06-29 09:36:30 -070095
Andreas Gampe641a4732017-08-24 13:21:35 -070096 void GenerateOdexForTest(
97 const std::string& dex_location,
98 const std::string& odex_location,
99 CompilerFilter::Filter filter,
100 const std::vector<std::string>& extra_args = {},
101 bool expect_success = true,
102 bool use_fd = false) {
103 GenerateOdexForTest(dex_location,
104 odex_location,
105 filter,
106 extra_args,
107 expect_success,
108 use_fd,
109 [](const OatFile&) {});
110 }
111
Andreas Gampe80ddf272018-01-11 09:41:00 -0800112 bool test_accepts_odex_file_on_failure = false;
113
Andreas Gampe641a4732017-08-24 13:21:35 -0700114 template <typename T>
115 void GenerateOdexForTest(
116 const std::string& dex_location,
117 const std::string& odex_location,
118 CompilerFilter::Filter filter,
119 const std::vector<std::string>& extra_args,
120 bool expect_success,
121 bool use_fd,
122 T check_oat) {
Andreas Gampef7882972017-03-20 16:35:24 -0700123 std::string error_msg;
Mathieu Chartier9e050df2017-08-09 10:05:47 -0700124 int status = GenerateOdexForTestWithStatus({dex_location},
Andreas Gampef7882972017-03-20 16:35:24 -0700125 odex_location,
126 filter,
127 &error_msg,
128 extra_args,
129 use_fd);
Andreas Gampe80ddf272018-01-11 09:41:00 -0800130 bool success = (WIFEXITED(status) && WEXITSTATUS(status) == 0);
Andreas Gampee1459ae2016-06-29 09:36:30 -0700131 if (expect_success) {
Andreas Gampe2e8a2562017-01-18 20:39:02 -0800132 ASSERT_TRUE(success) << error_msg << std::endl << output_;
Andreas Gampee1459ae2016-06-29 09:36:30 -0700133
134 // Verify the odex file was generated as expected.
135 std::unique_ptr<OatFile> odex_file(OatFile::Open(odex_location.c_str(),
136 odex_location.c_str(),
137 nullptr,
138 nullptr,
139 false,
140 /*low_4gb*/false,
141 dex_location.c_str(),
142 &error_msg));
143 ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
144
145 CheckFilter(filter, odex_file->GetCompilerFilter());
Calin Juravle1ce70852017-06-28 10:59:03 -0700146 check_oat(*(odex_file.get()));
Andreas Gampee1459ae2016-06-29 09:36:30 -0700147 } else {
148 ASSERT_FALSE(success) << output_;
149
150 error_msg_ = error_msg;
151
Andreas Gampe80ddf272018-01-11 09:41:00 -0800152 if (!test_accepts_odex_file_on_failure) {
153 // Verify there's no loadable odex file.
154 std::unique_ptr<OatFile> odex_file(OatFile::Open(odex_location.c_str(),
155 odex_location.c_str(),
156 nullptr,
157 nullptr,
158 false,
159 /*low_4gb*/false,
160 dex_location.c_str(),
161 &error_msg));
162 ASSERT_TRUE(odex_file.get() == nullptr);
163 }
Andreas Gampee1459ae2016-06-29 09:36:30 -0700164 }
165 }
166
Calin Juravle1ccf6132017-08-02 17:46:53 -0700167 // Check the input compiler filter against the generated oat file's filter. May be overridden
Andreas Gampee1459ae2016-06-29 09:36:30 -0700168 // in subclasses when equality is not expected.
169 virtual void CheckFilter(CompilerFilter::Filter expected, CompilerFilter::Filter actual) {
170 EXPECT_EQ(expected, actual);
171 }
172
Andreas Gampef7882972017-03-20 16:35:24 -0700173 int Dex2Oat(const std::vector<std::string>& dex2oat_args, std::string* error_msg) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700174 Runtime* runtime = Runtime::Current();
175
176 const std::vector<gc::space::ImageSpace*>& image_spaces =
177 runtime->GetHeap()->GetBootImageSpaces();
178 if (image_spaces.empty()) {
179 *error_msg = "No image location found for Dex2Oat.";
180 return false;
181 }
182 std::string image_location = image_spaces[0]->GetImageLocation();
183
184 std::vector<std::string> argv;
185 argv.push_back(runtime->GetCompilerExecutable());
Calin Juravle1ccf6132017-08-02 17:46:53 -0700186
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000187 if (runtime->IsJavaDebuggable()) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700188 argv.push_back("--debuggable");
189 }
190 runtime->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv);
191
192 if (!runtime->IsVerificationEnabled()) {
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100193 argv.push_back("--compiler-filter=assume-verified");
Andreas Gampee1459ae2016-06-29 09:36:30 -0700194 }
195
196 if (runtime->MustRelocateIfPossible()) {
197 argv.push_back("--runtime-arg");
198 argv.push_back("-Xrelocate");
199 } else {
200 argv.push_back("--runtime-arg");
201 argv.push_back("-Xnorelocate");
202 }
203
204 if (!kIsTargetBuild) {
205 argv.push_back("--host");
206 }
207
208 argv.push_back("--boot-image=" + image_location);
209
210 std::vector<std::string> compiler_options = runtime->GetCompilerOptions();
211 argv.insert(argv.end(), compiler_options.begin(), compiler_options.end());
212
213 argv.insert(argv.end(), dex2oat_args.begin(), dex2oat_args.end());
214
215 // We must set --android-root.
216 const char* android_root = getenv("ANDROID_ROOT");
217 CHECK(android_root != nullptr);
218 argv.push_back("--android-root=" + std::string(android_root));
219
Mathieu Chartier9e050df2017-08-09 10:05:47 -0700220 if (kDebugArgs) {
221 std::string all_args;
222 for (const std::string& arg : argv) {
223 all_args += arg + " ";
224 }
225 LOG(ERROR) << all_args;
226 }
227
Nicolas Geoffray56fe0f02016-06-30 15:07:46 +0100228 int link[2];
Andreas Gampee1459ae2016-06-29 09:36:30 -0700229
Nicolas Geoffray56fe0f02016-06-30 15:07:46 +0100230 if (pipe(link) == -1) {
231 return false;
232 }
Andreas Gampee1459ae2016-06-29 09:36:30 -0700233
Nicolas Geoffray56fe0f02016-06-30 15:07:46 +0100234 pid_t pid = fork();
235 if (pid == -1) {
236 return false;
237 }
Andreas Gampee1459ae2016-06-29 09:36:30 -0700238
Nicolas Geoffray56fe0f02016-06-30 15:07:46 +0100239 if (pid == 0) {
240 // We need dex2oat to actually log things.
241 setenv("ANDROID_LOG_TAGS", "*:d", 1);
242 dup2(link[1], STDERR_FILENO);
243 close(link[0]);
244 close(link[1]);
245 std::vector<const char*> c_args;
246 for (const std::string& str : argv) {
247 c_args.push_back(str.c_str());
Andreas Gampee1459ae2016-06-29 09:36:30 -0700248 }
Nicolas Geoffray56fe0f02016-06-30 15:07:46 +0100249 c_args.push_back(nullptr);
250 execv(c_args[0], const_cast<char* const*>(c_args.data()));
251 exit(1);
Andreas Gampef7882972017-03-20 16:35:24 -0700252 UNREACHABLE();
Nicolas Geoffray56fe0f02016-06-30 15:07:46 +0100253 } else {
254 close(link[1]);
255 char buffer[128];
256 memset(buffer, 0, 128);
257 ssize_t bytes_read = 0;
Andreas Gampee1459ae2016-06-29 09:36:30 -0700258
Nicolas Geoffray56fe0f02016-06-30 15:07:46 +0100259 while (TEMP_FAILURE_RETRY(bytes_read = read(link[0], buffer, 128)) > 0) {
260 output_ += std::string(buffer, bytes_read);
261 }
262 close(link[0]);
Andreas Gampef7882972017-03-20 16:35:24 -0700263 int status = -1;
Nicolas Geoffray56fe0f02016-06-30 15:07:46 +0100264 if (waitpid(pid, &status, 0) != -1) {
265 success_ = (status == 0);
266 }
Andreas Gampef7882972017-03-20 16:35:24 -0700267 return status;
Andreas Gampee1459ae2016-06-29 09:36:30 -0700268 }
Andreas Gampee1459ae2016-06-29 09:36:30 -0700269 }
270
271 std::string output_ = "";
272 std::string error_msg_ = "";
273 bool success_ = false;
274};
275
276class Dex2oatSwapTest : public Dex2oatTest {
277 protected:
278 void RunTest(bool use_fd, bool expect_use, const std::vector<std::string>& extra_args = {}) {
279 std::string dex_location = GetScratchDir() + "/Dex2OatSwapTest.jar";
280 std::string odex_location = GetOdexDir() + "/Dex2OatSwapTest.odex";
281
Andreas Gampe7adeda82016-07-25 08:27:35 -0700282 Copy(GetTestDexFileName(), dex_location);
Andreas Gampee1459ae2016-06-29 09:36:30 -0700283
284 std::vector<std::string> copy(extra_args);
285
286 std::unique_ptr<ScratchFile> sf;
287 if (use_fd) {
288 sf.reset(new ScratchFile());
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800289 copy.push_back(android::base::StringPrintf("--swap-fd=%d", sf->GetFd()));
Andreas Gampee1459ae2016-06-29 09:36:30 -0700290 } else {
291 std::string swap_location = GetOdexDir() + "/Dex2OatSwapTest.odex.swap";
292 copy.push_back("--swap-file=" + swap_location);
293 }
294 GenerateOdexForTest(dex_location, odex_location, CompilerFilter::kSpeed, copy);
295
296 CheckValidity();
297 ASSERT_TRUE(success_);
298 CheckResult(expect_use);
299 }
300
Andreas Gampe7adeda82016-07-25 08:27:35 -0700301 virtual std::string GetTestDexFileName() {
Vladimir Marko15357702017-02-09 10:37:31 +0000302 return Dex2oatEnvironmentTest::GetTestDexFileName("VerifierDeps");
Andreas Gampe7adeda82016-07-25 08:27:35 -0700303 }
304
305 virtual void CheckResult(bool expect_use) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700306 if (kIsTargetBuild) {
307 CheckTargetResult(expect_use);
308 } else {
309 CheckHostResult(expect_use);
310 }
311 }
312
Andreas Gampe7adeda82016-07-25 08:27:35 -0700313 virtual void CheckTargetResult(bool expect_use ATTRIBUTE_UNUSED) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700314 // TODO: Ignore for now, as we won't capture any output (it goes to the logcat). We may do
315 // something for variants with file descriptor where we can control the lifetime of
316 // the swap file and thus take a look at it.
317 }
318
Andreas Gampe7adeda82016-07-25 08:27:35 -0700319 virtual void CheckHostResult(bool expect_use) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700320 if (!kIsTargetBuild) {
321 if (expect_use) {
322 EXPECT_NE(output_.find("Large app, accepted running with swap."), std::string::npos)
323 << output_;
324 } else {
325 EXPECT_EQ(output_.find("Large app, accepted running with swap."), std::string::npos)
326 << output_;
327 }
328 }
329 }
330
331 // Check whether the dex2oat run was really successful.
Andreas Gampe7adeda82016-07-25 08:27:35 -0700332 virtual void CheckValidity() {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700333 if (kIsTargetBuild) {
334 CheckTargetValidity();
335 } else {
336 CheckHostValidity();
337 }
338 }
339
Andreas Gampe7adeda82016-07-25 08:27:35 -0700340 virtual void CheckTargetValidity() {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700341 // TODO: Ignore for now, as we won't capture any output (it goes to the logcat). We may do
342 // something for variants with file descriptor where we can control the lifetime of
343 // the swap file and thus take a look at it.
344 }
345
346 // On the host, we can get the dex2oat output. Here, look for "dex2oat took."
Andreas Gampe7adeda82016-07-25 08:27:35 -0700347 virtual void CheckHostValidity() {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700348 EXPECT_NE(output_.find("dex2oat took"), std::string::npos) << output_;
349 }
350};
351
352TEST_F(Dex2oatSwapTest, DoNotUseSwapDefaultSingleSmall) {
353 RunTest(false /* use_fd */, false /* expect_use */);
354 RunTest(true /* use_fd */, false /* expect_use */);
355}
356
357TEST_F(Dex2oatSwapTest, DoNotUseSwapSingle) {
358 RunTest(false /* use_fd */, false /* expect_use */, { "--swap-dex-size-threshold=0" });
359 RunTest(true /* use_fd */, false /* expect_use */, { "--swap-dex-size-threshold=0" });
360}
361
362TEST_F(Dex2oatSwapTest, DoNotUseSwapSmall) {
363 RunTest(false /* use_fd */, false /* expect_use */, { "--swap-dex-count-threshold=0" });
364 RunTest(true /* use_fd */, false /* expect_use */, { "--swap-dex-count-threshold=0" });
365}
366
367TEST_F(Dex2oatSwapTest, DoUseSwapSingleSmall) {
368 RunTest(false /* use_fd */,
369 true /* expect_use */,
370 { "--swap-dex-size-threshold=0", "--swap-dex-count-threshold=0" });
371 RunTest(true /* use_fd */,
372 true /* expect_use */,
373 { "--swap-dex-size-threshold=0", "--swap-dex-count-threshold=0" });
374}
375
Andreas Gampe7adeda82016-07-25 08:27:35 -0700376class Dex2oatSwapUseTest : public Dex2oatSwapTest {
377 protected:
378 void CheckHostResult(bool expect_use) OVERRIDE {
379 if (!kIsTargetBuild) {
380 if (expect_use) {
381 EXPECT_NE(output_.find("Large app, accepted running with swap."), std::string::npos)
382 << output_;
383 } else {
384 EXPECT_EQ(output_.find("Large app, accepted running with swap."), std::string::npos)
385 << output_;
386 }
387 }
388 }
389
390 std::string GetTestDexFileName() OVERRIDE {
391 // Use Statics as it has a handful of functions.
392 return CommonRuntimeTest::GetTestDexFileName("Statics");
393 }
394
395 void GrabResult1() {
396 if (!kIsTargetBuild) {
397 native_alloc_1_ = ParseNativeAlloc();
398 swap_1_ = ParseSwap(false /* expected */);
399 } else {
400 native_alloc_1_ = std::numeric_limits<size_t>::max();
401 swap_1_ = 0;
402 }
403 }
404
405 void GrabResult2() {
406 if (!kIsTargetBuild) {
407 native_alloc_2_ = ParseNativeAlloc();
408 swap_2_ = ParseSwap(true /* expected */);
409 } else {
410 native_alloc_2_ = 0;
411 swap_2_ = std::numeric_limits<size_t>::max();
412 }
413 }
414
415 private:
416 size_t ParseNativeAlloc() {
417 std::regex native_alloc_regex("dex2oat took.*native alloc=[^ ]+ \\(([0-9]+)B\\)");
418 std::smatch native_alloc_match;
419 bool found = std::regex_search(output_, native_alloc_match, native_alloc_regex);
420 if (!found) {
421 EXPECT_TRUE(found);
422 return 0;
423 }
424 if (native_alloc_match.size() != 2U) {
425 EXPECT_EQ(native_alloc_match.size(), 2U);
426 return 0;
427 }
428
429 std::istringstream stream(native_alloc_match[1].str());
430 size_t value;
431 stream >> value;
432
433 return value;
434 }
435
436 size_t ParseSwap(bool expected) {
437 std::regex swap_regex("dex2oat took[^\\n]+swap=[^ ]+ \\(([0-9]+)B\\)");
438 std::smatch swap_match;
439 bool found = std::regex_search(output_, swap_match, swap_regex);
440 if (found != expected) {
441 EXPECT_EQ(expected, found);
442 return 0;
443 }
444
445 if (!found) {
446 return 0;
447 }
448
449 if (swap_match.size() != 2U) {
450 EXPECT_EQ(swap_match.size(), 2U);
451 return 0;
452 }
453
454 std::istringstream stream(swap_match[1].str());
455 size_t value;
456 stream >> value;
457
458 return value;
459 }
460
461 protected:
462 size_t native_alloc_1_;
463 size_t native_alloc_2_;
464
465 size_t swap_1_;
466 size_t swap_2_;
467};
468
469TEST_F(Dex2oatSwapUseTest, CheckSwapUsage) {
Andreas Gampef4a67fd2017-05-04 09:55:36 -0700470 // Native memory usage isn't correctly tracked under sanitization.
471 TEST_DISABLED_FOR_MEMORY_TOOL_ASAN();
472
Vladimir Marko57070da2017-02-14 16:16:30 +0000473 // The `native_alloc_2_ >= native_alloc_1_` assertion below may not
Roland Levillain19772bf2017-02-16 11:28:10 +0000474 // hold true on some x86 systems; disable this test while we
475 // investigate (b/29259363).
476 TEST_DISABLED_FOR_X86();
Vladimir Marko57070da2017-02-14 16:16:30 +0000477
Andreas Gampe7adeda82016-07-25 08:27:35 -0700478 RunTest(false /* use_fd */,
479 false /* expect_use */);
480 GrabResult1();
481 std::string output_1 = output_;
482
483 output_ = "";
484
485 RunTest(false /* use_fd */,
486 true /* expect_use */,
487 { "--swap-dex-size-threshold=0", "--swap-dex-count-threshold=0" });
488 GrabResult2();
489 std::string output_2 = output_;
490
491 if (native_alloc_2_ >= native_alloc_1_ || swap_1_ >= swap_2_) {
492 EXPECT_LT(native_alloc_2_, native_alloc_1_);
493 EXPECT_LT(swap_1_, swap_2_);
494
495 LOG(ERROR) << output_1;
496 LOG(ERROR) << output_2;
497 }
498}
499
Andreas Gampe67f02822016-06-24 21:05:23 -0700500class Dex2oatVeryLargeTest : public Dex2oatTest {
501 protected:
502 void CheckFilter(CompilerFilter::Filter input ATTRIBUTE_UNUSED,
503 CompilerFilter::Filter result ATTRIBUTE_UNUSED) OVERRIDE {
504 // Ignore, we'll do our own checks.
505 }
506
507 void RunTest(CompilerFilter::Filter filter,
508 bool expect_large,
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700509 bool expect_downgrade,
Andreas Gampe67f02822016-06-24 21:05:23 -0700510 const std::vector<std::string>& extra_args = {}) {
511 std::string dex_location = GetScratchDir() + "/DexNoOat.jar";
512 std::string odex_location = GetOdexDir() + "/DexOdexNoOat.odex";
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700513 std::string app_image_file = GetScratchDir() + "/Test.art";
Andreas Gampe67f02822016-06-24 21:05:23 -0700514
515 Copy(GetDexSrc1(), dex_location);
516
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700517 std::vector<std::string> new_args(extra_args);
518 new_args.push_back("--app-image-file=" + app_image_file);
519 GenerateOdexForTest(dex_location, odex_location, filter, new_args);
Andreas Gampe67f02822016-06-24 21:05:23 -0700520
521 CheckValidity();
522 ASSERT_TRUE(success_);
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700523 CheckResult(dex_location,
524 odex_location,
525 app_image_file,
526 filter,
527 expect_large,
528 expect_downgrade);
Andreas Gampe67f02822016-06-24 21:05:23 -0700529 }
530
531 void CheckResult(const std::string& dex_location,
532 const std::string& odex_location,
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700533 const std::string& app_image_file,
Andreas Gampe67f02822016-06-24 21:05:23 -0700534 CompilerFilter::Filter filter,
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700535 bool expect_large,
536 bool expect_downgrade) {
537 if (expect_downgrade) {
538 EXPECT_TRUE(expect_large);
539 }
Andreas Gampe67f02822016-06-24 21:05:23 -0700540 // Host/target independent checks.
541 std::string error_msg;
542 std::unique_ptr<OatFile> odex_file(OatFile::Open(odex_location.c_str(),
543 odex_location.c_str(),
544 nullptr,
545 nullptr,
546 false,
547 /*low_4gb*/false,
548 dex_location.c_str(),
549 &error_msg));
550 ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700551 EXPECT_GT(app_image_file.length(), 0u);
552 std::unique_ptr<File> file(OS::OpenFileForReading(app_image_file.c_str()));
Andreas Gampe67f02822016-06-24 21:05:23 -0700553 if (expect_large) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700554 // Note: we cannot check the following
555 // EXPECT_FALSE(CompilerFilter::IsAotCompilationEnabled(odex_file->GetCompilerFilter()));
Andreas Gampe67f02822016-06-24 21:05:23 -0700556 // The reason is that the filter override currently happens when the dex files are
557 // loaded in dex2oat, which is after the oat file has been started. Thus, the header
558 // store cannot be changed, and the original filter is set in stone.
559
560 for (const OatDexFile* oat_dex_file : odex_file->GetOatDexFiles()) {
561 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
562 ASSERT_TRUE(dex_file != nullptr);
563 uint32_t class_def_count = dex_file->NumClassDefs();
564 ASSERT_LT(class_def_count, std::numeric_limits<uint16_t>::max());
565 for (uint16_t class_def_index = 0; class_def_index < class_def_count; ++class_def_index) {
566 OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
567 EXPECT_EQ(oat_class.GetType(), OatClassType::kOatClassNoneCompiled);
568 }
569 }
570
571 // If the input filter was "below," it should have been used.
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100572 if (!CompilerFilter::IsAsGoodAs(CompilerFilter::kExtract, filter)) {
Andreas Gampe67f02822016-06-24 21:05:23 -0700573 EXPECT_EQ(odex_file->GetCompilerFilter(), filter);
574 }
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700575
576 // If expect large, make sure the app image isn't generated or is empty.
577 if (file != nullptr) {
578 EXPECT_EQ(file->GetLength(), 0u);
579 }
Andreas Gampe67f02822016-06-24 21:05:23 -0700580 } else {
581 EXPECT_EQ(odex_file->GetCompilerFilter(), filter);
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700582 ASSERT_TRUE(file != nullptr) << app_image_file;
583 EXPECT_GT(file->GetLength(), 0u);
Andreas Gampe67f02822016-06-24 21:05:23 -0700584 }
585
586 // Host/target dependent checks.
587 if (kIsTargetBuild) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700588 CheckTargetResult(expect_downgrade);
Andreas Gampe67f02822016-06-24 21:05:23 -0700589 } else {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700590 CheckHostResult(expect_downgrade);
Andreas Gampe67f02822016-06-24 21:05:23 -0700591 }
592 }
593
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700594 void CheckTargetResult(bool expect_downgrade ATTRIBUTE_UNUSED) {
Andreas Gampe67f02822016-06-24 21:05:23 -0700595 // TODO: Ignore for now. May do something for fd things.
596 }
597
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700598 void CheckHostResult(bool expect_downgrade) {
Andreas Gampe67f02822016-06-24 21:05:23 -0700599 if (!kIsTargetBuild) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700600 if (expect_downgrade) {
601 EXPECT_NE(output_.find("Very large app, downgrading to"), std::string::npos) << output_;
Andreas Gampe67f02822016-06-24 21:05:23 -0700602 } else {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700603 EXPECT_EQ(output_.find("Very large app, downgrading to"), std::string::npos) << output_;
Andreas Gampe67f02822016-06-24 21:05:23 -0700604 }
605 }
606 }
607
608 // Check whether the dex2oat run was really successful.
609 void CheckValidity() {
610 if (kIsTargetBuild) {
611 CheckTargetValidity();
612 } else {
613 CheckHostValidity();
614 }
615 }
616
617 void CheckTargetValidity() {
618 // TODO: Ignore for now.
619 }
620
621 // On the host, we can get the dex2oat output. Here, look for "dex2oat took."
622 void CheckHostValidity() {
623 EXPECT_NE(output_.find("dex2oat took"), std::string::npos) << output_;
624 }
625};
626
627TEST_F(Dex2oatVeryLargeTest, DontUseVeryLarge) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700628 RunTest(CompilerFilter::kAssumeVerified, false, false);
629 RunTest(CompilerFilter::kExtract, false, false);
630 RunTest(CompilerFilter::kQuicken, false, false);
631 RunTest(CompilerFilter::kSpeed, false, false);
Andreas Gampe67f02822016-06-24 21:05:23 -0700632
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700633 RunTest(CompilerFilter::kAssumeVerified, false, false, { "--very-large-app-threshold=10000000" });
634 RunTest(CompilerFilter::kExtract, false, false, { "--very-large-app-threshold=10000000" });
635 RunTest(CompilerFilter::kQuicken, false, false, { "--very-large-app-threshold=10000000" });
636 RunTest(CompilerFilter::kSpeed, false, false, { "--very-large-app-threshold=10000000" });
Andreas Gampe67f02822016-06-24 21:05:23 -0700637}
638
639TEST_F(Dex2oatVeryLargeTest, UseVeryLarge) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700640 RunTest(CompilerFilter::kAssumeVerified, true, false, { "--very-large-app-threshold=100" });
641 RunTest(CompilerFilter::kExtract, true, false, { "--very-large-app-threshold=100" });
642 RunTest(CompilerFilter::kQuicken, true, true, { "--very-large-app-threshold=100" });
643 RunTest(CompilerFilter::kSpeed, true, true, { "--very-large-app-threshold=100" });
Andreas Gampe67f02822016-06-24 21:05:23 -0700644}
645
Mathieu Chartier97ab5e32017-02-22 13:35:44 -0800646// Regressin test for b/35665292.
647TEST_F(Dex2oatVeryLargeTest, SpeedProfileNoProfile) {
648 // Test that dex2oat doesn't crash with speed-profile but no input profile.
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700649 RunTest(CompilerFilter::kSpeedProfile, false, false);
Mathieu Chartier97ab5e32017-02-22 13:35:44 -0800650}
651
Jeff Hao608f2ce2016-10-19 11:17:11 -0700652class Dex2oatLayoutTest : public Dex2oatTest {
653 protected:
654 void CheckFilter(CompilerFilter::Filter input ATTRIBUTE_UNUSED,
655 CompilerFilter::Filter result ATTRIBUTE_UNUSED) OVERRIDE {
656 // Ignore, we'll do our own checks.
657 }
658
Jeff Hao41fba6a2016-11-28 11:53:33 -0800659 // Emits a profile with a single dex file with the given location and a single class index of 1.
660 void GenerateProfile(const std::string& test_profile,
661 const std::string& dex_location,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800662 size_t num_classes,
Jeff Hao41fba6a2016-11-28 11:53:33 -0800663 uint32_t checksum) {
664 int profile_test_fd = open(test_profile.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644);
665 CHECK_GE(profile_test_fd, 0);
666
667 ProfileCompilationInfo info;
668 std::string profile_key = ProfileCompilationInfo::GetProfileDexFileKey(dex_location);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800669 for (size_t i = 0; i < num_classes; ++i) {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700670 info.AddClassIndex(profile_key, checksum, dex::TypeIndex(1 + i), kMaxMethodIds);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800671 }
Jeff Hao41fba6a2016-11-28 11:53:33 -0800672 bool result = info.Save(profile_test_fd);
673 close(profile_test_fd);
674 ASSERT_TRUE(result);
675 }
676
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800677 void CompileProfileOdex(const std::string& dex_location,
678 const std::string& odex_location,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800679 const std::string& app_image_file_name,
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800680 bool use_fd,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800681 size_t num_profile_classes,
Nicolas Geoffray97fa9922017-03-09 13:13:25 +0000682 const std::vector<std::string>& extra_args = {},
683 bool expect_success = true) {
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800684 const std::string profile_location = GetScratchDir() + "/primary.prof";
Jeff Hao41fba6a2016-11-28 11:53:33 -0800685 const char* location = dex_location.c_str();
686 std::string error_msg;
687 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Sehr013fd802018-01-11 22:55:24 -0800688 const ArtDexFileLoader dex_file_loader;
689 ASSERT_TRUE(dex_file_loader.Open(
Nicolas Geoffray095c6c92017-10-19 13:59:55 +0100690 location, location, /* verify */ true, /* verify_checksum */ true, &error_msg, &dex_files));
Jeff Hao41fba6a2016-11-28 11:53:33 -0800691 EXPECT_EQ(dex_files.size(), 1U);
692 std::unique_ptr<const DexFile>& dex_file = dex_files[0];
Mathieu Chartier046854b2017-03-01 17:16:22 -0800693 GenerateProfile(profile_location,
694 dex_location,
695 num_profile_classes,
696 dex_file->GetLocationChecksum());
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800697 std::vector<std::string> copy(extra_args);
698 copy.push_back("--profile-file=" + profile_location);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800699 std::unique_ptr<File> app_image_file;
700 if (!app_image_file_name.empty()) {
701 if (use_fd) {
702 app_image_file.reset(OS::CreateEmptyFile(app_image_file_name.c_str()));
703 copy.push_back("--app-image-fd=" + std::to_string(app_image_file->Fd()));
704 } else {
705 copy.push_back("--app-image-file=" + app_image_file_name);
706 }
707 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800708 GenerateOdexForTest(dex_location,
709 odex_location,
710 CompilerFilter::kSpeedProfile,
711 copy,
Nicolas Geoffray97fa9922017-03-09 13:13:25 +0000712 expect_success,
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800713 use_fd);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800714 if (app_image_file != nullptr) {
715 ASSERT_EQ(app_image_file->FlushCloseOrErase(), 0) << "Could not flush and close art file";
716 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800717 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700718
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100719 uint64_t GetImageObjectSectionSize(const std::string& image_file_name) {
Mathieu Chartier046854b2017-03-01 17:16:22 -0800720 EXPECT_FALSE(image_file_name.empty());
721 std::unique_ptr<File> file(OS::OpenFileForReading(image_file_name.c_str()));
722 CHECK(file != nullptr);
723 ImageHeader image_header;
724 const bool success = file->ReadFully(&image_header, sizeof(image_header));
725 CHECK(success);
726 CHECK(image_header.IsValid());
727 ReaderMutexLock mu(Thread::Current(), *Locks::mutator_lock_);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100728 return image_header.GetObjectsSection().Size();
Mathieu Chartier046854b2017-03-01 17:16:22 -0800729 }
730
731 void RunTest(bool app_image) {
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800732 std::string dex_location = GetScratchDir() + "/DexNoOat.jar";
733 std::string odex_location = GetOdexDir() + "/DexOdexNoOat.odex";
Mathieu Chartier046854b2017-03-01 17:16:22 -0800734 std::string app_image_file = app_image ? (GetOdexDir() + "/DexOdexNoOat.art"): "";
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800735 Copy(GetDexSrc2(), dex_location);
736
Mathieu Chartier046854b2017-03-01 17:16:22 -0800737 uint64_t image_file_empty_profile = 0;
738 if (app_image) {
739 CompileProfileOdex(dex_location,
740 odex_location,
741 app_image_file,
742 /* use_fd */ false,
743 /* num_profile_classes */ 0);
744 CheckValidity();
745 ASSERT_TRUE(success_);
746 // Don't check the result since CheckResult relies on the class being in the profile.
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100747 image_file_empty_profile = GetImageObjectSectionSize(app_image_file);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800748 EXPECT_GT(image_file_empty_profile, 0u);
749 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700750
Mathieu Chartier046854b2017-03-01 17:16:22 -0800751 // Small profile.
752 CompileProfileOdex(dex_location,
753 odex_location,
754 app_image_file,
755 /* use_fd */ false,
756 /* num_profile_classes */ 1);
Jeff Hao608f2ce2016-10-19 11:17:11 -0700757 CheckValidity();
758 ASSERT_TRUE(success_);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800759 CheckResult(dex_location, odex_location, app_image_file);
760
761 if (app_image) {
762 // Test that the profile made a difference by adding more classes.
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100763 const uint64_t image_file_small_profile = GetImageObjectSectionSize(app_image_file);
764 ASSERT_LT(image_file_empty_profile, image_file_small_profile);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800765 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700766 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800767
768 void RunTestVDex() {
769 std::string dex_location = GetScratchDir() + "/DexNoOat.jar";
770 std::string odex_location = GetOdexDir() + "/DexOdexNoOat.odex";
771 std::string vdex_location = GetOdexDir() + "/DexOdexNoOat.vdex";
Mathieu Chartier046854b2017-03-01 17:16:22 -0800772 std::string app_image_file_name = GetOdexDir() + "/DexOdexNoOat.art";
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800773 Copy(GetDexSrc2(), dex_location);
774
775 std::unique_ptr<File> vdex_file1(OS::CreateEmptyFile(vdex_location.c_str()));
776 CHECK(vdex_file1 != nullptr) << vdex_location;
777 ScratchFile vdex_file2;
778 {
779 std::string input_vdex = "--input-vdex-fd=-1";
780 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file1->Fd());
781 CompileProfileOdex(dex_location,
782 odex_location,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800783 app_image_file_name,
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800784 /* use_fd */ true,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800785 /* num_profile_classes */ 1,
Mathieu Chartier02129102017-12-22 11:04:01 -0800786 { input_vdex, output_vdex, kDisableCompactDex });
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800787 EXPECT_GT(vdex_file1->GetLength(), 0u);
788 }
789 {
Nicolas Geoffray97fa9922017-03-09 13:13:25 +0000790 // Test that vdex and dexlayout fail gracefully.
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800791 std::string input_vdex = StringPrintf("--input-vdex-fd=%d", vdex_file1->Fd());
792 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file2.GetFd());
793 CompileProfileOdex(dex_location,
794 odex_location,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800795 app_image_file_name,
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800796 /* use_fd */ true,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800797 /* num_profile_classes */ 1,
Mathieu Chartier02129102017-12-22 11:04:01 -0800798 { input_vdex, output_vdex, kDisableCompactDex },
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +0100799 /* expect_success */ true);
800 EXPECT_GT(vdex_file2.GetFile()->GetLength(), 0u);
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800801 }
802 ASSERT_EQ(vdex_file1->FlushCloseOrErase(), 0) << "Could not flush and close vdex file";
803 CheckValidity();
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +0100804 ASSERT_TRUE(success_);
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800805 }
806
Mathieu Chartier046854b2017-03-01 17:16:22 -0800807 void CheckResult(const std::string& dex_location,
808 const std::string& odex_location,
809 const std::string& app_image_file_name) {
Jeff Hao608f2ce2016-10-19 11:17:11 -0700810 // Host/target independent checks.
811 std::string error_msg;
812 std::unique_ptr<OatFile> odex_file(OatFile::Open(odex_location.c_str(),
813 odex_location.c_str(),
814 nullptr,
815 nullptr,
816 false,
817 /*low_4gb*/false,
818 dex_location.c_str(),
819 &error_msg));
820 ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
821
Jeff Hao042e8982016-10-19 11:17:11 -0700822 const char* location = dex_location.c_str();
823 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Sehr013fd802018-01-11 22:55:24 -0800824 const ArtDexFileLoader dex_file_loader;
825 ASSERT_TRUE(dex_file_loader.Open(
Nicolas Geoffray095c6c92017-10-19 13:59:55 +0100826 location, location, /* verify */ true, /* verify_checksum */ true, &error_msg, &dex_files));
Jeff Hao042e8982016-10-19 11:17:11 -0700827 EXPECT_EQ(dex_files.size(), 1U);
828 std::unique_ptr<const DexFile>& old_dex_file = dex_files[0];
829
Jeff Hao608f2ce2016-10-19 11:17:11 -0700830 for (const OatDexFile* oat_dex_file : odex_file->GetOatDexFiles()) {
Jeff Hao042e8982016-10-19 11:17:11 -0700831 std::unique_ptr<const DexFile> new_dex_file = oat_dex_file->OpenDexFile(&error_msg);
832 ASSERT_TRUE(new_dex_file != nullptr);
833 uint32_t class_def_count = new_dex_file->NumClassDefs();
Jeff Hao608f2ce2016-10-19 11:17:11 -0700834 ASSERT_LT(class_def_count, std::numeric_limits<uint16_t>::max());
Jeff Hao042e8982016-10-19 11:17:11 -0700835 ASSERT_GE(class_def_count, 2U);
836
Mathieu Chartier24066ec2017-10-21 16:01:08 -0700837 // Make sure the indexes stay the same.
Jeff Hao042e8982016-10-19 11:17:11 -0700838 std::string old_class0 = old_dex_file->PrettyType(old_dex_file->GetClassDef(0).class_idx_);
839 std::string old_class1 = old_dex_file->PrettyType(old_dex_file->GetClassDef(1).class_idx_);
840 std::string new_class0 = new_dex_file->PrettyType(new_dex_file->GetClassDef(0).class_idx_);
841 std::string new_class1 = new_dex_file->PrettyType(new_dex_file->GetClassDef(1).class_idx_);
Mathieu Chartier24066ec2017-10-21 16:01:08 -0700842 EXPECT_EQ(old_class0, new_class0);
843 EXPECT_EQ(old_class1, new_class1);
Jeff Hao608f2ce2016-10-19 11:17:11 -0700844 }
845
Jeff Haoc155b052017-01-17 17:43:29 -0800846 EXPECT_EQ(odex_file->GetCompilerFilter(), CompilerFilter::kSpeedProfile);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800847
848 if (!app_image_file_name.empty()) {
849 // Go peek at the image header to make sure it was large enough to contain the class.
850 std::unique_ptr<File> file(OS::OpenFileForReading(app_image_file_name.c_str()));
851 ImageHeader image_header;
852 bool success = file->ReadFully(&image_header, sizeof(image_header));
853 ASSERT_TRUE(success);
854 ASSERT_TRUE(image_header.IsValid());
Vladimir Markocd87c3e2017-09-05 13:11:57 +0100855 EXPECT_GT(image_header.GetObjectsSection().Size(), 0u);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800856 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700857 }
858
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800859 // Check whether the dex2oat run was really successful.
860 void CheckValidity() {
861 if (kIsTargetBuild) {
862 CheckTargetValidity();
863 } else {
864 CheckHostValidity();
Jeff Hao608f2ce2016-10-19 11:17:11 -0700865 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800866 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700867
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800868 void CheckTargetValidity() {
869 // TODO: Ignore for now.
870 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700871
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800872 // On the host, we can get the dex2oat output. Here, look for "dex2oat took."
873 void CheckHostValidity() {
874 EXPECT_NE(output_.find("dex2oat took"), std::string::npos) << output_;
875 }
876};
Jeff Hao608f2ce2016-10-19 11:17:11 -0700877
878TEST_F(Dex2oatLayoutTest, TestLayout) {
Mathieu Chartier046854b2017-03-01 17:16:22 -0800879 RunTest(/* app-image */ false);
880}
881
882TEST_F(Dex2oatLayoutTest, TestLayoutAppImage) {
883 RunTest(/* app-image */ true);
Jeff Hao608f2ce2016-10-19 11:17:11 -0700884}
885
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800886TEST_F(Dex2oatLayoutTest, TestVdexLayout) {
887 RunTestVDex();
888}
889
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100890class Dex2oatUnquickenTest : public Dex2oatTest {
891 protected:
892 void RunUnquickenMultiDex() {
893 std::string dex_location = GetScratchDir() + "/UnquickenMultiDex.jar";
894 std::string odex_location = GetOdexDir() + "/UnquickenMultiDex.odex";
895 std::string vdex_location = GetOdexDir() + "/UnquickenMultiDex.vdex";
896 Copy(GetTestDexFileName("MultiDex"), dex_location);
897
898 std::unique_ptr<File> vdex_file1(OS::CreateEmptyFile(vdex_location.c_str()));
899 CHECK(vdex_file1 != nullptr) << vdex_location;
900 // Quicken the dex file into a vdex file.
901 {
902 std::string input_vdex = "--input-vdex-fd=-1";
903 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file1->Fd());
904 GenerateOdexForTest(dex_location,
905 odex_location,
906 CompilerFilter::kQuicken,
Mathieu Chartier02129102017-12-22 11:04:01 -0800907 { input_vdex, output_vdex, kDisableCompactDex },
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100908 /* expect_success */ true,
909 /* use_fd */ true);
910 EXPECT_GT(vdex_file1->GetLength(), 0u);
911 }
912 // Unquicken by running the verify compiler filter on the vdex file.
913 {
914 std::string input_vdex = StringPrintf("--input-vdex-fd=%d", vdex_file1->Fd());
915 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file1->Fd());
916 GenerateOdexForTest(dex_location,
917 odex_location,
918 CompilerFilter::kVerify,
Mathieu Chartier02129102017-12-22 11:04:01 -0800919 { input_vdex, output_vdex, kDisableCompactDex },
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100920 /* expect_success */ true,
921 /* use_fd */ true);
922 }
923 ASSERT_EQ(vdex_file1->FlushCloseOrErase(), 0) << "Could not flush and close vdex file";
924 CheckResult(dex_location, odex_location);
925 ASSERT_TRUE(success_);
926 }
927
928 void CheckResult(const std::string& dex_location, const std::string& odex_location) {
929 std::string error_msg;
930 std::unique_ptr<OatFile> odex_file(OatFile::Open(odex_location.c_str(),
931 odex_location.c_str(),
932 nullptr,
933 nullptr,
934 false,
935 /*low_4gb*/false,
936 dex_location.c_str(),
937 &error_msg));
938 ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
939 ASSERT_GE(odex_file->GetOatDexFiles().size(), 1u);
940
941 // Iterate over the dex files and ensure there is no quickened instruction.
942 for (const OatDexFile* oat_dex_file : odex_file->GetOatDexFiles()) {
943 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
944 for (uint32_t i = 0; i < dex_file->NumClassDefs(); ++i) {
945 const DexFile::ClassDef& class_def = dex_file->GetClassDef(i);
946 const uint8_t* class_data = dex_file->GetClassData(class_def);
947 if (class_data != nullptr) {
948 for (ClassDataItemIterator class_it(*dex_file, class_data);
949 class_it.HasNext();
950 class_it.Next()) {
951 if (class_it.IsAtMethod() && class_it.GetMethodCodeItem() != nullptr) {
Mathieu Chartier0021feb2017-11-07 00:08:52 -0800952 for (const DexInstructionPcPair& inst :
Mathieu Chartier698ebbc2018-01-05 11:00:42 -0800953 CodeItemInstructionAccessor(*dex_file, class_it.GetMethodCodeItem())) {
Mathieu Chartier02129102017-12-22 11:04:01 -0800954 ASSERT_FALSE(inst->IsQuickened()) << output_;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100955 }
956 }
957 }
958 }
959 }
960 }
961 }
962};
963
964TEST_F(Dex2oatUnquickenTest, UnquickenMultiDex) {
965 RunUnquickenMultiDex();
966}
967
Andreas Gampe2e8a2562017-01-18 20:39:02 -0800968class Dex2oatWatchdogTest : public Dex2oatTest {
969 protected:
970 void RunTest(bool expect_success, const std::vector<std::string>& extra_args = {}) {
971 std::string dex_location = GetScratchDir() + "/Dex2OatSwapTest.jar";
972 std::string odex_location = GetOdexDir() + "/Dex2OatSwapTest.odex";
973
974 Copy(GetTestDexFileName(), dex_location);
975
976 std::vector<std::string> copy(extra_args);
977
978 std::string swap_location = GetOdexDir() + "/Dex2OatSwapTest.odex.swap";
979 copy.push_back("--swap-file=" + swap_location);
Andreas Gampe22fa3762017-10-23 20:58:12 -0700980 copy.push_back("-j512"); // Excessive idle threads just slow down dex2oat.
Andreas Gampe2e8a2562017-01-18 20:39:02 -0800981 GenerateOdexForTest(dex_location,
982 odex_location,
983 CompilerFilter::kSpeed,
984 copy,
985 expect_success);
986 }
987
988 std::string GetTestDexFileName() {
989 return GetDexSrc1();
990 }
991};
992
993TEST_F(Dex2oatWatchdogTest, TestWatchdogOK) {
994 // Check with default.
995 RunTest(true);
996
997 // Check with ten minutes.
998 RunTest(true, { "--watchdog-timeout=600000" });
999}
1000
1001TEST_F(Dex2oatWatchdogTest, TestWatchdogTrigger) {
Roland Levillain68db2252017-08-14 12:48:47 +01001002 TEST_DISABLED_FOR_MEMORY_TOOL_VALGRIND(); // b/63052624
Andreas Gampe80ddf272018-01-11 09:41:00 -08001003
1004 // The watchdog is independent of dex2oat and will not delete intermediates. It is possible
1005 // that the compilation succeeds and the file is completely written by the time the watchdog
1006 // kills dex2oat (but the dex2oat threads must have been scheduled pretty badly).
1007 test_accepts_odex_file_on_failure = true;
1008
Andreas Gampe2e8a2562017-01-18 20:39:02 -08001009 // Check with ten milliseconds.
1010 RunTest(false, { "--watchdog-timeout=10" });
1011}
1012
Andreas Gampef7882972017-03-20 16:35:24 -07001013class Dex2oatReturnCodeTest : public Dex2oatTest {
1014 protected:
1015 int RunTest(const std::vector<std::string>& extra_args = {}) {
1016 std::string dex_location = GetScratchDir() + "/Dex2OatSwapTest.jar";
1017 std::string odex_location = GetOdexDir() + "/Dex2OatSwapTest.odex";
1018
1019 Copy(GetTestDexFileName(), dex_location);
1020
1021 std::string error_msg;
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001022 return GenerateOdexForTestWithStatus({dex_location},
Andreas Gampef7882972017-03-20 16:35:24 -07001023 odex_location,
1024 CompilerFilter::kSpeed,
1025 &error_msg,
1026 extra_args);
1027 }
1028
1029 std::string GetTestDexFileName() {
1030 return GetDexSrc1();
1031 }
1032};
1033
1034TEST_F(Dex2oatReturnCodeTest, TestCreateRuntime) {
Andreas Gampefd80b172017-04-26 22:25:31 -07001035 TEST_DISABLED_FOR_MEMORY_TOOL(); // b/19100793
Andreas Gampef7882972017-03-20 16:35:24 -07001036 int status = RunTest({ "--boot-image=/this/does/not/exist/yolo.oat" });
1037 EXPECT_EQ(static_cast<int>(dex2oat::ReturnCode::kCreateRuntime), WEXITSTATUS(status)) << output_;
1038}
1039
Calin Juravle1ce70852017-06-28 10:59:03 -07001040class Dex2oatClassLoaderContextTest : public Dex2oatTest {
1041 protected:
1042 void RunTest(const char* class_loader_context,
1043 const char* expected_classpath_key,
1044 bool expected_success,
1045 bool use_second_source = false) {
1046 std::string dex_location = GetUsedDexLocation();
1047 std::string odex_location = GetUsedOatLocation();
1048
1049 Copy(use_second_source ? GetDexSrc2() : GetDexSrc1(), dex_location);
1050
1051 std::string error_msg;
1052 std::vector<std::string> extra_args;
1053 if (class_loader_context != nullptr) {
1054 extra_args.push_back(std::string("--class-loader-context=") + class_loader_context);
1055 }
1056 auto check_oat = [expected_classpath_key](const OatFile& oat_file) {
1057 ASSERT_TRUE(expected_classpath_key != nullptr);
1058 const char* classpath = oat_file.GetOatHeader().GetStoreValueByKey(OatHeader::kClassPathKey);
1059 ASSERT_TRUE(classpath != nullptr);
1060 ASSERT_STREQ(expected_classpath_key, classpath);
1061 };
1062
1063 GenerateOdexForTest(dex_location,
1064 odex_location,
1065 CompilerFilter::kQuicken,
1066 extra_args,
1067 expected_success,
1068 /*use_fd*/ false,
1069 check_oat);
1070 }
1071
1072 std::string GetUsedDexLocation() {
1073 return GetScratchDir() + "/Context.jar";
1074 }
1075
1076 std::string GetUsedOatLocation() {
1077 return GetOdexDir() + "/Context.odex";
1078 }
1079
Calin Juravle7b0648a2017-07-07 18:40:50 -07001080 const char* kEmptyClassPathKey = "PCL[]";
Calin Juravle1ce70852017-06-28 10:59:03 -07001081};
1082
1083TEST_F(Dex2oatClassLoaderContextTest, InvalidContext) {
1084 RunTest("Invalid[]", /*expected_classpath_key*/ nullptr, /*expected_success*/ false);
1085}
1086
1087TEST_F(Dex2oatClassLoaderContextTest, EmptyContext) {
1088 RunTest("PCL[]", kEmptyClassPathKey, /*expected_success*/ true);
1089}
1090
1091TEST_F(Dex2oatClassLoaderContextTest, SpecialContext) {
1092 RunTest(OatFile::kSpecialSharedLibrary,
1093 OatFile::kSpecialSharedLibrary,
1094 /*expected_success*/ true);
1095}
1096
1097TEST_F(Dex2oatClassLoaderContextTest, ContextWithTheSourceDexFiles) {
1098 std::string context = "PCL[" + GetUsedDexLocation() + "]";
1099 RunTest(context.c_str(), kEmptyClassPathKey, /*expected_success*/ true);
1100}
1101
1102TEST_F(Dex2oatClassLoaderContextTest, ContextWithOtherDexFiles) {
1103 std::vector<std::unique_ptr<const DexFile>> dex_files = OpenTestDexFiles("Nested");
Calin Juravle1ce70852017-06-28 10:59:03 -07001104
1105 std::string context = "PCL[" + dex_files[0]->GetLocation() + "]";
Calin Juravle7b0648a2017-07-07 18:40:50 -07001106 std::string expected_classpath_key = "PCL[" +
1107 dex_files[0]->GetLocation() + "*" + std::to_string(dex_files[0]->GetLocationChecksum()) + "]";
Calin Juravle1ce70852017-06-28 10:59:03 -07001108 RunTest(context.c_str(), expected_classpath_key.c_str(), true);
1109}
1110
1111TEST_F(Dex2oatClassLoaderContextTest, ContextWithStrippedDexFiles) {
1112 std::string stripped_classpath = GetScratchDir() + "/stripped_classpath.jar";
1113 Copy(GetStrippedDexSrc1(), stripped_classpath);
1114
1115 std::string context = "PCL[" + stripped_classpath + "]";
1116 // Expect an empty context because stripped dex files cannot be open.
Calin Juravle7b0648a2017-07-07 18:40:50 -07001117 RunTest(context.c_str(), kEmptyClassPathKey , /*expected_success*/ true);
Calin Juravle1ce70852017-06-28 10:59:03 -07001118}
1119
1120TEST_F(Dex2oatClassLoaderContextTest, ContextWithStrippedDexFilesBackedByOdex) {
1121 std::string stripped_classpath = GetScratchDir() + "/stripped_classpath.jar";
1122 std::string odex_for_classpath = GetOdexDir() + "/stripped_classpath.odex";
1123
1124 Copy(GetDexSrc1(), stripped_classpath);
1125
1126 GenerateOdexForTest(stripped_classpath,
1127 odex_for_classpath,
1128 CompilerFilter::kQuicken,
1129 {},
1130 true);
1131
1132 // Strip the dex file
1133 Copy(GetStrippedDexSrc1(), stripped_classpath);
1134
1135 std::string context = "PCL[" + stripped_classpath + "]";
Calin Juravle7b0648a2017-07-07 18:40:50 -07001136 std::string expected_classpath_key;
Calin Juravle1ce70852017-06-28 10:59:03 -07001137 {
1138 // Open the oat file to get the expected classpath.
1139 OatFileAssistant oat_file_assistant(stripped_classpath.c_str(), kRuntimeISA, false);
1140 std::unique_ptr<OatFile> oat_file(oat_file_assistant.GetBestOatFile());
1141 std::vector<std::unique_ptr<const DexFile>> oat_dex_files =
1142 OatFileAssistant::LoadDexFiles(*oat_file, stripped_classpath.c_str());
Calin Juravle7b0648a2017-07-07 18:40:50 -07001143 expected_classpath_key = "PCL[";
1144 for (size_t i = 0; i < oat_dex_files.size(); i++) {
1145 if (i > 0) {
1146 expected_classpath_key + ":";
1147 }
1148 expected_classpath_key += oat_dex_files[i]->GetLocation() + "*" +
1149 std::to_string(oat_dex_files[i]->GetLocationChecksum());
1150 }
1151 expected_classpath_key += "]";
Calin Juravle1ce70852017-06-28 10:59:03 -07001152 }
1153
1154 RunTest(context.c_str(),
Calin Juravle7b0648a2017-07-07 18:40:50 -07001155 expected_classpath_key.c_str(),
Calin Juravle1ce70852017-06-28 10:59:03 -07001156 /*expected_success*/ true,
1157 /*use_second_source*/ true);
1158}
1159
1160TEST_F(Dex2oatClassLoaderContextTest, ContextWithNotExistentDexFiles) {
1161 std::string context = "PCL[does_not_exists.dex]";
1162 // Expect an empty context because stripped dex files cannot be open.
1163 RunTest(context.c_str(), kEmptyClassPathKey, /*expected_success*/ true);
1164}
1165
Calin Juravlec79470d2017-07-12 17:37:42 -07001166TEST_F(Dex2oatClassLoaderContextTest, ChainContext) {
1167 std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested");
1168 std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex");
1169
1170 std::string context = "PCL[" + GetTestDexFileName("Nested") + "];" +
1171 "DLC[" + GetTestDexFileName("MultiDex") + "]";
1172 std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "];" +
1173 "DLC[" + CreateClassPathWithChecksums(dex_files2) + "]";
1174
1175 RunTest(context.c_str(), expected_classpath_key.c_str(), true);
1176}
1177
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001178class Dex2oatDeterminism : public Dex2oatTest {};
1179
1180TEST_F(Dex2oatDeterminism, UnloadCompile) {
1181 if (!kUseReadBarrier &&
1182 gc::kCollectorTypeDefault != gc::kCollectorTypeCMS &&
1183 gc::kCollectorTypeDefault != gc::kCollectorTypeMS) {
1184 LOG(INFO) << "Test requires determinism support.";
1185 return;
1186 }
1187 Runtime* const runtime = Runtime::Current();
1188 std::string out_dir = GetScratchDir();
1189 const std::string base_oat_name = out_dir + "/base.oat";
1190 const std::string base_vdex_name = out_dir + "/base.vdex";
1191 const std::string unload_oat_name = out_dir + "/unload.oat";
1192 const std::string unload_vdex_name = out_dir + "/unload.vdex";
1193 const std::string no_unload_oat_name = out_dir + "/nounload.oat";
1194 const std::string no_unload_vdex_name = out_dir + "/nounload.vdex";
1195 const std::string app_image_name = out_dir + "/unload.art";
1196 std::string error_msg;
1197 const std::vector<gc::space::ImageSpace*>& spaces = runtime->GetHeap()->GetBootImageSpaces();
1198 ASSERT_GT(spaces.size(), 0u);
1199 const std::string image_location = spaces[0]->GetImageLocation();
1200 // Without passing in an app image, it will unload in between compilations.
1201 const int res = GenerateOdexForTestWithStatus(
1202 GetLibCoreDexFileNames(),
1203 base_oat_name,
1204 CompilerFilter::Filter::kQuicken,
1205 &error_msg,
1206 {"--force-determinism", "--avoid-storing-invocation"});
1207 EXPECT_EQ(res, 0);
1208 Copy(base_oat_name, unload_oat_name);
1209 Copy(base_vdex_name, unload_vdex_name);
1210 std::unique_ptr<File> unload_oat(OS::OpenFileForReading(unload_oat_name.c_str()));
1211 std::unique_ptr<File> unload_vdex(OS::OpenFileForReading(unload_vdex_name.c_str()));
1212 ASSERT_TRUE(unload_oat != nullptr);
1213 ASSERT_TRUE(unload_vdex != nullptr);
1214 EXPECT_GT(unload_oat->GetLength(), 0u);
1215 EXPECT_GT(unload_vdex->GetLength(), 0u);
1216 // Regenerate with an app image to disable the dex2oat unloading and verify that the output is
1217 // the same.
1218 const int res2 = GenerateOdexForTestWithStatus(
1219 GetLibCoreDexFileNames(),
1220 base_oat_name,
1221 CompilerFilter::Filter::kQuicken,
1222 &error_msg,
1223 {"--force-determinism", "--avoid-storing-invocation", "--app-image-file=" + app_image_name});
1224 EXPECT_EQ(res2, 0);
1225 Copy(base_oat_name, no_unload_oat_name);
1226 Copy(base_vdex_name, no_unload_vdex_name);
1227 std::unique_ptr<File> no_unload_oat(OS::OpenFileForReading(no_unload_oat_name.c_str()));
1228 std::unique_ptr<File> no_unload_vdex(OS::OpenFileForReading(no_unload_vdex_name.c_str()));
1229 ASSERT_TRUE(no_unload_oat != nullptr);
1230 ASSERT_TRUE(no_unload_vdex != nullptr);
1231 EXPECT_GT(no_unload_oat->GetLength(), 0u);
1232 EXPECT_GT(no_unload_vdex->GetLength(), 0u);
1233 // Verify that both of the files are the same (odex and vdex).
1234 EXPECT_EQ(unload_oat->GetLength(), no_unload_oat->GetLength());
1235 EXPECT_EQ(unload_vdex->GetLength(), no_unload_vdex->GetLength());
1236 EXPECT_EQ(unload_oat->Compare(no_unload_oat.get()), 0)
1237 << unload_oat_name << " " << no_unload_oat_name;
1238 EXPECT_EQ(unload_vdex->Compare(no_unload_vdex.get()), 0)
1239 << unload_vdex_name << " " << no_unload_vdex_name;
1240 // App image file.
1241 std::unique_ptr<File> app_image_file(OS::OpenFileForReading(app_image_name.c_str()));
1242 ASSERT_TRUE(app_image_file != nullptr);
1243 EXPECT_GT(app_image_file->GetLength(), 0u);
1244}
1245
Mathieu Chartier120aa282017-08-05 16:03:03 -07001246// Test that dexlayout section info is correctly written to the oat file for profile based
1247// compilation.
1248TEST_F(Dex2oatTest, LayoutSections) {
1249 using Hotness = ProfileCompilationInfo::MethodHotness;
1250 std::unique_ptr<const DexFile> dex(OpenTestDexFile("ManyMethods"));
1251 ScratchFile profile_file;
1252 // We can only layout method indices with code items, figure out which ones have this property
1253 // first.
1254 std::vector<uint16_t> methods;
1255 {
1256 const DexFile::TypeId* type_id = dex->FindTypeId("LManyMethods;");
1257 dex::TypeIndex type_idx = dex->GetIndexForTypeId(*type_id);
1258 const DexFile::ClassDef* class_def = dex->FindClassDef(type_idx);
1259 ClassDataItemIterator it(*dex, dex->GetClassData(*class_def));
1260 it.SkipAllFields();
1261 std::set<size_t> code_item_offsets;
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08001262 for (; it.HasNextMethod(); it.Next()) {
Mathieu Chartier120aa282017-08-05 16:03:03 -07001263 const uint16_t method_idx = it.GetMemberIndex();
1264 const size_t code_item_offset = it.GetMethodCodeItemOffset();
1265 if (code_item_offsets.insert(code_item_offset).second) {
1266 // Unique code item, add the method index.
1267 methods.push_back(method_idx);
1268 }
1269 }
1270 DCHECK(!it.HasNext());
1271 }
1272 ASSERT_GE(methods.size(), 8u);
1273 std::vector<uint16_t> hot_methods = {methods[1], methods[3], methods[5]};
1274 std::vector<uint16_t> startup_methods = {methods[1], methods[2], methods[7]};
1275 std::vector<uint16_t> post_methods = {methods[0], methods[2], methods[6]};
1276 // Here, we build the profile from the method lists.
1277 ProfileCompilationInfo info;
1278 info.AddMethodsForDex(
1279 static_cast<Hotness::Flag>(Hotness::kFlagHot | Hotness::kFlagStartup),
1280 dex.get(),
1281 hot_methods.begin(),
1282 hot_methods.end());
1283 info.AddMethodsForDex(
1284 Hotness::kFlagStartup,
1285 dex.get(),
1286 startup_methods.begin(),
1287 startup_methods.end());
1288 info.AddMethodsForDex(
1289 Hotness::kFlagPostStartup,
1290 dex.get(),
1291 post_methods.begin(),
1292 post_methods.end());
1293 for (uint16_t id : hot_methods) {
1294 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsHot());
1295 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsStartup());
1296 }
1297 for (uint16_t id : startup_methods) {
1298 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsStartup());
1299 }
1300 for (uint16_t id : post_methods) {
1301 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsPostStartup());
1302 }
1303 // Save the profile since we want to use it with dex2oat to produce an oat file.
1304 ASSERT_TRUE(info.Save(profile_file.GetFd()));
1305 // Generate a profile based odex.
1306 const std::string dir = GetScratchDir();
1307 const std::string oat_filename = dir + "/base.oat";
1308 const std::string vdex_filename = dir + "/base.vdex";
1309 std::string error_msg;
1310 const int res = GenerateOdexForTestWithStatus(
1311 {dex->GetLocation()},
1312 oat_filename,
1313 CompilerFilter::Filter::kQuicken,
1314 &error_msg,
1315 {"--profile-file=" + profile_file.GetFilename()});
1316 EXPECT_EQ(res, 0);
1317
1318 // Open our generated oat file.
1319 std::unique_ptr<OatFile> odex_file(OatFile::Open(oat_filename.c_str(),
1320 oat_filename.c_str(),
1321 nullptr,
1322 nullptr,
1323 false,
1324 /*low_4gb*/false,
1325 dex->GetLocation().c_str(),
1326 &error_msg));
1327 ASSERT_TRUE(odex_file != nullptr);
1328 std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
1329 ASSERT_EQ(oat_dex_files.size(), 1u);
1330 // Check that the code sections match what we expect.
1331 for (const OatDexFile* oat_dex : oat_dex_files) {
1332 const DexLayoutSections* const sections = oat_dex->GetDexLayoutSections();
1333 // Testing of logging the sections.
1334 ASSERT_TRUE(sections != nullptr);
1335 LOG(INFO) << *sections;
1336
1337 // Load the sections into temporary variables for convenience.
1338 const DexLayoutSection& code_section =
1339 sections->sections_[static_cast<size_t>(DexLayoutSections::SectionType::kSectionTypeCode)];
1340 const DexLayoutSection::Subsection& section_hot_code =
1341 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeHot)];
1342 const DexLayoutSection::Subsection& section_sometimes_used =
1343 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeSometimesUsed)];
1344 const DexLayoutSection::Subsection& section_startup_only =
1345 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeStartupOnly)];
1346 const DexLayoutSection::Subsection& section_unused =
1347 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeUnused)];
1348
1349 // All the sections should be non-empty.
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001350 EXPECT_GT(section_hot_code.Size(), 0u);
1351 EXPECT_GT(section_sometimes_used.Size(), 0u);
1352 EXPECT_GT(section_startup_only.Size(), 0u);
1353 EXPECT_GT(section_unused.Size(), 0u);
Mathieu Chartier120aa282017-08-05 16:03:03 -07001354
1355 // Open the dex file since we need to peek at the code items to verify the layout matches what
1356 // we expect.
1357 std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1358 ASSERT_TRUE(dex_file != nullptr) << error_msg;
1359 const DexFile::TypeId* type_id = dex_file->FindTypeId("LManyMethods;");
1360 ASSERT_TRUE(type_id != nullptr);
1361 dex::TypeIndex type_idx = dex_file->GetIndexForTypeId(*type_id);
1362 const DexFile::ClassDef* class_def = dex_file->FindClassDef(type_idx);
1363 ASSERT_TRUE(class_def != nullptr);
1364
1365 // Count how many code items are for each category, there should be at least one per category.
1366 size_t hot_count = 0;
1367 size_t post_startup_count = 0;
1368 size_t startup_count = 0;
1369 size_t unused_count = 0;
1370 // Visit all of the methdos of the main class and cross reference the method indices to their
1371 // corresponding code item offsets to verify the layout.
1372 ClassDataItemIterator it(*dex_file, dex_file->GetClassData(*class_def));
1373 it.SkipAllFields();
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08001374 for (; it.HasNextMethod(); it.Next()) {
Mathieu Chartier120aa282017-08-05 16:03:03 -07001375 const size_t method_idx = it.GetMemberIndex();
1376 const size_t code_item_offset = it.GetMethodCodeItemOffset();
1377 const bool is_hot = ContainsElement(hot_methods, method_idx);
1378 const bool is_startup = ContainsElement(startup_methods, method_idx);
1379 const bool is_post_startup = ContainsElement(post_methods, method_idx);
1380 if (is_hot) {
1381 // Hot is highest precedence, check that the hot methods are in the hot section.
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001382 EXPECT_TRUE(section_hot_code.Contains(code_item_offset));
Mathieu Chartier120aa282017-08-05 16:03:03 -07001383 ++hot_count;
1384 } else if (is_post_startup) {
1385 // Post startup is sometimes used section.
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001386 EXPECT_TRUE(section_sometimes_used.Contains(code_item_offset));
Mathieu Chartier120aa282017-08-05 16:03:03 -07001387 ++post_startup_count;
1388 } else if (is_startup) {
1389 // Startup at this point means not hot or post startup, these must be startup only then.
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001390 EXPECT_TRUE(section_startup_only.Contains(code_item_offset));
Mathieu Chartier120aa282017-08-05 16:03:03 -07001391 ++startup_count;
1392 } else {
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001393 if (section_unused.Contains(code_item_offset)) {
Alan Leung9595fd32017-10-17 17:08:19 -07001394 // If no flags are set, the method should be unused ...
1395 ++unused_count;
1396 } else {
1397 // or this method is part of the last code item and the end is 4 byte aligned.
1398 ClassDataItemIterator it2(*dex_file, dex_file->GetClassData(*class_def));
1399 it2.SkipAllFields();
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08001400 for (; it2.HasNextMethod(); it2.Next()) {
Alan Leung9595fd32017-10-17 17:08:19 -07001401 EXPECT_LE(it2.GetMethodCodeItemOffset(), code_item_offset);
1402 }
1403 uint32_t code_item_size = dex_file->FindCodeItemOffset(*class_def, method_idx);
1404 EXPECT_EQ((code_item_offset + code_item_size) % 4, 0u);
1405 }
Mathieu Chartier120aa282017-08-05 16:03:03 -07001406 }
1407 }
1408 DCHECK(!it.HasNext());
1409 EXPECT_GT(hot_count, 0u);
1410 EXPECT_GT(post_startup_count, 0u);
1411 EXPECT_GT(startup_count, 0u);
1412 EXPECT_GT(unused_count, 0u);
1413 }
1414}
1415
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001416// Test that generating compact dex works.
1417TEST_F(Dex2oatTest, GenerateCompactDex) {
1418 std::unique_ptr<const DexFile> dex(OpenTestDexFile("ManyMethods"));
1419 // Generate a compact dex based odex.
1420 const std::string dir = GetScratchDir();
1421 const std::string oat_filename = dir + "/base.oat";
1422 const std::string vdex_filename = dir + "/base.vdex";
1423 std::string error_msg;
1424 const int res = GenerateOdexForTestWithStatus(
1425 {dex->GetLocation()},
1426 oat_filename,
1427 CompilerFilter::Filter::kQuicken,
1428 &error_msg,
1429 {"--compact-dex-level=fast"});
1430 EXPECT_EQ(res, 0);
1431 // Open our generated oat file.
1432 std::unique_ptr<OatFile> odex_file(OatFile::Open(oat_filename.c_str(),
1433 oat_filename.c_str(),
1434 nullptr,
1435 nullptr,
1436 false,
1437 /*low_4gb*/false,
1438 dex->GetLocation().c_str(),
1439 &error_msg));
1440 ASSERT_TRUE(odex_file != nullptr);
1441 std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
1442 ASSERT_EQ(oat_dex_files.size(), 1u);
1443 // Check that each dex is a compact dex.
1444 for (const OatDexFile* oat_dex : oat_dex_files) {
1445 std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1446 ASSERT_TRUE(dex_file != nullptr) << error_msg;
1447 ASSERT_TRUE(dex_file->IsCompactDexFile());
1448 }
1449}
1450
Andreas Gampef39208f2017-10-19 15:06:59 -07001451class Dex2oatVerifierAbort : public Dex2oatTest {};
1452
1453TEST_F(Dex2oatVerifierAbort, HardFail) {
1454 // Use VerifierDeps as it has hard-failing classes.
1455 std::unique_ptr<const DexFile> dex(OpenTestDexFile("VerifierDeps"));
1456 std::string out_dir = GetScratchDir();
1457 const std::string base_oat_name = out_dir + "/base.oat";
1458 std::string error_msg;
1459 const int res_fail = GenerateOdexForTestWithStatus(
1460 {dex->GetLocation()},
1461 base_oat_name,
1462 CompilerFilter::Filter::kQuicken,
1463 &error_msg,
1464 {"--abort-on-hard-verifier-error"});
1465 EXPECT_NE(0, res_fail);
1466
1467 const int res_no_fail = GenerateOdexForTestWithStatus(
1468 {dex->GetLocation()},
1469 base_oat_name,
1470 CompilerFilter::Filter::kQuicken,
1471 &error_msg,
1472 {"--no-abort-on-hard-verifier-error"});
1473 EXPECT_EQ(0, res_no_fail);
1474}
1475
1476TEST_F(Dex2oatVerifierAbort, SoftFail) {
1477 // Use VerifierDepsMulti as it has hard-failing classes.
1478 std::unique_ptr<const DexFile> dex(OpenTestDexFile("VerifierDepsMulti"));
1479 std::string out_dir = GetScratchDir();
1480 const std::string base_oat_name = out_dir + "/base.oat";
1481 std::string error_msg;
1482 const int res_fail = GenerateOdexForTestWithStatus(
1483 {dex->GetLocation()},
1484 base_oat_name,
1485 CompilerFilter::Filter::kQuicken,
1486 &error_msg,
1487 {"--abort-on-soft-verifier-error"});
1488 EXPECT_NE(0, res_fail);
1489
1490 const int res_no_fail = GenerateOdexForTestWithStatus(
1491 {dex->GetLocation()},
1492 base_oat_name,
1493 CompilerFilter::Filter::kQuicken,
1494 &error_msg,
1495 {"--no-abort-on-soft-verifier-error"});
1496 EXPECT_EQ(0, res_no_fail);
1497}
1498
Andreas Gampecac31ad2017-11-06 20:01:17 -08001499class Dex2oatDedupeCode : public Dex2oatTest {};
1500
1501TEST_F(Dex2oatDedupeCode, DedupeTest) {
1502 // Use MyClassNatives. It has lots of native methods that will produce deduplicate-able code.
1503 std::unique_ptr<const DexFile> dex(OpenTestDexFile("MyClassNatives"));
1504 std::string out_dir = GetScratchDir();
1505 const std::string base_oat_name = out_dir + "/base.oat";
1506 size_t no_dedupe_size = 0;
1507 GenerateOdexForTest(dex->GetLocation(),
1508 base_oat_name,
1509 CompilerFilter::Filter::kSpeed,
1510 { "--deduplicate-code=false" },
1511 true, // expect_success
1512 false, // use_fd
1513 [&no_dedupe_size](const OatFile& o) {
1514 no_dedupe_size = o.Size();
1515 });
1516
1517 size_t dedupe_size = 0;
1518 GenerateOdexForTest(dex->GetLocation(),
1519 base_oat_name,
1520 CompilerFilter::Filter::kSpeed,
1521 { "--deduplicate-code=true" },
1522 true, // expect_success
1523 false, // use_fd
1524 [&dedupe_size](const OatFile& o) {
1525 dedupe_size = o.Size();
1526 });
1527
1528 EXPECT_LT(dedupe_size, no_dedupe_size);
1529}
1530
Andreas Gampee1459ae2016-06-29 09:36:30 -07001531} // namespace art