blob: 84e46226dd3783d50a53dd0f1a7b6d5d28a49d0f [file] [log] [blame]
Brian Carlstrom7940e442013-07-12 13:46:57 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Andreas Gamped687e372015-04-28 23:16:03 -070017#include <inttypes.h>
Brian Carlstrom7940e442013-07-12 13:46:57 -070018#include <stdio.h>
19#include <stdlib.h>
20#include <sys/stat.h>
Evgenii Stepanov1e133742015-05-20 12:30:59 -070021#include "base/memory_tool.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070022
Andreas Gampe097f34c2017-08-23 08:57:51 -070023#include <forward_list>
Brian Carlstrom7940e442013-07-12 13:46:57 -070024#include <fstream>
25#include <iostream>
Andreas Gampe67f02822016-06-24 21:05:23 -070026#include <limits>
Calin Juravlebdd9d712021-04-05 17:59:10 -070027#include <log/log.h>
Brian Carlstrom7940e442013-07-12 13:46:57 -070028#include <sstream>
29#include <string>
Andreas Gampe097f34c2017-08-23 08:57:51 -070030#include <type_traits>
Brian Carlstrom7940e442013-07-12 13:46:57 -070031#include <vector>
32
Orion Hodsonffc791c2019-11-14 19:19:28 +000033#if defined(__linux__)
34#include <sched.h>
35#if defined(__arm__)
Vladimir Markof94b7812014-06-05 15:48:04 +010036#include <sys/personality.h>
37#include <sys/utsname.h>
Orion Hodsonffc791c2019-11-14 19:19:28 +000038#endif // __arm__
Vladimir Markof94b7812014-06-05 15:48:04 +010039#endif
40
Orion Hodsonffc791c2019-11-14 19:19:28 +000041#include "android-base/parseint.h"
Andreas Gampe46ee31b2016-12-14 10:11:49 -080042#include "android-base/stringprintf.h"
Andreas Gampe9186ced2016-12-12 14:28:21 -080043#include "android-base/strings.h"
Nicolas Geoffray1ece2992021-01-06 17:02:04 +000044#include "android-base/unique_fd.h"
Andreas Gampe9186ced2016-12-12 14:28:21 -080045
Vladimir Markod1f73512020-04-02 10:50:35 +010046#include "aot_class_linker.h"
Ian Rogersd582fa42014-11-05 23:46:43 -080047#include "arch/instruction_set_features.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000048#include "art_method-inl.h"
Andreas Gampe8228cdf2017-05-30 15:03:54 -070049#include "base/callee_save_type.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070050#include "base/dumpable.h"
David Sehr891a50e2017-10-27 17:01:07 -070051#include "base/file_utils.h"
David Sehr67bf42e2018-02-26 16:43:04 -080052#include "base/leb128.h"
Andreas Gampe794ad762015-02-23 08:12:24 -080053#include "base/macros.h"
David Sehrc431b9d2018-03-02 12:01:51 -080054#include "base/mutex.h"
55#include "base/os.h"
Roland Levillainc3854242021-05-06 00:19:19 +010056#include "base/fast_exit.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000057#include "base/scoped_flock.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070058#include "base/stl_util.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010059#include "base/time_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070060#include "base/timing_logger.h"
61#include "base/unix_file/fd_file.h"
David Sehrc431b9d2018-03-02 12:01:51 -080062#include "base/utils.h"
David Sehr79e26072018-04-06 17:58:50 -070063#include "base/zip_archive.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070064#include "class_linker.h"
Calin Juravle1ce70852017-06-28 10:59:03 -070065#include "class_loader_context.h"
Andreas Gampe097f34c2017-08-23 08:57:51 -070066#include "cmdline_parser.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000067#include "compiler.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000068#include "compiler_callbacks.h"
David Srbecky09c2a6b2016-03-11 17:11:44 +000069#include "debug/elf_debug_writer.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000070#include "debug/method_debug_info.h"
David Sehrb2ec9f52018-02-21 13:20:31 -080071#include "dex/descriptors_names.h"
David Sehr9e734c72018-01-04 17:56:19 -080072#include "dex/dex_file-inl.h"
Vladimir Marko21910692019-11-06 13:27:03 +000073#include "dex/dex_file_loader.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000074#include "dex/quick_compiler_callbacks.h"
75#include "dex/verification_results.h"
Andreas Gampe097f34c2017-08-23 08:57:51 -070076#include "dex2oat_options.h"
David Srbecky2faab002019-02-12 16:35:48 +000077#include "dexlayout.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070078#include "driver/compiler_driver.h"
Brian Carlstrom6449c622014-02-10 23:48:36 -080079#include "driver/compiler_options.h"
Andreas Gampe097f34c2017-08-23 08:57:51 -070080#include "driver/compiler_options_map-inl.h"
Andreas Gampe88ec7f42014-11-05 10:18:32 -080081#include "elf_file.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070082#include "gc/space/image_space.h"
83#include "gc/space/space-inl.h"
Mathieu Chartier72041a02017-07-14 18:23:25 -070084#include "gc/verification.h"
Andreas Gampe2969bcd2015-03-09 12:57:41 -070085#include "interpreter/unstarted_runtime.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010086#include "jni/java_vm_ext.h"
Vladimir Marko74527972016-11-29 15:57:32 +000087#include "linker/elf_writer.h"
88#include "linker/elf_writer_quick.h"
Vladimir Marko74527972016-11-29 15:57:32 +000089#include "linker/image_writer.h"
Vladimir Marko944da602016-02-19 12:27:55 +000090#include "linker/multi_oat_relative_patcher.h"
Vladimir Marko74527972016-11-29 15:57:32 +000091#include "linker/oat_writer.h"
Vladimir Marko37d6d772020-03-05 17:13:28 +000092#include "mirror/class-alloc-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070093#include "mirror/class_loader.h"
94#include "mirror/object-inl.h"
95#include "mirror/object_array-inl.h"
Vladimir Markod3d00c02019-11-07 15:09:07 +000096#include "oat.h"
Andreas Gampe2ff3b972017-06-05 18:14:53 -070097#include "oat_file.h"
Jeff Haob11ffb72016-04-07 15:40:54 -070098#include "oat_file_assistant.h"
Nicolas Geoffray1d4f0092020-08-07 14:01:05 +010099#include "palette/palette.h"
David Sehr82d046e2018-04-23 08:14:19 -0700100#include "profile/profile_compilation_info.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -0700101#include "runtime.h"
Vladimir Marko49b0f452015-12-10 13:49:19 +0000102#include "runtime_options.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -0700103#include "scoped_thread_state_change-inl.h"
David Srbecky2faab002019-02-12 16:35:48 +0000104#include "stream/buffered_output_stream.h"
105#include "stream/file_output_stream.h"
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000106#include "vdex_file.h"
David Brazdilca3c8c32016-09-06 14:04:48 +0100107#include "verifier/verifier_deps.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -0700108#include "well_known_classes.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -0700109
110namespace art {
111
Nicolas Geoffray2cee2132020-08-24 15:31:52 +0100112namespace dex2oat {
113 enum class ReturnCode : int {
114 kNoFailure = 0, // No failure, execution completed successfully.
115 kOther = 1, // Some other not closer specified error occurred.
116 kCreateRuntime = 2, // Dex2oat failed creating a runtime.
117 };
118} // namespace dex2oat
119
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800120using android::base::StringAppendV;
121using android::base::StringPrintf;
Vladimir Marko91f10322018-12-07 18:04:10 +0000122using gc::space::ImageSpace;
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800123
Andreas Gampee1459ae2016-06-29 09:36:30 -0700124static constexpr size_t kDefaultMinDexFilesForSwap = 2;
125static constexpr size_t kDefaultMinDexFileCumulativeSizeForSwap = 20 * MB;
126
Mathieu Chartier010126f2017-07-15 15:44:18 -0700127// Compiler filter override for very large apps.
128static constexpr CompilerFilter::Filter kLargeAppFilter = CompilerFilter::kVerify;
129
Brian Carlstrom6449c622014-02-10 23:48:36 -0800130static int original_argc;
131static char** original_argv;
132
133static std::string CommandLine() {
134 std::vector<std::string> command;
Andreas Gampe2a487eb2018-11-19 11:41:22 -0800135 command.reserve(original_argc);
Brian Carlstrom6449c622014-02-10 23:48:36 -0800136 for (int i = 0; i < original_argc; ++i) {
137 command.push_back(original_argv[i]);
138 }
Andreas Gampe9186ced2016-12-12 14:28:21 -0800139 return android::base::Join(command, ' ');
Brian Carlstrom6449c622014-02-10 23:48:36 -0800140}
141
Andreas Gampe046c7062015-05-18 23:22:54 -0700142// A stripped version. Remove some less essential parameters. If we see a "--zip-fd=" parameter, be
143// even more aggressive. There won't be much reasonable data here for us in that case anyways (the
144// locations are all staged).
145static std::string StrippedCommandLine() {
146 std::vector<std::string> command;
147
Calin Juravle07c6d722017-06-07 17:06:12 +0000148 // Do a pre-pass to look for zip-fd and the compiler filter.
Andreas Gampe046c7062015-05-18 23:22:54 -0700149 bool saw_zip_fd = false;
Calin Juravle07c6d722017-06-07 17:06:12 +0000150 bool saw_compiler_filter = false;
Andreas Gampe046c7062015-05-18 23:22:54 -0700151 for (int i = 0; i < original_argc; ++i) {
Andreas Gampe9186ced2016-12-12 14:28:21 -0800152 if (android::base::StartsWith(original_argv[i], "--zip-fd=")) {
Andreas Gampe046c7062015-05-18 23:22:54 -0700153 saw_zip_fd = true;
Andreas Gampe046c7062015-05-18 23:22:54 -0700154 }
Calin Juravle07c6d722017-06-07 17:06:12 +0000155 if (android::base::StartsWith(original_argv[i], "--compiler-filter=")) {
156 saw_compiler_filter = true;
Calin Juravle07c6d722017-06-07 17:06:12 +0000157 }
Andreas Gampe046c7062015-05-18 23:22:54 -0700158 }
159
160 // Now filter out things.
161 for (int i = 0; i < original_argc; ++i) {
162 // All runtime-arg parameters are dropped.
163 if (strcmp(original_argv[i], "--runtime-arg") == 0) {
164 i++; // Drop the next part, too.
165 continue;
166 }
167
168 // Any instruction-setXXX is dropped.
Andreas Gampe9186ced2016-12-12 14:28:21 -0800169 if (android::base::StartsWith(original_argv[i], "--instruction-set")) {
Andreas Gampe046c7062015-05-18 23:22:54 -0700170 continue;
171 }
172
173 // The boot image is dropped.
Andreas Gampe9186ced2016-12-12 14:28:21 -0800174 if (android::base::StartsWith(original_argv[i], "--boot-image=")) {
Andreas Gampe046c7062015-05-18 23:22:54 -0700175 continue;
176 }
177
Mathieu Chartier97590cc2016-02-03 15:50:29 -0800178 // The image format is dropped.
Andreas Gampe9186ced2016-12-12 14:28:21 -0800179 if (android::base::StartsWith(original_argv[i], "--image-format=")) {
Mathieu Chartier97590cc2016-02-03 15:50:29 -0800180 continue;
181 }
182
Andreas Gampe046c7062015-05-18 23:22:54 -0700183 // This should leave any dex-file and oat-file options, describing what we compiled.
184
185 // However, we prefer to drop this when we saw --zip-fd.
186 if (saw_zip_fd) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700187 // Drop anything --zip-X, --dex-X, --oat-X, --swap-X, or --app-image-X
Andreas Gampe9186ced2016-12-12 14:28:21 -0800188 if (android::base::StartsWith(original_argv[i], "--zip-") ||
189 android::base::StartsWith(original_argv[i], "--dex-") ||
190 android::base::StartsWith(original_argv[i], "--oat-") ||
191 android::base::StartsWith(original_argv[i], "--swap-") ||
192 android::base::StartsWith(original_argv[i], "--app-image-")) {
Andreas Gampe046c7062015-05-18 23:22:54 -0700193 continue;
194 }
195 }
196
197 command.push_back(original_argv[i]);
198 }
199
Calin Juravle07c6d722017-06-07 17:06:12 +0000200 if (!saw_compiler_filter) {
201 command.push_back("--compiler-filter=" +
202 CompilerFilter::NameOfFilter(CompilerFilter::kDefaultCompilerFilter));
203 }
204
Andreas Gampe046c7062015-05-18 23:22:54 -0700205 // Construct the final output.
206 if (command.size() <= 1U) {
Martin Stjernholmad909af2019-07-16 17:02:44 +0100207 // It seems only "/apex/com.android.art/bin/dex2oat" is left, or not
Roland Levillain38a938e2018-09-21 10:55:51 +0100208 // even that. Use a pretty line.
Andreas Gampe046c7062015-05-18 23:22:54 -0700209 return "Starting dex2oat.";
210 }
Andreas Gampe9186ced2016-12-12 14:28:21 -0800211 return android::base::Join(command, ' ');
Andreas Gampe046c7062015-05-18 23:22:54 -0700212}
213
Brian Carlstrom7940e442013-07-12 13:46:57 -0700214static void UsageErrorV(const char* fmt, va_list ap) {
215 std::string error;
216 StringAppendV(&error, fmt, ap);
217 LOG(ERROR) << error;
218}
219
220static void UsageError(const char* fmt, ...) {
221 va_list ap;
222 va_start(ap, fmt);
223 UsageErrorV(fmt, ap);
224 va_end(ap);
225}
226
Andreas Gampe794ad762015-02-23 08:12:24 -0800227NO_RETURN static void Usage(const char* fmt, ...) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700228 va_list ap;
229 va_start(ap, fmt);
230 UsageErrorV(fmt, ap);
231 va_end(ap);
232
Brian Carlstrom6449c622014-02-10 23:48:36 -0800233 UsageError("Command: %s", CommandLine().c_str());
234
Brian Carlstrom7940e442013-07-12 13:46:57 -0700235 UsageError("Usage: dex2oat [options]...");
236 UsageError("");
Alex Light0d47a822020-08-25 09:16:34 -0700237
238 std::stringstream oss;
239 VariableIndentationOutputStream vios(&oss);
240 auto parser = CreateDex2oatArgumentParser();
241 parser.DumpHelp(vios);
242 UsageError(oss.str().c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700243 std::cerr << "See log for usage error information\n";
244 exit(EXIT_FAILURE);
245}
246
Orion Hodsonffc791c2019-11-14 19:19:28 +0000247
248// Set CPU affinity from a string containing a comma-separated list of numeric CPU identifiers.
249static void SetCpuAffinity(const std::vector<int32_t>& cpu_list) {
250#ifdef __linux__
251 int cpu_count = sysconf(_SC_NPROCESSORS_CONF);
252 cpu_set_t target_cpu_set;
253 CPU_ZERO(&target_cpu_set);
254
255 for (int32_t cpu : cpu_list) {
256 if (cpu >= 0 && cpu < cpu_count) {
257 CPU_SET(cpu, &target_cpu_set);
258 } else {
259 // Argument error is considered fatal, suggests misconfigured system properties.
260 Usage("Invalid cpu \"d\" specified in --cpu-set argument (nprocessors = %d)",
261 cpu, cpu_count);
262 }
263 }
264
265 if (sched_setaffinity(getpid(), sizeof(target_cpu_set), &target_cpu_set) == -1) {
266 // Failure to set affinity may be outside control of requestor, log warning rather than
267 // treating as fatal.
268 PLOG(WARNING) << "Failed to set CPU affinity.";
269 }
270#else
271 LOG(WARNING) << "--cpu-set not supported on this platform.";
272#endif // __linux__
273}
274
275
276
Brian Carlstrom7940e442013-07-12 13:46:57 -0700277// The primary goal of the watchdog is to prevent stuck build servers
278// during development when fatal aborts lead to a cascade of failures
279// that result in a deadlock.
280class WatchDog {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800281// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks
Brian Carlstrom7940e442013-07-12 13:46:57 -0700282#undef CHECK_PTHREAD_CALL
283#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
284 do { \
285 int rc = call args; \
286 if (rc != 0) { \
287 errno = rc; \
288 std::string message(# call); \
289 message += " failed for "; \
290 message += reason; \
291 Fatal(message); \
292 } \
293 } while (false)
294
295 public:
Andreas Gampe2e8a2562017-01-18 20:39:02 -0800296 explicit WatchDog(int64_t timeout_in_milliseconds)
Andreas Gampe0f54b0d2017-12-27 08:37:02 -0800297 : timeout_in_milliseconds_(timeout_in_milliseconds),
Andreas Gampe2e8a2562017-01-18 20:39:02 -0800298 shutting_down_(false) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700299 const char* reason = "dex2oat watch dog thread startup";
Kenny Root51316382014-05-13 14:59:37 -0700300 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
Mathieu Chartierdbf44402017-02-22 16:07:23 -0800301#ifndef __APPLE__
302 pthread_condattr_t condattr;
liulvping8f7101e2017-01-16 15:14:43 +0800303 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_condattr_init, (&condattr), reason);
304 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_condattr_setclock, (&condattr, CLOCK_MONOTONIC), reason);
305 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, &condattr), reason);
306 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_condattr_destroy, (&condattr), reason);
Mathieu Chartierdbf44402017-02-22 16:07:23 -0800307#endif
Brian Carlstrom7940e442013-07-12 13:46:57 -0700308 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
309 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
310 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
311 }
312 ~WatchDog() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700313 const char* reason = "dex2oat watch dog thread shutdown";
314 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
315 shutting_down_ = true;
316 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
317 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
318
Kenny Root51316382014-05-13 14:59:37 -0700319 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700320
321 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
322 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
323 }
324
Koji Fukuia72ca6c2019-03-25 17:39:07 +0900325 static void SetRuntime(Runtime* runtime) {
326 const char* reason = "dex2oat watch dog set runtime";
327 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&runtime_mutex_), reason);
328 runtime_ = runtime;
329 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&runtime_mutex_), reason);
330 }
331
Andreas Gampe2e8a2562017-01-18 20:39:02 -0800332 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
333 // large.
334 static constexpr int64_t kWatchdogVerifyMultiplier =
335 kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
336
337 // When setting timeouts, keep in mind that the build server may not be as fast as your
338 // desktop. Debug builds are slower so they have larger timeouts.
339 static constexpr int64_t kWatchdogSlowdownFactor = kIsDebugBuild ? 5U : 1U;
340
341 // 9.5 minutes scaled by kSlowdownFactor. This is slightly smaller than the Package Manager
342 // watchdog (PackageManagerService.WATCHDOG_TIMEOUT, 10 minutes), so that dex2oat will abort
343 // itself before that watchdog would take down the system server.
344 static constexpr int64_t kWatchDogTimeoutSeconds = kWatchdogSlowdownFactor * (9 * 60 + 30);
345
346 static constexpr int64_t kDefaultWatchdogTimeoutInMS =
347 kWatchdogVerifyMultiplier * kWatchDogTimeoutSeconds * 1000;
348
Brian Carlstrom7940e442013-07-12 13:46:57 -0700349 private:
350 static void* CallBack(void* arg) {
351 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
352 ::art::SetThreadName("dex2oat watch dog");
353 self->Wait();
Kenny Root51316382014-05-13 14:59:37 -0700354 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700355 }
356
Andreas Gampe794ad762015-02-23 08:12:24 -0800357 NO_RETURN static void Fatal(const std::string& message) {
Andreas Gamped687e372015-04-28 23:16:03 -0700358 // TODO: When we can guarantee it won't prevent shutdown in error cases, move to LOG. However,
359 // it's rather easy to hang in unwinding.
360 // LogLine also avoids ART logging lock issues, as it's really only a wrapper around
361 // logcat logging or stderr output.
Tomasz Wasilczyk8d840902017-12-20 08:19:53 -0800362 LogHelper::LogLineLowStack(__FILE__, __LINE__, LogSeverity::FATAL, message.c_str());
363
Andreas Gampe48fde372017-06-06 07:43:46 -0700364 // If we're on the host, try to dump all threads to get a sense of what's going on. This is
365 // restricted to the host as the dump may itself go bad.
366 // TODO: Use a double watchdog timeout, so we can enable this on-device.
Koji Fukuia72ca6c2019-03-25 17:39:07 +0900367 Runtime* runtime = GetRuntime();
368 if (!kIsTargetBuild && runtime != nullptr) {
369 runtime->AttachCurrentThread("Watchdog thread attached for dumping",
370 true,
371 nullptr,
372 false);
373 runtime->DumpForSigQuit(std::cerr);
Andreas Gampecd607312017-06-05 17:03:05 -0700374 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700375 exit(1);
376 }
377
378 void Wait() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700379 timespec timeout_ts;
Mathieu Chartierdbf44402017-02-22 16:07:23 -0800380#if defined(__APPLE__)
381 InitTimeSpec(true, CLOCK_REALTIME, timeout_in_milliseconds_, 0, &timeout_ts);
382#else
liulvping8f7101e2017-01-16 15:14:43 +0800383 InitTimeSpec(true, CLOCK_MONOTONIC, timeout_in_milliseconds_, 0, &timeout_ts);
Mathieu Chartierdbf44402017-02-22 16:07:23 -0800384#endif
Brian Carlstrom7940e442013-07-12 13:46:57 -0700385 const char* reason = "dex2oat watch dog thread waiting";
386 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
387 while (!shutting_down_) {
Josh Gao2d899c42018-10-17 16:03:42 -0700388 int rc = pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts);
389 if (rc == EINTR) {
390 continue;
391 } else if (rc == ETIMEDOUT) {
Andreas Gamped687e372015-04-28 23:16:03 -0700392 Fatal(StringPrintf("dex2oat did not finish after %" PRId64 " seconds",
Andreas Gampe2e8a2562017-01-18 20:39:02 -0800393 timeout_in_milliseconds_/1000));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700394 } else if (rc != 0) {
Roland Levillaind6f8c8b2018-12-18 15:27:28 +0000395 std::string message(StringPrintf("pthread_cond_timedwait failed: %s", strerror(rc)));
Greg Kaiserf276f952019-03-26 08:15:44 -0700396 Fatal(message);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700397 }
398 }
399 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
400 }
401
Koji Fukuia72ca6c2019-03-25 17:39:07 +0900402 static Runtime* GetRuntime() {
403 const char* reason = "dex2oat watch dog get runtime";
404 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&runtime_mutex_), reason);
405 Runtime* runtime = runtime_;
406 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&runtime_mutex_), reason);
407 return runtime;
408 }
409
410 static pthread_mutex_t runtime_mutex_;
411 static Runtime* runtime_;
412
Brian Carlstrom7940e442013-07-12 13:46:57 -0700413 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
414 pthread_mutex_t mutex_;
415 pthread_cond_t cond_;
416 pthread_attr_t attr_;
417 pthread_t pthread_;
Andreas Gampef45d61c2017-06-07 10:29:33 -0700418
419 const int64_t timeout_in_milliseconds_;
420 bool shutting_down_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700421};
Brian Carlstrom7940e442013-07-12 13:46:57 -0700422
Koji Fukuia72ca6c2019-03-25 17:39:07 +0900423pthread_mutex_t WatchDog::runtime_mutex_ = PTHREAD_MUTEX_INITIALIZER;
424Runtime* WatchDog::runtime_ = nullptr;
425
Vladimir Marko37d6d772020-03-05 17:13:28 +0000426// Helper class for overriding `java.lang.ThreadLocal.nextHashCode`.
427//
428// The class ThreadLocal has a static field nextHashCode used for assigning hash codes to
429// new ThreadLocal objects. Since the class and the object referenced by the field are
430// in the boot image, they cannot be modified under normal rules for AOT compilation.
431// However, since this is a private detail that's used only for assigning hash codes and
432// everything should work fine with different hash codes, we override the field for the
433// compilation, providing another object that the AOT class initialization can modify.
434class ThreadLocalHashOverride {
435 public:
436 ThreadLocalHashOverride(bool apply, int32_t initial_value) {
437 Thread* self = Thread::Current();
438 ScopedObjectAccess soa(self);
439 hs_.emplace(self); // While holding the mutator lock.
440 Runtime* runtime = Runtime::Current();
441 klass_ = hs_->NewHandle(apply
442 ? runtime->GetClassLinker()->LookupClass(self,
443 "Ljava/lang/ThreadLocal;",
444 /*class_loader=*/ nullptr)
445 : nullptr);
Vladimir Marko7bbbe252020-03-20 12:14:55 +0000446 field_ = ((klass_ != nullptr) && klass_->IsVisiblyInitialized())
Vladimir Marko37d6d772020-03-05 17:13:28 +0000447 ? klass_->FindDeclaredStaticField("nextHashCode",
448 "Ljava/util/concurrent/atomic/AtomicInteger;")
449 : nullptr;
450 old_field_value_ =
451 hs_->NewHandle(field_ != nullptr ? field_->GetObject(klass_.Get()) : nullptr);
452 if (old_field_value_ != nullptr) {
453 gc::AllocatorType allocator_type = runtime->GetHeap()->GetCurrentAllocator();
454 StackHandleScope<1u> hs2(self);
455 Handle<mirror::Object> new_field_value = hs2.NewHandle(
456 old_field_value_->GetClass()->Alloc(self, allocator_type));
457 PointerSize pointer_size = runtime->GetClassLinker()->GetImagePointerSize();
458 ArtMethod* constructor = old_field_value_->GetClass()->FindConstructor("(I)V", pointer_size);
459 CHECK(constructor != nullptr);
460 uint32_t args[] = {
461 reinterpret_cast32<uint32_t>(new_field_value.Get()),
462 static_cast<uint32_t>(initial_value)
463 };
464 JValue result;
465 constructor->Invoke(self, args, sizeof(args), &result, /*shorty=*/ "VI");
466 CHECK(!self->IsExceptionPending());
467 field_->SetObject</*kTransactionActive=*/ false>(klass_.Get(), new_field_value.Get());
468 }
469 if (apply && old_field_value_ == nullptr) {
Vladimir Marko7bbbe252020-03-20 12:14:55 +0000470 if ((klass_ != nullptr) && klass_->IsVisiblyInitialized()) {
471 // This would mean that the implementation of ThreadLocal has changed
472 // and the code above is no longer applicable.
473 LOG(ERROR) << "Failed to override ThreadLocal.nextHashCode";
474 } else {
475 VLOG(compiler) << "ThreadLocal is not initialized in the primary boot image.";
476 }
Vladimir Marko37d6d772020-03-05 17:13:28 +0000477 }
478 }
479
480 ~ThreadLocalHashOverride() {
481 ScopedObjectAccess soa(hs_->Self());
482 if (old_field_value_ != nullptr) {
483 // Allow the overriding object to be collected.
484 field_->SetObject</*kTransactionActive=*/ false>(klass_.Get(), old_field_value_.Get());
485 }
486 hs_.reset(); // While holding the mutator lock.
487 }
488
489 private:
490 std::optional<StackHandleScope<2u>> hs_;
491 Handle<mirror::Class> klass_;
492 ArtField* field_;
493 Handle<mirror::Object> old_field_value_;
494};
495
Eric Holk94a810b2020-05-06 14:33:16 -0700496class OatKeyValueStore : public SafeMap<std::string, std::string> {
497 public:
498 using SafeMap::Put;
499
500 iterator Put(const std::string& k, bool v) {
501 return SafeMap::Put(k, v ? OatHeader::kTrueValue : OatHeader::kFalseValue);
502 }
503};
504
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100505class Dex2Oat final {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800506 public:
507 explicit Dex2Oat(TimingLogger* timings) :
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100508 compiler_kind_(Compiler::kOptimizing),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800509 // Take the default set of instruction features from the build.
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000510 key_value_store_(nullptr),
Andreas Gampe3f30e122015-09-17 14:03:21 -0700511 verification_results_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800512 runtime_(nullptr),
513 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
514 start_ns_(NanoTime()),
Andreas Gampec560fc02014-07-16 09:57:39 -0700515 start_cputime_ns_(ProcessCpuNanoTime()),
Vladimir Marko2afaff72018-11-30 17:01:50 +0000516 strip_(false),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800517 oat_fd_(-1),
Nicolas Geoffraya6a448a2016-11-10 10:49:40 +0000518 input_vdex_fd_(-1),
519 output_vdex_fd_(-1),
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000520 input_vdex_file_(nullptr),
Nicolas Geoffraybaeaa9b2018-01-26 14:31:17 +0000521 dm_fd_(-1),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800522 zip_fd_(-1),
Vladimir Markod0036ac2019-11-21 11:47:12 +0000523 image_fd_(-1),
524 have_multi_image_arg_(false),
525 multi_image_(false),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800526 image_base_(0U),
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800527 image_storage_mode_(ImageHeader::kStorageModeUncompressed),
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700528 passes_to_run_filename_(nullptr),
Mathieu Chartierff0baff2017-08-02 23:04:19 -0700529 dirty_image_objects_filename_(nullptr),
Vladimir Markod1f73512020-04-02 10:50:35 +0100530 updatable_bcp_packages_filename_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800531 is_host_(false),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000532 elf_writers_(),
533 oat_writers_(),
534 rodata_(),
Vladimir Marko10c13562015-11-25 14:33:36 +0000535 image_writer_(nullptr),
Andreas Gampe3f30e122015-09-17 14:03:21 -0700536 driver_(nullptr),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000537 opened_dex_files_maps_(),
538 opened_dex_files_(),
Mathieu Chartierd1ab1bd2017-08-04 10:21:50 -0700539 avoid_storing_invocation_(false),
Orion Hodson365f94f2021-01-13 16:27:57 +0000540 swap_fd_(File::kInvalidFd),
541 app_image_fd_(File::kInvalidFd),
542 profile_file_fd_(File::kInvalidFd),
Andreas Gampeace0dc12016-01-20 13:33:13 -0800543 timings_(timings),
David Sehrfe57c2b2020-03-27 14:58:54 +0000544 force_determinism_(false),
545 check_linkage_conditions_(false),
Eric Holkbc89ed42020-04-29 19:59:24 +0000546 crash_on_linkage_violation_(false),
Calin Juravle32de2a52021-05-26 15:37:00 -0700547 compile_individually_(false),
548 profile_load_attempted_(false)
Calin Juravle2e2db782016-02-23 12:00:03 +0000549 {}
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800550
551 ~Dex2Oat() {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800552 // Log completion time before deleting the runtime_, because this accesses
553 // the runtime.
554 LogCompletionTime();
555
Roland Levillain05e34f42018-05-24 13:19:05 +0000556 if (!kIsDebugBuild && !(kRunningOnMemoryTool && kMemoryToolDetectsLeaks)) {
Vladimir Marko307dac92015-10-20 11:20:09 +0100557 // We want to just exit on non-debug builds, not bringing the runtime down
558 // in an orderly fashion. So release the following fields.
Andreas Gampeafaf7f82018-10-16 11:32:38 -0700559 driver_.release(); // NOLINT
560 image_writer_.release(); // NOLINT
Vladimir Marko307dac92015-10-20 11:20:09 +0100561 for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files_) {
Andreas Gampeafaf7f82018-10-16 11:32:38 -0700562 dex_file.release(); // NOLINT
Vladimir Marko307dac92015-10-20 11:20:09 +0100563 }
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100564 new std::vector<MemMap>(std::move(opened_dex_files_maps_)); // Leak MemMaps.
David Brazdil7b49e6c2016-09-01 11:06:18 +0100565 for (std::unique_ptr<File>& vdex_file : vdex_files_) {
Andreas Gampeafaf7f82018-10-16 11:32:38 -0700566 vdex_file.release(); // NOLINT
David Brazdil7b49e6c2016-09-01 11:06:18 +0100567 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800568 for (std::unique_ptr<File>& oat_file : oat_files_) {
Andreas Gampeafaf7f82018-10-16 11:32:38 -0700569 oat_file.release(); // NOLINT
Jeff Haodcdc85b2015-12-04 14:06:18 -0800570 }
Andreas Gampeafaf7f82018-10-16 11:32:38 -0700571 runtime_.release(); // NOLINT
572 verification_results_.release(); // NOLINT
573 key_value_store_.release(); // NOLINT
Vladimir Markof94b7812014-06-05 15:48:04 +0100574 }
Alex Light4531afd2021-03-30 17:13:30 -0700575
576 // Remind the user if they passed testing only flags.
577 if (!kIsTargetBuild && force_allow_oj_inlines_) {
578 LOG(ERROR) << "Inlines allowed from core-oj! FOR TESTING USE ONLY! DO NOT DISTRIBUTE"
579 << " BINARIES BUILT WITH THIS OPTION!";
580 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700581 }
582
Roland Levillain9ec5e222015-08-17 20:18:41 +0100583 struct ParserOptions {
Vladimir Markod011d812018-11-29 12:35:24 +0000584 std::vector<std::string> oat_symbols;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800585 std::string boot_image_filename;
Andreas Gampe2e8a2562017-01-18 20:39:02 -0800586 int64_t watch_dog_timeout_in_ms = -1;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800587 bool watch_dog_enabled = true;
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000588 bool requested_specific_compiler = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800589 std::string error_msg;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100590 };
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800591
Andreas Gampe097f34c2017-08-23 08:57:51 -0700592 void ParseBase(const std::string& option) {
Roland Levillain9ec5e222015-08-17 20:18:41 +0100593 char* end;
Andreas Gampe097f34c2017-08-23 08:57:51 -0700594 image_base_ = strtoul(option.c_str(), &end, 16);
595 if (end == option.c_str() || *end != '\0') {
Roland Levillain9ec5e222015-08-17 20:18:41 +0100596 Usage("Failed to parse hexadecimal value for option %s", option.data());
597 }
598 }
599
Shubham Ajmera188b2bf2017-09-20 15:53:35 -0700600 bool VerifyProfileData() {
Vladimir Marko213ee2d2018-06-22 11:56:34 +0100601 return profile_compilation_info_->VerifyProfileData(compiler_options_->dex_files_for_oat_file_);
Shubham Ajmera188b2bf2017-09-20 15:53:35 -0700602 }
603
Andreas Gampe097f34c2017-08-23 08:57:51 -0700604 void ParseInstructionSetVariant(const std::string& option, ParserOptions* parser_options) {
Vladimir Markoa0431112018-06-25 09:32:54 +0100605 compiler_options_->instruction_set_features_ = InstructionSetFeatures::FromVariant(
606 compiler_options_->instruction_set_, option, &parser_options->error_msg);
607 if (compiler_options_->instruction_set_features_ == nullptr) {
Roland Levillain9ec5e222015-08-17 20:18:41 +0100608 Usage("%s", parser_options->error_msg.c_str());
609 }
610 }
611
Andreas Gampe097f34c2017-08-23 08:57:51 -0700612 void ParseInstructionSetFeatures(const std::string& option, ParserOptions* parser_options) {
Vladimir Markoa0431112018-06-25 09:32:54 +0100613 if (compiler_options_->instruction_set_features_ == nullptr) {
614 compiler_options_->instruction_set_features_ = InstructionSetFeatures::FromVariant(
615 compiler_options_->instruction_set_, "default", &parser_options->error_msg);
616 if (compiler_options_->instruction_set_features_ == nullptr) {
Roland Levillain9ec5e222015-08-17 20:18:41 +0100617 Usage("Problem initializing default instruction set features variant: %s",
618 parser_options->error_msg.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700619 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800620 }
Vladimir Markoa0431112018-06-25 09:32:54 +0100621 compiler_options_->instruction_set_features_ =
622 compiler_options_->instruction_set_features_->AddFeaturesFromString(
623 option, &parser_options->error_msg);
624 if (compiler_options_->instruction_set_features_ == nullptr) {
Andreas Gampe097f34c2017-08-23 08:57:51 -0700625 Usage("Error parsing '%s': %s", option.c_str(), parser_options->error_msg.c_str());
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800626 }
627 }
628
Jeff Hao436183f2016-01-12 16:36:50 -0800629 void ProcessOptions(ParserOptions* parser_options) {
Vladimir Marko695348f2020-05-19 14:42:02 +0100630 compiler_options_->compiler_type_ = CompilerOptions::CompilerType::kAotCompiler;
Vladimir Markoa2da9b92018-10-10 14:21:55 +0100631 compiler_options_->compile_pic_ = true; // All AOT compilation is PIC.
Vladimir Marko21910692019-11-06 13:27:03 +0000632
633 if (android_root_.empty()) {
634 const char* android_root_env_var = getenv("ANDROID_ROOT");
635 if (android_root_env_var == nullptr) {
636 Usage("--android-root unspecified and ANDROID_ROOT not set");
637 }
638 android_root_ += android_root_env_var;
639 }
640
641 if (!parser_options->boot_image_filename.empty()) {
642 boot_image_filename_ = parser_options->boot_image_filename;
643 }
644
Vladimir Marko9c4b9702018-11-14 15:09:02 +0000645 DCHECK(compiler_options_->image_type_ == CompilerOptions::ImageType::kNone);
Vladimir Markod0036ac2019-11-21 11:47:12 +0000646 if (!image_filenames_.empty() || image_fd_ != -1) {
Ulya Trafimovichc124d1d2020-01-27 14:50:38 +0000647 // If no boot image is provided, then dex2oat is compiling the primary boot image,
Nicolas Geoffray4cbb51a2020-02-07 11:25:54 +0000648 // otherwise it is compiling the boot image extension.
Ulya Trafimovichc124d1d2020-01-27 14:50:38 +0000649 compiler_options_->image_type_ = boot_image_filename_.empty()
650 ? CompilerOptions::ImageType::kBootImage
Nicolas Geoffray4cbb51a2020-02-07 11:25:54 +0000651 : CompilerOptions::ImageType::kBootImageExtension;
Vladimir Marko9c4b9702018-11-14 15:09:02 +0000652 }
653 if (app_image_fd_ != -1 || !app_image_file_name_.empty()) {
Vladimir Marko21910692019-11-06 13:27:03 +0000654 if (compiler_options_->IsBootImage() || compiler_options_->IsBootImageExtension()) {
Vladimir Markod0036ac2019-11-21 11:47:12 +0000655 Usage("Can't have both (--image or --image-fd) and (--app-image-fd or --app-image-file)");
Vladimir Marko9c4b9702018-11-14 15:09:02 +0000656 }
657 compiler_options_->image_type_ = CompilerOptions::ImageType::kAppImage;
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700658 }
659
Vladimir Markod0036ac2019-11-21 11:47:12 +0000660 if (!image_filenames_.empty() && image_fd_ != -1) {
661 Usage("Can't have both --image and --image-fd");
662 }
663
Jeff Haodcdc85b2015-12-04 14:06:18 -0800664 if (oat_filenames_.empty() && oat_fd_ == -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800665 Usage("Output must be supplied with either --oat-file or --oat-fd");
666 }
667
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000668 if (input_vdex_fd_ != -1 && !input_vdex_.empty()) {
669 Usage("Can't have both --input-vdex-fd and --input-vdex");
670 }
671
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +0100672 if (output_vdex_fd_ != -1 && !output_vdex_.empty()) {
673 Usage("Can't have both --output-vdex-fd and --output-vdex");
674 }
675
Jeff Haodcdc85b2015-12-04 14:06:18 -0800676 if (!oat_filenames_.empty() && oat_fd_ != -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800677 Usage("--oat-file should not be used with --oat-fd");
678 }
679
Nicolas Geoffraya6a448a2016-11-10 10:49:40 +0000680 if ((output_vdex_fd_ == -1) != (oat_fd_ == -1)) {
Sascha Roth5f71c652018-04-10 00:27:15 +0200681 Usage("VDEX and OAT output must be specified either with one --oat-file "
Nicolas Geoffraya6a448a2016-11-10 10:49:40 +0000682 "or with --oat-fd and --output-vdex-fd file descriptors");
David Brazdil7b49e6c2016-09-01 11:06:18 +0100683 }
684
Vladimir Markod0036ac2019-11-21 11:47:12 +0000685 if ((image_fd_ != -1) && (oat_fd_ == -1)) {
686 Usage("--image-fd must be used with --oat_fd and --output_vdex_fd");
687 }
688
Roland Levillain9ec5e222015-08-17 20:18:41 +0100689 if (!parser_options->oat_symbols.empty() && oat_fd_ != -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800690 Usage("--oat-symbols should not be used with --oat-fd");
691 }
692
Roland Levillain9ec5e222015-08-17 20:18:41 +0100693 if (!parser_options->oat_symbols.empty() && is_host_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800694 Usage("--oat-symbols should not be used with --host");
695 }
696
Nicolas Geoffraya6a448a2016-11-10 10:49:40 +0000697 if (output_vdex_fd_ != -1 && !image_filenames_.empty()) {
698 Usage("--output-vdex-fd should not be used with --image");
David Brazdil7b49e6c2016-09-01 11:06:18 +0100699 }
700
Jeff Haodcdc85b2015-12-04 14:06:18 -0800701 if (oat_fd_ != -1 && !image_filenames_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800702 Usage("--oat-fd should not be used with --image");
703 }
704
Nicolas Geoffraybaeaa9b2018-01-26 14:31:17 +0000705 if ((input_vdex_fd_ != -1 || !input_vdex_.empty()) &&
706 (dm_fd_ != -1 || !dm_file_location_.empty())) {
707 Usage("An input vdex should not be passed with a .dm file");
708 }
709
Jeff Haodcdc85b2015-12-04 14:06:18 -0800710 if (!parser_options->oat_symbols.empty() &&
711 parser_options->oat_symbols.size() != oat_filenames_.size()) {
712 Usage("--oat-file arguments do not match --oat-symbols arguments");
713 }
714
715 if (!image_filenames_.empty() && image_filenames_.size() != oat_filenames_.size()) {
716 Usage("--oat-file arguments do not match --image arguments");
717 }
718
Vladimir Marko21910692019-11-06 13:27:03 +0000719 if (!IsBootImage() && boot_image_filename_.empty()) {
720 DCHECK(!IsBootImageExtension());
Orion Hodson50f32512021-06-30 21:17:53 +0100721 boot_image_filename_ =
722 GetDefaultBootImageLocation(android_root_, /*deny_art_apex_data_files=*/false);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800723 }
724
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800725 if (dex_filenames_.empty() && zip_fd_ == -1) {
726 Usage("Input must be supplied with either --dex-file or --zip-fd");
727 }
728
729 if (!dex_filenames_.empty() && zip_fd_ != -1) {
730 Usage("--dex-file should not be used with --zip-fd");
731 }
732
733 if (!dex_filenames_.empty() && !zip_location_.empty()) {
734 Usage("--dex-file should not be used with --zip-location");
735 }
736
737 if (dex_locations_.empty()) {
Vladimir Markod011d812018-11-29 12:35:24 +0000738 dex_locations_ = dex_filenames_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800739 } else if (dex_locations_.size() != dex_filenames_.size()) {
740 Usage("--dex-location arguments do not match --dex-file arguments");
741 }
742
Jeff Haodcdc85b2015-12-04 14:06:18 -0800743 if (!dex_filenames_.empty() && !oat_filenames_.empty()) {
744 if (oat_filenames_.size() != 1 && oat_filenames_.size() != dex_filenames_.size()) {
745 Usage("--oat-file arguments must be singular or match --dex-file arguments");
746 }
747 }
748
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800749 if (zip_fd_ != -1 && zip_location_.empty()) {
750 Usage("--zip-location should be supplied with --zip-fd");
751 }
752
Vladimir Marko49b0f452015-12-10 13:49:19 +0000753 if (boot_image_filename_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800754 if (image_base_ == 0) {
Vladimir Marko66235942019-06-03 16:05:17 +0100755 Usage("Non-zero --base not specified for boot image");
756 }
757 } else {
758 if (image_base_ != 0) {
759 Usage("Non-zero --base specified for app image or boot image extension");
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800760 }
761 }
762
Vladimir Markod0036ac2019-11-21 11:47:12 +0000763 if (have_multi_image_arg_) {
764 if (!IsImage()) {
765 Usage("--multi-image or --single-image specified for non-image compilation");
766 }
767 } else {
768 // Use the default, i.e. multi-image for boot image and boot image extension.
769 multi_image_ = IsBootImage() || IsBootImageExtension(); // Shall pass checks below.
770 }
771 if (IsBootImage() && !multi_image_) {
772 Usage("--single-image specified for primary boot image");
773 }
774 if (IsAppImage() && multi_image_) {
775 Usage("--multi-image specified for app image");
776 }
777
778 if (image_fd_ != -1 && multi_image_) {
779 Usage("--single-image not specified for --image-fd");
780 }
781
Mathieu Chartiera8077802016-03-16 19:08:31 -0700782 const bool have_profile_file = !profile_file_.empty();
Orion Hodson365f94f2021-01-13 16:27:57 +0000783 const bool have_profile_fd = profile_file_fd_ != File::kInvalidFd;
Mathieu Chartiera8077802016-03-16 19:08:31 -0700784 if (have_profile_file && have_profile_fd) {
Calin Juravle2e2db782016-02-23 12:00:03 +0000785 Usage("Profile file should not be specified with both --profile-file-fd and --profile-file");
Calin Juravle998c2162015-12-21 15:39:33 +0200786 }
787
Roland Levillain9ec5e222015-08-17 20:18:41 +0100788 if (!parser_options->oat_symbols.empty()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800789 oat_unstripped_ = std::move(parser_options->oat_symbols);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800790 }
791
xueliang.zhong7f88c1a2018-11-06 11:42:41 +0000792 if (compiler_options_->instruction_set_features_ == nullptr) {
793 // '--instruction-set-features/--instruction-set-variant' were not used.
794 // Use features for the 'default' variant.
Vladimir Markoa0431112018-06-25 09:32:54 +0100795 compiler_options_->instruction_set_features_ = InstructionSetFeatures::FromVariant(
796 compiler_options_->instruction_set_, "default", &parser_options->error_msg);
797 if (compiler_options_->instruction_set_features_ == nullptr) {
Ian Rogersd582fa42014-11-05 23:46:43 -0800798 Usage("Problem initializing default instruction set features variant: %s",
Roland Levillain9ec5e222015-08-17 20:18:41 +0100799 parser_options->error_msg.c_str());
Ian Rogersd582fa42014-11-05 23:46:43 -0800800 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800801 }
802
Vladimir Markoa0431112018-06-25 09:32:54 +0100803 if (compiler_options_->instruction_set_ == kRuntimeISA) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800804 std::unique_ptr<const InstructionSetFeatures> runtime_features(
805 InstructionSetFeatures::FromCppDefines());
Vladimir Markoa0431112018-06-25 09:32:54 +0100806 if (!compiler_options_->GetInstructionSetFeatures()->Equals(runtime_features.get())) {
xueliang.zhong7f88c1a2018-11-06 11:42:41 +0000807 LOG(WARNING) << "Mismatch between dex2oat instruction set features to use ("
Vladimir Markoa0431112018-06-25 09:32:54 +0100808 << *compiler_options_->GetInstructionSetFeatures()
xueliang.zhong7f88c1a2018-11-06 11:42:41 +0000809 << ") and those from CPP defines (" << *runtime_features
Vladimir Markoa0431112018-06-25 09:32:54 +0100810 << ") for the command line:\n" << CommandLine();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800811 }
812 }
813
Vladimir Markod1f73512020-04-02 10:50:35 +0100814 if ((IsBootImage() || IsBootImageExtension()) && updatable_bcp_packages_filename_ != nullptr) {
815 Usage("Do not specify --updatable-bcp-packages-file for boot image compilation.");
816 }
817
Orion Hodsonffc791c2019-11-14 19:19:28 +0000818 if (!cpu_set_.empty()) {
819 SetCpuAffinity(cpu_set_);
820 }
821
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000822 if (compiler_options_->inline_max_code_units_ == CompilerOptions::kUnsetInlineMaxCodeUnits) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000823 compiler_options_->inline_max_code_units_ = CompilerOptions::kDefaultInlineMaxCodeUnits;
Roland Levillaina215b952015-08-07 11:38:32 +0100824 }
825
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800826 // Checks are all explicit until we know the architecture.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800827 // Set the compilation target's implicit checks options.
Vladimir Markoa0431112018-06-25 09:32:54 +0100828 switch (compiler_options_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +0000829 case InstructionSet::kArm:
830 case InstructionSet::kThumb2:
831 case InstructionSet::kArm64:
832 case InstructionSet::kX86:
833 case InstructionSet::kX86_64:
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000834 compiler_options_->implicit_null_checks_ = true;
835 compiler_options_->implicit_so_checks_ = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800836 break;
837
838 default:
839 // Defaults are correct.
840 break;
841 }
842
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800843 // Done with usage checks, enable watchdog if requested
Roland Levillain9ec5e222015-08-17 20:18:41 +0100844 if (parser_options->watch_dog_enabled) {
Andreas Gampe2e8a2562017-01-18 20:39:02 -0800845 int64_t timeout = parser_options->watch_dog_timeout_in_ms > 0
846 ? parser_options->watch_dog_timeout_in_ms
847 : WatchDog::kDefaultWatchdogTimeoutInMS;
848 watchdog_.reset(new WatchDog(timeout));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800849 }
850
851 // Fill some values into the key-value store for the oat header.
Eric Holk94a810b2020-05-06 14:33:16 -0700852 key_value_store_.reset(new OatKeyValueStore());
Andreas Gampeace0dc12016-01-20 13:33:13 -0800853
Vladimir Marko21910692019-11-06 13:27:03 +0000854 // Automatically force determinism for the boot image and boot image extensions in a host build.
855 if (!kIsTargetBuild && (IsBootImage() || IsBootImageExtension())) {
Vladimir Marko78342412019-07-25 17:28:02 +0100856 force_determinism_ = true;
Andreas Gampeace0dc12016-01-20 13:33:13 -0800857 }
858 compiler_options_->force_determinism_ = force_determinism_;
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700859
David Sehrfe57c2b2020-03-27 14:58:54 +0000860 compiler_options_->check_linkage_conditions_ = check_linkage_conditions_;
861 compiler_options_->crash_on_linkage_violation_ = crash_on_linkage_violation_;
862
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700863 if (passes_to_run_filename_ != nullptr) {
Vladimir Marko54159c62018-06-20 14:30:08 +0100864 passes_to_run_ = ReadCommentedInputFromFile<std::vector<std::string>>(
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700865 passes_to_run_filename_,
Vladimir Marko54159c62018-06-20 14:30:08 +0100866 nullptr); // No post-processing.
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700867 if (passes_to_run_.get() == nullptr) {
868 Usage("Failed to read list of passes to run.");
869 }
870 }
Vladimir Markof6afcc92020-02-05 10:10:03 +0000871
Nicolas Geoffray2c2248c2020-03-06 14:50:45 +0000872 // Trim the boot image location to not include any specified profile. Note
873 // that the logic below will include the first boot image extension, but not
874 // the ones that could be listed after the profile of that extension. This
875 // works for our current top use case:
876 // boot.art:/system/framework/boot-framework.art
877 // But this would need to be adjusted if we had to support different use
878 // cases.
Vladimir Markof6afcc92020-02-05 10:10:03 +0000879 size_t profile_separator_pos = boot_image_filename_.find(ImageSpace::kProfileSeparator);
880 if (profile_separator_pos != std::string::npos) {
881 DCHECK(!IsBootImage()); // For primary boot image the boot_image_filename_ is empty.
882 if (IsBootImageExtension()) {
883 Usage("Unsupported profile specification in boot image location (%s) for extension.",
884 boot_image_filename_.c_str());
885 }
Nicolas Geoffray2c2248c2020-03-06 14:50:45 +0000886 VLOG(compiler)
887 << "Truncating boot image location " << boot_image_filename_
888 << " because it contains profile specification. Truncated: "
889 << boot_image_filename_.substr(/*pos*/ 0u, /*length*/ profile_separator_pos);
890 boot_image_filename_.resize(profile_separator_pos);
Vladimir Markof6afcc92020-02-05 10:10:03 +0000891 }
892
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700893 compiler_options_->passes_to_run_ = passes_to_run_.get();
Roland Levillain9ec5e222015-08-17 20:18:41 +0100894 }
895
Jeff Hao436183f2016-01-12 16:36:50 -0800896 void ExpandOatAndImageFilenames() {
Vladimir Markod0036ac2019-11-21 11:47:12 +0000897 ArrayRef<const std::string> locations(dex_locations_);
898 if (!multi_image_) {
899 locations = locations.SubArray(/*pos=*/ 0u, /*length=*/ 1u);
Jeff Hao436183f2016-01-12 16:36:50 -0800900 }
Vladimir Markod0036ac2019-11-21 11:47:12 +0000901 if (image_fd_ == -1) {
902 if (image_filenames_[0].rfind('/') == std::string::npos) {
903 Usage("Unusable boot image filename %s", image_filenames_[0].c_str());
904 }
905 image_filenames_ = ImageSpace::ExpandMultiImageLocations(
906 locations, image_filenames_[0], IsBootImageExtension());
Jeff Hao436183f2016-01-12 16:36:50 -0800907
Vladimir Markod0036ac2019-11-21 11:47:12 +0000908 if (oat_filenames_[0].rfind('/') == std::string::npos) {
909 Usage("Unusable boot image oat filename %s", oat_filenames_[0].c_str());
910 }
911 oat_filenames_ = ImageSpace::ExpandMultiImageLocations(
912 locations, oat_filenames_[0], IsBootImageExtension());
913 } else {
914 DCHECK(!multi_image_);
915 std::vector<std::string> oat_locations = ImageSpace::ExpandMultiImageLocations(
916 locations, oat_location_, IsBootImageExtension());
917 DCHECK_EQ(1u, oat_locations.size());
918 oat_location_ = oat_locations[0];
Vladimir Markodb4b1de2018-12-07 17:18:07 +0000919 }
Vladimir Markodb4b1de2018-12-07 17:18:07 +0000920
bowen_lai8bd36c02016-10-12 13:28:55 +0800921 if (!oat_unstripped_.empty()) {
Vladimir Marko91f10322018-12-07 18:04:10 +0000922 if (oat_unstripped_[0].rfind('/') == std::string::npos) {
923 Usage("Unusable boot image symbol filename %s", oat_unstripped_[0].c_str());
bowen_lai8bd36c02016-10-12 13:28:55 +0800924 }
Vladimir Marko21910692019-11-06 13:27:03 +0000925 oat_unstripped_ = ImageSpace::ExpandMultiImageLocations(
Vladimir Markod0036ac2019-11-21 11:47:12 +0000926 locations, oat_unstripped_[0], IsBootImageExtension());
bowen_lai8bd36c02016-10-12 13:28:55 +0800927 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800928 }
929
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000930 void InsertCompileOptions(int argc, char** argv) {
Mathieu Chartierd1ab1bd2017-08-04 10:21:50 -0700931 if (!avoid_storing_invocation_) {
Vladimir Marko56581d82018-11-07 12:30:52 +0000932 std::ostringstream oss;
Mathieu Chartierd1ab1bd2017-08-04 10:21:50 -0700933 for (int i = 0; i < argc; ++i) {
934 if (i > 0) {
935 oss << ' ';
936 }
937 oss << argv[i];
Roland Levillain9ec5e222015-08-17 20:18:41 +0100938 }
Mathieu Chartierd1ab1bd2017-08-04 10:21:50 -0700939 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
Roland Levillain9ec5e222015-08-17 20:18:41 +0100940 }
Eric Holk94a810b2020-05-06 14:33:16 -0700941 key_value_store_->Put(OatHeader::kDebuggableKey, compiler_options_->debuggable_);
942 key_value_store_->Put(OatHeader::kNativeDebuggableKey,
943 compiler_options_->GetNativeDebuggable());
Andreas Gampe29d38e72016-03-23 15:31:51 +0000944 key_value_store_->Put(OatHeader::kCompilerFilter,
Eric Holk94a810b2020-05-06 14:33:16 -0700945 CompilerFilter::NameOfFilter(compiler_options_->GetCompilerFilter()));
946 key_value_store_->Put(OatHeader::kConcurrentCopying, kUseReadBarrier);
Eric Holkbc89ed42020-04-29 19:59:24 +0000947 key_value_store_->Put(OatHeader::kRequiresImage, compiler_options_->IsGeneratingImage());
Alex Light62afcf52018-12-18 14:19:25 -0800948 if (invocation_file_.get() != -1) {
949 std::ostringstream oss;
950 for (int i = 0; i < argc; ++i) {
951 if (i > 0) {
952 oss << std::endl;
953 }
954 oss << argv[i];
955 }
956 std::string invocation(oss.str());
957 if (TEMP_FAILURE_RETRY(write(invocation_file_.get(),
958 invocation.c_str(),
959 invocation.size())) == -1) {
960 Usage("Unable to write invocation file");
961 }
962 }
Roland Levillain9ec5e222015-08-17 20:18:41 +0100963 }
964
Andreas Gampe097f34c2017-08-23 08:57:51 -0700965 // This simple forward is here so the string specializations below don't look out of place.
966 template <typename T, typename U>
967 void AssignIfExists(Dex2oatArgumentMap& map,
968 const Dex2oatArgumentMap::Key<T>& key,
969 U* out) {
970 map.AssignIfExists(key, out);
971 }
972
973 // Specializations to handle const char* vs std::string.
974 void AssignIfExists(Dex2oatArgumentMap& map,
975 const Dex2oatArgumentMap::Key<std::string>& key,
976 const char** out) {
977 if (map.Exists(key)) {
978 char_backing_storage_.push_front(std::move(*map.Get(key)));
979 *out = char_backing_storage_.front().c_str();
980 }
981 }
982 void AssignIfExists(Dex2oatArgumentMap& map,
983 const Dex2oatArgumentMap::Key<std::vector<std::string>>& key,
984 std::vector<const char*>* out) {
985 if (map.Exists(key)) {
986 for (auto& val : *map.Get(key)) {
987 char_backing_storage_.push_front(std::move(val));
988 out->push_back(char_backing_storage_.front().c_str());
989 }
990 }
991 }
992
993 template <typename T>
994 void AssignTrueIfExists(Dex2oatArgumentMap& map,
995 const Dex2oatArgumentMap::Key<T>& key,
996 bool* out) {
997 if (map.Exists(key)) {
998 *out = true;
999 }
1000 }
1001
Vladimir Markod0036ac2019-11-21 11:47:12 +00001002 void AssignIfExists(Dex2oatArgumentMap& map,
1003 const Dex2oatArgumentMap::Key<std::string>& key,
1004 std::vector<std::string>* out) {
1005 DCHECK(out->empty());
1006 if (map.Exists(key)) {
1007 out->push_back(*map.Get(key));
1008 }
1009 }
1010
Roland Levillain9ec5e222015-08-17 20:18:41 +01001011 // Parse the arguments from the command line. In case of an unrecognized option or impossible
1012 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
1013 // returns, arguments have been successfully parsed.
1014 void ParseArgs(int argc, char** argv) {
1015 original_argc = argc;
1016 original_argv = argv;
1017
David Sehrc431b9d2018-03-02 12:01:51 -08001018 Locks::Init();
Andreas Gampe51d80cc2017-06-21 21:05:13 -07001019 InitLogging(argv, Runtime::Abort);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001020
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001021 compiler_options_.reset(new CompilerOptions());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001022
Andreas Gampe097f34c2017-08-23 08:57:51 -07001023 using M = Dex2oatArgumentMap;
1024 std::string error_msg;
1025 std::unique_ptr<M> args_uptr = M::Parse(argc, const_cast<const char**>(argv), &error_msg);
1026 if (args_uptr == nullptr) {
1027 Usage("Failed to parse command line: %s", error_msg.c_str());
1028 UNREACHABLE();
1029 }
1030
1031 M& args = *args_uptr;
1032
1033 std::unique_ptr<ParserOptions> parser_options(new ParserOptions());
1034
Mathieu Chartiereafe2a52017-10-19 15:29:42 -07001035 AssignIfExists(args, M::CompactDexLevel, &compact_dex_level_);
Andreas Gampe097f34c2017-08-23 08:57:51 -07001036 AssignIfExists(args, M::DexFiles, &dex_filenames_);
1037 AssignIfExists(args, M::DexLocations, &dex_locations_);
Vladimir Markod0036ac2019-11-21 11:47:12 +00001038 AssignIfExists(args, M::OatFile, &oat_filenames_);
Andreas Gampe097f34c2017-08-23 08:57:51 -07001039 AssignIfExists(args, M::OatSymbols, &parser_options->oat_symbols);
David Srbeckyde91fd42018-07-05 22:27:08 +01001040 AssignTrueIfExists(args, M::Strip, &strip_);
Vladimir Markod0036ac2019-11-21 11:47:12 +00001041 AssignIfExists(args, M::ImageFilename, &image_filenames_);
1042 AssignIfExists(args, M::ImageFd, &image_fd_);
Andreas Gampe097f34c2017-08-23 08:57:51 -07001043 AssignIfExists(args, M::ZipFd, &zip_fd_);
1044 AssignIfExists(args, M::ZipLocation, &zip_location_);
1045 AssignIfExists(args, M::InputVdexFd, &input_vdex_fd_);
1046 AssignIfExists(args, M::OutputVdexFd, &output_vdex_fd_);
1047 AssignIfExists(args, M::InputVdex, &input_vdex_);
1048 AssignIfExists(args, M::OutputVdex, &output_vdex_);
Nicolas Geoffraybaeaa9b2018-01-26 14:31:17 +00001049 AssignIfExists(args, M::DmFd, &dm_fd_);
1050 AssignIfExists(args, M::DmFile, &dm_file_location_);
Andreas Gampe097f34c2017-08-23 08:57:51 -07001051 AssignIfExists(args, M::OatFd, &oat_fd_);
1052 AssignIfExists(args, M::OatLocation, &oat_location_);
1053 AssignIfExists(args, M::Watchdog, &parser_options->watch_dog_enabled);
1054 AssignIfExists(args, M::WatchdogTimeout, &parser_options->watch_dog_timeout_in_ms);
1055 AssignIfExists(args, M::Threads, &thread_count_);
Orion Hodsonffc791c2019-11-14 19:19:28 +00001056 AssignIfExists(args, M::CpuSet, &cpu_set_);
Andreas Gampe097f34c2017-08-23 08:57:51 -07001057 AssignIfExists(args, M::Passes, &passes_to_run_filename_);
1058 AssignIfExists(args, M::BootImage, &parser_options->boot_image_filename);
1059 AssignIfExists(args, M::AndroidRoot, &android_root_);
1060 AssignIfExists(args, M::Profile, &profile_file_);
1061 AssignIfExists(args, M::ProfileFd, &profile_file_fd_);
1062 AssignIfExists(args, M::RuntimeOptions, &runtime_args_);
1063 AssignIfExists(args, M::SwapFile, &swap_file_name_);
1064 AssignIfExists(args, M::SwapFileFd, &swap_fd_);
1065 AssignIfExists(args, M::SwapDexSizeThreshold, &min_dex_file_cumulative_size_for_swap_);
1066 AssignIfExists(args, M::SwapDexCountThreshold, &min_dex_files_for_swap_);
1067 AssignIfExists(args, M::VeryLargeAppThreshold, &very_large_threshold_);
1068 AssignIfExists(args, M::AppImageFile, &app_image_file_name_);
1069 AssignIfExists(args, M::AppImageFileFd, &app_image_fd_);
1070 AssignIfExists(args, M::NoInlineFrom, &no_inline_from_string_);
1071 AssignIfExists(args, M::ClasspathDir, &classpath_dir_);
1072 AssignIfExists(args, M::DirtyImageObjects, &dirty_image_objects_filename_);
Vladimir Markod1f73512020-04-02 10:50:35 +01001073 AssignIfExists(args, M::UpdatableBcpPackagesFile, &updatable_bcp_packages_filename_);
Andreas Gampe097f34c2017-08-23 08:57:51 -07001074 AssignIfExists(args, M::ImageFormat, &image_storage_mode_);
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001075 AssignIfExists(args, M::CompilationReason, &compilation_reason_);
David Sehrfe57c2b2020-03-27 14:58:54 +00001076 AssignTrueIfExists(args, M::CheckLinkageConditions, &check_linkage_conditions_);
1077 AssignTrueIfExists(args, M::CrashOnLinkageViolation, &crash_on_linkage_violation_);
Alex Light4531afd2021-03-30 17:13:30 -07001078 AssignTrueIfExists(args, M::ForceAllowOjInlines, &force_allow_oj_inlines_);
Calin Juravle33787682019-07-26 14:27:18 -07001079 AssignIfExists(args, M::PublicSdk, &public_sdk_);
Nicolas Geoffrayd3c45c22021-04-27 13:21:28 +01001080 AssignIfExists(args, M::ApexVersions, &apex_versions_argument_);
Andreas Gampe097f34c2017-08-23 08:57:51 -07001081
1082 AssignIfExists(args, M::Backend, &compiler_kind_);
1083 parser_options->requested_specific_compiler = args.Exists(M::Backend);
1084
Vladimir Markoa0431112018-06-25 09:32:54 +01001085 AssignIfExists(args, M::TargetInstructionSet, &compiler_options_->instruction_set_);
Andreas Gampe097f34c2017-08-23 08:57:51 -07001086 // arm actually means thumb2.
Vladimir Markoa0431112018-06-25 09:32:54 +01001087 if (compiler_options_->instruction_set_ == InstructionSet::kArm) {
1088 compiler_options_->instruction_set_ = InstructionSet::kThumb2;
Andreas Gampe097f34c2017-08-23 08:57:51 -07001089 }
1090
1091 AssignTrueIfExists(args, M::Host, &is_host_);
Andreas Gampe097f34c2017-08-23 08:57:51 -07001092 AssignTrueIfExists(args, M::AvoidStoringInvocation, &avoid_storing_invocation_);
Alex Light62afcf52018-12-18 14:19:25 -08001093 if (args.Exists(M::InvocationFile)) {
1094 invocation_file_.reset(open(args.Get(M::InvocationFile)->c_str(),
1095 O_CREAT|O_WRONLY|O_TRUNC|O_CLOEXEC,
1096 S_IRUSR|S_IWUSR));
1097 if (invocation_file_.get() == -1) {
1098 int err = errno;
1099 Usage("Unable to open invocation file '%s' for writing due to %s.",
1100 args.Get(M::InvocationFile)->c_str(), strerror(err));
1101 }
1102 }
Mathieu Chartier792111c2018-02-15 13:02:15 -08001103 AssignIfExists(args, M::CopyDexFiles, &copy_dex_files_);
Andreas Gampe097f34c2017-08-23 08:57:51 -07001104
Vladimir Markod0036ac2019-11-21 11:47:12 +00001105 AssignTrueIfExists(args, M::MultiImage, &have_multi_image_arg_);
1106 AssignIfExists(args, M::MultiImage, &multi_image_);
1107
Andreas Gampe097f34c2017-08-23 08:57:51 -07001108 if (args.Exists(M::ForceDeterminism)) {
Andreas Gampe097f34c2017-08-23 08:57:51 -07001109 force_determinism_ = true;
1110 }
Eric Holkbc89ed42020-04-29 19:59:24 +00001111 AssignTrueIfExists(args, M::CompileIndividually, &compile_individually_);
Andreas Gampe097f34c2017-08-23 08:57:51 -07001112
1113 if (args.Exists(M::Base)) {
1114 ParseBase(*args.Get(M::Base));
1115 }
1116 if (args.Exists(M::TargetInstructionSetVariant)) {
1117 ParseInstructionSetVariant(*args.Get(M::TargetInstructionSetVariant), parser_options.get());
1118 }
1119 if (args.Exists(M::TargetInstructionSetFeatures)) {
1120 ParseInstructionSetFeatures(*args.Get(M::TargetInstructionSetFeatures), parser_options.get());
1121 }
1122 if (args.Exists(M::ClassLoaderContext)) {
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07001123 std::string class_loader_context_arg = *args.Get(M::ClassLoaderContext);
1124 class_loader_context_ = ClassLoaderContext::Create(class_loader_context_arg);
Andreas Gampe097f34c2017-08-23 08:57:51 -07001125 if (class_loader_context_ == nullptr) {
1126 Usage("Option --class-loader-context has an incorrect format: %s",
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07001127 class_loader_context_arg.c_str());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001128 }
David Brazdil89821862019-03-19 13:57:43 +00001129 if (args.Exists(M::ClassLoaderContextFds)) {
1130 std::string str_fds_arg = *args.Get(M::ClassLoaderContextFds);
1131 std::vector<std::string> str_fds = android::base::Split(str_fds_arg, ":");
1132 for (const std::string& str_fd : str_fds) {
1133 class_loader_context_fds_.push_back(std::stoi(str_fd, nullptr, 0));
1134 if (class_loader_context_fds_.back() < 0) {
1135 Usage("Option --class-loader-context-fds has incorrect format: %s",
1136 str_fds_arg.c_str());
1137 }
1138 }
1139 }
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07001140 if (args.Exists(M::StoredClassLoaderContext)) {
Mathieu Chartierc4440772018-04-16 14:40:56 -07001141 const std::string stored_context_arg = *args.Get(M::StoredClassLoaderContext);
1142 stored_class_loader_context_ = ClassLoaderContext::Create(stored_context_arg);
1143 if (stored_class_loader_context_ == nullptr) {
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07001144 Usage("Option --stored-class-loader-context has an incorrect format: %s",
Mathieu Chartierc4440772018-04-16 14:40:56 -07001145 stored_context_arg.c_str());
Vladimir Markod8860b42018-05-02 14:58:12 +01001146 } else if (class_loader_context_->VerifyClassLoaderContextMatch(
Mathieu Chartierc4440772018-04-16 14:40:56 -07001147 stored_context_arg,
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07001148 /*verify_names*/ false,
Vladimir Markod8860b42018-05-02 14:58:12 +01001149 /*verify_checksums*/ false) != ClassLoaderContext::VerificationResult::kVerifies) {
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07001150 Usage(
1151 "Option --stored-class-loader-context '%s' mismatches --class-loader-context '%s'",
Mathieu Chartierc4440772018-04-16 14:40:56 -07001152 stored_context_arg.c_str(),
1153 class_loader_context_arg.c_str());
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07001154 }
1155 }
1156 } else if (args.Exists(M::StoredClassLoaderContext)) {
1157 Usage("Option --stored-class-loader-context should only be used if "
1158 "--class-loader-context is also specified");
Roland Levillain9ec5e222015-08-17 20:18:41 +01001159 }
1160
Vladimir Marko89b85eb2020-02-04 15:51:44 +00001161 // If we have a profile, change the default compiler filter to speed-profile
1162 // before reading compiler options.
1163 static_assert(CompilerFilter::kDefaultCompilerFilter == CompilerFilter::kSpeed);
1164 DCHECK_EQ(compiler_options_->GetCompilerFilter(), CompilerFilter::kSpeed);
Calin Juravle32de2a52021-05-26 15:37:00 -07001165 if (HasProfileInput()) {
Vladimir Marko89b85eb2020-02-04 15:51:44 +00001166 compiler_options_->SetCompilerFilter(CompilerFilter::kSpeedProfile);
1167 }
1168
Andreas Gampe097f34c2017-08-23 08:57:51 -07001169 if (!ReadCompilerOptions(args, compiler_options_.get(), &error_msg)) {
1170 Usage(error_msg.c_str());
1171 }
1172
Jeff Hao436183f2016-01-12 16:36:50 -08001173 ProcessOptions(parser_options.get());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001174 }
1175
Jeff Haodcdc85b2015-12-04 14:06:18 -08001176 // Check whether the oat output files are writable, and open them for later. Also open a swap
1177 // file, if a name is given.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001178 bool OpenFile() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001179 // Prune non-existent dex files now so that we don't create empty oat files for multi-image.
1180 PruneNonExistentDexFiles();
1181
Vladimir Markod0036ac2019-11-21 11:47:12 +00001182 // Expand oat and image filenames for boot image and boot image extension.
1183 // This is mostly for multi-image but single-image also needs some processing.
1184 if (IsBootImage() || IsBootImageExtension()) {
Jeff Hao436183f2016-01-12 16:36:50 -08001185 ExpandOatAndImageFilenames();
1186 }
1187
David Brazdil7b49e6c2016-09-01 11:06:18 +01001188 // OAT and VDEX file handling
David Brazdil7b49e6c2016-09-01 11:06:18 +01001189 if (oat_fd_ == -1) {
1190 DCHECK(!oat_filenames_.empty());
Vladimir Markod011d812018-11-29 12:35:24 +00001191 for (const std::string& oat_filename : oat_filenames_) {
1192 std::unique_ptr<File> oat_file(OS::CreateEmptyFile(oat_filename.c_str()));
Calin Juravleb09be722017-09-25 16:42:48 -07001193 if (oat_file == nullptr) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001194 PLOG(ERROR) << "Failed to create oat file: " << oat_filename;
1195 return false;
1196 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01001197 if (fchmod(oat_file->Fd(), 0644) != 0) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001198 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_filename;
1199 oat_file->Erase();
1200 return false;
1201 }
1202 oat_files_.push_back(std::move(oat_file));
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00001203 DCHECK_EQ(input_vdex_fd_, -1);
1204 if (!input_vdex_.empty()) {
1205 std::string error_msg;
Richard Uhlerb8ab63a2017-01-31 11:27:37 +00001206 input_vdex_file_ = VdexFile::Open(input_vdex_,
1207 /* writable */ false,
1208 /* low_4gb */ false,
Nicolas Geoffray1cfea7a2017-05-24 14:44:38 +01001209 DoEagerUnquickeningOfVdex(),
Richard Uhlerb8ab63a2017-01-31 11:27:37 +00001210 &error_msg);
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00001211 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01001212
Nicolas Geoffraya6a448a2016-11-10 10:49:40 +00001213 DCHECK_EQ(output_vdex_fd_, -1);
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +01001214 std::string vdex_filename = output_vdex_.empty()
1215 ? ReplaceFileExtension(oat_filename, "vdex")
1216 : output_vdex_;
1217 if (vdex_filename == input_vdex_ && output_vdex_.empty()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00001218 update_input_vdex_ = true;
1219 std::unique_ptr<File> vdex_file(OS::OpenFileReadWrite(vdex_filename.c_str()));
1220 vdex_files_.push_back(std::move(vdex_file));
1221 } else {
1222 std::unique_ptr<File> vdex_file(OS::CreateEmptyFile(vdex_filename.c_str()));
Calin Juravleb09be722017-09-25 16:42:48 -07001223 if (vdex_file == nullptr) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00001224 PLOG(ERROR) << "Failed to open vdex file: " << vdex_filename;
1225 return false;
1226 }
1227 if (fchmod(vdex_file->Fd(), 0644) != 0) {
1228 PLOG(ERROR) << "Failed to make vdex file world readable: " << vdex_filename;
1229 vdex_file->Erase();
1230 return false;
1231 }
1232 vdex_files_.push_back(std::move(vdex_file));
David Brazdil7b49e6c2016-09-01 11:06:18 +01001233 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001234 }
1235 } else {
Josh Gaoafeec9f2018-08-30 14:05:56 -07001236 std::unique_ptr<File> oat_file(
1237 new File(DupCloexec(oat_fd_), oat_location_, /* check_usage */ true));
1238 if (!oat_file->IsOpened()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001239 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
1240 return false;
1241 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01001242 if (oat_file->SetLength(0) != 0) {
1243 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
Calin Juravleb09be722017-09-25 16:42:48 -07001244 oat_file->Erase();
1245 return false;
David Brazdil7b49e6c2016-09-01 11:06:18 +01001246 }
1247 oat_files_.push_back(std::move(oat_file));
1248
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00001249 if (input_vdex_fd_ != -1) {
1250 struct stat s;
1251 int rc = TEMP_FAILURE_RETRY(fstat(input_vdex_fd_, &s));
1252 if (rc == -1) {
1253 PLOG(WARNING) << "Failed getting length of vdex file";
1254 } else {
1255 std::string error_msg;
Richard Uhlerb8ab63a2017-01-31 11:27:37 +00001256 input_vdex_file_ = VdexFile::Open(input_vdex_fd_,
1257 s.st_size,
1258 "vdex",
1259 /* writable */ false,
1260 /* low_4gb */ false,
Nicolas Geoffray1cfea7a2017-05-24 14:44:38 +01001261 DoEagerUnquickeningOfVdex(),
Richard Uhlerb8ab63a2017-01-31 11:27:37 +00001262 &error_msg);
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00001263 // If there's any problem with the passed vdex, just warn and proceed
1264 // without it.
1265 if (input_vdex_file_ == nullptr) {
Richard Uhlerb8ab63a2017-01-31 11:27:37 +00001266 PLOG(WARNING) << "Failed opening vdex file: " << error_msg;
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00001267 }
1268 }
1269 }
1270
Nicolas Geoffraya6a448a2016-11-10 10:49:40 +00001271 DCHECK_NE(output_vdex_fd_, -1);
David Brazdil7b49e6c2016-09-01 11:06:18 +01001272 std::string vdex_location = ReplaceFileExtension(oat_location_, "vdex");
Josh Gaoafeec9f2018-08-30 14:05:56 -07001273 std::unique_ptr<File> vdex_file(new File(
1274 DupCloexec(output_vdex_fd_), vdex_location, /* check_usage */ true));
1275 if (!vdex_file->IsOpened()) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001276 PLOG(ERROR) << "Failed to create vdex file: " << vdex_location;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001277 return false;
1278 }
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00001279 if (input_vdex_file_ != nullptr && output_vdex_fd_ == input_vdex_fd_) {
1280 update_input_vdex_ = true;
1281 } else {
1282 if (vdex_file->SetLength(0) != 0) {
1283 PLOG(ERROR) << "Truncating vdex file " << vdex_location << " failed.";
Calin Juravleb09be722017-09-25 16:42:48 -07001284 vdex_file->Erase();
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00001285 return false;
1286 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01001287 }
1288 vdex_files_.push_back(std::move(vdex_file));
1289
Vladimir Markod011d812018-11-29 12:35:24 +00001290 oat_filenames_.push_back(oat_location_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001291 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001292
Nicolas Geoffray36930ec2017-05-09 13:23:34 +01001293 // If we're updating in place a vdex file, be defensive and put an invalid vdex magic in case
1294 // dex2oat gets killed.
1295 // Note: we're only invalidating the magic data in the file, as dex2oat needs the rest of
1296 // the information to remain valid.
1297 if (update_input_vdex_) {
Vladimir Markobb3560d2020-04-30 11:14:11 +01001298 File* vdex_file = vdex_files_.back().get();
Nicolas Geoffraya129d8a2021-03-18 22:23:04 +00001299 if (!vdex_file->PwriteFully(&VdexFile::VdexFileHeader::kVdexInvalidMagic,
1300 arraysize(VdexFile::VdexFileHeader::kVdexInvalidMagic),
Vladimir Markobb3560d2020-04-30 11:14:11 +01001301 /*offset=*/ 0u)) {
1302 PLOG(ERROR) << "Failed to invalidate vdex header. File: " << vdex_file->GetPath();
Nicolas Geoffray36930ec2017-05-09 13:23:34 +01001303 return false;
1304 }
1305
Vladimir Markobb3560d2020-04-30 11:14:11 +01001306 if (vdex_file->Flush() != 0) {
Nicolas Geoffray36930ec2017-05-09 13:23:34 +01001307 PLOG(ERROR) << "Failed to flush stream after invalidating header of vdex file."
Vladimir Markobb3560d2020-04-30 11:14:11 +01001308 << " File: " << vdex_file->GetPath();
Nicolas Geoffray36930ec2017-05-09 13:23:34 +01001309 return false;
1310 }
1311 }
1312
Nicolas Geoffraybaeaa9b2018-01-26 14:31:17 +00001313 if (dm_fd_ != -1 || !dm_file_location_.empty()) {
1314 std::string error_msg;
1315 if (dm_fd_ != -1) {
1316 dm_file_.reset(ZipArchive::OpenFromFd(dm_fd_, "DexMetadata", &error_msg));
1317 } else {
1318 dm_file_.reset(ZipArchive::Open(dm_file_location_.c_str(), &error_msg));
1319 }
1320 if (dm_file_ == nullptr) {
1321 LOG(WARNING) << "Could not open DexMetadata archive " << error_msg;
1322 }
1323 }
1324
1325 if (dm_file_ != nullptr) {
1326 DCHECK(input_vdex_file_ == nullptr);
1327 std::string error_msg;
1328 static const char* kDexMetadata = "DexMetadata";
1329 std::unique_ptr<ZipEntry> zip_entry(dm_file_->Find(VdexFile::kVdexNameInDmFile, &error_msg));
1330 if (zip_entry == nullptr) {
1331 LOG(INFO) << "No " << VdexFile::kVdexNameInDmFile << " file in DexMetadata archive. "
1332 << "Not doing fast verification.";
1333 } else {
Vladimir Markoc34bebf2018-08-16 16:12:49 +01001334 MemMap input_file = zip_entry->MapDirectlyOrExtract(
Mathieu Chartier792111c2018-02-15 13:02:15 -08001335 VdexFile::kVdexNameInDmFile,
1336 kDexMetadata,
Colin Cross2b41cca2018-11-16 22:43:41 -08001337 &error_msg,
1338 alignof(VdexFile));
Vladimir Markoc34bebf2018-08-16 16:12:49 +01001339 if (!input_file.IsValid()) {
Nicolas Geoffraybaeaa9b2018-01-26 14:31:17 +00001340 LOG(WARNING) << "Could not open vdex file in DexMetadata archive: " << error_msg;
1341 } else {
Vladimir Markoc34bebf2018-08-16 16:12:49 +01001342 input_vdex_file_ = std::make_unique<VdexFile>(std::move(input_file));
Calin Juravle32bf6d32021-02-02 19:29:29 -08001343 if (!input_vdex_file_->IsValid()) {
1344 // Ideally we would do this validation at the framework level but the framework
1345 // has not knowledge of the .vdex format and adding new APIs just for it is
1346 // overkill.
1347 // TODO(calin): include this in dex2oat metrics.
1348 LOG(WARNING) << "The dex metadata .vdex is not valid. Ignoring it.";
1349 input_vdex_file_ = nullptr;
1350 } else {
1351 if (input_vdex_file_->HasDexSection()) {
1352 LOG(ERROR) << "The dex metadata is not allowed to contain dex files";
Calin Juravlebdd9d712021-04-05 17:59:10 -07001353 android_errorWriteLog(0x534e4554, "178055795"); // Report to SafetyNet.
Calin Juravle32bf6d32021-02-02 19:29:29 -08001354 return false;
1355 }
1356 VLOG(verifier) << "Doing fast verification with vdex from DexMetadata archive";
Calin Juravle046cecf2020-12-07 18:31:28 -08001357 }
Nicolas Geoffraybaeaa9b2018-01-26 14:31:17 +00001358 }
1359 }
1360 }
1361
David Brazdil7b49e6c2016-09-01 11:06:18 +01001362 // Swap file handling
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001363 //
1364 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file
1365 // that we can use for swap.
1366 //
1367 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We
1368 // will immediately unlink to satisfy the swap fd assumption.
1369 if (swap_fd_ == -1 && !swap_file_name_.empty()) {
1370 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str()));
1371 if (swap_file.get() == nullptr) {
1372 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_;
1373 return false;
1374 }
Josh Gaoafeec9f2018-08-30 14:05:56 -07001375 swap_fd_ = swap_file->Release();
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001376 unlink(swap_file_name_.c_str());
1377 }
Jeff Hao436183f2016-01-12 16:36:50 -08001378
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001379 return true;
1380 }
1381
David Brazdil7b49e6c2016-09-01 11:06:18 +01001382 void EraseOutputFiles() {
1383 for (auto& files : { &vdex_files_, &oat_files_ }) {
1384 for (size_t i = 0; i < files->size(); ++i) {
1385 if ((*files)[i].get() != nullptr) {
1386 (*files)[i]->Erase();
1387 (*files)[i].reset();
1388 }
1389 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001390 }
Andreas Gampea650e702014-12-03 14:28:02 -08001391 }
1392
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08001393 void LoadClassProfileDescriptors() {
Mathieu Chartierf85b3db2018-04-02 18:16:21 -07001394 if (!IsImage()) {
1395 return;
1396 }
Calin Juravle32de2a52021-05-26 15:37:00 -07001397 if (DoProfileGuidedOptimizations()) {
Vladimir Markodc4bcce2018-06-21 16:15:42 +01001398 // TODO: The following comment looks outdated or misplaced.
Mathieu Chartier0b490842016-05-25 15:05:59 -07001399 // Filter out class path classes since we don't want to include these in the image.
Vladimir Marko213ee2d2018-06-22 11:56:34 +01001400 HashSet<std::string> image_classes = profile_compilation_info_->GetClassDescriptors(
1401 compiler_options_->dex_files_for_oat_file_);
Vladimir Markodc4bcce2018-06-21 16:15:42 +01001402 VLOG(compiler) << "Loaded " << image_classes.size()
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08001403 << " image class descriptors from profile";
1404 if (VLOG_IS_ON(compiler)) {
Vladimir Markodc4bcce2018-06-21 16:15:42 +01001405 for (const std::string& s : image_classes) {
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08001406 LOG(INFO) << "Image class " << s;
1407 }
1408 }
Vladimir Markodc4bcce2018-06-21 16:15:42 +01001409 compiler_options_->image_classes_.swap(image_classes);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08001410 }
1411 }
1412
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001413 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
1414 // boot class path.
Andreas Gampef7882972017-03-20 16:35:24 -07001415 dex2oat::ReturnCode Setup() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001416 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001417
Mathieu Chartierf68b6982019-06-27 09:40:20 -07001418 if (!PrepareDirtyObjects()) {
Andreas Gampef7882972017-03-20 16:35:24 -07001419 return dex2oat::ReturnCode::kOther;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001420 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001421
Vladimir Marko21910692019-11-06 13:27:03 +00001422 // Verification results are null since we don't know if we will need them yet as the compiler
Mathieu Chartiere01b6f62017-07-19 16:55:04 -07001423 // filter may change.
Andreas Gampe4585f872015-03-27 23:45:15 -07001424 callbacks_.reset(new QuickCompilerCallbacks(
Vladimir Marko21910692019-11-06 13:27:03 +00001425 // For class verification purposes, boot image extension is the same as boot image.
1426 (IsBootImage() || IsBootImageExtension())
1427 ? CompilerCallbacks::CallbackMode::kCompileBootImage
1428 : CompilerCallbacks::CallbackMode::kCompileApp));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001429
Vladimir Marko49b0f452015-12-10 13:49:19 +00001430 RuntimeArgumentMap runtime_options;
Mathieu Chartier46331a62017-07-21 09:49:10 -07001431 if (!PrepareRuntimeOptions(&runtime_options, callbacks_.get())) {
Andreas Gampef7882972017-03-20 16:35:24 -07001432 return dex2oat::ReturnCode::kOther;
Andreas Gampe1d00add2015-02-27 19:35:46 -08001433 }
1434
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001435 CreateOatWriters();
1436 if (!AddDexFileSources()) {
Andreas Gampef7882972017-03-20 16:35:24 -07001437 return dex2oat::ReturnCode::kOther;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001438 }
1439
Vladimir Marko0866ea42019-10-15 12:04:17 +00001440 {
1441 TimingLogger::ScopedTiming t_dex("Writing and opening dex files", timings_);
1442 for (size_t i = 0, size = oat_writers_.size(); i != size; ++i) {
1443 // Unzip or copy dex files straight to the oat file.
1444 std::vector<MemMap> opened_dex_files_map;
1445 std::vector<std::unique_ptr<const DexFile>> opened_dex_files;
1446 // No need to verify the dex file when we have a vdex file, which means it was already
1447 // verified.
Vladimir Markoef46e102020-02-20 13:44:11 +00001448 const bool verify =
1449 (input_vdex_file_ == nullptr) && !compiler_options_->AssumeDexFilesAreVerified();
Vladimir Marko0866ea42019-10-15 12:04:17 +00001450 if (!oat_writers_[i]->WriteAndOpenDexFiles(
1451 vdex_files_[i].get(),
1452 verify,
1453 update_input_vdex_,
1454 copy_dex_files_,
1455 &opened_dex_files_map,
1456 &opened_dex_files)) {
1457 return dex2oat::ReturnCode::kOther;
1458 }
1459 dex_files_per_oat_file_.push_back(MakeNonOwningPointerVector(opened_dex_files));
1460 if (opened_dex_files_map.empty()) {
1461 DCHECK(opened_dex_files.empty());
1462 } else {
1463 for (MemMap& map : opened_dex_files_map) {
1464 opened_dex_files_maps_.push_back(std::move(map));
1465 }
1466 for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files) {
Vladimir Marko26de8962020-12-22 14:36:47 +00001467 dex_file_oat_index_map_.insert(std::make_pair(dex_file.get(), i));
Vladimir Marko0866ea42019-10-15 12:04:17 +00001468 opened_dex_files_.push_back(std::move(dex_file));
1469 }
1470 }
1471 }
1472 }
1473
1474 compiler_options_->dex_files_for_oat_file_ = MakeNonOwningPointerVector(opened_dex_files_);
1475 const std::vector<const DexFile*>& dex_files = compiler_options_->dex_files_for_oat_file_;
1476
Calin Juravle92a78572021-04-05 17:43:17 -07001477 if (!ValidateInputVdexChecksums()) {
1478 return dex2oat::ReturnCode::kOther;
1479 }
1480
Vladimir Marko0866ea42019-10-15 12:04:17 +00001481 // Check if we need to downgrade the compiler-filter for size reasons.
1482 // Note: This does not affect the compiler filter already stored in the key-value
1483 // store which is used for determining whether the oat file is up to date,
1484 // together with the boot class path locations and checksums stored below.
1485 CompilerFilter::Filter original_compiler_filter = compiler_options_->GetCompilerFilter();
Vladimir Marko21910692019-11-06 13:27:03 +00001486 if (!IsBootImage() && !IsBootImageExtension() && IsVeryLarge(dex_files)) {
Vladimir Marko0866ea42019-10-15 12:04:17 +00001487 // Disable app image to make sure dex2oat unloading is enabled.
1488 compiler_options_->image_type_ = CompilerOptions::ImageType::kNone;
1489
1490 // If we need to downgrade the compiler-filter for size reasons, do that early before we read
1491 // it below for creating verification callbacks.
1492 if (!CompilerFilter::IsAsGoodAs(kLargeAppFilter, compiler_options_->GetCompilerFilter())) {
1493 LOG(INFO) << "Very large app, downgrading to verify.";
1494 compiler_options_->SetCompilerFilter(kLargeAppFilter);
1495 }
1496 }
1497
Nicolas Geoffray6cf7a9b2020-02-27 21:51:29 +00001498 if (CompilerFilter::IsAnyCompilationEnabled(compiler_options_->GetCompilerFilter()) ||
1499 IsImage()) {
1500 // Only modes with compilation or image generation require verification results.
1501 // Do this here instead of when we
Vladimir Marko0866ea42019-10-15 12:04:17 +00001502 // create the compilation callbacks since the compilation mode may have been changed by the
1503 // very large app logic.
1504 // Avoiding setting the verification results saves RAM by not adding the dex files later in
1505 // the function.
1506 // Note: When compiling boot image, this must be done before creating the Runtime.
1507 verification_results_.reset(new VerificationResults(compiler_options_.get()));
1508 callbacks_->SetVerificationResults(verification_results_.get());
1509 }
1510
Vladimir Marko21910692019-11-06 13:27:03 +00001511 if (IsBootImage() || IsBootImageExtension()) {
1512 // For boot image or boot image extension, pass opened dex files to the Runtime::Create().
Vladimir Marko0866ea42019-10-15 12:04:17 +00001513 // Note: Runtime acquires ownership of these dex files.
1514 runtime_options.Set(RuntimeArgumentMap::BootClassPathDexList, &opened_dex_files_);
1515 }
1516 if (!CreateRuntime(std::move(runtime_options))) {
1517 return dex2oat::ReturnCode::kCreateRuntime;
1518 }
Vladimir Marko21910692019-11-06 13:27:03 +00001519 ArrayRef<const DexFile* const> bcp_dex_files(runtime_->GetClassLinker()->GetBootClassPath());
1520 if (IsBootImage() || IsBootImageExtension()) {
1521 // Check boot class path dex files and, if compiling an extension, the images it depends on.
1522 if ((IsBootImage() && bcp_dex_files.size() != dex_files.size()) ||
1523 (IsBootImageExtension() && bcp_dex_files.size() <= dex_files.size())) {
1524 LOG(ERROR) << "Unexpected number of boot class path dex files for boot image or extension, "
1525 << bcp_dex_files.size() << (IsBootImage() ? " != " : " <= ") << dex_files.size();
1526 return dex2oat::ReturnCode::kOther;
1527 }
1528 if (!std::equal(dex_files.begin(), dex_files.end(), bcp_dex_files.end() - dex_files.size())) {
1529 LOG(ERROR) << "Boot class path dex files do not end with the compiled dex files.";
1530 return dex2oat::ReturnCode::kOther;
1531 }
1532 size_t bcp_df_pos = 0u;
1533 size_t bcp_df_end = bcp_dex_files.size();
1534 for (const std::string& bcp_location : runtime_->GetBootClassPathLocations()) {
1535 if (bcp_df_pos == bcp_df_end || bcp_dex_files[bcp_df_pos]->GetLocation() != bcp_location) {
1536 LOG(ERROR) << "Missing dex file for boot class component " << bcp_location;
1537 return dex2oat::ReturnCode::kOther;
1538 }
1539 CHECK(!DexFileLoader::IsMultiDexLocation(bcp_dex_files[bcp_df_pos]->GetLocation().c_str()));
1540 ++bcp_df_pos;
1541 while (bcp_df_pos != bcp_df_end &&
1542 DexFileLoader::IsMultiDexLocation(bcp_dex_files[bcp_df_pos]->GetLocation().c_str())) {
1543 ++bcp_df_pos;
1544 }
1545 }
1546 if (bcp_df_pos != bcp_df_end) {
1547 LOG(ERROR) << "Unexpected dex file in boot class path "
1548 << bcp_dex_files[bcp_df_pos]->GetLocation();
1549 return dex2oat::ReturnCode::kOther;
1550 }
1551 auto lacks_image = [](const DexFile* df) {
1552 if (kIsDebugBuild && df->GetOatDexFile() != nullptr) {
1553 const OatFile* oat_file = df->GetOatDexFile()->GetOatFile();
1554 CHECK(oat_file != nullptr);
1555 const auto& image_spaces = Runtime::Current()->GetHeap()->GetBootImageSpaces();
1556 CHECK(std::any_of(image_spaces.begin(),
1557 image_spaces.end(),
1558 [=](const ImageSpace* space) {
1559 return oat_file == space->GetOatFile();
1560 }));
1561 }
1562 return df->GetOatDexFile() == nullptr;
1563 };
1564 if (std::any_of(bcp_dex_files.begin(), bcp_dex_files.end() - dex_files.size(), lacks_image)) {
1565 LOG(ERROR) << "Missing required boot image(s) for boot image extension.";
1566 return dex2oat::ReturnCode::kOther;
1567 }
Vladimir Marko32388f42021-05-21 16:36:23 +01001568 } else {
1569 // Check that we loaded at least the primary boot image for app compilation.
1570 if (runtime_->GetHeap()->GetBootImageSpaces().empty()) {
1571 LOG(ERROR) << "Missing primary boot image for app compilation.";
1572 return dex2oat::ReturnCode::kOther;
1573 }
Vladimir Marko21910692019-11-06 13:27:03 +00001574 }
Vladimir Marko0866ea42019-10-15 12:04:17 +00001575
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001576 if (!compilation_reason_.empty()) {
1577 key_value_store_->Put(OatHeader::kCompilationReasonKey, compilation_reason_);
1578 }
1579
Vladimir Markoc10a0c62018-11-16 11:39:22 +00001580 if (IsBootImage()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001581 // If we're compiling the boot image, store the boot classpath into the Key-Value store.
Vladimir Marko91f10322018-12-07 18:04:10 +00001582 // We use this when loading the boot image.
1583 key_value_store_->Put(OatHeader::kBootClassPathKey, android::base::Join(dex_locations_, ':'));
Vladimir Marko21910692019-11-06 13:27:03 +00001584 } else if (IsBootImageExtension()) {
1585 // Validate the boot class path and record the dependency on the loaded boot images.
1586 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1587 Runtime* runtime = Runtime::Current();
1588 std::string full_bcp = android::base::Join(runtime->GetBootClassPathLocations(), ':');
1589 std::string extension_part = ":" + android::base::Join(dex_locations_, ':');
1590 if (!android::base::EndsWith(full_bcp, extension_part)) {
1591 LOG(ERROR) << "Full boot class path does not end with extension parts, full: " << full_bcp
1592 << ", extension: " << extension_part.substr(1u);
1593 return dex2oat::ReturnCode::kOther;
1594 }
1595 std::string bcp_dependency = full_bcp.substr(0u, full_bcp.size() - extension_part.size());
1596 key_value_store_->Put(OatHeader::kBootClassPathKey, bcp_dependency);
1597 ArrayRef<const DexFile* const> bcp_dex_files_dependency =
1598 bcp_dex_files.SubArray(/*pos=*/ 0u, bcp_dex_files.size() - dex_files.size());
1599 ArrayRef<ImageSpace* const> image_spaces(runtime->GetHeap()->GetBootImageSpaces());
1600 key_value_store_->Put(
1601 OatHeader::kBootClassPathChecksumsKey,
1602 gc::space::ImageSpace::GetBootClassPathChecksums(image_spaces, bcp_dex_files_dependency));
1603 } else {
Vladimir Marko0866ea42019-10-15 12:04:17 +00001604 if (CompilerFilter::DependsOnImageChecksum(original_compiler_filter)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001605 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
Vladimir Marko0ace5632018-12-14 11:11:47 +00001606 Runtime* runtime = Runtime::Current();
1607 key_value_store_->Put(OatHeader::kBootClassPathKey,
1608 android::base::Join(runtime->GetBootClassPathLocations(), ':'));
Vladimir Marko436c6f52019-07-25 14:50:14 +01001609 ArrayRef<ImageSpace* const> image_spaces(runtime->GetHeap()->GetBootImageSpaces());
Vladimir Marko0ace5632018-12-14 11:11:47 +00001610 key_value_store_->Put(
1611 OatHeader::kBootClassPathChecksumsKey,
1612 gc::space::ImageSpace::GetBootClassPathChecksums(image_spaces, bcp_dex_files));
Nicolas Geoffrayd3c45c22021-04-27 13:21:28 +01001613
1614 std::string versions = apex_versions_argument_.empty()
1615 ? runtime->GetApexVersions()
1616 : apex_versions_argument_;
1617 key_value_store_->Put(OatHeader::kApexVersionsKey, versions);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001618 }
1619
1620 // Open dex files for class path.
Calin Juravle19915892017-08-03 17:10:36 +00001621
Calin Juravle1ce70852017-06-28 10:59:03 -07001622 if (class_loader_context_ == nullptr) {
Calin Juravle19915892017-08-03 17:10:36 +00001623 // If no context was specified use the default one (which is an empty PathClassLoader).
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07001624 class_loader_context_ = ClassLoaderContext::Default();
Jeff Haof0192c82016-03-28 20:39:50 -07001625 }
Calin Juravle19915892017-08-03 17:10:36 +00001626
Calin Juravle1ce70852017-06-28 10:59:03 -07001627 DCHECK_EQ(oat_writers_.size(), 1u);
1628
1629 // Note: Ideally we would reject context where the source dex files are also
1630 // specified in the classpath (as it doesn't make sense). However this is currently
1631 // needed for non-prebuild tests and benchmarks which expects on the fly compilation.
1632 // Also, for secondary dex files we do not have control on the actual classpath.
1633 // Instead of aborting, remove all the source location from the context classpaths.
1634 if (class_loader_context_->RemoveLocationsFromClassPaths(
1635 oat_writers_[0]->GetSourceLocations())) {
1636 LOG(WARNING) << "The source files to be compiled are also in the classpath.";
1637 }
1638
1639 // We need to open the dex files before encoding the context in the oat file.
1640 // (because the encoding adds the dex checksum...)
1641 // TODO(calin): consider redesigning this so we don't have to open the dex files before
1642 // creating the actual class loader.
Calin Juravle5ff23932020-12-11 18:26:14 -08001643 if (!class_loader_context_->OpenDexFiles(classpath_dir_,
David Brazdil89821862019-03-19 13:57:43 +00001644 class_loader_context_fds_)) {
Calin Juravle1ce70852017-06-28 10:59:03 -07001645 // Do not abort if we couldn't open files from the classpath. They might be
1646 // apks without dex files and right now are opening flow will fail them.
1647 LOG(WARNING) << "Failed to open classpath dex files";
1648 }
1649
1650 // Store the class loader context in the oat header.
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07001651 // TODO: deprecate this since store_class_loader_context should be enough to cover the users
1652 // of classpath_dir as well.
Mathieu Chartierc4440772018-04-16 14:40:56 -07001653 std::string class_path_key =
1654 class_loader_context_->EncodeContextForOatFile(classpath_dir_,
1655 stored_class_loader_context_.get());
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07001656 key_value_store_->Put(OatHeader::kClassPathKey, class_path_key);
Vladimir Markod1f73512020-04-02 10:50:35 +01001657
1658 // Prepare exclusion list for updatable boot class path packages.
1659 if (!PrepareUpdatableBcpPackages()) {
1660 return dex2oat::ReturnCode::kOther;
1661 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001662 }
1663
Vladimir Marko4e6abea2019-10-23 10:20:20 +01001664 // Now that we have finalized key_value_store_, start writing the .rodata section.
1665 // Among other things, this creates type lookup tables that speed up the compilation.
1666 {
1667 TimingLogger::ScopedTiming t_dex("Starting .rodata", timings_);
1668 rodata_.reserve(oat_writers_.size());
1669 for (size_t i = 0, size = oat_writers_.size(); i != size; ++i) {
1670 rodata_.push_back(elf_writers_[i]->StartRoData());
1671 if (!oat_writers_[i]->StartRoData(dex_files_per_oat_file_[i],
1672 rodata_.back(),
1673 (i == 0u) ? key_value_store_.get() : nullptr)) {
1674 return dex2oat::ReturnCode::kOther;
1675 }
1676 }
1677 }
1678
Andreas Gampe7386da42016-06-08 18:18:47 -07001679 // We had to postpone the swap decision till now, as this is the point when we actually
1680 // know about the dex files we're going to use.
1681
1682 // Make sure that we didn't create the driver, yet.
1683 CHECK(driver_ == nullptr);
1684 // If we use a swap file, ensure we are above the threshold to make it necessary.
1685 if (swap_fd_ != -1) {
Vladimir Marko21910692019-11-06 13:27:03 +00001686 if (!UseSwap(IsBootImage() || IsBootImageExtension(), dex_files)) {
Andreas Gampe7386da42016-06-08 18:18:47 -07001687 close(swap_fd_);
1688 swap_fd_ = -1;
1689 VLOG(compiler) << "Decided to run without swap.";
1690 } else {
1691 LOG(INFO) << "Large app, accepted running with swap.";
1692 }
1693 }
1694 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001695
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001696 // If we're doing the image, override the compiler filter to force full compilation. Must be
1697 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1698 // compilation of class initializers.
1699 // Whilst we're in native take the opportunity to initialize well known classes.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001700 Thread* self = Thread::Current();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001701 WellKnownClasses::Init(self->GetJniEnv());
1702
Vladimir Marko21910692019-11-06 13:27:03 +00001703 if (!IsBootImage() && !IsBootImageExtension()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001704 constexpr bool kSaveDexInput = false;
1705 if (kSaveDexInput) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001706 SaveDexInput();
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001707 }
1708 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001709
1710 // Ensure opened dex files are writable for dex-to-dex transformations.
Vladimir Markoc34bebf2018-08-16 16:12:49 +01001711 for (MemMap& map : opened_dex_files_maps_) {
1712 if (!map.Protect(PROT_READ | PROT_WRITE)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001713 PLOG(ERROR) << "Failed to make .dex files writeable.";
Andreas Gampef7882972017-03-20 16:35:24 -07001714 return dex2oat::ReturnCode::kOther;
Vladimir Marko919f5532016-01-20 19:13:01 +00001715 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001716 }
1717
Mathieu Chartier72041a02017-07-14 18:23:25 -07001718 // Verification results are only required for modes that have any compilation. Avoid
1719 // adding the dex files if possible to prevent allocating large arrays.
1720 if (verification_results_ != nullptr) {
Vladimir Marko213ee2d2018-06-22 11:56:34 +01001721 for (const auto& dex_file : dex_files) {
Mathieu Chartier72041a02017-07-14 18:23:25 -07001722 // Pre-register dex files so that we can access verification results without locks during
1723 // compilation and verification.
Mathieu Chartier0733dc82017-07-17 14:05:28 -07001724 verification_results_->AddDexFile(dex_file);
1725 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001726 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001727
Vladimir Markoc3908792020-04-06 14:52:04 +01001728 // Setup VerifierDeps for compilation and report if we fail to parse the data.
1729 if (!DoEagerUnquickeningOfVdex() && input_vdex_file_ != nullptr) {
1730 std::unique_ptr<verifier::VerifierDeps> verifier_deps(
1731 new verifier::VerifierDeps(dex_files, /*output_only=*/ false));
1732 if (!verifier_deps->ParseStoredData(dex_files, input_vdex_file_->GetVerifierDepsData())) {
1733 return dex2oat::ReturnCode::kOther;
1734 }
1735 callbacks_->SetVerifierDeps(verifier_deps.release());
1736 } else {
1737 // Create the main VerifierDeps, here instead of in the compiler since we want to aggregate
1738 // the results for all the dex files, not just the results for the current dex file.
1739 callbacks_->SetVerifierDeps(new verifier::VerifierDeps(dex_files));
1740 }
1741
Andreas Gampef7882972017-03-20 16:35:24 -07001742 return dex2oat::ReturnCode::kNoFailure;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001743 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001744
Calin Juravle92a78572021-04-05 17:43:17 -07001745 // Validates that the input vdex checksums match the source dex checksums.
1746 // Note that this is only effective and relevant if the input_vdex_file does not
1747 // contain a dex section (e.g. when they come from .dm files).
1748 // If the input vdex does contain dex files, the dex files will be opened from there
1749 // and so this check is redundant.
1750 bool ValidateInputVdexChecksums() {
1751 if (input_vdex_file_ == nullptr) {
1752 // Nothing to validate
1753 return true;
1754 }
1755 if (input_vdex_file_->GetNumberOfDexFiles()
1756 != compiler_options_->dex_files_for_oat_file_.size()) {
1757 LOG(ERROR) << "Vdex file contains a different number of dex files than the source. "
1758 << " vdex_num=" << input_vdex_file_->GetNumberOfDexFiles()
1759 << " dex_source_num=" << compiler_options_->dex_files_for_oat_file_.size();
1760 return false;
1761 }
1762
1763 for (size_t i = 0; i < compiler_options_->dex_files_for_oat_file_.size(); i++) {
1764 uint32_t dex_source_checksum =
1765 compiler_options_->dex_files_for_oat_file_[i]->GetLocationChecksum();
1766 uint32_t vdex_checksum = input_vdex_file_->GetLocationChecksum(i);
1767 if (dex_source_checksum != vdex_checksum) {
1768 LOG(ERROR) << "Vdex file checksum different than source dex checksum for position " << i
1769 << std::hex
1770 << " vdex_checksum=0x" << vdex_checksum
1771 << " dex_source_checksum=0x" << dex_source_checksum
1772 << std::dec;
1773 return false;
1774 }
1775 }
1776 return true;
1777 }
1778
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001779 // If we need to keep the oat file open for the image writer.
1780 bool ShouldKeepOatFileOpen() const {
Orion Hodson365f94f2021-01-13 16:27:57 +00001781 return IsImage() && oat_fd_ != File::kInvalidFd;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001782 }
1783
Mathieu Chartier72041a02017-07-14 18:23:25 -07001784 // Doesn't return the class loader since it's not meant to be used for image compilation.
1785 void CompileDexFilesIndividually() {
1786 CHECK(!IsImage()) << "Not supported with image";
Vladimir Marko213ee2d2018-06-22 11:56:34 +01001787 for (const DexFile* dex_file : compiler_options_->dex_files_for_oat_file_) {
Mathieu Chartier72041a02017-07-14 18:23:25 -07001788 std::vector<const DexFile*> dex_files(1u, dex_file);
1789 VLOG(compiler) << "Compiling " << dex_file->GetLocation();
1790 jobject class_loader = CompileDexFiles(dex_files);
1791 CHECK(class_loader != nullptr);
1792 ScopedObjectAccess soa(Thread::Current());
1793 // Unload class loader to free RAM.
Ian Rogers55256cb2017-12-21 17:07:11 -08001794 jweak weak_class_loader = soa.Env()->GetVm()->AddWeakGlobalRef(
Mathieu Chartier72041a02017-07-14 18:23:25 -07001795 soa.Self(),
1796 soa.Decode<mirror::ClassLoader>(class_loader));
Ian Rogers55256cb2017-12-21 17:07:11 -08001797 soa.Env()->GetVm()->DeleteGlobalRef(soa.Self(), class_loader);
Roland Levillainaf290312018-02-27 20:02:17 +00001798 runtime_->GetHeap()->CollectGarbage(/* clear_soft_references */ true);
Mathieu Chartier72041a02017-07-14 18:23:25 -07001799 ObjPtr<mirror::ClassLoader> decoded_weak = soa.Decode<mirror::ClassLoader>(weak_class_loader);
1800 if (decoded_weak != nullptr) {
1801 LOG(FATAL) << "Failed to unload class loader, path from root set: "
1802 << runtime_->GetHeap()->GetVerification()->FirstPathFromRootSet(decoded_weak);
1803 }
1804 VLOG(compiler) << "Unloaded classloader";
1805 }
1806 }
1807
1808 bool ShouldCompileDexFilesIndividually() const {
Calin Juravle54348dc2021-06-17 15:40:52 -07001809 // Compile individually if we are allowed to, and
Eric Holkbc89ed42020-04-29 19:59:24 +00001810 // 1. not building an image, and
1811 // 2. not verifying a vdex file, and
1812 // 3. using multidex, and
Nicolas Geoffraya6fc7872017-08-14 11:29:22 +01001813 // 4. not doing any AOT compilation.
1814 // This means extract, no-vdex verify, and quicken, will use the individual compilation
1815 // mode (to reduce RAM used by the compiler).
Calin Juravle54348dc2021-06-17 15:40:52 -07001816 return compile_individually_ &&
Eric Holkbc89ed42020-04-29 19:59:24 +00001817 (!IsImage() && !update_input_vdex_ &&
1818 compiler_options_->dex_files_for_oat_file_.size() > 1 &&
1819 !CompilerFilter::IsAotCompilationEnabled(compiler_options_->GetCompilerFilter()));
Mathieu Chartier72041a02017-07-14 18:23:25 -07001820 }
1821
Vladimir Markoe1ee6f92020-03-13 11:30:59 +00001822 uint32_t GetCombinedChecksums() const {
1823 uint32_t combined_checksums = 0u;
1824 for (const DexFile* dex_file : compiler_options_->GetDexFilesForOatFile()) {
1825 combined_checksums ^= dex_file->GetLocationChecksum();
1826 }
1827 return combined_checksums;
1828 }
1829
Mathieu Chartier72041a02017-07-14 18:23:25 -07001830 // Set up and create the compiler driver and then invoke it to compile all the dex files.
1831 jobject Compile() {
1832 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
1833
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001834 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001835
Vladimir Marko47496c22016-01-27 16:15:08 +00001836 // Find the dex files we should not inline from.
Vladimir Marko47496c22016-01-27 16:15:08 +00001837 std::vector<std::string> no_inline_filters;
1838 Split(no_inline_from_string_, ',', &no_inline_filters);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001839
1840 // For now, on the host always have core-oj removed.
Vladimir Marko47496c22016-01-27 16:15:08 +00001841 const std::string core_oj = "core-oj";
1842 if (!kIsTargetBuild && !ContainsElement(no_inline_filters, core_oj)) {
Alex Light4531afd2021-03-30 17:13:30 -07001843 if (force_allow_oj_inlines_) {
1844 LOG(ERROR) << "Inlines allowed from core-oj! FOR TESTING USE ONLY! DO NOT DISTRIBUTE"
1845 << " BINARIES BUILT WITH THIS OPTION!";
1846 } else {
1847 no_inline_filters.push_back(core_oj);
1848 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001849 }
1850
Vladimir Marko47496c22016-01-27 16:15:08 +00001851 if (!no_inline_filters.empty()) {
Calin Juravle1ce70852017-06-28 10:59:03 -07001852 std::vector<const DexFile*> class_path_files;
Vladimir Marko21910692019-11-06 13:27:03 +00001853 if (!IsBootImage() && !IsBootImageExtension()) {
Calin Juravle1ce70852017-06-28 10:59:03 -07001854 // The class loader context is used only for apps.
1855 class_path_files = class_loader_context_->FlattenOpenedDexFiles();
1856 }
1857
Vladimir Marko213ee2d2018-06-22 11:56:34 +01001858 const std::vector<const DexFile*>& dex_files = compiler_options_->dex_files_for_oat_file_;
Vladimir Markodc4bcce2018-06-21 16:15:42 +01001859 std::vector<const DexFile*> no_inline_from_dex_files;
Vladimir Marko213ee2d2018-06-22 11:56:34 +01001860 const std::vector<const DexFile*>* dex_file_vectors[] = {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001861 &class_linker->GetBootClassPath(),
1862 &class_path_files,
Vladimir Marko213ee2d2018-06-22 11:56:34 +01001863 &dex_files
Jeff Haodcdc85b2015-12-04 14:06:18 -08001864 };
1865 for (const std::vector<const DexFile*>* dex_file_vector : dex_file_vectors) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001866 for (const DexFile* dex_file : *dex_file_vector) {
Vladimir Marko47496c22016-01-27 16:15:08 +00001867 for (const std::string& filter : no_inline_filters) {
1868 // Use dex_file->GetLocation() rather than dex_file->GetBaseLocation(). This
Calin Juravlea308a322017-07-18 16:51:51 -07001869 // allows tests to specify <test-dexfile>!classes2.dex if needed but if the
Vladimir Marko47496c22016-01-27 16:15:08 +00001870 // base location passes the StartsWith() test, so do all extra locations.
1871 std::string dex_location = dex_file->GetLocation();
1872 if (filter.find('/') == std::string::npos) {
1873 // The filter does not contain the path. Remove the path from dex_location as well.
1874 size_t last_slash = dex_file->GetLocation().rfind('/');
1875 if (last_slash != std::string::npos) {
1876 dex_location = dex_location.substr(last_slash + 1);
1877 }
1878 }
1879
Andreas Gampe9186ced2016-12-12 14:28:21 -08001880 if (android::base::StartsWith(dex_location, filter.c_str())) {
Vladimir Marko47496c22016-01-27 16:15:08 +00001881 VLOG(compiler) << "Disabling inlining from " << dex_file->GetLocation();
Vladimir Markodc4bcce2018-06-21 16:15:42 +01001882 no_inline_from_dex_files.push_back(dex_file);
Vladimir Marko47496c22016-01-27 16:15:08 +00001883 break;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001884 }
1885 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001886 }
Vladimir Marko47496c22016-01-27 16:15:08 +00001887 }
Vladimir Markodc4bcce2018-06-21 16:15:42 +01001888 if (!no_inline_from_dex_files.empty()) {
1889 compiler_options_->no_inline_from_.swap(no_inline_from_dex_files);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001890 }
1891 }
Vladimir Marko1a2a5cd2018-11-07 15:39:48 +00001892 compiler_options_->profile_compilation_info_ = profile_compilation_info_.get();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001893
Vladimir Marko307dac92015-10-20 11:20:09 +01001894 driver_.reset(new CompilerDriver(compiler_options_.get(),
Vladimir Marko307dac92015-10-20 11:20:09 +01001895 compiler_kind_,
Vladimir Marko307dac92015-10-20 11:20:09 +01001896 thread_count_,
Vladimir Marko1a2a5cd2018-11-07 15:39:48 +00001897 swap_fd_));
wulonghuabdf146c2020-03-27 11:15:42 +08001898
1899 driver_->PrepareDexFilesForOatFile(timings_);
1900
Vladimir Marko21910692019-11-06 13:27:03 +00001901 if (!IsBootImage() && !IsBootImageExtension()) {
Nicolas Geoffray486dda02017-09-11 14:15:52 +01001902 driver_->SetClasspathDexFiles(class_loader_context_->FlattenOpenedDexFiles());
1903 }
Nicolas Geoffray1cfea7a2017-05-24 14:44:38 +01001904
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001905 const bool compile_individually = ShouldCompileDexFilesIndividually();
1906 if (compile_individually) {
1907 // Set the compiler driver in the callbacks so that we can avoid re-verification. This not
1908 // only helps performance but also prevents reverifying quickened bytecodes. Attempting
1909 // verify quickened bytecode causes verification failures.
1910 // Only set the compiler filter if we are doing separate compilation since there is a bit
1911 // of overhead when checking if a class was previously verified.
1912 callbacks_->SetDoesClassUnloading(true, driver_.get());
1913 }
1914
Nicolas Geoffray1cfea7a2017-05-24 14:44:38 +01001915 // Setup vdex for compilation.
Vladimir Marko213ee2d2018-06-22 11:56:34 +01001916 const std::vector<const DexFile*>& dex_files = compiler_options_->dex_files_for_oat_file_;
Vladimir Marko37d6d772020-03-05 17:13:28 +00001917 // To allow initialization of classes that construct ThreadLocal objects in class initializer,
1918 // re-initialize the ThreadLocal.nextHashCode to a new object that's not in the boot image.
1919 ThreadLocalHashOverride thread_local_hash_override(
Vladimir Markoe1ee6f92020-03-13 11:30:59 +00001920 /*apply=*/ !IsBootImage(), /*initial_value=*/ 123456789u ^ GetCombinedChecksums());
Vladimir Marko37d6d772020-03-05 17:13:28 +00001921
Mathieu Chartier72041a02017-07-14 18:23:25 -07001922 // Invoke the compilation.
Mathieu Chartier9e050df2017-08-09 10:05:47 -07001923 if (compile_individually) {
Mathieu Chartier72041a02017-07-14 18:23:25 -07001924 CompileDexFilesIndividually();
1925 // Return a null classloader since we already freed released it.
1926 return nullptr;
1927 }
Vladimir Marko213ee2d2018-06-22 11:56:34 +01001928 return CompileDexFiles(dex_files);
Mathieu Chartier72041a02017-07-14 18:23:25 -07001929 }
1930
1931 // Create the class loader, use it to compile, and return.
1932 jobject CompileDexFiles(const std::vector<const DexFile*>& dex_files) {
1933 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
1934
1935 jobject class_loader = nullptr;
Vladimir Marko21910692019-11-06 13:27:03 +00001936 if (!IsBootImage() && !IsBootImageExtension()) {
Vladimir Marko213ee2d2018-06-22 11:56:34 +01001937 class_loader =
Vladimir Marko37d6d772020-03-05 17:13:28 +00001938 class_loader_context_->CreateClassLoader(compiler_options_->GetDexFilesForOatFile());
Vladimir Markoa879bdf2019-11-19 16:25:47 +00001939 }
1940 if (!IsBootImage()) {
Andreas Gampee9934582018-01-19 21:23:04 -08001941 callbacks_->SetDexFiles(&dex_files);
Calin Juravle33787682019-07-26 14:27:18 -07001942
1943 // We need to set this after we create the class loader so that the runtime can access
1944 // the hidden fields of the well known class loaders.
1945 if (!public_sdk_.empty()) {
1946 std::string error_msg;
1947 std::unique_ptr<SdkChecker> sdk_checker(SdkChecker::Create(public_sdk_, &error_msg));
1948 if (sdk_checker != nullptr) {
1949 AotClassLinker* aot_class_linker = down_cast<AotClassLinker*>(class_linker);
1950 aot_class_linker->SetSdkChecker(std::move(sdk_checker));
1951 } else {
1952 LOG(FATAL) << "Failed to create SdkChecker with dex files "
1953 << public_sdk_ << " Error: " << error_msg;
1954 UNREACHABLE();
1955 }
1956 }
Mathieu Chartier72041a02017-07-14 18:23:25 -07001957 }
1958
1959 // Register dex caches and key them to the class loader so that they only unload when the
1960 // class loader unloads.
1961 for (const auto& dex_file : dex_files) {
1962 ScopedObjectAccess soa(Thread::Current());
1963 // Registering the dex cache adds a strong root in the class loader that prevents the dex
1964 // cache from being unloaded early.
1965 ObjPtr<mirror::DexCache> dex_cache = class_linker->RegisterDexFile(
1966 *dex_file,
1967 soa.Decode<mirror::ClassLoader>(class_loader));
1968 if (dex_cache == nullptr) {
1969 soa.Self()->AssertPendingException();
1970 LOG(FATAL) << "Failed to register dex file " << dex_file->GetLocation() << " "
1971 << soa.Self()->GetException()->Dump();
1972 }
1973 }
Vladimir Marko2afaff72018-11-30 17:01:50 +00001974 driver_->InitializeThreadPools();
1975 driver_->PreCompile(class_loader,
1976 dex_files,
1977 timings_,
1978 &compiler_options_->image_classes_,
1979 verification_results_.get());
1980 callbacks_->SetVerificationResults(nullptr); // Should not be needed anymore.
1981 compiler_options_->verification_results_ = verification_results_.get();
Mathieu Chartier72041a02017-07-14 18:23:25 -07001982 driver_->CompileAll(class_loader, dex_files, timings_);
Vladimir Marko2afaff72018-11-30 17:01:50 +00001983 driver_->FreeThreadPools();
Mathieu Chartier72041a02017-07-14 18:23:25 -07001984 return class_loader;
Vladimir Markof4da6752014-08-01 19:04:18 +01001985 }
1986
Jeff Hao436183f2016-01-12 16:36:50 -08001987 // Notes on the interleaving of creating the images and oat files to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001988 // ensure the references between the two are correct.
1989 //
1990 // Currently we have a memory layout that looks something like this:
1991 //
1992 // +--------------+
Jeff Hao436183f2016-01-12 16:36:50 -08001993 // | images |
Brian Carlstrom7940e442013-07-12 13:46:57 -07001994 // +--------------+
Jeff Hao436183f2016-01-12 16:36:50 -08001995 // | oat files |
Brian Carlstrom7940e442013-07-12 13:46:57 -07001996 // +--------------+
1997 // | alloc spaces |
1998 // +--------------+
1999 //
Jeff Hao436183f2016-01-12 16:36:50 -08002000 // There are several constraints on the loading of the images and oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07002001 //
Jeff Hao436183f2016-01-12 16:36:50 -08002002 // 1. The images are expected to be loaded at an absolute address and
2003 // contain Objects with absolute pointers within the images.
Brian Carlstrom7940e442013-07-12 13:46:57 -07002004 //
Jeff Hao436183f2016-01-12 16:36:50 -08002005 // 2. There are absolute pointers from Methods in the images to their
2006 // code in the oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07002007 //
Jeff Hao436183f2016-01-12 16:36:50 -08002008 // 3. There are absolute pointers from the code in the oat files to Methods
2009 // in the images.
Brian Carlstrom7940e442013-07-12 13:46:57 -07002010 //
Jeff Hao436183f2016-01-12 16:36:50 -08002011 // 4. There are absolute pointers from code in the oat files to other code
2012 // in the oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07002013 //
2014 // To get this all correct, we go through several steps.
2015 //
Jeff Hao436183f2016-01-12 16:36:50 -08002016 // 1. We prepare offsets for all data in the oat files and calculate
Vladimir Markof4da6752014-08-01 19:04:18 +01002017 // the oat data size and code size. During this stage, we also set
2018 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07002019 //
Jeff Hao436183f2016-01-12 16:36:50 -08002020 // 2. We prepare offsets for the objects in the images and calculate
2021 // the image sizes.
Vladimir Markof4da6752014-08-01 19:04:18 +01002022 //
Jeff Hao436183f2016-01-12 16:36:50 -08002023 // 3. We create the oat files. Originally this was just our own proprietary
Vladimir Markof4da6752014-08-01 19:04:18 +01002024 // file but now it is contained within an ELF dynamic object (aka an .so
Jeff Hao436183f2016-01-12 16:36:50 -08002025 // file). Since we know the image sizes and oat data sizes and code sizes we
Vladimir Markof4da6752014-08-01 19:04:18 +01002026 // can prepare the ELF headers and we then know the ELF memory segment
2027 // layout and we can now resolve all references. The compiler provides
2028 // LinkerPatch information in each CompiledMethod and we resolve these,
2029 // using the layout information and image object locations provided by
2030 // image writer, as we're writing the method code.
2031 //
Jeff Hao436183f2016-01-12 16:36:50 -08002032 // 4. We create the image files. They need to know where the oat files
2033 // will be loaded after itself. Originally oat files were simply
2034 // memory mapped so we could predict where their contents were based
2035 // on the file size. Now that they are ELF files, we need to inspect
2036 // the ELF files to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01002037 // where the oat header is located within.
2038 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07002039 //
Vladimir Markof4da6752014-08-01 19:04:18 +01002040 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07002041 // load the .so at the desired location at runtime by offsetting the
2042 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01002043 // TODO: Do this in step 3. We already know the layout there.
2044 //
2045 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
2046 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002047
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002048 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
2049 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08002050 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
2051 // case (when the file will be explicitly erased).
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002052 bool WriteOutputFiles(jobject class_loader) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002053 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
2054
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002055 // Sync the data to the file, in case we did dex2dex transformations.
Vladimir Markoc34bebf2018-08-16 16:12:49 +01002056 for (MemMap& map : opened_dex_files_maps_) {
2057 if (!map.Sync()) {
2058 PLOG(ERROR) << "Failed to Sync() dex2dex output. Map: " << map.GetName();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002059 return false;
2060 }
2061 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002062
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002063 if (IsImage()) {
Vladimir Marko66235942019-06-03 16:05:17 +01002064 if (!IsBootImage()) {
2065 DCHECK_EQ(image_base_, 0u);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002066 gc::Heap* const heap = Runtime::Current()->GetHeap();
Vladimir Marko66235942019-06-03 16:05:17 +01002067 image_base_ = heap->GetBootImagesStartAddress() + heap->GetBootImagesSize();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002068 }
Vladimir Marko66235942019-06-03 16:05:17 +01002069 VLOG(compiler) << "Image base=" << reinterpret_cast<void*>(image_base_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002070
Vladimir Markoa0431112018-06-25 09:32:54 +01002071 image_writer_.reset(new linker::ImageWriter(*compiler_options_,
Vladimir Marko74527972016-11-29 15:57:32 +00002072 image_base_,
Vladimir Marko74527972016-11-29 15:57:32 +00002073 image_storage_mode_,
2074 oat_filenames_,
2075 dex_file_oat_index_map_,
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002076 class_loader,
Vladimir Marko74527972016-11-29 15:57:32 +00002077 dirty_image_objects_.get()));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002078
Vladimir Marko4b90b862020-03-13 17:19:06 +00002079 // We need to prepare method offsets in the image address space for resolving linker patches.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002080 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
David Srbecky86d6cd52020-12-02 18:13:10 +00002081 if (!image_writer_->PrepareImageAddressSpace(timings_)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002082 LOG(ERROR) << "Failed to prepare image address space.";
2083 return false;
2084 }
2085 }
2086
Vladimir Marko4e6abea2019-10-23 10:20:20 +01002087 // Initialize the writers with the compiler driver, image writer, and their
2088 // dex files. The writers were created without those being there yet.
2089 for (size_t i = 0, size = oat_files_.size(); i != size; ++i) {
2090 std::unique_ptr<linker::OatWriter>& oat_writer = oat_writers_[i];
2091 std::vector<const DexFile*>& dex_files = dex_files_per_oat_file_[i];
2092 oat_writer->Initialize(driver_.get(), image_writer_.get(), dex_files);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002093 }
2094
David Brazdil5d5a36b2016-09-14 15:34:10 +01002095 {
2096 TimingLogger::ScopedTiming t2("dex2oat Write VDEX", timings_);
Vladimir Marko21910692019-11-06 13:27:03 +00002097 DCHECK(IsBootImage() || IsBootImageExtension() || oat_files_.size() == 1u);
Nicolas Geoffray6bb7f1b2016-11-03 10:52:49 +00002098 verifier::VerifierDeps* verifier_deps = callbacks_->GetVerifierDeps();
David Brazdil5d5a36b2016-09-14 15:34:10 +01002099 for (size_t i = 0, size = oat_files_.size(); i != size; ++i) {
2100 File* vdex_file = vdex_files_[i].get();
Vladimir Marko9e4b42a2020-04-28 12:28:21 +01002101 if (!oat_writers_[i]->FinishVdexFile(vdex_file, verifier_deps)) {
2102 LOG(ERROR) << "Failed to finish VDEX file " << vdex_file->GetPath();
David Brazdil5d5a36b2016-09-14 15:34:10 +01002103 return false;
2104 }
2105 }
2106 }
2107
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002108 {
2109 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
Vladimir Markoa0431112018-06-25 09:32:54 +01002110 linker::MultiOatRelativePatcher patcher(compiler_options_->GetInstructionSet(),
2111 compiler_options_->GetInstructionSetFeatures(),
Vladimir Markoca1e0382018-04-11 09:58:41 +00002112 driver_->GetCompiledMethodStorage());
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002113 for (size_t i = 0, size = oat_files_.size(); i != size; ++i) {
Vladimir Marko74527972016-11-29 15:57:32 +00002114 std::unique_ptr<linker::ElfWriter>& elf_writer = elf_writers_[i];
2115 std::unique_ptr<linker::OatWriter>& oat_writer = oat_writers_[i];
Vladimir Marko944da602016-02-19 12:27:55 +00002116
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002117 oat_writer->PrepareLayout(&patcher);
Vladimir Markob066d432018-01-03 13:14:37 +00002118 elf_writer->PrepareDynamicSection(oat_writer->GetOatHeader().GetExecutableOffset(),
2119 oat_writer->GetCodeSize(),
2120 oat_writer->GetDataBimgRelRoSize(),
Vladimir Markoaad75c62016-10-03 08:46:48 +00002121 oat_writer->GetBssSize(),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002122 oat_writer->GetBssMethodsOffset(),
David Srbeckyec2cdf42017-12-08 16:21:25 +00002123 oat_writer->GetBssRootsOffset(),
2124 oat_writer->GetVdexSize());
Vladimir Marko944da602016-02-19 12:27:55 +00002125 if (IsImage()) {
2126 // Update oat layout.
2127 DCHECK(image_writer_ != nullptr);
2128 DCHECK_LT(i, oat_filenames_.size());
2129 image_writer_->UpdateOatFileLayout(i,
2130 elf_writer->GetLoadedSize(),
2131 oat_writer->GetOatDataOffset(),
David Brazdil7b49e6c2016-09-01 11:06:18 +01002132 oat_writer->GetOatSize());
Vladimir Marko944da602016-02-19 12:27:55 +00002133 }
2134 }
2135
2136 for (size_t i = 0, size = oat_files_.size(); i != size; ++i) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002137 std::unique_ptr<File>& oat_file = oat_files_[i];
Vladimir Marko74527972016-11-29 15:57:32 +00002138 std::unique_ptr<linker::ElfWriter>& elf_writer = elf_writers_[i];
2139 std::unique_ptr<linker::OatWriter>& oat_writer = oat_writers_[i];
Vladimir Marko10c13562015-11-25 14:33:36 +00002140
David Srbecky0c4572e2016-01-22 19:19:25 +00002141 // We need to mirror the layout of the ELF file in the compressed debug-info.
Vladimir Marko944da602016-02-19 12:27:55 +00002142 // Therefore PrepareDebugInfo() relies on the SetLoadedSectionSizes() call further above.
David Srbecky32210b92017-12-04 14:39:21 +00002143 debug::DebugInfo debug_info = oat_writer->GetDebugInfo(); // Keep the variable alive.
2144 elf_writer->PrepareDebugInfo(debug_info); // Processes the data on background thread.
David Srbecky0c4572e2016-01-22 19:19:25 +00002145
Vladimir Marko0866ea42019-10-15 12:04:17 +00002146 OutputStream* rodata = rodata_[i];
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002147 DCHECK(rodata != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002148 if (!oat_writer->WriteRodata(rodata)) {
2149 LOG(ERROR) << "Failed to write .rodata section to the ELF file " << oat_file->GetPath();
2150 return false;
2151 }
2152 elf_writer->EndRoData(rodata);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002153 rodata = nullptr;
Vladimir Marko10c13562015-11-25 14:33:36 +00002154
David Srbecky2faab002019-02-12 16:35:48 +00002155 OutputStream* text = elf_writer->StartText();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002156 if (!oat_writer->WriteCode(text)) {
2157 LOG(ERROR) << "Failed to write .text section to the ELF file " << oat_file->GetPath();
2158 return false;
2159 }
2160 elf_writer->EndText(text);
Vladimir Marko10c13562015-11-25 14:33:36 +00002161
Vladimir Markob066d432018-01-03 13:14:37 +00002162 if (oat_writer->GetDataBimgRelRoSize() != 0u) {
David Srbecky2faab002019-02-12 16:35:48 +00002163 OutputStream* data_bimg_rel_ro = elf_writer->StartDataBimgRelRo();
Vladimir Markob066d432018-01-03 13:14:37 +00002164 if (!oat_writer->WriteDataBimgRelRo(data_bimg_rel_ro)) {
2165 LOG(ERROR) << "Failed to write .data.bimg.rel.ro section to the ELF file "
2166 << oat_file->GetPath();
2167 return false;
2168 }
2169 elf_writer->EndDataBimgRelRo(data_bimg_rel_ro);
2170 }
2171
Vladimir Marko0ace5632018-12-14 11:11:47 +00002172 if (!oat_writer->WriteHeader(elf_writer->GetStream())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002173 LOG(ERROR) << "Failed to write oat header to the ELF file " << oat_file->GetPath();
2174 return false;
2175 }
2176
Vladimir Marko944da602016-02-19 12:27:55 +00002177 if (IsImage()) {
2178 // Update oat header information.
2179 DCHECK(image_writer_ != nullptr);
2180 DCHECK_LT(i, oat_filenames_.size());
2181 image_writer_->UpdateOatFileHeader(i, oat_writer->GetOatHeader());
2182 }
2183
Jeff Haodcdc85b2015-12-04 14:06:18 -08002184 elf_writer->WriteDynamicSection();
David Srbecky32210b92017-12-04 14:39:21 +00002185 elf_writer->WriteDebugInfo(oat_writer->GetDebugInfo());
Vladimir Marko10c13562015-11-25 14:33:36 +00002186
Jeff Haodcdc85b2015-12-04 14:06:18 -08002187 if (!elf_writer->End()) {
2188 LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath();
2189 return false;
2190 }
2191
David Brazdil7b49e6c2016-09-01 11:06:18 +01002192 if (!FlushOutputFile(&vdex_files_[i]) || !FlushOutputFile(&oat_files_[i])) {
2193 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002194 }
2195
Jeff Haodcdc85b2015-12-04 14:06:18 -08002196 VLOG(compiler) << "Oat file written successfully: " << oat_filenames_[i];
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002197
2198 oat_writer.reset();
David Srbeckyde91fd42018-07-05 22:27:08 +01002199 // We may still need the ELF writer later for stripping.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002200 }
2201 }
2202
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002203 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002204 }
2205
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002206 // If we are compiling an image, invoke the image creation routine. Else just skip.
2207 bool HandleImage() {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002208 if (IsImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002209 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
2210 if (!CreateImageFile()) {
2211 return false;
2212 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002213 VLOG(compiler) << "Images written successfully";
Brian Carlstrom45602482013-07-21 22:07:55 -07002214 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002215 return true;
2216 }
2217
David Srbeckyde91fd42018-07-05 22:27:08 +01002218 // Copy the full oat files to symbols directory and then strip the originals.
2219 bool CopyOatFilesToSymbolsDirectoryAndStrip() {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002220 for (size_t i = 0; i < oat_unstripped_.size(); ++i) {
2221 // If we don't want to strip in place, copy from stripped location to unstripped location.
2222 // We need to strip after image creation because FixupElf needs to use .strtab.
Vladimir Markod011d812018-11-29 12:35:24 +00002223 if (oat_unstripped_[i] != oat_filenames_[i]) {
David Srbeckyde91fd42018-07-05 22:27:08 +01002224 DCHECK(oat_files_[i].get() != nullptr && oat_files_[i]->IsOpened());
Jeff Haodcdc85b2015-12-04 14:06:18 -08002225
2226 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
David Srbeckyde91fd42018-07-05 22:27:08 +01002227 std::unique_ptr<File>& in = oat_files_[i];
Vladimir Markob55cc6d2016-10-17 15:25:10 +01002228 int64_t in_length = in->GetLength();
2229 if (in_length < 0) {
2230 PLOG(ERROR) << "Failed to get the length of oat file: " << in->GetPath();
2231 return false;
2232 }
Orion Hodson923141b2020-08-06 14:01:16 +01002233 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_unstripped_[i].c_str()));
2234 if (out == nullptr) {
2235 PLOG(ERROR) << "Failed to open oat file for writing: " << oat_unstripped_[i];
2236 return false;
2237 }
Vladimir Markob55cc6d2016-10-17 15:25:10 +01002238 if (!out->Copy(in.get(), 0, in_length)) {
2239 PLOG(ERROR) << "Failed to copy oat file to file: " << out->GetPath();
2240 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002241 }
2242 if (out->FlushCloseOrErase() != 0) {
2243 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_unstripped_[i];
2244 return false;
2245 }
2246 VLOG(compiler) << "Oat file copied successfully (unstripped): " << oat_unstripped_[i];
David Srbeckyde91fd42018-07-05 22:27:08 +01002247
2248 if (strip_) {
2249 TimingLogger::ScopedTiming t2("dex2oat OatFile strip", timings_);
2250 if (!elf_writers_[i]->StripDebugInfo()) {
2251 PLOG(ERROR) << "Failed strip oat file: " << in->GetPath();
2252 return false;
2253 }
2254 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002255 }
2256 }
2257 return true;
2258 }
2259
David Brazdil7b49e6c2016-09-01 11:06:18 +01002260 bool FlushOutputFile(std::unique_ptr<File>* file) {
2261 if (file->get() != nullptr) {
2262 if (file->get()->Flush() != 0) {
2263 PLOG(ERROR) << "Failed to flush output file: " << file->get()->GetPath();
2264 return false;
2265 }
2266 }
2267 return true;
2268 }
2269
David Srbeckyde91fd42018-07-05 22:27:08 +01002270 bool FlushCloseOutputFile(File* file) {
2271 if (file != nullptr) {
2272 if (file->FlushCloseOrErase() != 0) {
2273 PLOG(ERROR) << "Failed to flush and close output file: " << file->GetPath();
David Brazdil7b49e6c2016-09-01 11:06:18 +01002274 return false;
2275 }
2276 }
2277 return true;
2278 }
2279
2280 bool FlushOutputFiles() {
2281 TimingLogger::ScopedTiming t2("dex2oat Flush Output Files", timings_);
2282 for (auto& files : { &vdex_files_, &oat_files_ }) {
2283 for (size_t i = 0; i < files->size(); ++i) {
2284 if (!FlushOutputFile(&(*files)[i])) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002285 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08002286 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08002287 }
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00002288 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08002289 return true;
2290 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002291
David Brazdil7b49e6c2016-09-01 11:06:18 +01002292 bool FlushCloseOutputFiles() {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002293 bool result = true;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002294 for (auto& files : { &vdex_files_, &oat_files_ }) {
2295 for (size_t i = 0; i < files->size(); ++i) {
David Srbeckyde91fd42018-07-05 22:27:08 +01002296 result &= FlushCloseOutputFile((*files)[i].get());
David Brazdil7b49e6c2016-09-01 11:06:18 +01002297 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002298 }
2299 return result;
2300 }
2301
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002302 void DumpTiming() {
Nicolas Geoffray2d8801f2017-11-28 15:50:07 +00002303 if (compiler_options_->GetDumpTimings() ||
2304 (kIsDebugBuild && timings_->GetTotalNs() > MsToNs(1000))) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002305 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
2306 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002307 }
2308
Andreas Gampe10e477d2014-11-19 12:57:42 -08002309 bool IsImage() const {
Vladimir Marko21910692019-11-06 13:27:03 +00002310 return IsAppImage() || IsBootImage() || IsBootImageExtension();
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002311 }
2312
2313 bool IsAppImage() const {
Vladimir Markoaad75c62016-10-03 08:46:48 +00002314 return compiler_options_->IsAppImage();
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002315 }
2316
2317 bool IsBootImage() const {
Vladimir Markoaad75c62016-10-03 08:46:48 +00002318 return compiler_options_->IsBootImage();
Andreas Gampe10e477d2014-11-19 12:57:42 -08002319 }
2320
Vladimir Marko21910692019-11-06 13:27:03 +00002321 bool IsBootImageExtension() const {
2322 return compiler_options_->IsBootImageExtension();
2323 }
2324
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002325 bool IsHost() const {
2326 return is_host_;
2327 }
2328
Calin Juravle32de2a52021-05-26 15:37:00 -07002329 bool HasProfileInput() const {
Mathieu Chartierd0af56c2017-02-17 12:56:25 -08002330 return profile_file_fd_ != -1 || !profile_file_.empty();
Calin Juravle998c2162015-12-21 15:39:33 +02002331 }
2332
Calin Juravle32de2a52021-05-26 15:37:00 -07002333 // Must be called after the profile is loaded.
Mathieu Chartier11b3df32017-02-21 13:41:54 -08002334 bool DoProfileGuidedOptimizations() const {
Calin Juravle32de2a52021-05-26 15:37:00 -07002335 DCHECK(!HasProfileInput() || profile_load_attempted_)
2336 << "The profile has to be loaded before we can decided "
2337 << "if we do profile guided optimizations";
2338 return profile_compilation_info_ != nullptr && !profile_compilation_info_->IsEmpty();
Mathieu Chartier11b3df32017-02-21 13:41:54 -08002339 }
2340
Mathieu Chartiereafe2a52017-10-19 15:29:42 -07002341 bool DoGenerateCompactDex() const {
2342 return compact_dex_level_ != CompactDexLevel::kCompactDexLevelNone;
2343 }
2344
Mathieu Chartier11b3df32017-02-21 13:41:54 -08002345 bool DoDexLayoutOptimizations() const {
Mathieu Chartiereafe2a52017-10-19 15:29:42 -07002346 return DoProfileGuidedOptimizations() || DoGenerateCompactDex();
Mathieu Chartier11b3df32017-02-21 13:41:54 -08002347 }
2348
Igor Murashkin545412b2017-08-17 15:26:54 -07002349 bool DoOatLayoutOptimizations() const {
2350 return DoProfileGuidedOptimizations();
2351 }
2352
Mathieu Chartier2c4b0842017-12-13 11:49:51 -08002353 bool MayInvalidateVdexMetadata() const {
2354 // DexLayout can invalidate the vdex metadata if changing the class def order is enabled, so
2355 // we need to unquicken the vdex file eagerly, before passing it to dexlayout.
Nicolas Geoffray1cfea7a2017-05-24 14:44:38 +01002356 return DoDexLayoutOptimizations();
2357 }
2358
Mathieu Chartier2c4b0842017-12-13 11:49:51 -08002359 bool DoEagerUnquickeningOfVdex() const {
Nicolas Geoffraybaeaa9b2018-01-26 14:31:17 +00002360 return MayInvalidateVdexMetadata() && dm_file_ == nullptr;
Mathieu Chartier2c4b0842017-12-13 11:49:51 -08002361 }
2362
Calin Juravle2e2db782016-02-23 12:00:03 +00002363 bool LoadProfile() {
Calin Juravle32de2a52021-05-26 15:37:00 -07002364 DCHECK(HasProfileInput());
2365 profile_load_attempted_ = true;
Calin Juravlee6f87cc2017-05-24 17:41:05 -07002366 // TODO(calin): We should be using the runtime arena pool (instead of the
2367 // default profile arena). However the setup logic is messy and needs
2368 // cleaning up before that (e.g. the oat writers are created before the
2369 // runtime).
Vladimir Markoa2209802021-04-23 13:28:29 +00002370 bool for_boot_image = IsBootImage() || IsBootImageExtension();
2371 profile_compilation_info_.reset(new ProfileCompilationInfo(for_boot_image));
Victor Hsieh52fe49e2020-07-20 15:20:12 -07002372 // Dex2oat only uses the reference profile and that is not updated concurrently by the app or
2373 // other processes. So we don't need to lock (as we have to do in profman or when writing the
2374 // profile info).
2375 std::unique_ptr<File> profile_file;
Calin Juravle2e2db782016-02-23 12:00:03 +00002376 if (profile_file_fd_ != -1) {
Victor Hsieh52fe49e2020-07-20 15:20:12 -07002377 profile_file.reset(new File(DupCloexec(profile_file_fd_),
2378 "profile",
2379 /* check_usage= */ false,
2380 /* read_only_mode= */ true));
Andreas Gampe29d38e72016-03-23 15:31:51 +00002381 } else if (profile_file_ != "") {
Victor Hsieh52fe49e2020-07-20 15:20:12 -07002382 profile_file.reset(OS::OpenFileForReading(profile_file_.c_str()));
Calin Juravle998c2162015-12-21 15:39:33 +02002383 }
Calin Juravle877fd962016-01-05 14:29:29 +00002384
Narayan Kamatha3d27eb2017-05-11 13:50:59 +01002385 if (profile_file.get() == nullptr) {
Victor Hsieh52fe49e2020-07-20 15:20:12 -07002386 PLOG(ERROR) << "Cannot lock profiles";
Narayan Kamatha3d27eb2017-05-11 13:50:59 +01002387 return false;
2388 }
2389
2390 if (!profile_compilation_info_->Load(profile_file->Fd())) {
Calin Juravle2e2db782016-02-23 12:00:03 +00002391 profile_compilation_info_.reset(nullptr);
Narayan Kamatha3d27eb2017-05-11 13:50:59 +01002392 return false;
Calin Juravle2e2db782016-02-23 12:00:03 +00002393 }
Calin Juravle877fd962016-01-05 14:29:29 +00002394
Narayan Kamatha3d27eb2017-05-11 13:50:59 +01002395 return true;
Calin Juravle998c2162015-12-21 15:39:33 +02002396 }
2397
Calin Juravle32de2a52021-05-26 15:37:00 -07002398 // If we're asked to speed-profile the app but we have no profile, or the profile
2399 // is empty, change the filter to verify, and the image_type to none.
2400 // A speed-profile compilation without profile data is equivalent to verify and
2401 // this change will increase the precision of the telemetry data.
2402 void UpdateCompilerOptionsBasedOnProfile() {
2403 if (!DoProfileGuidedOptimizations() &&
2404 compiler_options_->GetCompilerFilter() == CompilerFilter::kSpeedProfile) {
2405 VLOG(compiler) << "Changing compiler filter to verify from speed-profile "
2406 << "because of empty or non existing profile";
2407
2408 compiler_options_->SetCompilerFilter(CompilerFilter::kVerify);
2409
2410 // Note that we could reset the image_type to CompilerOptions::ImageType::kNone
2411 // to prevent an app image generation.
2412 // However, if we were pass an image file we would essentially leave the image
2413 // file empty (possibly triggering some harmless errors when we try to load it).
2414 //
2415 // Letting the image_type_ be determined by whether or not we passed an image
2416 // file will at least write the appropriate header making it an empty but valid
2417 // image.
2418 }
2419 }
2420
Nicolas Geoffray1ece2992021-01-06 17:02:04 +00002421 class ScopedDex2oatReporting {
2422 public:
2423 explicit ScopedDex2oatReporting(const Dex2Oat& dex2oat) {
Nicolas Geoffray55309db2021-06-02 18:05:51 +01002424 bool should_report = false;
2425 PaletteShouldReportDex2oatCompilation(&should_report);
2426 if (should_report) {
Nicolas Geoffray1ece2992021-01-06 17:02:04 +00002427 if (dex2oat.zip_fd_ != -1) {
2428 zip_dup_fd_.reset(DupCloexecOrError(dex2oat.zip_fd_));
2429 if (zip_dup_fd_ < 0) {
2430 return;
2431 }
2432 }
2433 int image_fd = dex2oat.IsAppImage() ? dex2oat.app_image_fd_ : dex2oat.image_fd_;
2434 if (image_fd != -1) {
2435 image_dup_fd_.reset(DupCloexecOrError(image_fd));
2436 if (image_dup_fd_ < 0) {
2437 return;
2438 }
2439 }
2440 oat_dup_fd_.reset(DupCloexecOrError(dex2oat.oat_fd_));
2441 if (oat_dup_fd_ < 0) {
2442 return;
2443 }
2444 vdex_dup_fd_.reset(DupCloexecOrError(dex2oat.output_vdex_fd_));
2445 if (vdex_dup_fd_ < 0) {
2446 return;
2447 }
Nicolas Geoffray55309db2021-06-02 18:05:51 +01002448 PaletteNotifyStartDex2oatCompilation(zip_dup_fd_,
Nicolas Geoffray1ece2992021-01-06 17:02:04 +00002449 image_dup_fd_,
2450 oat_dup_fd_,
2451 vdex_dup_fd_);
2452 }
2453 error_reporting_ = false;
2454 }
2455
2456 ~ScopedDex2oatReporting() {
Nicolas Geoffray55309db2021-06-02 18:05:51 +01002457 if (!error_reporting_) {
2458 bool should_report = false;
2459 PaletteShouldReportDex2oatCompilation(&should_report);
2460 if (should_report) {
2461 PaletteNotifyEndDex2oatCompilation(zip_dup_fd_,
2462 image_dup_fd_,
2463 oat_dup_fd_,
2464 vdex_dup_fd_);
2465 }
Nicolas Geoffray1ece2992021-01-06 17:02:04 +00002466 }
2467 }
2468
2469 bool ErrorReporting() const { return error_reporting_; }
2470
2471 private:
2472 int DupCloexecOrError(int fd) {
2473 int dup_fd = DupCloexec(fd);
2474 if (dup_fd < 0) {
2475 LOG(ERROR) << "Error dup'ing a file descriptor " << strerror(errno);
2476 error_reporting_ = true;
2477 }
2478 return dup_fd;
2479 }
2480 android::base::unique_fd oat_dup_fd_;
2481 android::base::unique_fd vdex_dup_fd_;
2482 android::base::unique_fd zip_dup_fd_;
2483 android::base::unique_fd image_dup_fd_;
2484 bool error_reporting_ = false;
2485 };
2486
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002487 private:
Andreas Gampee1459ae2016-06-29 09:36:30 -07002488 bool UseSwap(bool is_image, const std::vector<const DexFile*>& dex_files) {
2489 if (is_image) {
2490 // Don't use swap, we know generation should succeed, and we don't want to slow it down.
2491 return false;
2492 }
2493 if (dex_files.size() < min_dex_files_for_swap_) {
2494 // If there are less dex files than the threshold, assume it's gonna be fine.
2495 return false;
2496 }
2497 size_t dex_files_size = 0;
2498 for (const auto* dex_file : dex_files) {
2499 dex_files_size += dex_file->GetHeader().file_size_;
2500 }
2501 return dex_files_size >= min_dex_file_cumulative_size_for_swap_;
2502 }
2503
Vladimir Marko213ee2d2018-06-22 11:56:34 +01002504 bool IsVeryLarge(const std::vector<const DexFile*>& dex_files) {
Andreas Gampe67f02822016-06-24 21:05:23 -07002505 size_t dex_files_size = 0;
2506 for (const auto* dex_file : dex_files) {
2507 dex_files_size += dex_file->GetHeader().file_size_;
2508 }
2509 return dex_files_size >= very_large_threshold_;
2510 }
2511
Jeff Haoc23b0c02017-07-27 18:19:38 -07002512 bool PrepareDirtyObjects() {
2513 if (dirty_image_objects_filename_ != nullptr) {
Vladimir Marko54159c62018-06-20 14:30:08 +01002514 dirty_image_objects_ = ReadCommentedInputFromFile<HashSet<std::string>>(
Jeff Haoc23b0c02017-07-27 18:19:38 -07002515 dirty_image_objects_filename_,
Vladimir Marko54159c62018-06-20 14:30:08 +01002516 nullptr);
Jeff Haoc23b0c02017-07-27 18:19:38 -07002517 if (dirty_image_objects_ == nullptr) {
2518 LOG(ERROR) << "Failed to create list of dirty objects from '"
2519 << dirty_image_objects_filename_ << "'";
2520 return false;
2521 }
2522 } else {
2523 dirty_image_objects_.reset(nullptr);
2524 }
2525 return true;
2526 }
2527
Vladimir Markod1f73512020-04-02 10:50:35 +01002528 bool PrepareUpdatableBcpPackages() {
2529 DCHECK(!IsBootImage() && !IsBootImageExtension());
2530 AotClassLinker* aot_class_linker = down_cast<AotClassLinker*>(runtime_->GetClassLinker());
2531 if (updatable_bcp_packages_filename_ != nullptr) {
2532 std::unique_ptr<std::vector<std::string>> updatable_bcp_packages =
2533 ReadCommentedInputFromFile<std::vector<std::string>>(updatable_bcp_packages_filename_,
2534 nullptr); // No post-processing.
2535 if (updatable_bcp_packages == nullptr) {
2536 LOG(ERROR) << "Failed to load updatable boot class path packages from '"
2537 << updatable_bcp_packages_filename_ << "'";
2538 return false;
2539 }
2540 return aot_class_linker->SetUpdatableBootClassPackages(*updatable_bcp_packages);
2541 } else {
2542 // Use the default list based on updatable packages for Android 11.
2543 return aot_class_linker->SetUpdatableBootClassPackages({
2544 // Reserved conscrypt packages (includes sub-packages under these paths).
2545 // "android.net.ssl", // Covered by android.net below.
2546 "com.android.org.conscrypt",
2547 // Reserved updatable-media package (includes sub-packages under this path).
2548 "android.media",
2549 // Reserved framework-mediaprovider package (includes sub-packages under this path).
2550 "android.provider",
2551 // Reserved framework-statsd packages (includes sub-packages under these paths).
2552 "android.app",
2553 "android.os",
2554 "android.util",
Vladimir Marko9db35462020-06-09 14:10:13 +01002555 "com.android.internal.statsd",
Vladimir Markod1f73512020-04-02 10:50:35 +01002556 // Reserved framework-permission packages (includes sub-packages under this path).
2557 "android.permission",
2558 // "android.app.role", // Covered by android.app above.
2559 // Reserved framework-sdkextensions package (includes sub-packages under this path).
2560 // "android.os.ext", // Covered by android.os above.
2561 // Reserved framework-wifi packages (includes sub-packages under these paths).
2562 "android.hardware.wifi",
2563 // "android.net.wifi", // Covered by android.net below.
Paul Duffinf43e0e12020-05-28 18:56:47 +01002564 "com.android.wifi.x",
Vladimir Markod1f73512020-04-02 10:50:35 +01002565 // Reserved framework-tethering package (includes sub-packages under this path).
2566 "android.net",
2567 });
2568 }
2569 }
2570
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002571 void PruneNonExistentDexFiles() {
2572 DCHECK_EQ(dex_filenames_.size(), dex_locations_.size());
2573 size_t kept = 0u;
2574 for (size_t i = 0, size = dex_filenames_.size(); i != size; ++i) {
Vladimir Markod011d812018-11-29 12:35:24 +00002575 if (!OS::FileExists(dex_filenames_[i].c_str())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002576 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filenames_[i] << "'";
2577 } else {
Vladimir Markod011d812018-11-29 12:35:24 +00002578 if (kept != i) {
2579 dex_filenames_[kept] = dex_filenames_[i];
2580 dex_locations_[kept] = dex_locations_[i];
2581 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002582 ++kept;
2583 }
2584 }
2585 dex_filenames_.resize(kept);
2586 dex_locations_.resize(kept);
2587 }
2588
2589 bool AddDexFileSources() {
2590 TimingLogger::ScopedTiming t2("AddDexFileSources", timings_);
Nicolas Geoffraybc177272018-01-24 14:55:32 +00002591 if (input_vdex_file_ != nullptr && input_vdex_file_->HasDexSection()) {
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00002592 DCHECK_EQ(oat_writers_.size(), 1u);
2593 const std::string& name = zip_location_.empty() ? dex_locations_[0] : zip_location_;
2594 DCHECK(!name.empty());
2595 if (!oat_writers_[0]->AddVdexDexFilesSource(*input_vdex_file_.get(), name.c_str())) {
2596 return false;
2597 }
2598 } else if (zip_fd_ != -1) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002599 DCHECK_EQ(oat_writers_.size(), 1u);
wangshumin3949e5e2019-11-08 19:25:50 +08002600 if (!oat_writers_[0]->AddDexFileSource(File(zip_fd_, /* check_usage */ false),
2601 zip_location_.c_str())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002602 return false;
2603 }
2604 } else if (oat_writers_.size() > 1u) {
2605 // Multi-image.
2606 DCHECK_EQ(oat_writers_.size(), dex_filenames_.size());
2607 DCHECK_EQ(oat_writers_.size(), dex_locations_.size());
2608 for (size_t i = 0, size = oat_writers_.size(); i != size; ++i) {
Vladimir Markod011d812018-11-29 12:35:24 +00002609 if (!oat_writers_[i]->AddDexFileSource(dex_filenames_[i].c_str(),
2610 dex_locations_[i].c_str())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002611 return false;
2612 }
2613 }
2614 } else {
2615 DCHECK_EQ(oat_writers_.size(), 1u);
2616 DCHECK_EQ(dex_filenames_.size(), dex_locations_.size());
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002617 for (size_t i = 0; i != dex_filenames_.size(); ++i) {
Vladimir Markod011d812018-11-29 12:35:24 +00002618 if (!oat_writers_[0]->AddDexFileSource(dex_filenames_[i].c_str(),
2619 dex_locations_[i].c_str())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002620 return false;
2621 }
2622 }
2623 }
2624 return true;
2625 }
2626
2627 void CreateOatWriters() {
2628 TimingLogger::ScopedTiming t2("CreateOatWriters", timings_);
2629 elf_writers_.reserve(oat_files_.size());
2630 oat_writers_.reserve(oat_files_.size());
2631 for (const std::unique_ptr<File>& oat_file : oat_files_) {
Vladimir Markoa0431112018-06-25 09:32:54 +01002632 elf_writers_.emplace_back(linker::CreateElfWriterQuick(*compiler_options_, oat_file.get()));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002633 elf_writers_.back()->Start();
Mathieu Chartier4a265c22018-04-09 14:25:14 -07002634 bool do_oat_writer_layout = DoDexLayoutOptimizations() || DoOatLayoutOptimizations();
Vladimir Marko74527972016-11-29 15:57:32 +00002635 oat_writers_.emplace_back(new linker::OatWriter(
Vladimir Markoa0431112018-06-25 09:32:54 +01002636 *compiler_options_,
Igor Murashkin545412b2017-08-17 15:26:54 -07002637 timings_,
Mathieu Chartier603ccab2017-10-20 14:34:28 -07002638 do_oat_writer_layout ? profile_compilation_info_.get() : nullptr,
2639 compact_dex_level_));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002640 }
2641 }
2642
Vladimir Marko49b0f452015-12-10 13:49:19 +00002643 void SaveDexInput() {
Vladimir Marko213ee2d2018-06-22 11:56:34 +01002644 const std::vector<const DexFile*>& dex_files = compiler_options_->dex_files_for_oat_file_;
2645 for (size_t i = 0, size = dex_files.size(); i != size; ++i) {
2646 const DexFile* dex_file = dex_files[i];
Vladimir Marko49b0f452015-12-10 13:49:19 +00002647 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
2648 getpid(), i));
2649 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
2650 if (tmp_file.get() == nullptr) {
2651 PLOG(ERROR) << "Failed to open file " << tmp_file_name
2652 << ". Try: adb shell chmod 777 /data/local/tmp";
2653 continue;
2654 }
2655 // This is just dumping files for debugging. Ignore errors, and leave remnants.
2656 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
2657 UNUSED(tmp_file->Flush());
2658 UNUSED(tmp_file->Close());
2659 LOG(INFO) << "Wrote input to " << tmp_file_name;
2660 }
2661 }
2662
Mathieu Chartier46331a62017-07-21 09:49:10 -07002663 bool PrepareRuntimeOptions(RuntimeArgumentMap* runtime_options,
2664 QuickCompilerCallbacks* callbacks) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002665 RuntimeOptions raw_options;
Vladimir Marko21910692019-11-06 13:27:03 +00002666 if (IsBootImage()) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002667 std::string boot_class_path = "-Xbootclasspath:";
Andreas Gampe9186ced2016-12-12 14:28:21 -08002668 boot_class_path += android::base::Join(dex_filenames_, ':');
Vladimir Marko49b0f452015-12-10 13:49:19 +00002669 raw_options.push_back(std::make_pair(boot_class_path, nullptr));
2670 std::string boot_class_path_locations = "-Xbootclasspath-locations:";
Andreas Gampe9186ced2016-12-12 14:28:21 -08002671 boot_class_path_locations += android::base::Join(dex_locations_, ':');
Vladimir Marko49b0f452015-12-10 13:49:19 +00002672 raw_options.push_back(std::make_pair(boot_class_path_locations, nullptr));
2673 } else {
2674 std::string boot_image_option = "-Ximage:";
2675 boot_image_option += boot_image_filename_;
2676 raw_options.push_back(std::make_pair(boot_image_option, nullptr));
2677 }
2678 for (size_t i = 0; i < runtime_args_.size(); i++) {
2679 raw_options.push_back(std::make_pair(runtime_args_[i], nullptr));
2680 }
2681
Mathieu Chartier46331a62017-07-21 09:49:10 -07002682 raw_options.push_back(std::make_pair("compilercallbacks", callbacks));
Vladimir Marko49b0f452015-12-10 13:49:19 +00002683 raw_options.push_back(
Vladimir Markoa0431112018-06-25 09:32:54 +01002684 std::make_pair("imageinstructionset",
2685 GetInstructionSetString(compiler_options_->GetInstructionSet())));
Vladimir Marko49b0f452015-12-10 13:49:19 +00002686
Andreas Gampec8e35202017-04-28 15:47:12 -07002687 // Never allow implicit image compilation.
2688 raw_options.push_back(std::make_pair("-Xnoimage-dex2oat", nullptr));
Vladimir Marko49b0f452015-12-10 13:49:19 +00002689 // Disable libsigchain. We don't don't need it during compilation and it prevents us
2690 // from getting a statically linked version of dex2oat (because of dlsym and RTLD_NEXT).
2691 raw_options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
Lin Zang97f3f7d2016-01-13 10:25:00 +08002692 // Disable Hspace compaction to save heap size virtual space.
2693 // Only need disable Hspace for OOM becasue background collector is equal to
2694 // foreground collector by default for dex2oat.
2695 raw_options.push_back(std::make_pair("-XX:DisableHSpaceCompactForOOM", nullptr));
Vladimir Marko49b0f452015-12-10 13:49:19 +00002696
2697 if (!Runtime::ParseOptions(raw_options, false, runtime_options)) {
2698 LOG(ERROR) << "Failed to parse runtime options";
2699 return false;
2700 }
2701 return true;
2702 }
2703
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002704 // Create a runtime necessary for compilation.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002705 bool CreateRuntime(RuntimeArgumentMap&& runtime_options) {
Vladimir Markoe1ee6f92020-03-13 11:30:59 +00002706 // To make identity hashcode deterministic, set a seed based on the dex file checksums.
2707 // That makes the seed also most likely different for different inputs, for example
2708 // for primary boot image and different extensions that could be loaded together.
2709 mirror::Object::SetHashCodeSeed(987654321u ^ GetCombinedChecksums());
2710
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002711 TimingLogger::ScopedTiming t_runtime("Create runtime", timings_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002712 if (!Runtime::Create(std::move(runtime_options))) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002713 LOG(ERROR) << "Failed to create runtime";
2714 return false;
2715 }
Andreas Gampe49c144d2016-11-14 10:11:16 -08002716
2717 // Runtime::Init will rename this thread to be "main". Prefer "dex2oat" so that "top" and
2718 // "ps -a" don't change to non-descript "main."
2719 SetThreadName(kIsDebugBuild ? "dex2oatd" : "dex2oat");
2720
Vladimir Marko307dac92015-10-20 11:20:09 +01002721 runtime_.reset(Runtime::Current());
Vladimir Markoa0431112018-06-25 09:32:54 +01002722 runtime_->SetInstructionSet(compiler_options_->GetInstructionSet());
Andreas Gampe8228cdf2017-05-30 15:03:54 -07002723 for (uint32_t i = 0; i < static_cast<uint32_t>(CalleeSaveType::kLastCalleeSaveType); ++i) {
2724 CalleeSaveType type = CalleeSaveType(i);
Vladimir Marko307dac92015-10-20 11:20:09 +01002725 if (!runtime_->HasCalleeSaveMethod(type)) {
2726 runtime_->SetCalleeSaveMethod(runtime_->CreateCalleeSaveMethod(), type);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002727 }
2728 }
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002729
2730 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
2731 // set up.
Andreas Gampe799681b2015-05-15 19:24:12 -07002732 interpreter::UnstartedRuntime::Initialize();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002733
Vladimir Markodcfcce42018-06-27 10:00:28 +00002734 Thread* self = Thread::Current();
2735 runtime_->RunRootClinits(self);
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002736
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002737 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
2738 // Runtime::Start, give it away now so that we don't starve GC.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002739 self->TransitionFromRunnableToSuspended(kNative);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002740
Koji Fukuia72ca6c2019-03-25 17:39:07 +09002741 WatchDog::SetRuntime(runtime_.get());
2742
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002743 return true;
Vladimir Marko919f5532016-01-20 19:13:01 +00002744 }
2745
Jeff Haodcdc85b2015-12-04 14:06:18 -08002746 // Let the ImageWriter write the image files. If we do not compile PIC, also fix up the oat files.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002747 bool CreateImageFile()
Mathieu Chartier90443472015-07-16 20:32:27 -07002748 REQUIRES(!Locks::mutator_lock_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002749 CHECK(image_writer_ != nullptr);
Vladimir Markod0036ac2019-11-21 11:47:12 +00002750 if (IsAppImage()) {
2751 DCHECK(image_filenames_.empty());
2752 if (app_image_fd_ != -1) {
2753 image_filenames_.push_back(StringPrintf("FileDescriptor[%d]", app_image_fd_));
2754 } else {
2755 image_filenames_.push_back(app_image_file_name_);
2756 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002757 }
Vladimir Markod0036ac2019-11-21 11:47:12 +00002758 if (image_fd_ != -1) {
2759 DCHECK(image_filenames_.empty());
2760 image_filenames_.push_back(StringPrintf("FileDescriptor[%d]", image_fd_));
2761 }
2762 if (!image_writer_->Write(IsAppImage() ? app_image_fd_ : image_fd_,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002763 image_filenames_,
Vladimir Markod0036ac2019-11-21 11:47:12 +00002764 IsAppImage() ? 1u : dex_locations_.size())) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002765 LOG(ERROR) << "Failure during image file creation";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002766 return false;
2767 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002768
Jeff Haodcdc85b2015-12-04 14:06:18 -08002769 // We need the OatDataBegin entries.
Vladimir Marko944da602016-02-19 12:27:55 +00002770 dchecked_vector<uintptr_t> oat_data_begins;
2771 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
2772 oat_data_begins.push_back(image_writer_->GetOatDataBegin(i));
Jeff Haodcdc85b2015-12-04 14:06:18 -08002773 }
Vladimir Markoa2da9b92018-10-10 14:21:55 +01002774 // Destroy ImageWriter.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002775 image_writer_.reset();
2776
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002777 return true;
2778 }
2779
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002780 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
2781 // the given function.
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07002782 template <typename T>
Vladimir Marko54159c62018-06-20 14:30:08 +01002783 static std::unique_ptr<T> ReadCommentedInputFromFile(
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002784 const char* input_filename, std::function<std::string(const char*)>* process) {
Vladimir Marko50fe6dc2020-08-07 17:38:51 +01002785 std::ifstream input_file(input_filename, std::ifstream::in);
2786 if (!input_file.good()) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002787 LOG(ERROR) << "Failed to open input file " << input_filename;
2788 return nullptr;
2789 }
Vladimir Marko50fe6dc2020-08-07 17:38:51 +01002790 std::unique_ptr<T> result = ReadCommentedInputStream<T>(input_file, process);
2791 input_file.close();
Vladimir Marko54159c62018-06-20 14:30:08 +01002792 return result;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002793 }
2794
2795 // Read lines from the given file from the given zip file, dropping comments and empty lines.
2796 // Post-process each line with the given function.
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07002797 template <typename T>
Vladimir Marko54159c62018-06-20 14:30:08 +01002798 static std::unique_ptr<T> ReadCommentedInputFromZip(
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002799 const char* zip_filename,
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002800 const char* input_filename,
2801 std::function<std::string(const char*)>* process,
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002802 std::string* error_msg) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002803 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
2804 if (zip_archive.get() == nullptr) {
2805 return nullptr;
2806 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002807 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(input_filename, error_msg));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002808 if (zip_entry.get() == nullptr) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002809 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002810 zip_filename, error_msg->c_str());
2811 return nullptr;
2812 }
Vladimir Markoc34bebf2018-08-16 16:12:49 +01002813 MemMap input_file = zip_entry->ExtractToMemMap(zip_filename, input_filename, error_msg);
2814 if (!input_file.IsValid()) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002815 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002816 zip_filename, error_msg->c_str());
2817 return nullptr;
2818 }
Vladimir Markoc34bebf2018-08-16 16:12:49 +01002819 const std::string input_string(reinterpret_cast<char*>(input_file.Begin()), input_file.Size());
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002820 std::istringstream input_stream(input_string);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07002821 return ReadCommentedInputStream<T>(input_stream, process);
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002822 }
2823
2824 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
2825 // with the given function.
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07002826 template <typename T>
Vladimir Marko54159c62018-06-20 14:30:08 +01002827 static std::unique_ptr<T> ReadCommentedInputStream(
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002828 std::istream& in_stream,
2829 std::function<std::string(const char*)>* process) {
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07002830 std::unique_ptr<T> output(new T());
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002831 while (in_stream.good()) {
2832 std::string dot;
2833 std::getline(in_stream, dot);
Andreas Gampe9186ced2016-12-12 14:28:21 -08002834 if (android::base::StartsWith(dot, "#") || dot.empty()) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002835 continue;
2836 }
2837 if (process != nullptr) {
2838 std::string descriptor((*process)(dot.c_str()));
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07002839 output->insert(output->end(), descriptor);
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002840 } else {
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07002841 output->insert(output->end(), dot);
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002842 }
2843 }
Vladimir Marko54159c62018-06-20 14:30:08 +01002844 return output;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002845 }
2846
Mathieu Chartier49285c52014-12-02 15:43:48 -08002847 void LogCompletionTime() {
Andreas Gampe1d00add2015-02-27 19:35:46 -08002848 // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there
2849 // is no image, there won't be a Runtime::Current().
Brian Carlstroma11a34c2015-03-06 08:44:45 -08002850 // Note: driver creation can fail when loading an invalid dex file.
Andreas Gampec560fc02014-07-16 09:57:39 -07002851 LOG(INFO) << "dex2oat took "
2852 << PrettyDuration(NanoTime() - start_ns_)
Andreas Gampecc967752016-12-12 13:49:00 -08002853 << " (" << PrettyDuration(ProcessCpuNanoTime() - start_cputime_ns_) << " cpu)"
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002854 << " (threads: " << thread_count_ << ") "
Andreas Gampe3f30e122015-09-17 14:03:21 -07002855 << ((Runtime::Current() != nullptr && driver_ != nullptr) ?
Andreas Gampe1d00add2015-02-27 19:35:46 -08002856 driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) :
2857 "");
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002858 }
2859
Jeff Haodcdc85b2015-12-04 14:06:18 -08002860 std::string StripIsaFrom(const char* image_filename, InstructionSet isa) {
2861 std::string res(image_filename);
2862 size_t last_slash = res.rfind('/');
2863 if (last_slash == std::string::npos || last_slash == 0) {
2864 return res;
2865 }
2866 size_t penultimate_slash = res.rfind('/', last_slash - 1);
2867 if (penultimate_slash == std::string::npos) {
2868 return res;
2869 }
2870 // Check that the string in-between is the expected one.
2871 if (res.substr(penultimate_slash + 1, last_slash - penultimate_slash - 1) !=
2872 GetInstructionSetString(isa)) {
2873 LOG(WARNING) << "Unexpected string when trying to strip isa: " << res;
2874 return res;
2875 }
2876 return res.substr(0, penultimate_slash) + res.substr(last_slash);
2877 }
2878
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002879 std::unique_ptr<CompilerOptions> compiler_options_;
2880 Compiler::Kind compiler_kind_;
2881
Eric Holk94a810b2020-05-06 14:33:16 -07002882 std::unique_ptr<OatKeyValueStore> key_value_store_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002883
Vladimir Marko307dac92015-10-20 11:20:09 +01002884 std::unique_ptr<VerificationResults> verification_results_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002885
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002886 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
2887
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002888 std::unique_ptr<Runtime> runtime_;
2889
Calin Juravle1ce70852017-06-28 10:59:03 -07002890 // The spec describing how the class loader should be setup for compilation.
2891 std::unique_ptr<ClassLoaderContext> class_loader_context_;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08002892
David Brazdil89821862019-03-19 13:57:43 +00002893 // Optional list of file descriptors corresponding to dex file locations in
2894 // flattened `class_loader_context_`.
2895 std::vector<int> class_loader_context_fds_;
2896
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002897 // The class loader context stored in the oat file. May be equal to class_loader_context_.
Mathieu Chartierc4440772018-04-16 14:40:56 -07002898 std::unique_ptr<ClassLoaderContext> stored_class_loader_context_;
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07002899
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002900 size_t thread_count_;
Orion Hodsonffc791c2019-11-14 19:19:28 +00002901 std::vector<int32_t> cpu_set_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002902 uint64_t start_ns_;
Andreas Gampec560fc02014-07-16 09:57:39 -07002903 uint64_t start_cputime_ns_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002904 std::unique_ptr<WatchDog> watchdog_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002905 std::vector<std::unique_ptr<File>> oat_files_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002906 std::vector<std::unique_ptr<File>> vdex_files_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002907 std::string oat_location_;
Vladimir Markod011d812018-11-29 12:35:24 +00002908 std::vector<std::string> oat_filenames_;
2909 std::vector<std::string> oat_unstripped_;
David Srbeckyde91fd42018-07-05 22:27:08 +01002910 bool strip_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002911 int oat_fd_;
Nicolas Geoffraya6a448a2016-11-10 10:49:40 +00002912 int input_vdex_fd_;
2913 int output_vdex_fd_;
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00002914 std::string input_vdex_;
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +01002915 std::string output_vdex_;
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00002916 std::unique_ptr<VdexFile> input_vdex_file_;
Nicolas Geoffraybaeaa9b2018-01-26 14:31:17 +00002917 int dm_fd_;
2918 std::string dm_file_location_;
2919 std::unique_ptr<ZipArchive> dm_file_;
Vladimir Markod011d812018-11-29 12:35:24 +00002920 std::vector<std::string> dex_filenames_;
2921 std::vector<std::string> dex_locations_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002922 int zip_fd_;
2923 std::string zip_location_;
Vladimir Marko49b0f452015-12-10 13:49:19 +00002924 std::string boot_image_filename_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002925 std::vector<const char*> runtime_args_;
Vladimir Markod011d812018-11-29 12:35:24 +00002926 std::vector<std::string> image_filenames_;
Vladimir Markod0036ac2019-11-21 11:47:12 +00002927 int image_fd_;
2928 bool have_multi_image_arg_;
2929 bool multi_image_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002930 uintptr_t image_base_;
Mathieu Chartierceb07b32015-12-10 09:33:21 -08002931 ImageHeader::StorageMode image_storage_mode_;
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07002932 const char* passes_to_run_filename_;
Jeff Haoc23b0c02017-07-27 18:19:38 -07002933 const char* dirty_image_objects_filename_;
Vladimir Markod1f73512020-04-02 10:50:35 +01002934 const char* updatable_bcp_packages_filename_;
Vladimir Marko54159c62018-06-20 14:30:08 +01002935 std::unique_ptr<HashSet<std::string>> dirty_image_objects_;
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07002936 std::unique_ptr<std::vector<std::string>> passes_to_run_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002937 bool is_host_;
2938 std::string android_root_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002939 std::string no_inline_from_string_;
Alex Light4531afd2021-03-30 17:13:30 -07002940 bool force_allow_oj_inlines_ = false;
Mathieu Chartiera7f6b812017-12-11 13:34:29 -08002941 CompactDexLevel compact_dex_level_ = kDefaultCompactDexLevel;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002942
Vladimir Marko74527972016-11-29 15:57:32 +00002943 std::vector<std::unique_ptr<linker::ElfWriter>> elf_writers_;
2944 std::vector<std::unique_ptr<linker::OatWriter>> oat_writers_;
David Srbecky2faab002019-02-12 16:35:48 +00002945 std::vector<OutputStream*> rodata_;
2946 std::vector<std::unique_ptr<OutputStream>> vdex_out_;
Vladimir Marko74527972016-11-29 15:57:32 +00002947 std::unique_ptr<linker::ImageWriter> image_writer_;
Vladimir Marko307dac92015-10-20 11:20:09 +01002948 std::unique_ptr<CompilerDriver> driver_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002949
Vladimir Markoc34bebf2018-08-16 16:12:49 +01002950 std::vector<MemMap> opened_dex_files_maps_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002951 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
2952
Mathieu Chartierd1ab1bd2017-08-04 10:21:50 -07002953 bool avoid_storing_invocation_;
Alex Light62afcf52018-12-18 14:19:25 -08002954 android::base::unique_fd invocation_file_;
Andreas Gampee21dc3d2014-12-08 16:59:43 -08002955 std::string swap_file_name_;
2956 int swap_fd_;
Andreas Gampee1459ae2016-06-29 09:36:30 -07002957 size_t min_dex_files_for_swap_ = kDefaultMinDexFilesForSwap;
2958 size_t min_dex_file_cumulative_size_for_swap_ = kDefaultMinDexFileCumulativeSizeForSwap;
Andreas Gampe67f02822016-06-24 21:05:23 -07002959 size_t very_large_threshold_ = std::numeric_limits<size_t>::max();
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002960 std::string app_image_file_name_;
2961 int app_image_fd_;
Calin Juravle2e2db782016-02-23 12:00:03 +00002962 std::string profile_file_;
2963 int profile_file_fd_;
Calin Juravle998c2162015-12-21 15:39:33 +02002964 std::unique_ptr<ProfileCompilationInfo> profile_compilation_info_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002965 TimingLogger* timings_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002966 std::vector<std::vector<const DexFile*>> dex_files_per_oat_file_;
Vladimir Marko26de8962020-12-22 14:36:47 +00002967 HashMap<const DexFile*, size_t> dex_file_oat_index_map_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002968
2969 // Backing storage.
Andreas Gampe097f34c2017-08-23 08:57:51 -07002970 std::forward_list<std::string> char_backing_storage_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002971
Andreas Gampeace0dc12016-01-20 13:33:13 -08002972 // See CompilerOptions.force_determinism_.
2973 bool force_determinism_;
David Sehrfe57c2b2020-03-27 14:58:54 +00002974 // See CompilerOptions.crash_on_linkage_violation_.
2975 bool check_linkage_conditions_;
2976 // See CompilerOptions.crash_on_linkage_violation_.
2977 bool crash_on_linkage_violation_;
Andreas Gampeace0dc12016-01-20 13:33:13 -08002978
Jeff Hao16d48432017-04-05 17:05:46 -07002979 // Directory of relative classpaths.
2980 std::string classpath_dir_;
2981
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002982 // Whether the given input vdex is also the output.
2983 bool update_input_vdex_ = false;
2984
Nicolas Geoffray66ff8a82018-02-28 13:27:55 +00002985 // By default, copy the dex to the vdex file only if dex files are
2986 // compressed in APK.
Andreas Gampe15544172018-06-25 15:09:06 -07002987 linker::CopyOption copy_dex_files_ = linker::CopyOption::kOnlyIfCompressed;
Mathieu Chartier792111c2018-02-15 13:02:15 -08002988
Calin Juravle0e09dfc2018-02-12 19:01:09 -08002989 // The reason for invoking the compiler.
2990 std::string compilation_reason_;
2991
Eric Holkbc89ed42020-04-29 19:59:24 +00002992 // Whether to force individual compilation.
2993 bool compile_individually_;
2994
Calin Juravle33787682019-07-26 14:27:18 -07002995 // The classpath that determines if a given symbol should be resolved at compile time or not.
2996 std::string public_sdk_;
2997
Nicolas Geoffrayd3c45c22021-04-27 13:21:28 +01002998 // The apex versions of jars in the boot classpath. Set through command line
2999 // argument.
3000 std::string apex_versions_argument_;
3001
Calin Juravle32de2a52021-05-26 15:37:00 -07003002 // Whether or we attempted to load the profile (if given).
3003 bool profile_load_attempted_;
3004
Andreas Gampe88ec7f42014-11-05 10:18:32 -08003005 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
3006};
3007
Andreas Gampe88ec7f42014-11-05 10:18:32 -08003008static void b13564922() {
3009#if defined(__linux__) && defined(__arm__)
Lokesh Gidra58520df2020-05-13 17:08:43 +00003010 int major, minor;
3011 struct utsname uts;
3012 if (uname(&uts) != -1 &&
3013 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
3014 ((major < 3) || ((major == 3) && (minor < 4)))) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08003015 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
3016 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
3017 int old_personality = personality(0xffffffff);
3018 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
3019 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
3020 if (new_personality == -1) {
3021 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
3022 }
3023 }
3024 }
3025#endif
3026}
3027
Mathieu Chartier72041a02017-07-14 18:23:25 -07003028class ScopedGlobalRef {
3029 public:
3030 explicit ScopedGlobalRef(jobject obj) : obj_(obj) {}
3031 ~ScopedGlobalRef() {
3032 if (obj_ != nullptr) {
3033 ScopedObjectAccess soa(Thread::Current());
Ian Rogers55256cb2017-12-21 17:07:11 -08003034 soa.Env()->GetVm()->DeleteGlobalRef(soa.Self(), obj_);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003035 }
3036 }
3037
3038 private:
3039 jobject obj_;
3040};
3041
Nicolas Geoffray1ece2992021-01-06 17:02:04 +00003042static dex2oat::ReturnCode DoCompilation(Dex2Oat& dex2oat) {
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08003043 dex2oat.LoadClassProfileDescriptors();
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00003044 jobject class_loader = dex2oat.Compile();
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003045 // Keep the class loader that was used for compilation live for the rest of the compilation
3046 // process.
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00003047 ScopedGlobalRef global_ref(class_loader);
Andreas Gampe10e477d2014-11-19 12:57:42 -08003048
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00003049 if (!dex2oat.WriteOutputFiles(class_loader)) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01003050 dex2oat.EraseOutputFiles();
Andreas Gampe7b565912017-03-20 15:48:52 -07003051 return dex2oat::ReturnCode::kOther;
Andreas Gampe10e477d2014-11-19 12:57:42 -08003052 }
3053
Nicolas Geoffray1ece2992021-01-06 17:02:04 +00003054 // Flush output files. Keep them open as we might still modify them later (strip them).
David Srbeckyde91fd42018-07-05 22:27:08 +01003055 if (!dex2oat.FlushOutputFiles()) {
3056 dex2oat.EraseOutputFiles();
Andreas Gampe7b565912017-03-20 15:48:52 -07003057 return dex2oat::ReturnCode::kOther;
Andreas Gampe10e477d2014-11-19 12:57:42 -08003058 }
3059
Jeff Haodcdc85b2015-12-04 14:06:18 -08003060 // Creates the boot.art and patches the oat files.
Andreas Gampe10e477d2014-11-19 12:57:42 -08003061 if (!dex2oat.HandleImage()) {
Andreas Gampe7b565912017-03-20 15:48:52 -07003062 return dex2oat::ReturnCode::kOther;
Andreas Gampe10e477d2014-11-19 12:57:42 -08003063 }
3064
3065 // When given --host, finish early without stripping.
3066 if (dex2oat.IsHost()) {
Mathieu Chartier00bf2602017-03-02 10:14:08 -08003067 if (!dex2oat.FlushCloseOutputFiles()) {
Andreas Gampe7b565912017-03-20 15:48:52 -07003068 return dex2oat::ReturnCode::kOther;
Mathieu Chartier00bf2602017-03-02 10:14:08 -08003069 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08003070 dex2oat.DumpTiming();
Andreas Gampe7b565912017-03-20 15:48:52 -07003071 return dex2oat::ReturnCode::kNoFailure;
Andreas Gampe10e477d2014-11-19 12:57:42 -08003072 }
3073
Jeff Haodcdc85b2015-12-04 14:06:18 -08003074 // Copy stripped to unstripped location, if necessary. This will implicitly flush & close the
3075 // stripped versions. If this is given, we expect to be able to open writable files by name.
David Srbeckyde91fd42018-07-05 22:27:08 +01003076 if (!dex2oat.CopyOatFilesToSymbolsDirectoryAndStrip()) {
Andreas Gampe7b565912017-03-20 15:48:52 -07003077 return dex2oat::ReturnCode::kOther;
Andreas Gampe10e477d2014-11-19 12:57:42 -08003078 }
3079
Nicolas Geoffray1ece2992021-01-06 17:02:04 +00003080 // FlushClose again, as stripping might have re-opened the oat files.
David Brazdil7b49e6c2016-09-01 11:06:18 +01003081 if (!dex2oat.FlushCloseOutputFiles()) {
Andreas Gampe7b565912017-03-20 15:48:52 -07003082 return dex2oat::ReturnCode::kOther;
Andreas Gampe10e477d2014-11-19 12:57:42 -08003083 }
3084
3085 dex2oat.DumpTiming();
Andreas Gampe7b565912017-03-20 15:48:52 -07003086 return dex2oat::ReturnCode::kNoFailure;
Andreas Gampe10e477d2014-11-19 12:57:42 -08003087}
3088
Andreas Gampe7b565912017-03-20 15:48:52 -07003089static dex2oat::ReturnCode Dex2oat(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08003090 b13564922();
3091
3092 TimingLogger timings("compiler", false, false);
3093
Roland Levillain5c7e2602016-02-23 18:08:53 +00003094 // Allocate `dex2oat` on the heap instead of on the stack, as Clang
3095 // might produce a stack frame too large for this function or for
3096 // functions inlining it (such as main), that would not fit the
3097 // requirements of the `-Wframe-larger-than` option.
Andreas Gampe8bdda5a2017-06-08 15:30:36 -07003098 std::unique_ptr<Dex2Oat> dex2oat = std::make_unique<Dex2Oat>(&timings);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08003099
3100 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
Roland Levillain5c7e2602016-02-23 18:08:53 +00003101 dex2oat->ParseArgs(argc, argv);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08003102
Calin Juravle814a80f2019-06-26 15:01:10 -07003103 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap, vdex and profiles.
3104
Calin Juravleb077e152016-02-18 18:47:37 +00003105 // If needed, process profile information for profile guided compilation.
Calin Juravle998c2162015-12-21 15:39:33 +02003106 // This operation involves I/O.
Calin Juravle32de2a52021-05-26 15:37:00 -07003107 if (dex2oat->HasProfileInput()) {
Calin Juravleb077e152016-02-18 18:47:37 +00003108 if (!dex2oat->LoadProfile()) {
3109 LOG(ERROR) << "Failed to process profile file";
Andreas Gampe7b565912017-03-20 15:48:52 -07003110 return dex2oat::ReturnCode::kOther;
Calin Juravle998c2162015-12-21 15:39:33 +02003111 }
3112 }
3113
Calin Juravle32de2a52021-05-26 15:37:00 -07003114 // Check if we need to update any of the compiler options (such as the filter)
3115 // and do it before anything else (so that the other operations have a true
3116 // view of the state).
3117 dex2oat->UpdateCompilerOptionsBasedOnProfile();
3118
3119 // Insert the compiler options in the key value store.
3120 // We have to do this after we altered any incoming arguments
3121 // (such as the compiler filter).
3122 dex2oat->InsertCompileOptions(argc, argv);
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00003123
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003124 // Check early that the result of compilation can be written
Roland Levillain5c7e2602016-02-23 18:08:53 +00003125 if (!dex2oat->OpenFile()) {
Calin Juravle046cecf2020-12-07 18:31:28 -08003126 // Flush close so that the File Guard checks don't fail the assertions.
3127 dex2oat->FlushCloseOutputFiles();
Andreas Gampe7b565912017-03-20 15:48:52 -07003128 return dex2oat::ReturnCode::kOther;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003129 }
3130
Andreas Gampe046c7062015-05-18 23:22:54 -07003131 // Print the complete line when any of the following is true:
3132 // 1) Debug build
3133 // 2) Compiling an image
3134 // 3) Compiling with --host
3135 // 4) Compiling on the host (not a target build)
3136 // Otherwise, print a stripped command line.
Vladimir Marko21910692019-11-06 13:27:03 +00003137 if (kIsDebugBuild ||
3138 dex2oat->IsBootImage() || dex2oat->IsBootImageExtension() ||
3139 dex2oat->IsHost() ||
3140 !kIsTargetBuild) {
Andreas Gampe046c7062015-05-18 23:22:54 -07003141 LOG(INFO) << CommandLine();
3142 } else {
3143 LOG(INFO) << StrippedCommandLine();
3144 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08003145
Nicolas Geoffray1ece2992021-01-06 17:02:04 +00003146 Dex2Oat::ScopedDex2oatReporting sdr(*dex2oat.get());
3147
3148 if (sdr.ErrorReporting()) {
3149 dex2oat->EraseOutputFiles();
3150 return dex2oat::ReturnCode::kOther;
3151 }
3152
Andreas Gampef7882972017-03-20 16:35:24 -07003153 dex2oat::ReturnCode setup_code = dex2oat->Setup();
3154 if (setup_code != dex2oat::ReturnCode::kNoFailure) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01003155 dex2oat->EraseOutputFiles();
Andreas Gampef7882972017-03-20 16:35:24 -07003156 return setup_code;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08003157 }
3158
Shubham Ajmera188b2bf2017-09-20 15:53:35 -07003159 // TODO: Due to the cyclic dependencies, profile loading and verifying are
3160 // being done separately. Refactor and place the two next to each other.
3161 // If verification fails, we don't abort the compilation and instead log an
3162 // error.
3163 // TODO(b/62602192, b/65260586): We should consider aborting compilation when
3164 // the profile verification fails.
3165 // Note: If dex2oat fails, installd will remove the oat files causing the app
3166 // to fallback to apk with possible in-memory extraction. We want to avoid
3167 // that, and thus we're lenient towards profile corruptions.
Calin Juravle32de2a52021-05-26 15:37:00 -07003168 if (dex2oat->DoProfileGuidedOptimizations()) {
Shubham Ajmera188b2bf2017-09-20 15:53:35 -07003169 dex2oat->VerifyProfileData();
3170 }
3171
Wojciech Staszkiewicz529827d2016-09-15 10:30:30 -07003172 // Helps debugging on device. Can be used to determine which dalvikvm instance invoked a dex2oat
3173 // instance. Used by tools/bisection_search/bisection_search.py.
Wojciech Staszkiewicz0a4c75f2016-09-13 12:06:36 -07003174 VLOG(compiler) << "Running dex2oat (parent PID = " << getppid() << ")";
3175
Nicolas Geoffray1ece2992021-01-06 17:02:04 +00003176 dex2oat::ReturnCode result = DoCompilation(*dex2oat);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003177
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003178 return result;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08003179}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003180} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07003181
3182int main(int argc, char** argv) {
Andreas Gampe7b565912017-03-20 15:48:52 -07003183 int result = static_cast<int>(art::Dex2oat(argc, argv));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08003184 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
Roland Levillain05e34f42018-05-24 13:19:05 +00003185 // time (bug 10645725) unless we're a debug or instrumented build or running on a memory tool.
3186 // Note: The Dex2Oat class should not destruct the runtime in this case.
3187 if (!art::kIsDebugBuild && !art::kIsPGOInstrumentation && !art::kRunningOnMemoryTool) {
Roland Levillainc3854242021-05-06 00:19:19 +01003188 art::FastExit(result);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08003189 }
3190 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07003191}