blob: 5590c8b3abfea5a7078fe63af56ace20c03885ec [file] [log] [blame]
Andreas Gampee1459ae2016-06-29 09:36:30 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Igor Murashkin5573c372017-11-16 13:34:30 -080017#include <regex>
Andreas Gampe7adeda82016-07-25 08:27:35 -070018#include <sstream>
Andreas Gampee1459ae2016-06-29 09:36:30 -070019#include <string>
20#include <vector>
Andreas Gampee1459ae2016-06-29 09:36:30 -070021
Andreas Gampe46ee31b2016-12-14 10:11:49 -080022#include <sys/wait.h>
23#include <unistd.h>
24
Andreas Gampe57943812017-12-06 21:39:13 -080025#include <android-base/logging.h>
26#include <android-base/stringprintf.h>
Andreas Gampe46ee31b2016-12-14 10:11:49 -080027
Andreas Gampee1459ae2016-06-29 09:36:30 -070028#include "common_runtime_test.h"
29
Andreas Gampee1459ae2016-06-29 09:36:30 -070030#include "base/macros.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070031#include "base/mutex-inl.h"
David Sehr8f4b0562018-03-02 12:01:51 -080032#include "base/utils.h"
David Sehr013fd802018-01-11 22:55:24 -080033#include "dex/art_dex_file_loader.h"
Mathieu Chartier05f90d12018-02-07 13:47:17 -080034#include "dex/base64_test_util.h"
David Sehre6564f42018-03-19 08:39:26 -070035#include "dex/bytecode_utils.h"
David Sehr9e734c72018-01-04 17:56:19 -080036#include "dex/code_item_accessors-inl.h"
37#include "dex/dex_file-inl.h"
38#include "dex/dex_file_loader.h"
Andreas Gampee1459ae2016-06-29 09:36:30 -070039#include "dex2oat_environment_test.h"
Andreas Gampef7882972017-03-20 16:35:24 -070040#include "dex2oat_return_codes.h"
Calin Juravle33083d62017-01-18 15:29:12 -080041#include "jit/profile_compilation_info.h"
Andreas Gampe67f02822016-06-24 21:05:23 -070042#include "oat.h"
43#include "oat_file.h"
Mathieu Chartier792111c2018-02-15 13:02:15 -080044#include "vdex_file.h"
45#include "ziparchive/zip_writer.h"
Andreas Gampee1459ae2016-06-29 09:36:30 -070046
Andreas Gampee1459ae2016-06-29 09:36:30 -070047namespace art {
48
Mathieu Chartierea650f32017-05-24 12:04:13 -070049static constexpr size_t kMaxMethodIds = 65535;
Mathieu Chartier9e050df2017-08-09 10:05:47 -070050static constexpr bool kDebugArgs = false;
Mathieu Chartier02129102017-12-22 11:04:01 -080051static const char* kDisableCompactDex = "--compact-dex-level=none";
Mathieu Chartierea650f32017-05-24 12:04:13 -070052
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080053using android::base::StringPrintf;
54
Andreas Gampee1459ae2016-06-29 09:36:30 -070055class Dex2oatTest : public Dex2oatEnvironmentTest {
56 public:
57 virtual void TearDown() OVERRIDE {
58 Dex2oatEnvironmentTest::TearDown();
59
60 output_ = "";
61 error_msg_ = "";
62 success_ = false;
63 }
64
65 protected:
Mathieu Chartier9e050df2017-08-09 10:05:47 -070066 int GenerateOdexForTestWithStatus(const std::vector<std::string>& dex_locations,
Andreas Gampef7882972017-03-20 16:35:24 -070067 const std::string& odex_location,
68 CompilerFilter::Filter filter,
69 std::string* error_msg,
70 const std::vector<std::string>& extra_args = {},
71 bool use_fd = false) {
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080072 std::unique_ptr<File> oat_file;
Andreas Gampee1459ae2016-06-29 09:36:30 -070073 std::vector<std::string> args;
Mathieu Chartier9e050df2017-08-09 10:05:47 -070074 // Add dex file args.
75 for (const std::string& dex_location : dex_locations) {
76 args.push_back("--dex-file=" + dex_location);
77 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080078 if (use_fd) {
79 oat_file.reset(OS::CreateEmptyFile(odex_location.c_str()));
80 CHECK(oat_file != nullptr) << odex_location;
81 args.push_back("--oat-fd=" + std::to_string(oat_file->Fd()));
Mathieu Chartier046854b2017-03-01 17:16:22 -080082 args.push_back("--oat-location=" + odex_location);
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080083 } else {
84 args.push_back("--oat-file=" + odex_location);
85 }
Andreas Gampee1459ae2016-06-29 09:36:30 -070086 args.push_back("--compiler-filter=" + CompilerFilter::NameOfFilter(filter));
87 args.push_back("--runtime-arg");
88 args.push_back("-Xnorelocate");
89
90 args.insert(args.end(), extra_args.begin(), extra_args.end());
91
Andreas Gampef7882972017-03-20 16:35:24 -070092 int status = Dex2Oat(args, error_msg);
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080093 if (oat_file != nullptr) {
Andreas Gampef7882972017-03-20 16:35:24 -070094 CHECK_EQ(oat_file->FlushClose(), 0) << "Could not flush and close oat file";
Mathieu Chartier8bc343b2017-03-01 15:20:30 -080095 }
Andreas Gampef7882972017-03-20 16:35:24 -070096 return status;
97 }
Andreas Gampee1459ae2016-06-29 09:36:30 -070098
Andreas Gampe641a4732017-08-24 13:21:35 -070099 void GenerateOdexForTest(
100 const std::string& dex_location,
101 const std::string& odex_location,
102 CompilerFilter::Filter filter,
103 const std::vector<std::string>& extra_args = {},
104 bool expect_success = true,
105 bool use_fd = false) {
106 GenerateOdexForTest(dex_location,
107 odex_location,
108 filter,
109 extra_args,
110 expect_success,
111 use_fd,
112 [](const OatFile&) {});
113 }
114
Andreas Gampe80ddf272018-01-11 09:41:00 -0800115 bool test_accepts_odex_file_on_failure = false;
116
Andreas Gampe641a4732017-08-24 13:21:35 -0700117 template <typename T>
118 void GenerateOdexForTest(
119 const std::string& dex_location,
120 const std::string& odex_location,
121 CompilerFilter::Filter filter,
122 const std::vector<std::string>& extra_args,
123 bool expect_success,
124 bool use_fd,
125 T check_oat) {
Andreas Gampef7882972017-03-20 16:35:24 -0700126 std::string error_msg;
Mathieu Chartier9e050df2017-08-09 10:05:47 -0700127 int status = GenerateOdexForTestWithStatus({dex_location},
Andreas Gampef7882972017-03-20 16:35:24 -0700128 odex_location,
129 filter,
130 &error_msg,
131 extra_args,
132 use_fd);
Andreas Gampe80ddf272018-01-11 09:41:00 -0800133 bool success = (WIFEXITED(status) && WEXITSTATUS(status) == 0);
Andreas Gampee1459ae2016-06-29 09:36:30 -0700134 if (expect_success) {
Andreas Gampe2e8a2562017-01-18 20:39:02 -0800135 ASSERT_TRUE(success) << error_msg << std::endl << output_;
Andreas Gampee1459ae2016-06-29 09:36:30 -0700136
137 // Verify the odex file was generated as expected.
138 std::unique_ptr<OatFile> odex_file(OatFile::Open(odex_location.c_str(),
139 odex_location.c_str(),
140 nullptr,
141 nullptr,
142 false,
143 /*low_4gb*/false,
144 dex_location.c_str(),
145 &error_msg));
146 ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
147
148 CheckFilter(filter, odex_file->GetCompilerFilter());
Calin Juravle1ce70852017-06-28 10:59:03 -0700149 check_oat(*(odex_file.get()));
Andreas Gampee1459ae2016-06-29 09:36:30 -0700150 } else {
151 ASSERT_FALSE(success) << output_;
152
153 error_msg_ = error_msg;
154
Andreas Gampe80ddf272018-01-11 09:41:00 -0800155 if (!test_accepts_odex_file_on_failure) {
156 // Verify there's no loadable odex file.
157 std::unique_ptr<OatFile> odex_file(OatFile::Open(odex_location.c_str(),
158 odex_location.c_str(),
159 nullptr,
160 nullptr,
161 false,
162 /*low_4gb*/false,
163 dex_location.c_str(),
164 &error_msg));
165 ASSERT_TRUE(odex_file.get() == nullptr);
166 }
Andreas Gampee1459ae2016-06-29 09:36:30 -0700167 }
168 }
169
Calin Juravle1ccf6132017-08-02 17:46:53 -0700170 // Check the input compiler filter against the generated oat file's filter. May be overridden
Andreas Gampee1459ae2016-06-29 09:36:30 -0700171 // in subclasses when equality is not expected.
172 virtual void CheckFilter(CompilerFilter::Filter expected, CompilerFilter::Filter actual) {
173 EXPECT_EQ(expected, actual);
174 }
175
Andreas Gampef7882972017-03-20 16:35:24 -0700176 int Dex2Oat(const std::vector<std::string>& dex2oat_args, std::string* error_msg) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700177 Runtime* runtime = Runtime::Current();
178
179 const std::vector<gc::space::ImageSpace*>& image_spaces =
180 runtime->GetHeap()->GetBootImageSpaces();
181 if (image_spaces.empty()) {
182 *error_msg = "No image location found for Dex2Oat.";
183 return false;
184 }
185 std::string image_location = image_spaces[0]->GetImageLocation();
186
187 std::vector<std::string> argv;
188 argv.push_back(runtime->GetCompilerExecutable());
Calin Juravle1ccf6132017-08-02 17:46:53 -0700189
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000190 if (runtime->IsJavaDebuggable()) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700191 argv.push_back("--debuggable");
192 }
193 runtime->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv);
194
195 if (!runtime->IsVerificationEnabled()) {
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100196 argv.push_back("--compiler-filter=assume-verified");
Andreas Gampee1459ae2016-06-29 09:36:30 -0700197 }
198
199 if (runtime->MustRelocateIfPossible()) {
200 argv.push_back("--runtime-arg");
201 argv.push_back("-Xrelocate");
202 } else {
203 argv.push_back("--runtime-arg");
204 argv.push_back("-Xnorelocate");
205 }
206
207 if (!kIsTargetBuild) {
208 argv.push_back("--host");
209 }
210
211 argv.push_back("--boot-image=" + image_location);
212
213 std::vector<std::string> compiler_options = runtime->GetCompilerOptions();
214 argv.insert(argv.end(), compiler_options.begin(), compiler_options.end());
215
216 argv.insert(argv.end(), dex2oat_args.begin(), dex2oat_args.end());
217
218 // We must set --android-root.
219 const char* android_root = getenv("ANDROID_ROOT");
220 CHECK(android_root != nullptr);
221 argv.push_back("--android-root=" + std::string(android_root));
222
Mathieu Chartier9e050df2017-08-09 10:05:47 -0700223 if (kDebugArgs) {
224 std::string all_args;
225 for (const std::string& arg : argv) {
226 all_args += arg + " ";
227 }
228 LOG(ERROR) << all_args;
229 }
230
Nicolas Geoffray56fe0f02016-06-30 15:07:46 +0100231 int link[2];
Andreas Gampee1459ae2016-06-29 09:36:30 -0700232
Nicolas Geoffray56fe0f02016-06-30 15:07:46 +0100233 if (pipe(link) == -1) {
234 return false;
235 }
Andreas Gampee1459ae2016-06-29 09:36:30 -0700236
Nicolas Geoffray56fe0f02016-06-30 15:07:46 +0100237 pid_t pid = fork();
238 if (pid == -1) {
239 return false;
240 }
Andreas Gampee1459ae2016-06-29 09:36:30 -0700241
Nicolas Geoffray56fe0f02016-06-30 15:07:46 +0100242 if (pid == 0) {
243 // We need dex2oat to actually log things.
244 setenv("ANDROID_LOG_TAGS", "*:d", 1);
245 dup2(link[1], STDERR_FILENO);
246 close(link[0]);
247 close(link[1]);
248 std::vector<const char*> c_args;
249 for (const std::string& str : argv) {
250 c_args.push_back(str.c_str());
Andreas Gampee1459ae2016-06-29 09:36:30 -0700251 }
Nicolas Geoffray56fe0f02016-06-30 15:07:46 +0100252 c_args.push_back(nullptr);
253 execv(c_args[0], const_cast<char* const*>(c_args.data()));
254 exit(1);
Andreas Gampef7882972017-03-20 16:35:24 -0700255 UNREACHABLE();
Nicolas Geoffray56fe0f02016-06-30 15:07:46 +0100256 } else {
257 close(link[1]);
258 char buffer[128];
259 memset(buffer, 0, 128);
260 ssize_t bytes_read = 0;
Andreas Gampee1459ae2016-06-29 09:36:30 -0700261
Nicolas Geoffray56fe0f02016-06-30 15:07:46 +0100262 while (TEMP_FAILURE_RETRY(bytes_read = read(link[0], buffer, 128)) > 0) {
263 output_ += std::string(buffer, bytes_read);
264 }
265 close(link[0]);
Andreas Gampef7882972017-03-20 16:35:24 -0700266 int status = -1;
Nicolas Geoffray56fe0f02016-06-30 15:07:46 +0100267 if (waitpid(pid, &status, 0) != -1) {
268 success_ = (status == 0);
269 }
Andreas Gampef7882972017-03-20 16:35:24 -0700270 return status;
Andreas Gampee1459ae2016-06-29 09:36:30 -0700271 }
Andreas Gampee1459ae2016-06-29 09:36:30 -0700272 }
273
274 std::string output_ = "";
275 std::string error_msg_ = "";
276 bool success_ = false;
277};
278
279class Dex2oatSwapTest : public Dex2oatTest {
280 protected:
281 void RunTest(bool use_fd, bool expect_use, const std::vector<std::string>& extra_args = {}) {
282 std::string dex_location = GetScratchDir() + "/Dex2OatSwapTest.jar";
283 std::string odex_location = GetOdexDir() + "/Dex2OatSwapTest.odex";
284
Andreas Gampe7adeda82016-07-25 08:27:35 -0700285 Copy(GetTestDexFileName(), dex_location);
Andreas Gampee1459ae2016-06-29 09:36:30 -0700286
287 std::vector<std::string> copy(extra_args);
288
289 std::unique_ptr<ScratchFile> sf;
290 if (use_fd) {
291 sf.reset(new ScratchFile());
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800292 copy.push_back(android::base::StringPrintf("--swap-fd=%d", sf->GetFd()));
Andreas Gampee1459ae2016-06-29 09:36:30 -0700293 } else {
294 std::string swap_location = GetOdexDir() + "/Dex2OatSwapTest.odex.swap";
295 copy.push_back("--swap-file=" + swap_location);
296 }
297 GenerateOdexForTest(dex_location, odex_location, CompilerFilter::kSpeed, copy);
298
299 CheckValidity();
300 ASSERT_TRUE(success_);
301 CheckResult(expect_use);
302 }
303
Andreas Gampe7adeda82016-07-25 08:27:35 -0700304 virtual std::string GetTestDexFileName() {
Vladimir Marko15357702017-02-09 10:37:31 +0000305 return Dex2oatEnvironmentTest::GetTestDexFileName("VerifierDeps");
Andreas Gampe7adeda82016-07-25 08:27:35 -0700306 }
307
308 virtual void CheckResult(bool expect_use) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700309 if (kIsTargetBuild) {
310 CheckTargetResult(expect_use);
311 } else {
312 CheckHostResult(expect_use);
313 }
314 }
315
Andreas Gampe7adeda82016-07-25 08:27:35 -0700316 virtual void CheckTargetResult(bool expect_use ATTRIBUTE_UNUSED) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700317 // TODO: Ignore for now, as we won't capture any output (it goes to the logcat). We may do
318 // something for variants with file descriptor where we can control the lifetime of
319 // the swap file and thus take a look at it.
320 }
321
Andreas Gampe7adeda82016-07-25 08:27:35 -0700322 virtual void CheckHostResult(bool expect_use) {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700323 if (!kIsTargetBuild) {
324 if (expect_use) {
325 EXPECT_NE(output_.find("Large app, accepted running with swap."), std::string::npos)
326 << output_;
327 } else {
328 EXPECT_EQ(output_.find("Large app, accepted running with swap."), std::string::npos)
329 << output_;
330 }
331 }
332 }
333
334 // Check whether the dex2oat run was really successful.
Andreas Gampe7adeda82016-07-25 08:27:35 -0700335 virtual void CheckValidity() {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700336 if (kIsTargetBuild) {
337 CheckTargetValidity();
338 } else {
339 CheckHostValidity();
340 }
341 }
342
Andreas Gampe7adeda82016-07-25 08:27:35 -0700343 virtual void CheckTargetValidity() {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700344 // TODO: Ignore for now, as we won't capture any output (it goes to the logcat). We may do
345 // something for variants with file descriptor where we can control the lifetime of
346 // the swap file and thus take a look at it.
347 }
348
349 // On the host, we can get the dex2oat output. Here, look for "dex2oat took."
Andreas Gampe7adeda82016-07-25 08:27:35 -0700350 virtual void CheckHostValidity() {
Andreas Gampee1459ae2016-06-29 09:36:30 -0700351 EXPECT_NE(output_.find("dex2oat took"), std::string::npos) << output_;
352 }
353};
354
355TEST_F(Dex2oatSwapTest, DoNotUseSwapDefaultSingleSmall) {
356 RunTest(false /* use_fd */, false /* expect_use */);
357 RunTest(true /* use_fd */, false /* expect_use */);
358}
359
360TEST_F(Dex2oatSwapTest, DoNotUseSwapSingle) {
361 RunTest(false /* use_fd */, false /* expect_use */, { "--swap-dex-size-threshold=0" });
362 RunTest(true /* use_fd */, false /* expect_use */, { "--swap-dex-size-threshold=0" });
363}
364
365TEST_F(Dex2oatSwapTest, DoNotUseSwapSmall) {
366 RunTest(false /* use_fd */, false /* expect_use */, { "--swap-dex-count-threshold=0" });
367 RunTest(true /* use_fd */, false /* expect_use */, { "--swap-dex-count-threshold=0" });
368}
369
370TEST_F(Dex2oatSwapTest, DoUseSwapSingleSmall) {
371 RunTest(false /* use_fd */,
372 true /* expect_use */,
373 { "--swap-dex-size-threshold=0", "--swap-dex-count-threshold=0" });
374 RunTest(true /* use_fd */,
375 true /* expect_use */,
376 { "--swap-dex-size-threshold=0", "--swap-dex-count-threshold=0" });
377}
378
Andreas Gampe7adeda82016-07-25 08:27:35 -0700379class Dex2oatSwapUseTest : public Dex2oatSwapTest {
380 protected:
381 void CheckHostResult(bool expect_use) OVERRIDE {
382 if (!kIsTargetBuild) {
383 if (expect_use) {
384 EXPECT_NE(output_.find("Large app, accepted running with swap."), std::string::npos)
385 << output_;
386 } else {
387 EXPECT_EQ(output_.find("Large app, accepted running with swap."), std::string::npos)
388 << output_;
389 }
390 }
391 }
392
393 std::string GetTestDexFileName() OVERRIDE {
394 // Use Statics as it has a handful of functions.
395 return CommonRuntimeTest::GetTestDexFileName("Statics");
396 }
397
398 void GrabResult1() {
399 if (!kIsTargetBuild) {
400 native_alloc_1_ = ParseNativeAlloc();
401 swap_1_ = ParseSwap(false /* expected */);
402 } else {
403 native_alloc_1_ = std::numeric_limits<size_t>::max();
404 swap_1_ = 0;
405 }
406 }
407
408 void GrabResult2() {
409 if (!kIsTargetBuild) {
410 native_alloc_2_ = ParseNativeAlloc();
411 swap_2_ = ParseSwap(true /* expected */);
412 } else {
413 native_alloc_2_ = 0;
414 swap_2_ = std::numeric_limits<size_t>::max();
415 }
416 }
417
418 private:
419 size_t ParseNativeAlloc() {
420 std::regex native_alloc_regex("dex2oat took.*native alloc=[^ ]+ \\(([0-9]+)B\\)");
421 std::smatch native_alloc_match;
422 bool found = std::regex_search(output_, native_alloc_match, native_alloc_regex);
423 if (!found) {
424 EXPECT_TRUE(found);
425 return 0;
426 }
427 if (native_alloc_match.size() != 2U) {
428 EXPECT_EQ(native_alloc_match.size(), 2U);
429 return 0;
430 }
431
432 std::istringstream stream(native_alloc_match[1].str());
433 size_t value;
434 stream >> value;
435
436 return value;
437 }
438
439 size_t ParseSwap(bool expected) {
440 std::regex swap_regex("dex2oat took[^\\n]+swap=[^ ]+ \\(([0-9]+)B\\)");
441 std::smatch swap_match;
442 bool found = std::regex_search(output_, swap_match, swap_regex);
443 if (found != expected) {
444 EXPECT_EQ(expected, found);
445 return 0;
446 }
447
448 if (!found) {
449 return 0;
450 }
451
452 if (swap_match.size() != 2U) {
453 EXPECT_EQ(swap_match.size(), 2U);
454 return 0;
455 }
456
457 std::istringstream stream(swap_match[1].str());
458 size_t value;
459 stream >> value;
460
461 return value;
462 }
463
464 protected:
465 size_t native_alloc_1_;
466 size_t native_alloc_2_;
467
468 size_t swap_1_;
469 size_t swap_2_;
470};
471
472TEST_F(Dex2oatSwapUseTest, CheckSwapUsage) {
Andreas Gampef4a67fd2017-05-04 09:55:36 -0700473 // Native memory usage isn't correctly tracked under sanitization.
474 TEST_DISABLED_FOR_MEMORY_TOOL_ASAN();
475
Vladimir Marko57070da2017-02-14 16:16:30 +0000476 // The `native_alloc_2_ >= native_alloc_1_` assertion below may not
Roland Levillain19772bf2017-02-16 11:28:10 +0000477 // hold true on some x86 systems; disable this test while we
478 // investigate (b/29259363).
479 TEST_DISABLED_FOR_X86();
Vladimir Marko57070da2017-02-14 16:16:30 +0000480
Andreas Gampe7adeda82016-07-25 08:27:35 -0700481 RunTest(false /* use_fd */,
482 false /* expect_use */);
483 GrabResult1();
484 std::string output_1 = output_;
485
486 output_ = "";
487
488 RunTest(false /* use_fd */,
489 true /* expect_use */,
490 { "--swap-dex-size-threshold=0", "--swap-dex-count-threshold=0" });
491 GrabResult2();
492 std::string output_2 = output_;
493
494 if (native_alloc_2_ >= native_alloc_1_ || swap_1_ >= swap_2_) {
495 EXPECT_LT(native_alloc_2_, native_alloc_1_);
496 EXPECT_LT(swap_1_, swap_2_);
497
498 LOG(ERROR) << output_1;
499 LOG(ERROR) << output_2;
500 }
501}
502
Andreas Gampe67f02822016-06-24 21:05:23 -0700503class Dex2oatVeryLargeTest : public Dex2oatTest {
504 protected:
505 void CheckFilter(CompilerFilter::Filter input ATTRIBUTE_UNUSED,
506 CompilerFilter::Filter result ATTRIBUTE_UNUSED) OVERRIDE {
507 // Ignore, we'll do our own checks.
508 }
509
510 void RunTest(CompilerFilter::Filter filter,
511 bool expect_large,
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700512 bool expect_downgrade,
Andreas Gampe67f02822016-06-24 21:05:23 -0700513 const std::vector<std::string>& extra_args = {}) {
514 std::string dex_location = GetScratchDir() + "/DexNoOat.jar";
515 std::string odex_location = GetOdexDir() + "/DexOdexNoOat.odex";
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700516 std::string app_image_file = GetScratchDir() + "/Test.art";
Andreas Gampe67f02822016-06-24 21:05:23 -0700517
518 Copy(GetDexSrc1(), dex_location);
519
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700520 std::vector<std::string> new_args(extra_args);
521 new_args.push_back("--app-image-file=" + app_image_file);
522 GenerateOdexForTest(dex_location, odex_location, filter, new_args);
Andreas Gampe67f02822016-06-24 21:05:23 -0700523
524 CheckValidity();
525 ASSERT_TRUE(success_);
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700526 CheckResult(dex_location,
527 odex_location,
528 app_image_file,
529 filter,
530 expect_large,
531 expect_downgrade);
Andreas Gampe67f02822016-06-24 21:05:23 -0700532 }
533
534 void CheckResult(const std::string& dex_location,
535 const std::string& odex_location,
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700536 const std::string& app_image_file,
Andreas Gampe67f02822016-06-24 21:05:23 -0700537 CompilerFilter::Filter filter,
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700538 bool expect_large,
539 bool expect_downgrade) {
540 if (expect_downgrade) {
541 EXPECT_TRUE(expect_large);
542 }
Andreas Gampe67f02822016-06-24 21:05:23 -0700543 // Host/target independent checks.
544 std::string error_msg;
545 std::unique_ptr<OatFile> odex_file(OatFile::Open(odex_location.c_str(),
546 odex_location.c_str(),
547 nullptr,
548 nullptr,
549 false,
550 /*low_4gb*/false,
551 dex_location.c_str(),
552 &error_msg));
553 ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700554 EXPECT_GT(app_image_file.length(), 0u);
555 std::unique_ptr<File> file(OS::OpenFileForReading(app_image_file.c_str()));
Andreas Gampe67f02822016-06-24 21:05:23 -0700556 if (expect_large) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700557 // Note: we cannot check the following
558 // EXPECT_FALSE(CompilerFilter::IsAotCompilationEnabled(odex_file->GetCompilerFilter()));
Andreas Gampe67f02822016-06-24 21:05:23 -0700559 // The reason is that the filter override currently happens when the dex files are
560 // loaded in dex2oat, which is after the oat file has been started. Thus, the header
561 // store cannot be changed, and the original filter is set in stone.
562
563 for (const OatDexFile* oat_dex_file : odex_file->GetOatDexFiles()) {
564 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
565 ASSERT_TRUE(dex_file != nullptr);
566 uint32_t class_def_count = dex_file->NumClassDefs();
567 ASSERT_LT(class_def_count, std::numeric_limits<uint16_t>::max());
568 for (uint16_t class_def_index = 0; class_def_index < class_def_count; ++class_def_index) {
569 OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
570 EXPECT_EQ(oat_class.GetType(), OatClassType::kOatClassNoneCompiled);
571 }
572 }
573
574 // If the input filter was "below," it should have been used.
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100575 if (!CompilerFilter::IsAsGoodAs(CompilerFilter::kExtract, filter)) {
Andreas Gampe67f02822016-06-24 21:05:23 -0700576 EXPECT_EQ(odex_file->GetCompilerFilter(), filter);
577 }
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700578
579 // If expect large, make sure the app image isn't generated or is empty.
580 if (file != nullptr) {
581 EXPECT_EQ(file->GetLength(), 0u);
582 }
Andreas Gampe67f02822016-06-24 21:05:23 -0700583 } else {
584 EXPECT_EQ(odex_file->GetCompilerFilter(), filter);
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700585 ASSERT_TRUE(file != nullptr) << app_image_file;
586 EXPECT_GT(file->GetLength(), 0u);
Andreas Gampe67f02822016-06-24 21:05:23 -0700587 }
588
589 // Host/target dependent checks.
590 if (kIsTargetBuild) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700591 CheckTargetResult(expect_downgrade);
Andreas Gampe67f02822016-06-24 21:05:23 -0700592 } else {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700593 CheckHostResult(expect_downgrade);
Andreas Gampe67f02822016-06-24 21:05:23 -0700594 }
595 }
596
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700597 void CheckTargetResult(bool expect_downgrade ATTRIBUTE_UNUSED) {
Andreas Gampe67f02822016-06-24 21:05:23 -0700598 // TODO: Ignore for now. May do something for fd things.
599 }
600
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700601 void CheckHostResult(bool expect_downgrade) {
Andreas Gampe67f02822016-06-24 21:05:23 -0700602 if (!kIsTargetBuild) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700603 if (expect_downgrade) {
604 EXPECT_NE(output_.find("Very large app, downgrading to"), std::string::npos) << output_;
Andreas Gampe67f02822016-06-24 21:05:23 -0700605 } else {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700606 EXPECT_EQ(output_.find("Very large app, downgrading to"), std::string::npos) << output_;
Andreas Gampe67f02822016-06-24 21:05:23 -0700607 }
608 }
609 }
610
611 // Check whether the dex2oat run was really successful.
612 void CheckValidity() {
613 if (kIsTargetBuild) {
614 CheckTargetValidity();
615 } else {
616 CheckHostValidity();
617 }
618 }
619
620 void CheckTargetValidity() {
621 // TODO: Ignore for now.
622 }
623
624 // On the host, we can get the dex2oat output. Here, look for "dex2oat took."
625 void CheckHostValidity() {
626 EXPECT_NE(output_.find("dex2oat took"), std::string::npos) << output_;
627 }
628};
629
630TEST_F(Dex2oatVeryLargeTest, DontUseVeryLarge) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700631 RunTest(CompilerFilter::kAssumeVerified, false, false);
632 RunTest(CompilerFilter::kExtract, false, false);
633 RunTest(CompilerFilter::kQuicken, false, false);
634 RunTest(CompilerFilter::kSpeed, false, false);
Andreas Gampe67f02822016-06-24 21:05:23 -0700635
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700636 RunTest(CompilerFilter::kAssumeVerified, false, false, { "--very-large-app-threshold=10000000" });
637 RunTest(CompilerFilter::kExtract, false, false, { "--very-large-app-threshold=10000000" });
638 RunTest(CompilerFilter::kQuicken, false, false, { "--very-large-app-threshold=10000000" });
639 RunTest(CompilerFilter::kSpeed, false, false, { "--very-large-app-threshold=10000000" });
Andreas Gampe67f02822016-06-24 21:05:23 -0700640}
641
642TEST_F(Dex2oatVeryLargeTest, UseVeryLarge) {
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700643 RunTest(CompilerFilter::kAssumeVerified, true, false, { "--very-large-app-threshold=100" });
644 RunTest(CompilerFilter::kExtract, true, false, { "--very-large-app-threshold=100" });
645 RunTest(CompilerFilter::kQuicken, true, true, { "--very-large-app-threshold=100" });
646 RunTest(CompilerFilter::kSpeed, true, true, { "--very-large-app-threshold=100" });
Andreas Gampe67f02822016-06-24 21:05:23 -0700647}
648
Mathieu Chartier97ab5e32017-02-22 13:35:44 -0800649// Regressin test for b/35665292.
650TEST_F(Dex2oatVeryLargeTest, SpeedProfileNoProfile) {
651 // Test that dex2oat doesn't crash with speed-profile but no input profile.
Mathieu Chartier8cce65a2017-08-17 00:06:39 -0700652 RunTest(CompilerFilter::kSpeedProfile, false, false);
Mathieu Chartier97ab5e32017-02-22 13:35:44 -0800653}
654
Jeff Hao608f2ce2016-10-19 11:17:11 -0700655class Dex2oatLayoutTest : public Dex2oatTest {
656 protected:
657 void CheckFilter(CompilerFilter::Filter input ATTRIBUTE_UNUSED,
658 CompilerFilter::Filter result ATTRIBUTE_UNUSED) OVERRIDE {
659 // Ignore, we'll do our own checks.
660 }
661
Jeff Hao41fba6a2016-11-28 11:53:33 -0800662 // Emits a profile with a single dex file with the given location and a single class index of 1.
663 void GenerateProfile(const std::string& test_profile,
664 const std::string& dex_location,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800665 size_t num_classes,
Jeff Hao41fba6a2016-11-28 11:53:33 -0800666 uint32_t checksum) {
667 int profile_test_fd = open(test_profile.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644);
668 CHECK_GE(profile_test_fd, 0);
669
670 ProfileCompilationInfo info;
671 std::string profile_key = ProfileCompilationInfo::GetProfileDexFileKey(dex_location);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800672 for (size_t i = 0; i < num_classes; ++i) {
Mathieu Chartierea650f32017-05-24 12:04:13 -0700673 info.AddClassIndex(profile_key, checksum, dex::TypeIndex(1 + i), kMaxMethodIds);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800674 }
Jeff Hao41fba6a2016-11-28 11:53:33 -0800675 bool result = info.Save(profile_test_fd);
676 close(profile_test_fd);
677 ASSERT_TRUE(result);
678 }
679
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800680 void CompileProfileOdex(const std::string& dex_location,
681 const std::string& odex_location,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800682 const std::string& app_image_file_name,
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800683 bool use_fd,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800684 size_t num_profile_classes,
Nicolas Geoffray97fa9922017-03-09 13:13:25 +0000685 const std::vector<std::string>& extra_args = {},
686 bool expect_success = true) {
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800687 const std::string profile_location = GetScratchDir() + "/primary.prof";
Jeff Hao41fba6a2016-11-28 11:53:33 -0800688 const char* location = dex_location.c_str();
689 std::string error_msg;
690 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Sehr013fd802018-01-11 22:55:24 -0800691 const ArtDexFileLoader dex_file_loader;
692 ASSERT_TRUE(dex_file_loader.Open(
Nicolas Geoffray095c6c92017-10-19 13:59:55 +0100693 location, location, /* verify */ true, /* verify_checksum */ true, &error_msg, &dex_files));
Jeff Hao41fba6a2016-11-28 11:53:33 -0800694 EXPECT_EQ(dex_files.size(), 1U);
695 std::unique_ptr<const DexFile>& dex_file = dex_files[0];
Mathieu Chartier046854b2017-03-01 17:16:22 -0800696 GenerateProfile(profile_location,
697 dex_location,
698 num_profile_classes,
699 dex_file->GetLocationChecksum());
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800700 std::vector<std::string> copy(extra_args);
701 copy.push_back("--profile-file=" + profile_location);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800702 std::unique_ptr<File> app_image_file;
703 if (!app_image_file_name.empty()) {
704 if (use_fd) {
705 app_image_file.reset(OS::CreateEmptyFile(app_image_file_name.c_str()));
706 copy.push_back("--app-image-fd=" + std::to_string(app_image_file->Fd()));
707 } else {
708 copy.push_back("--app-image-file=" + app_image_file_name);
709 }
710 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800711 GenerateOdexForTest(dex_location,
712 odex_location,
713 CompilerFilter::kSpeedProfile,
714 copy,
Nicolas Geoffray97fa9922017-03-09 13:13:25 +0000715 expect_success,
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800716 use_fd);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800717 if (app_image_file != nullptr) {
718 ASSERT_EQ(app_image_file->FlushCloseOrErase(), 0) << "Could not flush and close art file";
719 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800720 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700721
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100722 uint64_t GetImageObjectSectionSize(const std::string& image_file_name) {
Mathieu Chartier046854b2017-03-01 17:16:22 -0800723 EXPECT_FALSE(image_file_name.empty());
724 std::unique_ptr<File> file(OS::OpenFileForReading(image_file_name.c_str()));
725 CHECK(file != nullptr);
726 ImageHeader image_header;
727 const bool success = file->ReadFully(&image_header, sizeof(image_header));
728 CHECK(success);
729 CHECK(image_header.IsValid());
730 ReaderMutexLock mu(Thread::Current(), *Locks::mutator_lock_);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100731 return image_header.GetObjectsSection().Size();
Mathieu Chartier046854b2017-03-01 17:16:22 -0800732 }
733
734 void RunTest(bool app_image) {
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800735 std::string dex_location = GetScratchDir() + "/DexNoOat.jar";
736 std::string odex_location = GetOdexDir() + "/DexOdexNoOat.odex";
Mathieu Chartier046854b2017-03-01 17:16:22 -0800737 std::string app_image_file = app_image ? (GetOdexDir() + "/DexOdexNoOat.art"): "";
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800738 Copy(GetDexSrc2(), dex_location);
739
Mathieu Chartier046854b2017-03-01 17:16:22 -0800740 uint64_t image_file_empty_profile = 0;
741 if (app_image) {
742 CompileProfileOdex(dex_location,
743 odex_location,
744 app_image_file,
745 /* use_fd */ false,
746 /* num_profile_classes */ 0);
747 CheckValidity();
748 ASSERT_TRUE(success_);
749 // Don't check the result since CheckResult relies on the class being in the profile.
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100750 image_file_empty_profile = GetImageObjectSectionSize(app_image_file);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800751 EXPECT_GT(image_file_empty_profile, 0u);
752 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700753
Mathieu Chartier046854b2017-03-01 17:16:22 -0800754 // Small profile.
755 CompileProfileOdex(dex_location,
756 odex_location,
757 app_image_file,
758 /* use_fd */ false,
759 /* num_profile_classes */ 1);
Jeff Hao608f2ce2016-10-19 11:17:11 -0700760 CheckValidity();
761 ASSERT_TRUE(success_);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800762 CheckResult(dex_location, odex_location, app_image_file);
763
764 if (app_image) {
765 // Test that the profile made a difference by adding more classes.
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100766 const uint64_t image_file_small_profile = GetImageObjectSectionSize(app_image_file);
767 ASSERT_LT(image_file_empty_profile, image_file_small_profile);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800768 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700769 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800770
771 void RunTestVDex() {
772 std::string dex_location = GetScratchDir() + "/DexNoOat.jar";
773 std::string odex_location = GetOdexDir() + "/DexOdexNoOat.odex";
774 std::string vdex_location = GetOdexDir() + "/DexOdexNoOat.vdex";
Mathieu Chartier046854b2017-03-01 17:16:22 -0800775 std::string app_image_file_name = GetOdexDir() + "/DexOdexNoOat.art";
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800776 Copy(GetDexSrc2(), dex_location);
777
778 std::unique_ptr<File> vdex_file1(OS::CreateEmptyFile(vdex_location.c_str()));
779 CHECK(vdex_file1 != nullptr) << vdex_location;
780 ScratchFile vdex_file2;
781 {
782 std::string input_vdex = "--input-vdex-fd=-1";
783 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file1->Fd());
784 CompileProfileOdex(dex_location,
785 odex_location,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800786 app_image_file_name,
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800787 /* use_fd */ true,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800788 /* num_profile_classes */ 1,
Mathieu Chartierf1609832018-01-31 03:09:56 -0800789 { input_vdex, output_vdex });
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800790 EXPECT_GT(vdex_file1->GetLength(), 0u);
791 }
792 {
Nicolas Geoffray97fa9922017-03-09 13:13:25 +0000793 // Test that vdex and dexlayout fail gracefully.
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800794 std::string input_vdex = StringPrintf("--input-vdex-fd=%d", vdex_file1->Fd());
795 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file2.GetFd());
796 CompileProfileOdex(dex_location,
797 odex_location,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800798 app_image_file_name,
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800799 /* use_fd */ true,
Mathieu Chartier046854b2017-03-01 17:16:22 -0800800 /* num_profile_classes */ 1,
Mathieu Chartierd27923c2018-02-08 21:00:03 -0800801 { input_vdex, output_vdex },
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +0100802 /* expect_success */ true);
803 EXPECT_GT(vdex_file2.GetFile()->GetLength(), 0u);
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800804 }
805 ASSERT_EQ(vdex_file1->FlushCloseOrErase(), 0) << "Could not flush and close vdex file";
806 CheckValidity();
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +0100807 ASSERT_TRUE(success_);
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800808 }
809
Mathieu Chartier046854b2017-03-01 17:16:22 -0800810 void CheckResult(const std::string& dex_location,
811 const std::string& odex_location,
812 const std::string& app_image_file_name) {
Jeff Hao608f2ce2016-10-19 11:17:11 -0700813 // Host/target independent checks.
814 std::string error_msg;
815 std::unique_ptr<OatFile> odex_file(OatFile::Open(odex_location.c_str(),
816 odex_location.c_str(),
817 nullptr,
818 nullptr,
819 false,
820 /*low_4gb*/false,
821 dex_location.c_str(),
822 &error_msg));
823 ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
824
Jeff Hao042e8982016-10-19 11:17:11 -0700825 const char* location = dex_location.c_str();
826 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Sehr013fd802018-01-11 22:55:24 -0800827 const ArtDexFileLoader dex_file_loader;
828 ASSERT_TRUE(dex_file_loader.Open(
Nicolas Geoffray095c6c92017-10-19 13:59:55 +0100829 location, location, /* verify */ true, /* verify_checksum */ true, &error_msg, &dex_files));
Jeff Hao042e8982016-10-19 11:17:11 -0700830 EXPECT_EQ(dex_files.size(), 1U);
831 std::unique_ptr<const DexFile>& old_dex_file = dex_files[0];
832
Jeff Hao608f2ce2016-10-19 11:17:11 -0700833 for (const OatDexFile* oat_dex_file : odex_file->GetOatDexFiles()) {
Jeff Hao042e8982016-10-19 11:17:11 -0700834 std::unique_ptr<const DexFile> new_dex_file = oat_dex_file->OpenDexFile(&error_msg);
835 ASSERT_TRUE(new_dex_file != nullptr);
836 uint32_t class_def_count = new_dex_file->NumClassDefs();
Jeff Hao608f2ce2016-10-19 11:17:11 -0700837 ASSERT_LT(class_def_count, std::numeric_limits<uint16_t>::max());
Jeff Hao042e8982016-10-19 11:17:11 -0700838 ASSERT_GE(class_def_count, 2U);
839
Mathieu Chartier24066ec2017-10-21 16:01:08 -0700840 // Make sure the indexes stay the same.
Jeff Hao042e8982016-10-19 11:17:11 -0700841 std::string old_class0 = old_dex_file->PrettyType(old_dex_file->GetClassDef(0).class_idx_);
842 std::string old_class1 = old_dex_file->PrettyType(old_dex_file->GetClassDef(1).class_idx_);
843 std::string new_class0 = new_dex_file->PrettyType(new_dex_file->GetClassDef(0).class_idx_);
844 std::string new_class1 = new_dex_file->PrettyType(new_dex_file->GetClassDef(1).class_idx_);
Mathieu Chartier24066ec2017-10-21 16:01:08 -0700845 EXPECT_EQ(old_class0, new_class0);
846 EXPECT_EQ(old_class1, new_class1);
Jeff Hao608f2ce2016-10-19 11:17:11 -0700847 }
848
Jeff Haoc155b052017-01-17 17:43:29 -0800849 EXPECT_EQ(odex_file->GetCompilerFilter(), CompilerFilter::kSpeedProfile);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800850
851 if (!app_image_file_name.empty()) {
852 // Go peek at the image header to make sure it was large enough to contain the class.
853 std::unique_ptr<File> file(OS::OpenFileForReading(app_image_file_name.c_str()));
854 ImageHeader image_header;
855 bool success = file->ReadFully(&image_header, sizeof(image_header));
856 ASSERT_TRUE(success);
857 ASSERT_TRUE(image_header.IsValid());
Vladimir Markocd87c3e2017-09-05 13:11:57 +0100858 EXPECT_GT(image_header.GetObjectsSection().Size(), 0u);
Mathieu Chartier046854b2017-03-01 17:16:22 -0800859 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700860 }
861
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800862 // Check whether the dex2oat run was really successful.
863 void CheckValidity() {
864 if (kIsTargetBuild) {
865 CheckTargetValidity();
866 } else {
867 CheckHostValidity();
Jeff Hao608f2ce2016-10-19 11:17:11 -0700868 }
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800869 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700870
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800871 void CheckTargetValidity() {
872 // TODO: Ignore for now.
873 }
Jeff Hao608f2ce2016-10-19 11:17:11 -0700874
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800875 // On the host, we can get the dex2oat output. Here, look for "dex2oat took."
876 void CheckHostValidity() {
877 EXPECT_NE(output_.find("dex2oat took"), std::string::npos) << output_;
878 }
879};
Jeff Hao608f2ce2016-10-19 11:17:11 -0700880
881TEST_F(Dex2oatLayoutTest, TestLayout) {
Mathieu Chartier046854b2017-03-01 17:16:22 -0800882 RunTest(/* app-image */ false);
883}
884
885TEST_F(Dex2oatLayoutTest, TestLayoutAppImage) {
886 RunTest(/* app-image */ true);
Jeff Hao608f2ce2016-10-19 11:17:11 -0700887}
888
Mathieu Chartier8bc343b2017-03-01 15:20:30 -0800889TEST_F(Dex2oatLayoutTest, TestVdexLayout) {
890 RunTestVDex();
891}
892
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100893class Dex2oatUnquickenTest : public Dex2oatTest {
894 protected:
895 void RunUnquickenMultiDex() {
896 std::string dex_location = GetScratchDir() + "/UnquickenMultiDex.jar";
897 std::string odex_location = GetOdexDir() + "/UnquickenMultiDex.odex";
898 std::string vdex_location = GetOdexDir() + "/UnquickenMultiDex.vdex";
899 Copy(GetTestDexFileName("MultiDex"), dex_location);
900
901 std::unique_ptr<File> vdex_file1(OS::CreateEmptyFile(vdex_location.c_str()));
902 CHECK(vdex_file1 != nullptr) << vdex_location;
903 // Quicken the dex file into a vdex file.
904 {
905 std::string input_vdex = "--input-vdex-fd=-1";
906 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file1->Fd());
907 GenerateOdexForTest(dex_location,
908 odex_location,
909 CompilerFilter::kQuicken,
Mathieu Chartierf1609832018-01-31 03:09:56 -0800910 { input_vdex, output_vdex },
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100911 /* expect_success */ true,
912 /* use_fd */ true);
913 EXPECT_GT(vdex_file1->GetLength(), 0u);
914 }
915 // Unquicken by running the verify compiler filter on the vdex file.
916 {
917 std::string input_vdex = StringPrintf("--input-vdex-fd=%d", vdex_file1->Fd());
918 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file1->Fd());
919 GenerateOdexForTest(dex_location,
920 odex_location,
921 CompilerFilter::kVerify,
Mathieu Chartier02129102017-12-22 11:04:01 -0800922 { input_vdex, output_vdex, kDisableCompactDex },
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100923 /* expect_success */ true,
924 /* use_fd */ true);
925 }
926 ASSERT_EQ(vdex_file1->FlushCloseOrErase(), 0) << "Could not flush and close vdex file";
927 CheckResult(dex_location, odex_location);
928 ASSERT_TRUE(success_);
929 }
930
Mathieu Chartierd27923c2018-02-08 21:00:03 -0800931 void RunUnquickenMultiDexCDex() {
932 std::string dex_location = GetScratchDir() + "/UnquickenMultiDex.jar";
933 std::string odex_location = GetOdexDir() + "/UnquickenMultiDex.odex";
934 std::string odex_location2 = GetOdexDir() + "/UnquickenMultiDex2.odex";
935 std::string vdex_location = GetOdexDir() + "/UnquickenMultiDex.vdex";
936 std::string vdex_location2 = GetOdexDir() + "/UnquickenMultiDex2.vdex";
937 Copy(GetTestDexFileName("MultiDex"), dex_location);
938
939 std::unique_ptr<File> vdex_file1(OS::CreateEmptyFile(vdex_location.c_str()));
940 std::unique_ptr<File> vdex_file2(OS::CreateEmptyFile(vdex_location2.c_str()));
941 CHECK(vdex_file1 != nullptr) << vdex_location;
942 CHECK(vdex_file2 != nullptr) << vdex_location2;
943
944 // Quicken the dex file into a vdex file.
945 {
946 std::string input_vdex = "--input-vdex-fd=-1";
947 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file1->Fd());
948 GenerateOdexForTest(dex_location,
949 odex_location,
950 CompilerFilter::kQuicken,
951 { input_vdex, output_vdex, "--compact-dex-level=fast"},
952 /* expect_success */ true,
953 /* use_fd */ true);
954 EXPECT_GT(vdex_file1->GetLength(), 0u);
955 }
956
957 // Unquicken by running the verify compiler filter on the vdex file.
958 {
959 std::string input_vdex = StringPrintf("--input-vdex-fd=%d", vdex_file1->Fd());
960 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_file2->Fd());
961 GenerateOdexForTest(dex_location,
962 odex_location2,
963 CompilerFilter::kVerify,
964 { input_vdex, output_vdex, "--compact-dex-level=none"},
965 /* expect_success */ true,
966 /* use_fd */ true);
967 }
968 ASSERT_EQ(vdex_file1->FlushCloseOrErase(), 0) << "Could not flush and close vdex file";
969 ASSERT_EQ(vdex_file2->FlushCloseOrErase(), 0) << "Could not flush and close vdex file";
970 CheckResult(dex_location, odex_location2);
971 ASSERT_TRUE(success_);
972 }
973
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100974 void CheckResult(const std::string& dex_location, const std::string& odex_location) {
975 std::string error_msg;
976 std::unique_ptr<OatFile> odex_file(OatFile::Open(odex_location.c_str(),
977 odex_location.c_str(),
978 nullptr,
979 nullptr,
980 false,
981 /*low_4gb*/false,
982 dex_location.c_str(),
983 &error_msg));
984 ASSERT_TRUE(odex_file.get() != nullptr) << error_msg;
985 ASSERT_GE(odex_file->GetOatDexFiles().size(), 1u);
986
987 // Iterate over the dex files and ensure there is no quickened instruction.
988 for (const OatDexFile* oat_dex_file : odex_file->GetOatDexFiles()) {
989 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
990 for (uint32_t i = 0; i < dex_file->NumClassDefs(); ++i) {
991 const DexFile::ClassDef& class_def = dex_file->GetClassDef(i);
992 const uint8_t* class_data = dex_file->GetClassData(class_def);
993 if (class_data != nullptr) {
994 for (ClassDataItemIterator class_it(*dex_file, class_data);
995 class_it.HasNext();
996 class_it.Next()) {
997 if (class_it.IsAtMethod() && class_it.GetMethodCodeItem() != nullptr) {
Mathieu Chartier0021feb2017-11-07 00:08:52 -0800998 for (const DexInstructionPcPair& inst :
Mathieu Chartier698ebbc2018-01-05 11:00:42 -0800999 CodeItemInstructionAccessor(*dex_file, class_it.GetMethodCodeItem())) {
Mathieu Chartier2daa1342018-02-20 16:19:28 -08001000 ASSERT_FALSE(inst->IsQuickened()) << inst->Opcode() << " " << output_;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001001 }
1002 }
1003 }
1004 }
1005 }
1006 }
1007 }
1008};
1009
1010TEST_F(Dex2oatUnquickenTest, UnquickenMultiDex) {
1011 RunUnquickenMultiDex();
1012}
1013
Mathieu Chartierd27923c2018-02-08 21:00:03 -08001014TEST_F(Dex2oatUnquickenTest, UnquickenMultiDexCDex) {
1015 RunUnquickenMultiDexCDex();
1016}
1017
Andreas Gampe2e8a2562017-01-18 20:39:02 -08001018class Dex2oatWatchdogTest : public Dex2oatTest {
1019 protected:
1020 void RunTest(bool expect_success, const std::vector<std::string>& extra_args = {}) {
1021 std::string dex_location = GetScratchDir() + "/Dex2OatSwapTest.jar";
1022 std::string odex_location = GetOdexDir() + "/Dex2OatSwapTest.odex";
1023
1024 Copy(GetTestDexFileName(), dex_location);
1025
1026 std::vector<std::string> copy(extra_args);
1027
1028 std::string swap_location = GetOdexDir() + "/Dex2OatSwapTest.odex.swap";
1029 copy.push_back("--swap-file=" + swap_location);
Andreas Gampe22fa3762017-10-23 20:58:12 -07001030 copy.push_back("-j512"); // Excessive idle threads just slow down dex2oat.
Andreas Gampe2e8a2562017-01-18 20:39:02 -08001031 GenerateOdexForTest(dex_location,
1032 odex_location,
1033 CompilerFilter::kSpeed,
1034 copy,
1035 expect_success);
1036 }
1037
1038 std::string GetTestDexFileName() {
1039 return GetDexSrc1();
1040 }
1041};
1042
1043TEST_F(Dex2oatWatchdogTest, TestWatchdogOK) {
1044 // Check with default.
1045 RunTest(true);
1046
1047 // Check with ten minutes.
1048 RunTest(true, { "--watchdog-timeout=600000" });
1049}
1050
1051TEST_F(Dex2oatWatchdogTest, TestWatchdogTrigger) {
Roland Levillain68db2252017-08-14 12:48:47 +01001052 TEST_DISABLED_FOR_MEMORY_TOOL_VALGRIND(); // b/63052624
Andreas Gampe80ddf272018-01-11 09:41:00 -08001053
1054 // The watchdog is independent of dex2oat and will not delete intermediates. It is possible
1055 // that the compilation succeeds and the file is completely written by the time the watchdog
1056 // kills dex2oat (but the dex2oat threads must have been scheduled pretty badly).
1057 test_accepts_odex_file_on_failure = true;
1058
Andreas Gampe2e8a2562017-01-18 20:39:02 -08001059 // Check with ten milliseconds.
1060 RunTest(false, { "--watchdog-timeout=10" });
1061}
1062
Andreas Gampef7882972017-03-20 16:35:24 -07001063class Dex2oatReturnCodeTest : public Dex2oatTest {
1064 protected:
1065 int RunTest(const std::vector<std::string>& extra_args = {}) {
1066 std::string dex_location = GetScratchDir() + "/Dex2OatSwapTest.jar";
1067 std::string odex_location = GetOdexDir() + "/Dex2OatSwapTest.odex";
1068
1069 Copy(GetTestDexFileName(), dex_location);
1070
1071 std::string error_msg;
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001072 return GenerateOdexForTestWithStatus({dex_location},
Andreas Gampef7882972017-03-20 16:35:24 -07001073 odex_location,
1074 CompilerFilter::kSpeed,
1075 &error_msg,
1076 extra_args);
1077 }
1078
1079 std::string GetTestDexFileName() {
1080 return GetDexSrc1();
1081 }
1082};
1083
1084TEST_F(Dex2oatReturnCodeTest, TestCreateRuntime) {
Andreas Gampefd80b172017-04-26 22:25:31 -07001085 TEST_DISABLED_FOR_MEMORY_TOOL(); // b/19100793
Andreas Gampef7882972017-03-20 16:35:24 -07001086 int status = RunTest({ "--boot-image=/this/does/not/exist/yolo.oat" });
1087 EXPECT_EQ(static_cast<int>(dex2oat::ReturnCode::kCreateRuntime), WEXITSTATUS(status)) << output_;
1088}
1089
Calin Juravle1ce70852017-06-28 10:59:03 -07001090class Dex2oatClassLoaderContextTest : public Dex2oatTest {
1091 protected:
1092 void RunTest(const char* class_loader_context,
1093 const char* expected_classpath_key,
1094 bool expected_success,
1095 bool use_second_source = false) {
1096 std::string dex_location = GetUsedDexLocation();
1097 std::string odex_location = GetUsedOatLocation();
1098
1099 Copy(use_second_source ? GetDexSrc2() : GetDexSrc1(), dex_location);
1100
1101 std::string error_msg;
1102 std::vector<std::string> extra_args;
1103 if (class_loader_context != nullptr) {
1104 extra_args.push_back(std::string("--class-loader-context=") + class_loader_context);
1105 }
1106 auto check_oat = [expected_classpath_key](const OatFile& oat_file) {
1107 ASSERT_TRUE(expected_classpath_key != nullptr);
1108 const char* classpath = oat_file.GetOatHeader().GetStoreValueByKey(OatHeader::kClassPathKey);
1109 ASSERT_TRUE(classpath != nullptr);
1110 ASSERT_STREQ(expected_classpath_key, classpath);
1111 };
1112
1113 GenerateOdexForTest(dex_location,
1114 odex_location,
1115 CompilerFilter::kQuicken,
1116 extra_args,
1117 expected_success,
1118 /*use_fd*/ false,
1119 check_oat);
1120 }
1121
1122 std::string GetUsedDexLocation() {
1123 return GetScratchDir() + "/Context.jar";
1124 }
1125
1126 std::string GetUsedOatLocation() {
1127 return GetOdexDir() + "/Context.odex";
1128 }
1129
Calin Juravle7b0648a2017-07-07 18:40:50 -07001130 const char* kEmptyClassPathKey = "PCL[]";
Calin Juravle1ce70852017-06-28 10:59:03 -07001131};
1132
1133TEST_F(Dex2oatClassLoaderContextTest, InvalidContext) {
1134 RunTest("Invalid[]", /*expected_classpath_key*/ nullptr, /*expected_success*/ false);
1135}
1136
1137TEST_F(Dex2oatClassLoaderContextTest, EmptyContext) {
1138 RunTest("PCL[]", kEmptyClassPathKey, /*expected_success*/ true);
1139}
1140
1141TEST_F(Dex2oatClassLoaderContextTest, SpecialContext) {
1142 RunTest(OatFile::kSpecialSharedLibrary,
1143 OatFile::kSpecialSharedLibrary,
1144 /*expected_success*/ true);
1145}
1146
1147TEST_F(Dex2oatClassLoaderContextTest, ContextWithTheSourceDexFiles) {
1148 std::string context = "PCL[" + GetUsedDexLocation() + "]";
1149 RunTest(context.c_str(), kEmptyClassPathKey, /*expected_success*/ true);
1150}
1151
1152TEST_F(Dex2oatClassLoaderContextTest, ContextWithOtherDexFiles) {
1153 std::vector<std::unique_ptr<const DexFile>> dex_files = OpenTestDexFiles("Nested");
Calin Juravle1ce70852017-06-28 10:59:03 -07001154
1155 std::string context = "PCL[" + dex_files[0]->GetLocation() + "]";
Calin Juravle7b0648a2017-07-07 18:40:50 -07001156 std::string expected_classpath_key = "PCL[" +
1157 dex_files[0]->GetLocation() + "*" + std::to_string(dex_files[0]->GetLocationChecksum()) + "]";
Calin Juravle1ce70852017-06-28 10:59:03 -07001158 RunTest(context.c_str(), expected_classpath_key.c_str(), true);
1159}
1160
1161TEST_F(Dex2oatClassLoaderContextTest, ContextWithStrippedDexFiles) {
1162 std::string stripped_classpath = GetScratchDir() + "/stripped_classpath.jar";
1163 Copy(GetStrippedDexSrc1(), stripped_classpath);
1164
1165 std::string context = "PCL[" + stripped_classpath + "]";
1166 // Expect an empty context because stripped dex files cannot be open.
Calin Juravle7b0648a2017-07-07 18:40:50 -07001167 RunTest(context.c_str(), kEmptyClassPathKey , /*expected_success*/ true);
Calin Juravle1ce70852017-06-28 10:59:03 -07001168}
1169
1170TEST_F(Dex2oatClassLoaderContextTest, ContextWithStrippedDexFilesBackedByOdex) {
1171 std::string stripped_classpath = GetScratchDir() + "/stripped_classpath.jar";
1172 std::string odex_for_classpath = GetOdexDir() + "/stripped_classpath.odex";
1173
1174 Copy(GetDexSrc1(), stripped_classpath);
1175
1176 GenerateOdexForTest(stripped_classpath,
1177 odex_for_classpath,
1178 CompilerFilter::kQuicken,
1179 {},
1180 true);
1181
1182 // Strip the dex file
1183 Copy(GetStrippedDexSrc1(), stripped_classpath);
1184
1185 std::string context = "PCL[" + stripped_classpath + "]";
Calin Juravle7b0648a2017-07-07 18:40:50 -07001186 std::string expected_classpath_key;
Calin Juravle1ce70852017-06-28 10:59:03 -07001187 {
1188 // Open the oat file to get the expected classpath.
Nicolas Geoffray29742602017-12-14 10:09:03 +00001189 OatFileAssistant oat_file_assistant(stripped_classpath.c_str(), kRuntimeISA, false, false);
Calin Juravle1ce70852017-06-28 10:59:03 -07001190 std::unique_ptr<OatFile> oat_file(oat_file_assistant.GetBestOatFile());
1191 std::vector<std::unique_ptr<const DexFile>> oat_dex_files =
1192 OatFileAssistant::LoadDexFiles(*oat_file, stripped_classpath.c_str());
Calin Juravle7b0648a2017-07-07 18:40:50 -07001193 expected_classpath_key = "PCL[";
1194 for (size_t i = 0; i < oat_dex_files.size(); i++) {
1195 if (i > 0) {
1196 expected_classpath_key + ":";
1197 }
1198 expected_classpath_key += oat_dex_files[i]->GetLocation() + "*" +
1199 std::to_string(oat_dex_files[i]->GetLocationChecksum());
1200 }
1201 expected_classpath_key += "]";
Calin Juravle1ce70852017-06-28 10:59:03 -07001202 }
1203
1204 RunTest(context.c_str(),
Calin Juravle7b0648a2017-07-07 18:40:50 -07001205 expected_classpath_key.c_str(),
Calin Juravle1ce70852017-06-28 10:59:03 -07001206 /*expected_success*/ true,
1207 /*use_second_source*/ true);
1208}
1209
1210TEST_F(Dex2oatClassLoaderContextTest, ContextWithNotExistentDexFiles) {
1211 std::string context = "PCL[does_not_exists.dex]";
1212 // Expect an empty context because stripped dex files cannot be open.
1213 RunTest(context.c_str(), kEmptyClassPathKey, /*expected_success*/ true);
1214}
1215
Calin Juravlec79470d2017-07-12 17:37:42 -07001216TEST_F(Dex2oatClassLoaderContextTest, ChainContext) {
1217 std::vector<std::unique_ptr<const DexFile>> dex_files1 = OpenTestDexFiles("Nested");
1218 std::vector<std::unique_ptr<const DexFile>> dex_files2 = OpenTestDexFiles("MultiDex");
1219
1220 std::string context = "PCL[" + GetTestDexFileName("Nested") + "];" +
1221 "DLC[" + GetTestDexFileName("MultiDex") + "]";
1222 std::string expected_classpath_key = "PCL[" + CreateClassPathWithChecksums(dex_files1) + "];" +
1223 "DLC[" + CreateClassPathWithChecksums(dex_files2) + "]";
1224
1225 RunTest(context.c_str(), expected_classpath_key.c_str(), true);
1226}
1227
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001228class Dex2oatDeterminism : public Dex2oatTest {};
1229
1230TEST_F(Dex2oatDeterminism, UnloadCompile) {
1231 if (!kUseReadBarrier &&
1232 gc::kCollectorTypeDefault != gc::kCollectorTypeCMS &&
1233 gc::kCollectorTypeDefault != gc::kCollectorTypeMS) {
1234 LOG(INFO) << "Test requires determinism support.";
1235 return;
1236 }
1237 Runtime* const runtime = Runtime::Current();
1238 std::string out_dir = GetScratchDir();
1239 const std::string base_oat_name = out_dir + "/base.oat";
1240 const std::string base_vdex_name = out_dir + "/base.vdex";
1241 const std::string unload_oat_name = out_dir + "/unload.oat";
1242 const std::string unload_vdex_name = out_dir + "/unload.vdex";
1243 const std::string no_unload_oat_name = out_dir + "/nounload.oat";
1244 const std::string no_unload_vdex_name = out_dir + "/nounload.vdex";
1245 const std::string app_image_name = out_dir + "/unload.art";
1246 std::string error_msg;
1247 const std::vector<gc::space::ImageSpace*>& spaces = runtime->GetHeap()->GetBootImageSpaces();
1248 ASSERT_GT(spaces.size(), 0u);
1249 const std::string image_location = spaces[0]->GetImageLocation();
1250 // Without passing in an app image, it will unload in between compilations.
1251 const int res = GenerateOdexForTestWithStatus(
1252 GetLibCoreDexFileNames(),
1253 base_oat_name,
1254 CompilerFilter::Filter::kQuicken,
1255 &error_msg,
1256 {"--force-determinism", "--avoid-storing-invocation"});
1257 EXPECT_EQ(res, 0);
1258 Copy(base_oat_name, unload_oat_name);
1259 Copy(base_vdex_name, unload_vdex_name);
1260 std::unique_ptr<File> unload_oat(OS::OpenFileForReading(unload_oat_name.c_str()));
1261 std::unique_ptr<File> unload_vdex(OS::OpenFileForReading(unload_vdex_name.c_str()));
1262 ASSERT_TRUE(unload_oat != nullptr);
1263 ASSERT_TRUE(unload_vdex != nullptr);
1264 EXPECT_GT(unload_oat->GetLength(), 0u);
1265 EXPECT_GT(unload_vdex->GetLength(), 0u);
1266 // Regenerate with an app image to disable the dex2oat unloading and verify that the output is
1267 // the same.
1268 const int res2 = GenerateOdexForTestWithStatus(
1269 GetLibCoreDexFileNames(),
1270 base_oat_name,
1271 CompilerFilter::Filter::kQuicken,
1272 &error_msg,
1273 {"--force-determinism", "--avoid-storing-invocation", "--app-image-file=" + app_image_name});
1274 EXPECT_EQ(res2, 0);
1275 Copy(base_oat_name, no_unload_oat_name);
1276 Copy(base_vdex_name, no_unload_vdex_name);
1277 std::unique_ptr<File> no_unload_oat(OS::OpenFileForReading(no_unload_oat_name.c_str()));
1278 std::unique_ptr<File> no_unload_vdex(OS::OpenFileForReading(no_unload_vdex_name.c_str()));
1279 ASSERT_TRUE(no_unload_oat != nullptr);
1280 ASSERT_TRUE(no_unload_vdex != nullptr);
1281 EXPECT_GT(no_unload_oat->GetLength(), 0u);
1282 EXPECT_GT(no_unload_vdex->GetLength(), 0u);
1283 // Verify that both of the files are the same (odex and vdex).
1284 EXPECT_EQ(unload_oat->GetLength(), no_unload_oat->GetLength());
1285 EXPECT_EQ(unload_vdex->GetLength(), no_unload_vdex->GetLength());
1286 EXPECT_EQ(unload_oat->Compare(no_unload_oat.get()), 0)
1287 << unload_oat_name << " " << no_unload_oat_name;
1288 EXPECT_EQ(unload_vdex->Compare(no_unload_vdex.get()), 0)
1289 << unload_vdex_name << " " << no_unload_vdex_name;
1290 // App image file.
1291 std::unique_ptr<File> app_image_file(OS::OpenFileForReading(app_image_name.c_str()));
1292 ASSERT_TRUE(app_image_file != nullptr);
1293 EXPECT_GT(app_image_file->GetLength(), 0u);
1294}
1295
Mathieu Chartier120aa282017-08-05 16:03:03 -07001296// Test that dexlayout section info is correctly written to the oat file for profile based
1297// compilation.
1298TEST_F(Dex2oatTest, LayoutSections) {
1299 using Hotness = ProfileCompilationInfo::MethodHotness;
1300 std::unique_ptr<const DexFile> dex(OpenTestDexFile("ManyMethods"));
1301 ScratchFile profile_file;
1302 // We can only layout method indices with code items, figure out which ones have this property
1303 // first.
1304 std::vector<uint16_t> methods;
1305 {
1306 const DexFile::TypeId* type_id = dex->FindTypeId("LManyMethods;");
1307 dex::TypeIndex type_idx = dex->GetIndexForTypeId(*type_id);
1308 const DexFile::ClassDef* class_def = dex->FindClassDef(type_idx);
1309 ClassDataItemIterator it(*dex, dex->GetClassData(*class_def));
1310 it.SkipAllFields();
1311 std::set<size_t> code_item_offsets;
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08001312 for (; it.HasNextMethod(); it.Next()) {
Mathieu Chartier120aa282017-08-05 16:03:03 -07001313 const uint16_t method_idx = it.GetMemberIndex();
1314 const size_t code_item_offset = it.GetMethodCodeItemOffset();
1315 if (code_item_offsets.insert(code_item_offset).second) {
1316 // Unique code item, add the method index.
1317 methods.push_back(method_idx);
1318 }
1319 }
1320 DCHECK(!it.HasNext());
1321 }
1322 ASSERT_GE(methods.size(), 8u);
1323 std::vector<uint16_t> hot_methods = {methods[1], methods[3], methods[5]};
1324 std::vector<uint16_t> startup_methods = {methods[1], methods[2], methods[7]};
1325 std::vector<uint16_t> post_methods = {methods[0], methods[2], methods[6]};
1326 // Here, we build the profile from the method lists.
1327 ProfileCompilationInfo info;
1328 info.AddMethodsForDex(
1329 static_cast<Hotness::Flag>(Hotness::kFlagHot | Hotness::kFlagStartup),
1330 dex.get(),
1331 hot_methods.begin(),
1332 hot_methods.end());
1333 info.AddMethodsForDex(
1334 Hotness::kFlagStartup,
1335 dex.get(),
1336 startup_methods.begin(),
1337 startup_methods.end());
1338 info.AddMethodsForDex(
1339 Hotness::kFlagPostStartup,
1340 dex.get(),
1341 post_methods.begin(),
1342 post_methods.end());
1343 for (uint16_t id : hot_methods) {
1344 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsHot());
1345 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsStartup());
1346 }
1347 for (uint16_t id : startup_methods) {
1348 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsStartup());
1349 }
1350 for (uint16_t id : post_methods) {
1351 EXPECT_TRUE(info.GetMethodHotness(MethodReference(dex.get(), id)).IsPostStartup());
1352 }
1353 // Save the profile since we want to use it with dex2oat to produce an oat file.
1354 ASSERT_TRUE(info.Save(profile_file.GetFd()));
1355 // Generate a profile based odex.
1356 const std::string dir = GetScratchDir();
1357 const std::string oat_filename = dir + "/base.oat";
1358 const std::string vdex_filename = dir + "/base.vdex";
1359 std::string error_msg;
1360 const int res = GenerateOdexForTestWithStatus(
1361 {dex->GetLocation()},
1362 oat_filename,
1363 CompilerFilter::Filter::kQuicken,
1364 &error_msg,
1365 {"--profile-file=" + profile_file.GetFilename()});
1366 EXPECT_EQ(res, 0);
1367
1368 // Open our generated oat file.
1369 std::unique_ptr<OatFile> odex_file(OatFile::Open(oat_filename.c_str(),
1370 oat_filename.c_str(),
1371 nullptr,
1372 nullptr,
1373 false,
1374 /*low_4gb*/false,
1375 dex->GetLocation().c_str(),
1376 &error_msg));
1377 ASSERT_TRUE(odex_file != nullptr);
1378 std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
1379 ASSERT_EQ(oat_dex_files.size(), 1u);
1380 // Check that the code sections match what we expect.
1381 for (const OatDexFile* oat_dex : oat_dex_files) {
1382 const DexLayoutSections* const sections = oat_dex->GetDexLayoutSections();
1383 // Testing of logging the sections.
1384 ASSERT_TRUE(sections != nullptr);
1385 LOG(INFO) << *sections;
1386
1387 // Load the sections into temporary variables for convenience.
1388 const DexLayoutSection& code_section =
1389 sections->sections_[static_cast<size_t>(DexLayoutSections::SectionType::kSectionTypeCode)];
1390 const DexLayoutSection::Subsection& section_hot_code =
1391 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeHot)];
1392 const DexLayoutSection::Subsection& section_sometimes_used =
1393 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeSometimesUsed)];
1394 const DexLayoutSection::Subsection& section_startup_only =
1395 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeStartupOnly)];
1396 const DexLayoutSection::Subsection& section_unused =
1397 code_section.parts_[static_cast<size_t>(LayoutType::kLayoutTypeUnused)];
1398
1399 // All the sections should be non-empty.
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001400 EXPECT_GT(section_hot_code.Size(), 0u);
1401 EXPECT_GT(section_sometimes_used.Size(), 0u);
1402 EXPECT_GT(section_startup_only.Size(), 0u);
1403 EXPECT_GT(section_unused.Size(), 0u);
Mathieu Chartier120aa282017-08-05 16:03:03 -07001404
1405 // Open the dex file since we need to peek at the code items to verify the layout matches what
1406 // we expect.
1407 std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1408 ASSERT_TRUE(dex_file != nullptr) << error_msg;
1409 const DexFile::TypeId* type_id = dex_file->FindTypeId("LManyMethods;");
1410 ASSERT_TRUE(type_id != nullptr);
1411 dex::TypeIndex type_idx = dex_file->GetIndexForTypeId(*type_id);
1412 const DexFile::ClassDef* class_def = dex_file->FindClassDef(type_idx);
1413 ASSERT_TRUE(class_def != nullptr);
1414
1415 // Count how many code items are for each category, there should be at least one per category.
1416 size_t hot_count = 0;
1417 size_t post_startup_count = 0;
1418 size_t startup_count = 0;
1419 size_t unused_count = 0;
1420 // Visit all of the methdos of the main class and cross reference the method indices to their
1421 // corresponding code item offsets to verify the layout.
1422 ClassDataItemIterator it(*dex_file, dex_file->GetClassData(*class_def));
1423 it.SkipAllFields();
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08001424 for (; it.HasNextMethod(); it.Next()) {
Mathieu Chartier120aa282017-08-05 16:03:03 -07001425 const size_t method_idx = it.GetMemberIndex();
1426 const size_t code_item_offset = it.GetMethodCodeItemOffset();
1427 const bool is_hot = ContainsElement(hot_methods, method_idx);
1428 const bool is_startup = ContainsElement(startup_methods, method_idx);
1429 const bool is_post_startup = ContainsElement(post_methods, method_idx);
1430 if (is_hot) {
1431 // Hot is highest precedence, check that the hot methods are in the hot section.
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001432 EXPECT_TRUE(section_hot_code.Contains(code_item_offset));
Mathieu Chartier120aa282017-08-05 16:03:03 -07001433 ++hot_count;
1434 } else if (is_post_startup) {
1435 // Post startup is sometimes used section.
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001436 EXPECT_TRUE(section_sometimes_used.Contains(code_item_offset));
Mathieu Chartier120aa282017-08-05 16:03:03 -07001437 ++post_startup_count;
1438 } else if (is_startup) {
1439 // Startup at this point means not hot or post startup, these must be startup only then.
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001440 EXPECT_TRUE(section_startup_only.Contains(code_item_offset));
Mathieu Chartier120aa282017-08-05 16:03:03 -07001441 ++startup_count;
1442 } else {
Mathieu Chartier3e0c5172017-11-12 12:58:40 -08001443 if (section_unused.Contains(code_item_offset)) {
Alan Leung9595fd32017-10-17 17:08:19 -07001444 // If no flags are set, the method should be unused ...
1445 ++unused_count;
1446 } else {
1447 // or this method is part of the last code item and the end is 4 byte aligned.
1448 ClassDataItemIterator it2(*dex_file, dex_file->GetClassData(*class_def));
1449 it2.SkipAllFields();
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08001450 for (; it2.HasNextMethod(); it2.Next()) {
Alan Leung9595fd32017-10-17 17:08:19 -07001451 EXPECT_LE(it2.GetMethodCodeItemOffset(), code_item_offset);
1452 }
1453 uint32_t code_item_size = dex_file->FindCodeItemOffset(*class_def, method_idx);
1454 EXPECT_EQ((code_item_offset + code_item_size) % 4, 0u);
1455 }
Mathieu Chartier120aa282017-08-05 16:03:03 -07001456 }
1457 }
1458 DCHECK(!it.HasNext());
1459 EXPECT_GT(hot_count, 0u);
1460 EXPECT_GT(post_startup_count, 0u);
1461 EXPECT_GT(startup_count, 0u);
1462 EXPECT_GT(unused_count, 0u);
1463 }
1464}
1465
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001466// Test that generating compact dex works.
1467TEST_F(Dex2oatTest, GenerateCompactDex) {
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001468 // Generate a compact dex based odex.
1469 const std::string dir = GetScratchDir();
1470 const std::string oat_filename = dir + "/base.oat";
1471 const std::string vdex_filename = dir + "/base.vdex";
Mathieu Chartier6f716502018-03-14 14:00:04 -07001472 const std::string dex_location = GetTestDexFileName("MultiDex");
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001473 std::string error_msg;
1474 const int res = GenerateOdexForTestWithStatus(
Mathieu Chartier6f716502018-03-14 14:00:04 -07001475 { dex_location },
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001476 oat_filename,
1477 CompilerFilter::Filter::kQuicken,
1478 &error_msg,
1479 {"--compact-dex-level=fast"});
1480 EXPECT_EQ(res, 0);
1481 // Open our generated oat file.
1482 std::unique_ptr<OatFile> odex_file(OatFile::Open(oat_filename.c_str(),
1483 oat_filename.c_str(),
1484 nullptr,
1485 nullptr,
1486 false,
1487 /*low_4gb*/false,
Mathieu Chartier6f716502018-03-14 14:00:04 -07001488 dex_location.c_str(),
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001489 &error_msg));
1490 ASSERT_TRUE(odex_file != nullptr);
1491 std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
Mathieu Chartier6f716502018-03-14 14:00:04 -07001492 ASSERT_GT(oat_dex_files.size(), 1u);
1493 // Check that each dex is a compact dex file.
1494 std::vector<std::unique_ptr<const CompactDexFile>> compact_dex_files;
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001495 for (const OatDexFile* oat_dex : oat_dex_files) {
1496 std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1497 ASSERT_TRUE(dex_file != nullptr) << error_msg;
1498 ASSERT_TRUE(dex_file->IsCompactDexFile());
Mathieu Chartier6f716502018-03-14 14:00:04 -07001499 compact_dex_files.push_back(
1500 std::unique_ptr<const CompactDexFile>(dex_file.release()->AsCompactDexFile()));
1501 }
1502 for (const std::unique_ptr<const CompactDexFile>& dex_file : compact_dex_files) {
1503 // Test that every code item is in the owned section.
1504 const CompactDexFile::Header& header = dex_file->GetHeader();
1505 EXPECT_LE(header.OwnedDataBegin(), header.OwnedDataEnd());
1506 EXPECT_LE(header.OwnedDataBegin(), header.data_size_);
1507 EXPECT_LE(header.OwnedDataEnd(), header.data_size_);
1508 for (uint32_t i = 0; i < dex_file->NumClassDefs(); ++i) {
1509 const DexFile::ClassDef& class_def = dex_file->GetClassDef(i);
1510 class_def.VisitMethods(dex_file.get(), [&](const ClassDataItemIterator& it) {
1511 if (it.GetMethodCodeItemOffset() != 0u) {
1512 ASSERT_GE(it.GetMethodCodeItemOffset(), header.OwnedDataBegin());
1513 ASSERT_LT(it.GetMethodCodeItemOffset(), header.OwnedDataEnd());
1514 }
1515 });
1516 }
1517 // Test that the owned sections don't overlap.
1518 for (const std::unique_ptr<const CompactDexFile>& other_dex : compact_dex_files) {
1519 if (dex_file != other_dex) {
1520 ASSERT_TRUE(
1521 (dex_file->GetHeader().OwnedDataBegin() >= other_dex->GetHeader().OwnedDataEnd()) ||
1522 (dex_file->GetHeader().OwnedDataEnd() <= other_dex->GetHeader().OwnedDataBegin()));
1523 }
1524 }
Mathieu Chartier603ccab2017-10-20 14:34:28 -07001525 }
1526}
1527
Andreas Gampef39208f2017-10-19 15:06:59 -07001528class Dex2oatVerifierAbort : public Dex2oatTest {};
1529
1530TEST_F(Dex2oatVerifierAbort, HardFail) {
1531 // Use VerifierDeps as it has hard-failing classes.
1532 std::unique_ptr<const DexFile> dex(OpenTestDexFile("VerifierDeps"));
1533 std::string out_dir = GetScratchDir();
1534 const std::string base_oat_name = out_dir + "/base.oat";
1535 std::string error_msg;
1536 const int res_fail = GenerateOdexForTestWithStatus(
1537 {dex->GetLocation()},
1538 base_oat_name,
1539 CompilerFilter::Filter::kQuicken,
1540 &error_msg,
1541 {"--abort-on-hard-verifier-error"});
1542 EXPECT_NE(0, res_fail);
1543
1544 const int res_no_fail = GenerateOdexForTestWithStatus(
1545 {dex->GetLocation()},
1546 base_oat_name,
1547 CompilerFilter::Filter::kQuicken,
1548 &error_msg,
1549 {"--no-abort-on-hard-verifier-error"});
1550 EXPECT_EQ(0, res_no_fail);
1551}
1552
1553TEST_F(Dex2oatVerifierAbort, SoftFail) {
1554 // Use VerifierDepsMulti as it has hard-failing classes.
1555 std::unique_ptr<const DexFile> dex(OpenTestDexFile("VerifierDepsMulti"));
1556 std::string out_dir = GetScratchDir();
1557 const std::string base_oat_name = out_dir + "/base.oat";
1558 std::string error_msg;
1559 const int res_fail = GenerateOdexForTestWithStatus(
1560 {dex->GetLocation()},
1561 base_oat_name,
1562 CompilerFilter::Filter::kQuicken,
1563 &error_msg,
1564 {"--abort-on-soft-verifier-error"});
1565 EXPECT_NE(0, res_fail);
1566
1567 const int res_no_fail = GenerateOdexForTestWithStatus(
1568 {dex->GetLocation()},
1569 base_oat_name,
1570 CompilerFilter::Filter::kQuicken,
1571 &error_msg,
1572 {"--no-abort-on-soft-verifier-error"});
1573 EXPECT_EQ(0, res_no_fail);
1574}
1575
Andreas Gampecac31ad2017-11-06 20:01:17 -08001576class Dex2oatDedupeCode : public Dex2oatTest {};
1577
1578TEST_F(Dex2oatDedupeCode, DedupeTest) {
1579 // Use MyClassNatives. It has lots of native methods that will produce deduplicate-able code.
1580 std::unique_ptr<const DexFile> dex(OpenTestDexFile("MyClassNatives"));
1581 std::string out_dir = GetScratchDir();
1582 const std::string base_oat_name = out_dir + "/base.oat";
1583 size_t no_dedupe_size = 0;
1584 GenerateOdexForTest(dex->GetLocation(),
1585 base_oat_name,
1586 CompilerFilter::Filter::kSpeed,
1587 { "--deduplicate-code=false" },
1588 true, // expect_success
1589 false, // use_fd
1590 [&no_dedupe_size](const OatFile& o) {
1591 no_dedupe_size = o.Size();
1592 });
1593
1594 size_t dedupe_size = 0;
1595 GenerateOdexForTest(dex->GetLocation(),
1596 base_oat_name,
1597 CompilerFilter::Filter::kSpeed,
1598 { "--deduplicate-code=true" },
1599 true, // expect_success
1600 false, // use_fd
1601 [&dedupe_size](const OatFile& o) {
1602 dedupe_size = o.Size();
1603 });
1604
1605 EXPECT_LT(dedupe_size, no_dedupe_size);
1606}
1607
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00001608TEST_F(Dex2oatTest, UncompressedTest) {
1609 std::unique_ptr<const DexFile> dex(OpenTestDexFile("MainUncompressed"));
1610 std::string out_dir = GetScratchDir();
1611 const std::string base_oat_name = out_dir + "/base.oat";
1612 GenerateOdexForTest(dex->GetLocation(),
1613 base_oat_name,
1614 CompilerFilter::Filter::kQuicken,
1615 { },
1616 true, // expect_success
1617 false, // use_fd
1618 [](const OatFile& o) {
1619 CHECK(!o.ContainsDexCode());
1620 });
1621}
1622
Mathieu Chartier700a9852018-02-06 18:27:38 -08001623TEST_F(Dex2oatTest, EmptyUncompressedDexTest) {
1624 std::string out_dir = GetScratchDir();
1625 const std::string base_oat_name = out_dir + "/base.oat";
1626 std::string error_msg;
1627 int status = GenerateOdexForTestWithStatus(
1628 { GetTestDexFileName("MainEmptyUncompressed") },
1629 base_oat_name,
1630 CompilerFilter::Filter::kQuicken,
1631 &error_msg,
1632 { },
1633 /*use_fd*/ false);
1634 // Expect to fail with code 1 and not SIGSEGV or SIGABRT.
1635 ASSERT_TRUE(WIFEXITED(status));
1636 ASSERT_EQ(WEXITSTATUS(status), 1) << error_msg;
1637}
1638
Mathieu Chartier05f90d12018-02-07 13:47:17 -08001639// Dex file that has duplicate methods have different code items and debug info.
1640static const char kDuplicateMethodInputDex[] =
1641 "ZGV4CjAzOQDEy8VPdj4qHpgPYFWtLCtOykfFP4kB8tGYDAAAcAAAAHhWNBIAAAAAAAAAANALAABI"
1642 "AAAAcAAAAA4AAACQAQAABQAAAMgBAAANAAAABAIAABkAAABsAgAABAAAADQDAADgCAAAuAMAADgI"
1643 "AABCCAAASggAAE8IAABcCAAAaggAAHkIAACICAAAlggAAKQIAACyCAAAwAgAAM4IAADcCAAA6ggA"
1644 "APgIAAD7CAAA/wgAABcJAAAuCQAARQkAAFQJAAB4CQAAmAkAALsJAADSCQAA5gkAAPoJAAAVCgAA"
1645 "KQoAADsKAABCCgAASgoAAFIKAABbCgAAZAoAAGwKAAB0CgAAfAoAAIQKAACMCgAAlAoAAJwKAACk"
1646 "CgAArQoAALcKAADACgAAwwoAAMcKAADcCgAA6QoAAPEKAAD3CgAA/QoAAAMLAAAJCwAAEAsAABcL"
1647 "AAAdCwAAIwsAACkLAAAvCwAANQsAADsLAABBCwAARwsAAE0LAABSCwAAWwsAAF4LAABoCwAAbwsA"
1648 "ABEAAAASAAAAEwAAABQAAAAVAAAAFgAAABcAAAAYAAAAGQAAABoAAAAbAAAAHAAAAC4AAAAwAAAA"
1649 "DwAAAAkAAAAAAAAAEAAAAAoAAACoBwAALgAAAAwAAAAAAAAALwAAAAwAAACoBwAALwAAAAwAAACw"
1650 "BwAAAgAJADUAAAACAAkANgAAAAIACQA3AAAAAgAJADgAAAACAAkAOQAAAAIACQA6AAAAAgAJADsA"
1651 "AAACAAkAPAAAAAIACQA9AAAAAgAJAD4AAAACAAkAPwAAAAIACQBAAAAACwAHAEIAAAAAAAIAAQAA"
1652 "AAAAAwAeAAAAAQACAAEAAAABAAMAHgAAAAIAAgAAAAAAAgACAAEAAAADAAIAAQAAAAMAAgAfAAAA"
1653 "AwACACAAAAADAAIAIQAAAAMAAgAiAAAAAwACACMAAAADAAIAJAAAAAMAAgAlAAAAAwACACYAAAAD"
1654 "AAIAJwAAAAMAAgAoAAAAAwACACkAAAADAAIAKgAAAAMABAA0AAAABwADAEMAAAAIAAIAAQAAAAoA"
1655 "AgABAAAACgABADIAAAAKAAAARQAAAAAAAAAAAAAACAAAAAAAAAAdAAAAaAcAALYHAAAAAAAAAQAA"
1656 "AAAAAAAIAAAAAAAAAB0AAAB4BwAAxAcAAAAAAAACAAAAAAAAAAgAAAAAAAAAHQAAAIgHAADSBwAA"
1657 "AAAAAAMAAAAAAAAACAAAAAAAAAAdAAAAmAcAAPoHAAAAAAAAAAAAAAEAAAAAAAAArAYAADEAAAAa"
1658 "AAMAaQAAABoABABpAAEAGgAHAGkABAAaAAgAaQAFABoACQBpAAYAGgAKAGkABwAaAAsAaQAIABoA"
1659 "DABpAAkAGgANAGkACgAaAA4AaQALABoABQBpAAIAGgAGAGkAAwAOAAAAAQABAAEAAACSBgAABAAA"
1660 "AHAQFQAAAA4ABAABAAIAAACWBgAAFwAAAGIADAAiAQoAcBAWAAEAGgICAG4gFwAhAG4gFwAxAG4Q"
1661 "GAABAAwBbiAUABAADgAAAAEAAQABAAAAngYAAAQAAABwEBUAAAAOAAIAAQACAAAAogYAAAYAAABi"
1662 "AAwAbiAUABAADgABAAEAAQAAAKgGAAAEAAAAcBAVAAAADgABAAEAAQAAALsGAAAEAAAAcBAVAAAA"
1663 "DgABAAAAAQAAAL8GAAAGAAAAYgAAAHEQAwAAAA4AAQAAAAEAAADEBgAABgAAAGIAAQBxEAMAAAAO"
1664 "AAEAAAABAAAA8QYAAAYAAABiAAIAcRABAAAADgABAAAAAQAAAPYGAAAGAAAAYgADAHEQAwAAAA4A"
1665 "AQAAAAEAAADJBgAABgAAAGIABABxEAMAAAAOAAEAAAABAAAAzgYAAAYAAABiAAEAcRADAAAADgAB"
1666 "AAAAAQAAANMGAAAGAAAAYgAGAHEQAwAAAA4AAQAAAAEAAADYBgAABgAAAGIABwBxEAMAAAAOAAEA"
1667 "AAABAAAA3QYAAAYAAABiAAgAcRABAAAADgABAAAAAQAAAOIGAAAGAAAAYgAJAHEQAwAAAA4AAQAA"
1668 "AAEAAADnBgAABgAAAGIACgBxEAMAAAAOAAEAAAABAAAA7AYAAAYAAABiAAsAcRABAAAADgABAAEA"
1669 "AAAAAPsGAAAlAAAAcQAHAAAAcQAIAAAAcQALAAAAcQAMAAAAcQANAAAAcQAOAAAAcQAPAAAAcQAQ"
1670 "AAAAcQARAAAAcQASAAAAcQAJAAAAcQAKAAAADgAnAA4AKQFFDgEWDwAhAA4AIwFFDloAEgAOABMA"
1671 "DktLS0tLS0tLS0tLABEADgAuAA5aADIADloANgAOWgA6AA5aAD4ADloAQgAOWgBGAA5aAEoADloA"
1672 "TgAOWgBSAA5aAFYADloAWgAOWgBeATQOPDw8PDw8PDw8PDw8AAIEAUYYAwIFAjEECEEXLAIFAjEE"
1673 "CEEXKwIFAjEECEEXLQIGAUYcAxgAGAEYAgAAAAIAAAAMBwAAEgcAAAIAAAAMBwAAGwcAAAIAAAAM"
1674 "BwAAJAcAAAEAAAAtBwAAPAcAAAAAAAAAAAAAAAAAAEgHAAAAAAAAAAAAAAAAAABUBwAAAAAAAAAA"
1675 "AAAAAAAAYAcAAAAAAAAAAAAAAAAAAAEAAAAJAAAAAQAAAA0AAAACAACAgASsCAEIxAgAAAIAAoCA"
1676 "BIQJAQicCQwAAgAACQEJAQkBCQEJAQkBCQEJAQkBCQEJAQkEiIAEuAcBgIAEuAkAAA4ABoCABNAJ"
1677 "AQnoCQAJhAoACaAKAAm8CgAJ2AoACfQKAAmQCwAJrAsACcgLAAnkCwAJgAwACZwMAAm4DAg8Y2xp"
1678 "bml0PgAGPGluaXQ+AANBQUEAC0hlbGxvIFdvcmxkAAxIZWxsbyBXb3JsZDEADUhlbGxvIFdvcmxk"
1679 "MTAADUhlbGxvIFdvcmxkMTEADEhlbGxvIFdvcmxkMgAMSGVsbG8gV29ybGQzAAxIZWxsbyBXb3Js"
1680 "ZDQADEhlbGxvIFdvcmxkNQAMSGVsbG8gV29ybGQ2AAxIZWxsbyBXb3JsZDcADEhlbGxvIFdvcmxk"
1681 "OAAMSGVsbG8gV29ybGQ5AAFMAAJMTAAWTE1hbnlNZXRob2RzJFByaW50ZXIyOwAVTE1hbnlNZXRo"
1682 "b2RzJFByaW50ZXI7ABVMTWFueU1ldGhvZHMkU3RyaW5nczsADUxNYW55TWV0aG9kczsAIkxkYWx2"
1683 "aWsvYW5ub3RhdGlvbi9FbmNsb3NpbmdDbGFzczsAHkxkYWx2aWsvYW5ub3RhdGlvbi9Jbm5lckNs"
1684 "YXNzOwAhTGRhbHZpay9hbm5vdGF0aW9uL01lbWJlckNsYXNzZXM7ABVMamF2YS9pby9QcmludFN0"
1685 "cmVhbTsAEkxqYXZhL2xhbmcvT2JqZWN0OwASTGphdmEvbGFuZy9TdHJpbmc7ABlMamF2YS9sYW5n"
1686 "L1N0cmluZ0J1aWxkZXI7ABJMamF2YS9sYW5nL1N5c3RlbTsAEE1hbnlNZXRob2RzLmphdmEABVBy"
1687 "aW50AAZQcmludDAABlByaW50MQAHUHJpbnQxMAAHUHJpbnQxMQAGUHJpbnQyAAZQcmludDMABlBy"
1688 "aW50NAAGUHJpbnQ1AAZQcmludDYABlByaW50NwAGUHJpbnQ4AAZQcmludDkAB1ByaW50ZXIACFBy"
1689 "aW50ZXIyAAdTdHJpbmdzAAFWAAJWTAATW0xqYXZhL2xhbmcvU3RyaW5nOwALYWNjZXNzRmxhZ3MA"
1690 "BmFwcGVuZAAEYXJncwAEbWFpbgAEbXNnMAAEbXNnMQAFbXNnMTAABW1zZzExAARtc2cyAARtc2cz"
1691 "AARtc2c0AARtc2c1AARtc2c2AARtc2c3AARtc2c4AARtc2c5AARuYW1lAANvdXQAB3ByaW50bG4A"
1692 "AXMACHRvU3RyaW5nAAV2YWx1ZQBffn5EOHsibWluLWFwaSI6MTAwMDAsInNoYS0xIjoiZmViODZj"
1693 "MDA2ZWZhY2YxZDc5ODRiODVlMTc5MGZlZjdhNzY3YWViYyIsInZlcnNpb24iOiJ2MS4xLjUtZGV2"
1694 "In0AEAAAAAAAAAABAAAAAAAAAAEAAABIAAAAcAAAAAIAAAAOAAAAkAEAAAMAAAAFAAAAyAEAAAQA"
1695 "AAANAAAABAIAAAUAAAAZAAAAbAIAAAYAAAAEAAAANAMAAAEgAAAUAAAAuAMAAAMgAAAUAAAAkgYA"
1696 "AAQgAAAFAAAADAcAAAMQAAAEAAAAOQcAAAYgAAAEAAAAaAcAAAEQAAACAAAAqAcAAAAgAAAEAAAA"
1697 "tgcAAAIgAABIAAAAOAgAAAAQAAABAAAA0AsAAAAAAAA=";
1698
1699static void WriteBase64ToFile(const char* base64, File* file) {
1700 // Decode base64.
1701 CHECK(base64 != nullptr);
1702 size_t length;
1703 std::unique_ptr<uint8_t[]> bytes(DecodeBase64(base64, &length));
1704 CHECK(bytes != nullptr);
1705 if (!file->WriteFully(bytes.get(), length)) {
1706 PLOG(FATAL) << "Failed to write base64 as file";
1707 }
1708}
1709
1710TEST_F(Dex2oatTest, CompactDexGenerationFailure) {
1711 ScratchFile temp_dex;
1712 WriteBase64ToFile(kDuplicateMethodInputDex, temp_dex.GetFile());
1713 std::string out_dir = GetScratchDir();
1714 const std::string oat_filename = out_dir + "/base.oat";
1715 // The dex won't pass the method verifier, only use the verify filter.
1716 GenerateOdexForTest(temp_dex.GetFilename(),
1717 oat_filename,
1718 CompilerFilter::Filter::kVerify,
1719 { },
1720 true, // expect_success
1721 false, // use_fd
1722 [](const OatFile& o) {
1723 CHECK(o.ContainsDexCode());
1724 });
1725 // Open our generated oat file.
1726 std::string error_msg;
1727 std::unique_ptr<OatFile> odex_file(OatFile::Open(oat_filename.c_str(),
1728 oat_filename.c_str(),
1729 nullptr,
1730 nullptr,
1731 false,
1732 /*low_4gb*/false,
1733 temp_dex.GetFilename().c_str(),
1734 &error_msg));
1735 ASSERT_TRUE(odex_file != nullptr);
1736 std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
1737 ASSERT_EQ(oat_dex_files.size(), 1u);
1738 // The dexes should have failed to convert to compact dex.
1739 for (const OatDexFile* oat_dex : oat_dex_files) {
1740 std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1741 ASSERT_TRUE(dex_file != nullptr) << error_msg;
1742 ASSERT_TRUE(!dex_file->IsCompactDexFile());
1743 }
1744}
1745
Mathieu Chartiercda83be2018-03-01 23:55:55 -08001746TEST_F(Dex2oatTest, CompactDexGenerationFailureMultiDex) {
1747 // Create a multidex file with only one dex that gets rejected for cdex conversion.
1748 ScratchFile apk_file;
1749 {
1750 FILE* file = fdopen(apk_file.GetFd(), "w+b");
1751 ZipWriter writer(file);
1752 // Add vdex to zip.
1753 writer.StartEntry("classes.dex", ZipWriter::kCompress);
1754 size_t length = 0u;
1755 std::unique_ptr<uint8_t[]> bytes(DecodeBase64(kDuplicateMethodInputDex, &length));
1756 ASSERT_GE(writer.WriteBytes(&bytes[0], length), 0);
1757 writer.FinishEntry();
1758 writer.StartEntry("classes2.dex", ZipWriter::kCompress);
1759 std::unique_ptr<const DexFile> dex(OpenTestDexFile("ManyMethods"));
1760 ASSERT_GE(writer.WriteBytes(dex->Begin(), dex->Size()), 0);
1761 writer.FinishEntry();
1762 writer.Finish();
1763 ASSERT_EQ(apk_file.GetFile()->Flush(), 0);
1764 }
1765 const std::string dex_location = apk_file.GetFilename();
1766 const std::string odex_location = GetOdexDir() + "/output.odex";
1767 GenerateOdexForTest(dex_location,
1768 odex_location,
1769 CompilerFilter::kQuicken,
1770 { "--compact-dex-level=fast" },
1771 true);
1772}
1773
Andreas Gampe25419b52018-02-08 21:30:26 -08001774TEST_F(Dex2oatTest, StderrLoggerOutput) {
1775 std::string dex_location = GetScratchDir() + "/Dex2OatStderrLoggerTest.jar";
1776 std::string odex_location = GetOdexDir() + "/Dex2OatStderrLoggerTest.odex";
1777
1778 // Test file doesn't matter.
1779 Copy(GetDexSrc1(), dex_location);
1780
1781 GenerateOdexForTest(dex_location,
1782 odex_location,
1783 CompilerFilter::kQuicken,
1784 { "--runtime-arg", "-Xuse-stderr-logger" },
1785 true);
1786 // Look for some random part of dex2oat logging. With the stderr logger this should be captured,
1787 // even on device.
1788 EXPECT_NE(std::string::npos, output_.find("dex2oat took"));
1789}
1790
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001791TEST_F(Dex2oatTest, VerifyCompilationReason) {
1792 std::string dex_location = GetScratchDir() + "/Dex2OatCompilationReason.jar";
1793 std::string odex_location = GetOdexDir() + "/Dex2OatCompilationReason.odex";
1794
1795 // Test file doesn't matter.
1796 Copy(GetDexSrc1(), dex_location);
1797
1798 GenerateOdexForTest(dex_location,
1799 odex_location,
1800 CompilerFilter::kVerify,
1801 { "--compilation-reason=install" },
1802 true);
1803 std::string error_msg;
1804 std::unique_ptr<OatFile> odex_file(OatFile::Open(odex_location.c_str(),
1805 odex_location.c_str(),
1806 nullptr,
1807 nullptr,
1808 false,
1809 /*low_4gb*/false,
1810 dex_location.c_str(),
1811 &error_msg));
1812 ASSERT_TRUE(odex_file != nullptr);
1813 ASSERT_STREQ("install", odex_file->GetCompilationReason());
1814}
1815
1816TEST_F(Dex2oatTest, VerifyNoCompilationReason) {
1817 std::string dex_location = GetScratchDir() + "/Dex2OatNoCompilationReason.jar";
1818 std::string odex_location = GetOdexDir() + "/Dex2OatNoCompilationReason.odex";
1819
1820 // Test file doesn't matter.
1821 Copy(GetDexSrc1(), dex_location);
1822
1823 GenerateOdexForTest(dex_location,
1824 odex_location,
1825 CompilerFilter::kVerify,
1826 {},
1827 true);
1828 std::string error_msg;
1829 std::unique_ptr<OatFile> odex_file(OatFile::Open(odex_location.c_str(),
1830 odex_location.c_str(),
1831 nullptr,
1832 nullptr,
1833 false,
1834 /*low_4gb*/false,
1835 dex_location.c_str(),
1836 &error_msg));
1837 ASSERT_TRUE(odex_file != nullptr);
1838 ASSERT_EQ(nullptr, odex_file->GetCompilationReason());
1839}
1840
Mathieu Chartier792111c2018-02-15 13:02:15 -08001841TEST_F(Dex2oatTest, DontExtract) {
1842 std::unique_ptr<const DexFile> dex(OpenTestDexFile("ManyMethods"));
1843 std::string error_msg;
1844 const std::string out_dir = GetScratchDir();
1845 const std::string dex_location = dex->GetLocation();
1846 const std::string odex_location = out_dir + "/base.oat";
1847 const std::string vdex_location = out_dir + "/base.vdex";
1848 GenerateOdexForTest(dex_location,
1849 odex_location,
1850 CompilerFilter::Filter::kVerify,
1851 { "--copy-dex-files=false" },
1852 true, // expect_success
1853 false, // use_fd
1854 [](const OatFile&) {
1855 });
1856 {
1857 // Check the vdex doesn't have dex.
1858 std::unique_ptr<VdexFile> vdex(VdexFile::Open(vdex_location.c_str(),
1859 /*writable*/ false,
1860 /*low_4gb*/ false,
1861 /*unquicken*/ false,
1862 &error_msg));
1863 ASSERT_TRUE(vdex != nullptr);
Nicolas Geoffrayc334f832018-03-02 10:52:16 +00001864 EXPECT_FALSE(vdex->HasDexSection()) << output_;
Mathieu Chartier792111c2018-02-15 13:02:15 -08001865 }
1866 std::unique_ptr<OatFile> odex_file(OatFile::Open(odex_location.c_str(),
1867 odex_location.c_str(),
1868 nullptr,
1869 nullptr,
1870 false,
1871 /*low_4gb*/ false,
1872 dex_location.c_str(),
1873 &error_msg));
1874 ASSERT_TRUE(odex_file != nullptr) << dex_location;
1875 std::vector<const OatDexFile*> oat_dex_files = odex_file->GetOatDexFiles();
1876 ASSERT_EQ(oat_dex_files.size(), 1u);
1877 // Verify that the oat file can still open the dex files.
1878 for (const OatDexFile* oat_dex : oat_dex_files) {
1879 std::unique_ptr<const DexFile> dex_file(oat_dex->OpenDexFile(&error_msg));
1880 ASSERT_TRUE(dex_file != nullptr) << error_msg;
1881 }
1882 // Create a dm file and use it to verify.
1883 // Add produced artifacts to a zip file that doesn't contain the classes.dex.
1884 ScratchFile dm_file;
1885 {
1886 std::unique_ptr<File> vdex_file(OS::OpenFileForReading(vdex_location.c_str()));
1887 ASSERT_TRUE(vdex_file != nullptr);
1888 ASSERT_GT(vdex_file->GetLength(), 0u);
1889 FILE* file = fdopen(dm_file.GetFd(), "w+b");
1890 ZipWriter writer(file);
1891 auto write_all_bytes = [&](File* file) {
1892 std::unique_ptr<uint8_t[]> bytes(new uint8_t[file->GetLength()]);
1893 ASSERT_TRUE(file->ReadFully(&bytes[0], file->GetLength()));
1894 ASSERT_GE(writer.WriteBytes(&bytes[0], file->GetLength()), 0);
1895 };
1896 // Add vdex to zip.
1897 writer.StartEntry(VdexFile::kVdexNameInDmFile, ZipWriter::kCompress);
1898 write_all_bytes(vdex_file.get());
1899 writer.FinishEntry();
1900 writer.Finish();
1901 ASSERT_EQ(dm_file.GetFile()->Flush(), 0);
1902 }
1903
1904 // Generate a quickened dex by using the input dm file to verify.
1905 GenerateOdexForTest(dex_location,
1906 odex_location,
1907 CompilerFilter::Filter::kQuicken,
Mathieu Chartier026dc0b2018-02-20 10:07:51 -08001908 { "--dump-timings",
1909 "--dm-file=" + dm_file.GetFilename(),
1910 // Pass -Xuse-stderr-logger have dex2oat output in output_ on target.
1911 "--runtime-arg",
1912 "-Xuse-stderr-logger" },
Mathieu Chartier792111c2018-02-15 13:02:15 -08001913 true, // expect_success
1914 false, // use_fd
1915 [](const OatFile& o) {
1916 CHECK(o.ContainsDexCode());
1917 });
Mathieu Chartier026dc0b2018-02-20 10:07:51 -08001918 // Check the output for "Fast verify", this is printed from --dump-timings.
1919 std::istringstream iss(output_);
1920 std::string line;
1921 bool found_fast_verify = false;
1922 const std::string kFastVerifyString = "Fast Verify";
1923 while (std::getline(iss, line) && !found_fast_verify) {
1924 found_fast_verify = found_fast_verify || line.find(kFastVerifyString) != std::string::npos;
Mathieu Chartier792111c2018-02-15 13:02:15 -08001925 }
Mathieu Chartier026dc0b2018-02-20 10:07:51 -08001926 EXPECT_TRUE(found_fast_verify) << "Expected to find " << kFastVerifyString << "\n" << output_;
Mathieu Chartier792111c2018-02-15 13:02:15 -08001927}
1928
Mathieu Chartier2daa1342018-02-20 16:19:28 -08001929// Test that dex files with quickened opcodes aren't dequickened.
1930TEST_F(Dex2oatTest, QuickenedInput) {
1931 std::string error_msg;
1932 ScratchFile temp_dex;
1933 MutateDexFile(temp_dex.GetFile(), GetTestDexFileName("ManyMethods"), [] (DexFile* dex) {
1934 bool mutated_successfully = false;
1935 // Change the dex instructions to make an opcode that spans past the end of the code item.
1936 for (size_t i = 0; i < dex->NumClassDefs(); ++i) {
1937 const DexFile::ClassDef& def = dex->GetClassDef(i);
1938 const uint8_t* data = dex->GetClassData(def);
1939 if (data == nullptr) {
1940 continue;
1941 }
1942 ClassDataItemIterator it(*dex, data);
1943 it.SkipAllFields();
1944 while (it.HasNextMethod()) {
1945 DexFile::CodeItem* item = const_cast<DexFile::CodeItem*>(it.GetMethodCodeItem());
1946 if (item != nullptr) {
1947 CodeItemInstructionAccessor instructions(*dex, item);
1948 // Make a quickened instruction that doesn't run past the end of the code item.
1949 if (instructions.InsnsSizeInCodeUnits() > 2) {
1950 const_cast<Instruction&>(instructions.InstructionAt(0)).SetOpcode(
1951 Instruction::IGET_BYTE_QUICK);
1952 mutated_successfully = true;
1953 }
1954 }
1955 it.Next();
1956 }
1957 }
1958 CHECK(mutated_successfully)
1959 << "Failed to find candidate code item with only one code unit in last instruction.";
1960 });
1961
1962 std::string dex_location = temp_dex.GetFilename();
1963 std::string odex_location = GetOdexDir() + "/quickened.odex";
1964 std::string vdex_location = GetOdexDir() + "/quickened.vdex";
1965 std::unique_ptr<File> vdex_output(OS::CreateEmptyFile(vdex_location.c_str()));
1966 // Quicken the dex
1967 {
1968 std::string input_vdex = "--input-vdex-fd=-1";
1969 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_output->Fd());
1970 GenerateOdexForTest(dex_location,
1971 odex_location,
1972 CompilerFilter::kQuicken,
1973 // Disable cdex since we want to compare against the original dex file
1974 // after unquickening.
1975 { input_vdex, output_vdex, kDisableCompactDex },
1976 /* expect_success */ true,
1977 /* use_fd */ true);
1978 }
1979 // Unquicken by running the verify compiler filter on the vdex file and verify it matches.
1980 std::string odex_location2 = GetOdexDir() + "/unquickened.odex";
1981 std::string vdex_location2 = GetOdexDir() + "/unquickened.vdex";
1982 std::unique_ptr<File> vdex_unquickened(OS::CreateEmptyFile(vdex_location2.c_str()));
1983 {
1984 std::string input_vdex = StringPrintf("--input-vdex-fd=%d", vdex_output->Fd());
1985 std::string output_vdex = StringPrintf("--output-vdex-fd=%d", vdex_unquickened->Fd());
1986 GenerateOdexForTest(dex_location,
1987 odex_location2,
1988 CompilerFilter::kVerify,
1989 // Disable cdex to avoid needing to write out the shared section.
1990 { input_vdex, output_vdex, kDisableCompactDex },
1991 /* expect_success */ true,
1992 /* use_fd */ true);
1993 }
1994 ASSERT_EQ(vdex_unquickened->Flush(), 0) << "Could not flush and close vdex file";
1995 ASSERT_TRUE(success_);
1996 {
1997 // Check that hte vdex has one dex and compare it to the original one.
1998 std::unique_ptr<VdexFile> vdex(VdexFile::Open(vdex_location2.c_str(),
1999 /*writable*/ false,
2000 /*low_4gb*/ false,
2001 /*unquicken*/ false,
2002 &error_msg));
2003 std::vector<std::unique_ptr<const DexFile>> dex_files;
2004 bool result = vdex->OpenAllDexFiles(&dex_files, &error_msg);
2005 ASSERT_TRUE(result) << error_msg;
2006 ASSERT_EQ(dex_files.size(), 1u) << error_msg;
2007 ScratchFile temp;
2008 ASSERT_TRUE(temp.GetFile()->WriteFully(dex_files[0]->Begin(), dex_files[0]->Size()));
2009 ASSERT_EQ(temp.GetFile()->Flush(), 0) << "Could not flush extracted dex";
2010 EXPECT_EQ(temp.GetFile()->Compare(temp_dex.GetFile()), 0);
2011 }
2012 ASSERT_EQ(vdex_output->FlushCloseOrErase(), 0) << "Could not flush and close";
2013 ASSERT_EQ(vdex_unquickened->FlushCloseOrErase(), 0) << "Could not flush and close";
2014}
2015
Andreas Gampee1459ae2016-06-29 09:36:30 -07002016} // namespace art