1 /*
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
17 #include <inttypes.h>
18 #include <log/log.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <sys/stat.h>
22
23 #include <algorithm>
24 #include <forward_list>
25 #include <fstream>
26 #include <iostream>
27 #include <limits>
28 #include <memory>
29 #include <sstream>
30 #include <string>
31 #include <type_traits>
32 #include <vector>
33
34 #if defined(__linux__)
35 #include <sched.h>
36 #if defined(__arm__)
37 #include <sys/personality.h>
38 #include <sys/utsname.h>
39 #endif // __arm__
40 #endif
41
42 #include <android-base/parseint.h>
43 #include <android-base/properties.h>
44 #include <android-base/scopeguard.h>
45 #include <android-base/stringprintf.h>
46 #include <android-base/strings.h>
47 #include <android-base/unique_fd.h>
48
49 #include "aot_class_linker.h"
50 #include "arch/instruction_set_features.h"
51 #include "art_method-inl.h"
52 #include "base/callee_save_type.h"
53 #include "base/dumpable.h"
54 #include "base/fast_exit.h"
55 #include "base/file_utils.h"
56 #include "base/globals.h"
57 #include "base/leb128.h"
58 #include "base/macros.h"
59 #include "base/memory_tool.h"
60 #include "base/mutex.h"
61 #include "base/os.h"
62 #include "base/scoped_flock.h"
63 #include "base/stl_util.h"
64 #include "base/time_utils.h"
65 #include "base/timing_logger.h"
66 #include "base/unix_file/fd_file.h"
67 #include "base/utils.h"
68 #include "base/zip_archive.h"
69 #include "class_linker.h"
70 #include "class_loader_context.h"
71 #include "class_root-inl.h"
72 #include "cmdline_parser.h"
73 #include "compiler.h"
74 #include "compiler_callbacks.h"
75 #include "debug/elf_debug_writer.h"
76 #include "debug/method_debug_info.h"
77 #include "dex/descriptors_names.h"
78 #include "dex/dex_file-inl.h"
79 #include "dex/dex_file_loader.h"
80 #include "dex/quick_compiler_callbacks.h"
81 #include "dex/verification_results.h"
82 #include "dex2oat_options.h"
83 #include "driver/compiler_driver.h"
84 #include "driver/compiler_options.h"
85 #include "driver/compiler_options_map-inl.h"
86 #include "gc/space/image_space.h"
87 #include "gc/space/space-inl.h"
88 #include "gc/verification.h"
89 #include "interpreter/unstarted_runtime.h"
90 #include "jni/java_vm_ext.h"
91 #include "linker/elf_writer.h"
92 #include "linker/elf_writer_quick.h"
93 #include "linker/image_writer.h"
94 #include "linker/multi_oat_relative_patcher.h"
95 #include "linker/oat_writer.h"
96 #include "mirror/class-alloc-inl.h"
97 #include "mirror/class_loader.h"
98 #include "mirror/object-inl.h"
99 #include "mirror/object_array-inl.h"
100 #include "oat/elf_file.h"
101 #include "oat/oat.h"
102 #include "oat/oat_file.h"
103 #include "oat/oat_file_assistant.h"
104 #include "palette/palette.h"
105 #include "profile/profile_compilation_info.h"
106 #include "runtime.h"
107 #include "runtime_intrinsics.h"
108 #include "runtime_options.h"
109 #include "scoped_thread_state_change-inl.h"
110 #include "stream/buffered_output_stream.h"
111 #include "stream/file_output_stream.h"
112 #include "vdex_file.h"
113 #include "verifier/verifier_deps.h"
114
115 namespace art {
116
117 namespace dex2oat {
118 enum class ReturnCode : int {
119 kNoFailure = 0, // No failure, execution completed successfully.
120 kOther = 1, // Some other not closer specified error occurred.
121 kCreateRuntime = 2, // Dex2oat failed creating a runtime.
122 };
123 } // namespace dex2oat
124
125 using android::base::StringAppendV;
126 using android::base::StringPrintf;
127 using gc::space::ImageSpace;
128
129 static constexpr size_t kDefaultMinDexFilesForSwap = 2;
130 static constexpr size_t kDefaultMinDexFileCumulativeSizeForSwap = 20 * MB;
131
132 // Compiler filter override for very large apps.
133 static constexpr CompilerFilter::Filter kLargeAppFilter = CompilerFilter::kVerify;
134
135 static int original_argc;
136 static char** original_argv;
137
CommandLine()138 static std::string CommandLine() {
139 std::vector<std::string> command;
140 command.reserve(original_argc);
141 for (int i = 0; i < original_argc; ++i) {
142 command.push_back(original_argv[i]);
143 }
144 return android::base::Join(command, ' ');
145 }
146
147 // A stripped version. Remove some less essential parameters. If we see a "--zip-fd=" parameter, be
148 // even more aggressive. There won't be much reasonable data here for us in that case anyways (the
149 // locations are all staged).
StrippedCommandLine()150 static std::string StrippedCommandLine() {
151 std::vector<std::string> command;
152
153 // Do a pre-pass to look for zip-fd and the compiler filter.
154 bool saw_zip_fd = false;
155 bool saw_compiler_filter = false;
156 for (int i = 0; i < original_argc; ++i) {
157 std::string_view arg(original_argv[i]);
158 if (arg.starts_with("--zip-fd=")) {
159 saw_zip_fd = true;
160 }
161 if (arg.starts_with("--compiler-filter=")) {
162 saw_compiler_filter = true;
163 }
164 }
165
166 // Now filter out things.
167 for (int i = 0; i < original_argc; ++i) {
168 std::string_view arg(original_argv[i]);
169 // All runtime-arg parameters are dropped.
170 if (arg == "--runtime-arg") {
171 i++; // Drop the next part, too.
172 continue;
173 }
174
175 // Any instruction-setXXX is dropped.
176 if (arg.starts_with("--instruction-set")) {
177 continue;
178 }
179
180 // The boot image is dropped.
181 if (arg.starts_with("--boot-image=")) {
182 continue;
183 }
184
185 // The image format is dropped.
186 if (arg.starts_with("--image-format=")) {
187 continue;
188 }
189
190 // This should leave any dex-file and oat-file options, describing what we compiled.
191
192 // However, we prefer to drop this when we saw --zip-fd.
193 if (saw_zip_fd) {
194 // Drop anything --zip-X, --dex-X, --oat-X, --swap-X, or --app-image-X
195 if (arg.starts_with("--zip-") ||
196 arg.starts_with("--dex-") ||
197 arg.starts_with("--oat-") ||
198 arg.starts_with("--swap-") ||
199 arg.starts_with("--app-image-")) {
200 continue;
201 }
202 }
203
204 command.push_back(std::string(arg));
205 }
206
207 if (!saw_compiler_filter) {
208 command.push_back("--compiler-filter=" +
209 CompilerFilter::NameOfFilter(CompilerFilter::kDefaultCompilerFilter));
210 }
211
212 // Construct the final output.
213 if (command.size() <= 1U) {
214 // It seems only "/apex/com.android.art/bin/dex2oat" is left, or not
215 // even that. Use a pretty line.
216 return "Starting dex2oat.";
217 }
218 return android::base::Join(command, ' ');
219 }
220
UsageErrorV(const char * fmt,va_list ap)221 static void UsageErrorV(const char* fmt, va_list ap) {
222 std::string error;
223 StringAppendV(&error, fmt, ap);
224 LOG(ERROR) << error;
225 }
226
UsageError(const char * fmt,...)227 static void UsageError(const char* fmt, ...) {
228 va_list ap;
229 va_start(ap, fmt);
230 UsageErrorV(fmt, ap);
231 va_end(ap);
232 }
233
Usage(const char * fmt,...)234 NO_RETURN static void Usage(const char* fmt, ...) {
235 va_list ap;
236 va_start(ap, fmt);
237 UsageErrorV(fmt, ap);
238 va_end(ap);
239
240 UsageError("Command: %s", CommandLine().c_str());
241
242 UsageError("Usage: dex2oat [options]...");
243 UsageError("");
244
245 std::stringstream oss;
246 VariableIndentationOutputStream vios(&oss);
247 auto parser = CreateDex2oatArgumentParser();
248 parser.DumpHelp(vios);
249 UsageError(oss.str().c_str());
250 std::cerr << "See log for usage error information\n";
251 exit(EXIT_FAILURE);
252 }
253
254
255 // Set CPU affinity from a string containing a comma-separated list of numeric CPU identifiers.
SetCpuAffinity(const std::vector<int32_t> & cpu_list)256 static void SetCpuAffinity(const std::vector<int32_t>& cpu_list) {
257 #ifdef __linux__
258 int cpu_count = sysconf(_SC_NPROCESSORS_CONF);
259 cpu_set_t target_cpu_set;
260 CPU_ZERO(&target_cpu_set);
261
262 for (int32_t cpu : cpu_list) {
263 if (cpu >= 0 && cpu < cpu_count) {
264 CPU_SET(cpu, &target_cpu_set);
265 } else {
266 // Argument error is considered fatal, suggests misconfigured system properties.
267 Usage("Invalid cpu \"d\" specified in --cpu-set argument (nprocessors = %d)",
268 cpu, cpu_count);
269 }
270 }
271
272 if (sched_setaffinity(getpid(), sizeof(target_cpu_set), &target_cpu_set) == -1) {
273 // Failure to set affinity may be outside control of requestor, log warning rather than
274 // treating as fatal.
275 PLOG(WARNING) << "Failed to set CPU affinity.";
276 }
277 #else
278 LOG(WARNING) << "--cpu-set not supported on this platform.";
279 #endif // __linux__
280 }
281
282
283
284 // The primary goal of the watchdog is to prevent stuck build servers
285 // during development when fatal aborts lead to a cascade of failures
286 // that result in a deadlock.
287 class WatchDog {
288 // WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks
289 #undef CHECK_PTHREAD_CALL
290 #define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
291 do { \
292 int rc = call args; \
293 if (rc != 0) { \
294 errno = rc; \
295 std::string message(# call); \
296 message += " failed for "; \
297 message += reason; \
298 Fatal(message); \
299 } \
300 } while (false)
301
302 public:
WatchDog(int64_t timeout_in_milliseconds)303 explicit WatchDog(int64_t timeout_in_milliseconds)
304 : timeout_in_milliseconds_(timeout_in_milliseconds),
305 shutting_down_(false) {
306 const char* reason = "dex2oat watch dog thread startup";
307 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
308 #ifndef __APPLE__
309 pthread_condattr_t condattr;
310 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_condattr_init, (&condattr), reason);
311 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_condattr_setclock, (&condattr, CLOCK_MONOTONIC), reason);
312 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, &condattr), reason);
313 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_condattr_destroy, (&condattr), reason);
314 #endif
315 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
316 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
317 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
318 }
~WatchDog()319 ~WatchDog() {
320 const char* reason = "dex2oat watch dog thread shutdown";
321 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
322 shutting_down_ = true;
323 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
324 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
325
326 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
327
328 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
329 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
330 }
331
SetRuntime(Runtime * runtime)332 static void SetRuntime(Runtime* runtime) {
333 const char* reason = "dex2oat watch dog set runtime";
334 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&runtime_mutex_), reason);
335 runtime_ = runtime;
336 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&runtime_mutex_), reason);
337 }
338
339 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
340 // large.
341 static constexpr int64_t kWatchdogVerifyMultiplier =
342 kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
343
344 // When setting timeouts, keep in mind that the build server may not be as fast as your
345 // desktop. Debug builds are slower so they have larger timeouts.
346 static constexpr int64_t kWatchdogSlowdownFactor = kIsDebugBuild ? 5U : 1U;
347
348 // 9.5 minutes scaled by kSlowdownFactor. This is slightly smaller than the Package Manager
349 // watchdog (PackageManagerService.WATCHDOG_TIMEOUT, 10 minutes), so that dex2oat will abort
350 // itself before that watchdog would take down the system server.
351 static constexpr int64_t kWatchDogTimeoutSeconds = kWatchdogSlowdownFactor * (9 * 60 + 30);
352
353 static constexpr int64_t kDefaultWatchdogTimeoutInMS =
354 kWatchdogVerifyMultiplier * kWatchDogTimeoutSeconds * 1000;
355
356 private:
CallBack(void * arg)357 static void* CallBack(void* arg) {
358 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
359 ::art::SetThreadName("dex2oat watch dog");
360 self->Wait();
361 return nullptr;
362 }
363
Fatal(const std::string & message)364 NO_RETURN static void Fatal(const std::string& message) {
365 // TODO: When we can guarantee it won't prevent shutdown in error cases, move to LOG. However,
366 // it's rather easy to hang in unwinding.
367 // LogLine also avoids ART logging lock issues, as it's really only a wrapper around
368 // logcat logging or stderr output.
369 LogHelper::LogLineLowStack(__FILE__, __LINE__, LogSeverity::FATAL, message.c_str());
370
371 // If we're on the host, try to dump all threads to get a sense of what's going on. This is
372 // restricted to the host as the dump may itself go bad.
373 // TODO: Use a double watchdog timeout, so we can enable this on-device.
374 Runtime* runtime = GetRuntime();
375 if (!kIsTargetBuild && runtime != nullptr) {
376 runtime->AttachCurrentThread("Watchdog thread attached for dumping",
377 true,
378 nullptr,
379 false);
380 runtime->DumpForSigQuit(std::cerr);
381 }
382 exit(static_cast<int>(dex2oat::ReturnCode::kOther));
383 }
384
Wait()385 void Wait() {
386 timespec timeout_ts;
387 #if defined(__APPLE__)
388 InitTimeSpec(true, CLOCK_REALTIME, timeout_in_milliseconds_, 0, &timeout_ts);
389 #else
390 InitTimeSpec(true, CLOCK_MONOTONIC, timeout_in_milliseconds_, 0, &timeout_ts);
391 #endif
392 const char* reason = "dex2oat watch dog thread waiting";
393 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
394 while (!shutting_down_) {
395 int rc = pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts);
396 if (rc == EINTR) {
397 continue;
398 } else if (rc == ETIMEDOUT) {
399 Fatal(StringPrintf("dex2oat did not finish after %" PRId64 " milliseconds",
400 timeout_in_milliseconds_));
401 } else if (rc != 0) {
402 std::string message(StringPrintf("pthread_cond_timedwait failed: %s", strerror(rc)));
403 Fatal(message);
404 }
405 }
406 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
407 }
408
GetRuntime()409 static Runtime* GetRuntime() {
410 const char* reason = "dex2oat watch dog get runtime";
411 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&runtime_mutex_), reason);
412 Runtime* runtime = runtime_;
413 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&runtime_mutex_), reason);
414 return runtime;
415 }
416
417 static pthread_mutex_t runtime_mutex_;
418 static Runtime* runtime_;
419
420 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
421 pthread_mutex_t mutex_;
422 pthread_cond_t cond_;
423 pthread_attr_t attr_;
424 pthread_t pthread_;
425
426 const int64_t timeout_in_milliseconds_;
427 bool shutting_down_;
428 };
429
430 pthread_mutex_t WatchDog::runtime_mutex_ = PTHREAD_MUTEX_INITIALIZER;
431 Runtime* WatchDog::runtime_ = nullptr;
432
433 // Helper class for overriding `java.lang.ThreadLocal.nextHashCode`.
434 //
435 // The class ThreadLocal has a static field nextHashCode used for assigning hash codes to
436 // new ThreadLocal objects. Since the class and the object referenced by the field are
437 // in the boot image, they cannot be modified under normal rules for AOT compilation.
438 // However, since this is a private detail that's used only for assigning hash codes and
439 // everything should work fine with different hash codes, we override the field for the
440 // compilation, providing another object that the AOT class initialization can modify.
441 class ThreadLocalHashOverride {
442 public:
ThreadLocalHashOverride(bool apply,int32_t initial_value)443 ThreadLocalHashOverride(bool apply, int32_t initial_value) {
444 Thread* self = Thread::Current();
445 ScopedObjectAccess soa(self);
446 hs_.emplace(self); // While holding the mutator lock.
447 Runtime* runtime = Runtime::Current();
448 klass_ = hs_->NewHandle(apply
449 ? runtime->GetClassLinker()->LookupClass(self,
450 "Ljava/lang/ThreadLocal;",
451 /*class_loader=*/ nullptr)
452 : nullptr);
453 field_ = ((klass_ != nullptr) && klass_->IsVisiblyInitialized())
454 ? klass_->FindDeclaredStaticField("nextHashCode",
455 "Ljava/util/concurrent/atomic/AtomicInteger;")
456 : nullptr;
457 old_field_value_ =
458 hs_->NewHandle(field_ != nullptr ? field_->GetObject(klass_.Get()) : nullptr);
459 if (old_field_value_ != nullptr) {
460 gc::AllocatorType allocator_type = runtime->GetHeap()->GetCurrentAllocator();
461 StackHandleScope<1u> hs2(self);
462 Handle<mirror::Object> new_field_value = hs2.NewHandle(
463 old_field_value_->GetClass()->Alloc(self, allocator_type));
464 PointerSize pointer_size = runtime->GetClassLinker()->GetImagePointerSize();
465 ArtMethod* constructor = old_field_value_->GetClass()->FindConstructor("(I)V", pointer_size);
466 CHECK(constructor != nullptr);
467 uint32_t args[] = {
468 reinterpret_cast32<uint32_t>(new_field_value.Get()),
469 static_cast<uint32_t>(initial_value)
470 };
471 JValue result;
472 constructor->Invoke(self, args, sizeof(args), &result, /*shorty=*/ "VI");
473 CHECK(!self->IsExceptionPending());
474 field_->SetObject</*kTransactionActive=*/ false>(klass_.Get(), new_field_value.Get());
475 }
476 if (apply && old_field_value_ == nullptr) {
477 if ((klass_ != nullptr) && klass_->IsVisiblyInitialized()) {
478 // This would mean that the implementation of ThreadLocal has changed
479 // and the code above is no longer applicable.
480 LOG(ERROR) << "Failed to override ThreadLocal.nextHashCode";
481 } else {
482 VLOG(compiler) << "ThreadLocal is not initialized in the primary boot image.";
483 }
484 }
485 }
486
~ThreadLocalHashOverride()487 ~ThreadLocalHashOverride() {
488 ScopedObjectAccess soa(hs_->Self());
489 if (old_field_value_ != nullptr) {
490 // Allow the overriding object to be collected.
491 field_->SetObject</*kTransactionActive=*/ false>(klass_.Get(), old_field_value_.Get());
492 }
493 hs_.reset(); // While holding the mutator lock.
494 }
495
496 private:
497 std::optional<StackHandleScope<2u>> hs_;
498 Handle<mirror::Class> klass_;
499 ArtField* field_;
500 Handle<mirror::Object> old_field_value_;
501 };
502
503 class OatKeyValueStore : public SafeMap<std::string, std::string> {
504 public:
505 using SafeMap::Put;
506
Put(const std::string & k,bool v)507 iterator Put(const std::string& k, bool v) {
508 return SafeMap::Put(k, v ? OatHeader::kTrueValue : OatHeader::kFalseValue);
509 }
510 };
511
512 class Dex2Oat final {
513 public:
Dex2Oat(TimingLogger * timings)514 explicit Dex2Oat(TimingLogger* timings)
515 : key_value_store_(nullptr),
516 verification_results_(nullptr),
517 runtime_(nullptr),
518 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
519 start_ns_(NanoTime()),
520 start_cputime_ns_(ProcessCpuNanoTime()),
521 strip_(false),
522 oat_fd_(-1),
523 input_vdex_fd_(-1),
524 output_vdex_fd_(-1),
525 input_vdex_file_(nullptr),
526 dm_fd_(-1),
527 zip_fd_(-1),
528 image_fd_(-1),
529 have_multi_image_arg_(false),
530 image_base_(0U),
531 image_storage_mode_(ImageHeader::kStorageModeUncompressed),
532 passes_to_run_filename_(nullptr),
533 is_host_(false),
534 elf_writers_(),
535 oat_writers_(),
536 rodata_(),
537 image_writer_(nullptr),
538 driver_(nullptr),
539 opened_dex_files_maps_(),
540 opened_dex_files_(),
541 avoid_storing_invocation_(false),
542 swap_fd_(File::kInvalidFd),
543 app_image_fd_(File::kInvalidFd),
544 timings_(timings),
545 force_determinism_(false),
546 check_linkage_conditions_(false),
547 crash_on_linkage_violation_(false),
548 compile_individually_(false),
549 profile_load_attempted_(false),
550 should_report_dex2oat_compilation_(false) {}
551
~Dex2Oat()552 ~Dex2Oat() {
553 // Log completion time before deleting the runtime_, because this accesses
554 // the runtime.
555 LogCompletionTime();
556
557 if (!kIsDebugBuild && !(kRunningOnMemoryTool && kMemoryToolDetectsLeaks)) {
558 // We want to just exit on non-debug builds, not bringing the runtime down
559 // in an orderly fashion. So release the following fields.
560 if (!compiler_options_->GetDumpStats()) {
561 // The --dump-stats get logged when the optimizing compiler gets destroyed, so we can't
562 // release the driver_.
563 driver_.release(); // NOLINT
564 }
565 image_writer_.release(); // NOLINT
566 for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files_) {
567 dex_file.release(); // NOLINT
568 }
569 new std::vector<MemMap>(std::move(opened_dex_files_maps_)); // Leak MemMaps.
570 for (std::unique_ptr<File>& vdex_file : vdex_files_) {
571 vdex_file.release(); // NOLINT
572 }
573 for (std::unique_ptr<File>& oat_file : oat_files_) {
574 oat_file.release(); // NOLINT
575 }
576 runtime_.release(); // NOLINT
577 verification_results_.release(); // NOLINT
578 key_value_store_.release(); // NOLINT
579 }
580
581 // Remind the user if they passed testing only flags.
582 if (!kIsTargetBuild && force_allow_oj_inlines_) {
583 LOG(ERROR) << "Inlines allowed from core-oj! FOR TESTING USE ONLY! DO NOT DISTRIBUTE"
584 << " BINARIES BUILT WITH THIS OPTION!";
585 }
586 }
587
588 struct ParserOptions {
589 std::vector<std::string> oat_symbols;
590 std::string boot_image_filename;
591 int64_t watch_dog_timeout_in_ms = -1;
592 bool watch_dog_enabled = true;
593 bool requested_specific_compiler = false;
594 std::string error_msg;
595 };
596
ParseBase(const std::string & option)597 void ParseBase(const std::string& option) {
598 char* end;
599 image_base_ = strtoul(option.c_str(), &end, 16);
600 if (end == option.c_str() || *end != '\0') {
601 Usage("Failed to parse hexadecimal value for option %s", option.data());
602 }
603 }
604
VerifyProfileData()605 bool VerifyProfileData() {
606 return profile_compilation_info_->VerifyProfileData(compiler_options_->dex_files_for_oat_file_);
607 }
608
ParseInstructionSetVariant(const std::string & option,ParserOptions * parser_options)609 void ParseInstructionSetVariant(const std::string& option, ParserOptions* parser_options) {
610 if (kIsTargetBuild) {
611 compiler_options_->instruction_set_features_ = InstructionSetFeatures::FromVariantAndHwcap(
612 compiler_options_->instruction_set_, option, &parser_options->error_msg);
613 } else {
614 compiler_options_->instruction_set_features_ = InstructionSetFeatures::FromVariant(
615 compiler_options_->instruction_set_, option, &parser_options->error_msg);
616 }
617 if (compiler_options_->instruction_set_features_ == nullptr) {
618 Usage("%s", parser_options->error_msg.c_str());
619 }
620 }
621
ParseInstructionSetFeatures(const std::string & option,ParserOptions * parser_options)622 void ParseInstructionSetFeatures(const std::string& option, ParserOptions* parser_options) {
623 if (compiler_options_->instruction_set_features_ == nullptr) {
624 compiler_options_->instruction_set_features_ = InstructionSetFeatures::FromVariant(
625 compiler_options_->instruction_set_, "default", &parser_options->error_msg);
626 if (compiler_options_->instruction_set_features_ == nullptr) {
627 Usage("Problem initializing default instruction set features variant: %s",
628 parser_options->error_msg.c_str());
629 }
630 }
631 compiler_options_->instruction_set_features_ =
632 compiler_options_->instruction_set_features_->AddFeaturesFromString(
633 option, &parser_options->error_msg);
634 if (compiler_options_->instruction_set_features_ == nullptr) {
635 Usage("Error parsing '%s': %s", option.c_str(), parser_options->error_msg.c_str());
636 }
637 }
638
ProcessOptions(ParserOptions * parser_options)639 void ProcessOptions(ParserOptions* parser_options) {
640 compiler_options_->compiler_type_ = CompilerOptions::CompilerType::kAotCompiler;
641 compiler_options_->compile_pic_ = true; // All AOT compilation is PIC.
642
643 // TODO: This should be a command line option for cross-compilation. b/289805127
644 compiler_options_->emit_read_barrier_ = gUseReadBarrier;
645
646 if (android_root_.empty()) {
647 const char* android_root_env_var = getenv("ANDROID_ROOT");
648 if (android_root_env_var == nullptr) {
649 Usage("--android-root unspecified and ANDROID_ROOT not set");
650 }
651 android_root_ += android_root_env_var;
652 }
653
654 if (!parser_options->boot_image_filename.empty()) {
655 boot_image_filename_ = parser_options->boot_image_filename;
656 }
657
658 DCHECK(compiler_options_->image_type_ == CompilerOptions::ImageType::kNone);
659 if (!image_filenames_.empty() || image_fd_ != -1) {
660 // If no boot image is provided, then dex2oat is compiling the primary boot image,
661 // otherwise it is compiling the boot image extension.
662 compiler_options_->image_type_ = boot_image_filename_.empty()
663 ? CompilerOptions::ImageType::kBootImage
664 : CompilerOptions::ImageType::kBootImageExtension;
665 }
666 if (app_image_fd_ != -1 || !app_image_file_name_.empty()) {
667 if (compiler_options_->IsBootImage() || compiler_options_->IsBootImageExtension()) {
668 Usage("Can't have both (--image or --image-fd) and (--app-image-fd or --app-image-file)");
669 }
670 if (profile_files_.empty() && profile_file_fds_.empty()) {
671 LOG(WARNING) << "Generating an app image without a profile. This will result in an app "
672 "image with no classes. Did you forget to add the profile with either "
673 "--profile-file-fd or --profile-file?";
674 }
675 compiler_options_->image_type_ = CompilerOptions::ImageType::kAppImage;
676 }
677
678 if (!image_filenames_.empty() && image_fd_ != -1) {
679 Usage("Can't have both --image and --image-fd");
680 }
681
682 if (oat_filenames_.empty() && oat_fd_ == -1) {
683 Usage("Output must be supplied with either --oat-file or --oat-fd");
684 }
685
686 if (input_vdex_fd_ != -1 && !input_vdex_.empty()) {
687 Usage("Can't have both --input-vdex-fd and --input-vdex");
688 }
689
690 if (output_vdex_fd_ != -1 && !output_vdex_.empty()) {
691 Usage("Can't have both --output-vdex-fd and --output-vdex");
692 }
693
694 if (!oat_filenames_.empty() && oat_fd_ != -1) {
695 Usage("--oat-file should not be used with --oat-fd");
696 }
697
698 if ((output_vdex_fd_ == -1) != (oat_fd_ == -1)) {
699 Usage("VDEX and OAT output must be specified either with one --oat-file "
700 "or with --oat-fd and --output-vdex-fd file descriptors");
701 }
702
703 if ((image_fd_ != -1) && (oat_fd_ == -1)) {
704 Usage("--image-fd must be used with --oat_fd and --output_vdex_fd");
705 }
706
707 if (!parser_options->oat_symbols.empty() && oat_fd_ != -1) {
708 Usage("--oat-symbols should not be used with --oat-fd");
709 }
710
711 if (!parser_options->oat_symbols.empty() && is_host_) {
712 Usage("--oat-symbols should not be used with --host");
713 }
714
715 if (output_vdex_fd_ != -1 && !image_filenames_.empty()) {
716 Usage("--output-vdex-fd should not be used with --image");
717 }
718
719 if (oat_fd_ != -1 && !image_filenames_.empty()) {
720 Usage("--oat-fd should not be used with --image");
721 }
722
723 if (!parser_options->oat_symbols.empty() &&
724 parser_options->oat_symbols.size() != oat_filenames_.size()) {
725 Usage("--oat-file arguments do not match --oat-symbols arguments");
726 }
727
728 if (!image_filenames_.empty() && image_filenames_.size() != oat_filenames_.size()) {
729 Usage("--oat-file arguments do not match --image arguments");
730 }
731
732 if (!IsBootImage() && boot_image_filename_.empty()) {
733 DCHECK(!IsBootImageExtension());
734 if (std::any_of(runtime_args_.begin(), runtime_args_.end(), [](std::string_view arg) {
735 return arg.starts_with("-Xbootclasspath:");
736 })) {
737 LOG(WARNING) << "--boot-image is not specified while -Xbootclasspath is specified. Running "
738 "dex2oat in imageless mode";
739 } else {
740 boot_image_filename_ =
741 GetDefaultBootImageLocation(android_root_, /*deny_art_apex_data_files=*/false);
742 }
743 }
744
745 if (dex_filenames_.empty() && zip_fd_ == -1) {
746 Usage("Input must be supplied with either --dex-file or --zip-fd");
747 }
748
749 if (!dex_filenames_.empty() && zip_fd_ != -1) {
750 Usage("--dex-file should not be used with --zip-fd");
751 }
752
753 if (!dex_filenames_.empty() && !zip_location_.empty()) {
754 Usage("--dex-file should not be used with --zip-location");
755 }
756
757 if (dex_locations_.empty()) {
758 dex_locations_ = dex_filenames_;
759 } else if (dex_locations_.size() != dex_filenames_.size()) {
760 Usage("--dex-location arguments do not match --dex-file arguments");
761 }
762
763 if (!dex_filenames_.empty() && !oat_filenames_.empty()) {
764 if (oat_filenames_.size() != 1 && oat_filenames_.size() != dex_filenames_.size()) {
765 Usage("--oat-file arguments must be singular or match --dex-file arguments");
766 }
767 }
768
769 if (!dex_fds_.empty() && dex_fds_.size() != dex_filenames_.size()) {
770 Usage("--dex-fd arguments do not match --dex-file arguments");
771 }
772
773 if (zip_fd_ != -1 && zip_location_.empty()) {
774 Usage("--zip-location should be supplied with --zip-fd");
775 }
776
777 if (boot_image_filename_.empty()) {
778 if (image_base_ == 0) {
779 Usage("Non-zero --base not specified for boot image");
780 }
781 } else {
782 if (image_base_ != 0) {
783 Usage("Non-zero --base specified for app image or boot image extension");
784 }
785 }
786
787 if (have_multi_image_arg_) {
788 if (!IsImage()) {
789 Usage("--multi-image or --single-image specified for non-image compilation");
790 }
791 } else {
792 // Use the default, i.e. multi-image for boot image and boot image extension.
793 // This shall pass the checks below.
794 compiler_options_->multi_image_ = IsBootImage() || IsBootImageExtension();
795 }
796 // On target we support generating a single image for the primary boot image.
797 if (!kIsTargetBuild && !force_allow_oj_inlines_) {
798 if (IsBootImage() && !compiler_options_->multi_image_) {
799 Usage(
800 "--single-image specified for primary boot image on host. Please "
801 "use the flag --force-allow-oj-inlines and do not distribute "
802 "binaries.");
803 }
804 }
805 if (IsAppImage() && compiler_options_->multi_image_) {
806 Usage("--multi-image specified for app image");
807 }
808
809 if (image_fd_ != -1 && compiler_options_->multi_image_) {
810 Usage("--single-image not specified for --image-fd");
811 }
812
813 const bool have_profile_file = !profile_files_.empty();
814 const bool have_profile_fd = !profile_file_fds_.empty();
815 if (have_profile_file && have_profile_fd) {
816 Usage("Profile files should not be specified with both --profile-file-fd and --profile-file");
817 }
818
819 if (!parser_options->oat_symbols.empty()) {
820 oat_unstripped_ = std::move(parser_options->oat_symbols);
821 }
822
823 if (compiler_options_->instruction_set_features_ == nullptr) {
824 // '--instruction-set-features/--instruction-set-variant' were not used.
825 // Use features for the 'default' variant.
826 compiler_options_->instruction_set_features_ = InstructionSetFeatures::FromVariant(
827 compiler_options_->instruction_set_, "default", &parser_options->error_msg);
828 if (compiler_options_->instruction_set_features_ == nullptr) {
829 Usage("Problem initializing default instruction set features variant: %s",
830 parser_options->error_msg.c_str());
831 }
832 }
833
834 if (compiler_options_->instruction_set_ == kRuntimeISA) {
835 std::unique_ptr<const InstructionSetFeatures> runtime_features(
836 InstructionSetFeatures::FromCppDefines());
837 if (!compiler_options_->GetInstructionSetFeatures()->Equals(runtime_features.get())) {
838 LOG(WARNING) << "Mismatch between dex2oat instruction set features to use ("
839 << *compiler_options_->GetInstructionSetFeatures()
840 << ") and those from CPP defines (" << *runtime_features
841 << ") for the command line:\n" << CommandLine();
842 }
843 }
844
845 if (!dirty_image_objects_filenames_.empty() && !dirty_image_objects_fds_.empty()) {
846 Usage("--dirty-image-objects and --dirty-image-objects-fd should not be both specified");
847 }
848
849 if (!preloaded_classes_files_.empty() && !preloaded_classes_fds_.empty()) {
850 Usage("--preloaded-classes and --preloaded-classes-fds should not be both specified");
851 }
852
853 if (!cpu_set_.empty()) {
854 SetCpuAffinity(cpu_set_);
855 }
856
857 if (compiler_options_->inline_max_code_units_ == CompilerOptions::kUnsetInlineMaxCodeUnits) {
858 compiler_options_->inline_max_code_units_ = CompilerOptions::kDefaultInlineMaxCodeUnits;
859 }
860
861 // Checks are all explicit until we know the architecture.
862 // Set the compilation target's implicit checks options.
863 switch (compiler_options_->GetInstructionSet()) {
864 case InstructionSet::kArm64:
865 compiler_options_->implicit_suspend_checks_ = true;
866 FALLTHROUGH_INTENDED;
867 case InstructionSet::kArm:
868 case InstructionSet::kThumb2:
869 case InstructionSet::kRiscv64:
870 case InstructionSet::kX86:
871 case InstructionSet::kX86_64:
872 compiler_options_->implicit_null_checks_ = true;
873 compiler_options_->implicit_so_checks_ = true;
874 break;
875
876 default:
877 // Defaults are correct.
878 break;
879 }
880
881 // Done with usage checks, enable watchdog if requested
882 if (parser_options->watch_dog_enabled) {
883 int64_t timeout = parser_options->watch_dog_timeout_in_ms > 0
884 ? parser_options->watch_dog_timeout_in_ms
885 : WatchDog::kDefaultWatchdogTimeoutInMS;
886 watchdog_.reset(new WatchDog(timeout));
887 }
888
889 // Fill some values into the key-value store for the oat header.
890 key_value_store_.reset(new OatKeyValueStore());
891
892 // Automatically force determinism for the boot image and boot image extensions in a host build.
893 if (!kIsTargetBuild && (IsBootImage() || IsBootImageExtension())) {
894 force_determinism_ = true;
895 }
896 compiler_options_->force_determinism_ = force_determinism_;
897
898 compiler_options_->check_linkage_conditions_ = check_linkage_conditions_;
899 compiler_options_->crash_on_linkage_violation_ = crash_on_linkage_violation_;
900
901 if (passes_to_run_filename_ != nullptr) {
902 passes_to_run_ = ReadCommentedInputFromFile<std::vector<std::string>>(
903 passes_to_run_filename_,
904 nullptr); // No post-processing.
905 if (passes_to_run_.get() == nullptr) {
906 Usage("Failed to read list of passes to run.");
907 }
908 }
909
910 // Prune profile specifications of the boot image location.
911 std::vector<std::string> boot_images =
912 android::base::Split(boot_image_filename_, {ImageSpace::kComponentSeparator});
913 bool boot_image_filename_pruned = false;
914 for (std::string& boot_image : boot_images) {
915 size_t profile_separator_pos = boot_image.find(ImageSpace::kProfileSeparator);
916 if (profile_separator_pos != std::string::npos) {
917 boot_image.resize(profile_separator_pos);
918 boot_image_filename_pruned = true;
919 }
920 }
921 if (boot_image_filename_pruned) {
922 std::string new_boot_image_filename =
923 android::base::Join(boot_images, ImageSpace::kComponentSeparator);
924 VLOG(compiler) << "Pruning profile specifications of the boot image location. Before: "
925 << boot_image_filename_ << ", After: " << new_boot_image_filename;
926 boot_image_filename_ = std::move(new_boot_image_filename);
927 }
928
929 compiler_options_->passes_to_run_ = passes_to_run_.get();
930 }
931
ExpandOatAndImageFilenames()932 void ExpandOatAndImageFilenames() {
933 ArrayRef<const std::string> locations(dex_locations_);
934 if (!compiler_options_->multi_image_) {
935 locations = locations.SubArray(/*pos=*/ 0u, /*length=*/ 1u);
936 }
937 if (image_fd_ == -1) {
938 if (image_filenames_[0].rfind('/') == std::string::npos) {
939 Usage("Unusable boot image filename %s", image_filenames_[0].c_str());
940 }
941 image_filenames_ = ImageSpace::ExpandMultiImageLocations(
942 locations, image_filenames_[0], IsBootImageExtension());
943
944 if (oat_filenames_[0].rfind('/') == std::string::npos) {
945 Usage("Unusable boot image oat filename %s", oat_filenames_[0].c_str());
946 }
947 oat_filenames_ = ImageSpace::ExpandMultiImageLocations(
948 locations, oat_filenames_[0], IsBootImageExtension());
949 } else {
950 DCHECK(!compiler_options_->multi_image_);
951 std::vector<std::string> oat_locations = ImageSpace::ExpandMultiImageLocations(
952 locations, oat_location_, IsBootImageExtension());
953 DCHECK_EQ(1u, oat_locations.size());
954 oat_location_ = oat_locations[0];
955 }
956
957 if (!oat_unstripped_.empty()) {
958 if (oat_unstripped_[0].rfind('/') == std::string::npos) {
959 Usage("Unusable boot image symbol filename %s", oat_unstripped_[0].c_str());
960 }
961 oat_unstripped_ = ImageSpace::ExpandMultiImageLocations(
962 locations, oat_unstripped_[0], IsBootImageExtension());
963 }
964 }
965
InsertCompileOptions(int argc,char ** argv)966 void InsertCompileOptions(int argc, char** argv) {
967 if (!avoid_storing_invocation_) {
968 std::ostringstream oss;
969 for (int i = 0; i < argc; ++i) {
970 if (i > 0) {
971 oss << ' ';
972 }
973 oss << argv[i];
974 }
975 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
976 }
977 key_value_store_->Put(OatHeader::kDebuggableKey, compiler_options_->debuggable_);
978 key_value_store_->Put(OatHeader::kNativeDebuggableKey,
979 compiler_options_->GetNativeDebuggable());
980 key_value_store_->Put(OatHeader::kCompilerFilter,
981 CompilerFilter::NameOfFilter(compiler_options_->GetCompilerFilter()));
982 key_value_store_->Put(OatHeader::kConcurrentCopying, compiler_options_->EmitReadBarrier());
983 if (invocation_file_.get() != -1) {
984 std::ostringstream oss;
985 for (int i = 0; i < argc; ++i) {
986 if (i > 0) {
987 oss << std::endl;
988 }
989 oss << argv[i];
990 }
991 std::string invocation(oss.str());
992 if (TEMP_FAILURE_RETRY(write(invocation_file_.get(),
993 invocation.c_str(),
994 invocation.size())) == -1) {
995 Usage("Unable to write invocation file");
996 }
997 }
998 }
999
1000 // This simple forward is here so the string specializations below don't look out of place.
1001 template <typename T, typename U>
AssignIfExists(Dex2oatArgumentMap & map,const Dex2oatArgumentMap::Key<T> & key,U * out)1002 void AssignIfExists(Dex2oatArgumentMap& map,
1003 const Dex2oatArgumentMap::Key<T>& key,
1004 U* out) {
1005 map.AssignIfExists(key, out);
1006 }
1007
1008 // Specializations to handle const char* vs std::string.
AssignIfExists(Dex2oatArgumentMap & map,const Dex2oatArgumentMap::Key<std::string> & key,const char ** out)1009 void AssignIfExists(Dex2oatArgumentMap& map,
1010 const Dex2oatArgumentMap::Key<std::string>& key,
1011 const char** out) {
1012 if (map.Exists(key)) {
1013 char_backing_storage_.push_front(std::move(*map.Get(key)));
1014 *out = char_backing_storage_.front().c_str();
1015 }
1016 }
AssignIfExists(Dex2oatArgumentMap & map,const Dex2oatArgumentMap::Key<std::vector<std::string>> & key,std::vector<const char * > * out)1017 void AssignIfExists(Dex2oatArgumentMap& map,
1018 const Dex2oatArgumentMap::Key<std::vector<std::string>>& key,
1019 std::vector<const char*>* out) {
1020 if (map.Exists(key)) {
1021 for (auto& val : *map.Get(key)) {
1022 char_backing_storage_.push_front(std::move(val));
1023 out->push_back(char_backing_storage_.front().c_str());
1024 }
1025 }
1026 }
1027
1028 template <typename T>
AssignTrueIfExists(Dex2oatArgumentMap & map,const Dex2oatArgumentMap::Key<T> & key,bool * out)1029 void AssignTrueIfExists(Dex2oatArgumentMap& map,
1030 const Dex2oatArgumentMap::Key<T>& key,
1031 bool* out) {
1032 if (map.Exists(key)) {
1033 *out = true;
1034 }
1035 }
1036
AssignIfExists(Dex2oatArgumentMap & map,const Dex2oatArgumentMap::Key<std::string> & key,std::vector<std::string> * out)1037 void AssignIfExists(Dex2oatArgumentMap& map,
1038 const Dex2oatArgumentMap::Key<std::string>& key,
1039 std::vector<std::string>* out) {
1040 DCHECK(out->empty());
1041 if (map.Exists(key)) {
1042 out->push_back(*map.Get(key));
1043 }
1044 }
1045
1046 // Parse the arguments from the command line. In case of an unrecognized option or impossible
1047 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
1048 // returns, arguments have been successfully parsed.
ParseArgs(int argc,char ** argv)1049 void ParseArgs(int argc, char** argv) {
1050 original_argc = argc;
1051 original_argv = argv;
1052
1053 Locks::Init();
1054 InitLogging(argv, Runtime::Abort);
1055
1056 compiler_options_.reset(new CompilerOptions());
1057
1058 using M = Dex2oatArgumentMap;
1059 std::string error_msg;
1060 std::unique_ptr<M> args_uptr = M::Parse(argc, const_cast<const char**>(argv), &error_msg);
1061 if (args_uptr == nullptr) {
1062 Usage("Failed to parse command line: %s", error_msg.c_str());
1063 UNREACHABLE();
1064 }
1065
1066 M& args = *args_uptr;
1067
1068 std::string compact_dex_level;
1069 std::unique_ptr<ParserOptions> parser_options(new ParserOptions());
1070
1071 AssignIfExists(args, M::CompactDexLevel, &compact_dex_level);
1072 AssignIfExists(args, M::DexFiles, &dex_filenames_);
1073 AssignIfExists(args, M::DexLocations, &dex_locations_);
1074 AssignIfExists(args, M::DexFds, &dex_fds_);
1075 AssignIfExists(args, M::OatFile, &oat_filenames_);
1076 AssignIfExists(args, M::OatSymbols, &parser_options->oat_symbols);
1077 AssignTrueIfExists(args, M::Strip, &strip_);
1078 AssignIfExists(args, M::ImageFilename, &image_filenames_);
1079 AssignIfExists(args, M::ImageFd, &image_fd_);
1080 AssignIfExists(args, M::ZipFd, &zip_fd_);
1081 AssignIfExists(args, M::ZipLocation, &zip_location_);
1082 AssignIfExists(args, M::InputVdexFd, &input_vdex_fd_);
1083 AssignIfExists(args, M::OutputVdexFd, &output_vdex_fd_);
1084 AssignIfExists(args, M::InputVdex, &input_vdex_);
1085 AssignIfExists(args, M::OutputVdex, &output_vdex_);
1086 AssignIfExists(args, M::DmFd, &dm_fd_);
1087 AssignIfExists(args, M::DmFile, &dm_file_location_);
1088 AssignIfExists(args, M::OatFd, &oat_fd_);
1089 AssignIfExists(args, M::OatLocation, &oat_location_);
1090 AssignIfExists(args, M::Watchdog, &parser_options->watch_dog_enabled);
1091 AssignIfExists(args, M::WatchdogTimeout, &parser_options->watch_dog_timeout_in_ms);
1092 AssignIfExists(args, M::Threads, &thread_count_);
1093 AssignIfExists(args, M::CpuSet, &cpu_set_);
1094 AssignIfExists(args, M::Passes, &passes_to_run_filename_);
1095 AssignIfExists(args, M::BootImage, &parser_options->boot_image_filename);
1096 AssignIfExists(args, M::AndroidRoot, &android_root_);
1097 AssignIfExists(args, M::Profile, &profile_files_);
1098 AssignIfExists(args, M::ProfileFd, &profile_file_fds_);
1099 AssignIfExists(args, M::PreloadedClasses, &preloaded_classes_files_);
1100 AssignIfExists(args, M::PreloadedClassesFds, &preloaded_classes_fds_);
1101 AssignIfExists(args, M::RuntimeOptions, &runtime_args_);
1102 AssignIfExists(args, M::SwapFile, &swap_file_name_);
1103 AssignIfExists(args, M::SwapFileFd, &swap_fd_);
1104 AssignIfExists(args, M::SwapDexSizeThreshold, &min_dex_file_cumulative_size_for_swap_);
1105 AssignIfExists(args, M::SwapDexCountThreshold, &min_dex_files_for_swap_);
1106 AssignIfExists(args, M::VeryLargeAppThreshold, &very_large_threshold_);
1107 AssignIfExists(args, M::AppImageFile, &app_image_file_name_);
1108 AssignIfExists(args, M::AppImageFileFd, &app_image_fd_);
1109 AssignIfExists(args, M::NoInlineFrom, &no_inline_from_string_);
1110 AssignIfExists(args, M::ClasspathDir, &classpath_dir_);
1111 AssignIfExists(args, M::DirtyImageObjects, &dirty_image_objects_filenames_);
1112 AssignIfExists(args, M::DirtyImageObjectsFd, &dirty_image_objects_fds_);
1113 AssignIfExists(args, M::ImageFormat, &image_storage_mode_);
1114 AssignIfExists(args, M::CompilationReason, &compilation_reason_);
1115 AssignTrueIfExists(args, M::CheckLinkageConditions, &check_linkage_conditions_);
1116 AssignTrueIfExists(args, M::CrashOnLinkageViolation, &crash_on_linkage_violation_);
1117 AssignTrueIfExists(args, M::ForceAllowOjInlines, &force_allow_oj_inlines_);
1118 AssignIfExists(args, M::PublicSdk, &public_sdk_);
1119 AssignIfExists(args, M::ApexVersions, &apex_versions_argument_);
1120
1121 if (!compact_dex_level.empty()) {
1122 LOG(WARNING) << "Obsolete flag --compact-dex-level ignored";
1123 }
1124
1125 AssignIfExists(args, M::TargetInstructionSet, &compiler_options_->instruction_set_);
1126 // arm actually means thumb2.
1127 if (compiler_options_->instruction_set_ == InstructionSet::kArm) {
1128 compiler_options_->instruction_set_ = InstructionSet::kThumb2;
1129 }
1130
1131 AssignTrueIfExists(args, M::Host, &is_host_);
1132 AssignTrueIfExists(args, M::AvoidStoringInvocation, &avoid_storing_invocation_);
1133 if (args.Exists(M::InvocationFile)) {
1134 invocation_file_.reset(open(args.Get(M::InvocationFile)->c_str(),
1135 O_CREAT|O_WRONLY|O_TRUNC|O_CLOEXEC,
1136 S_IRUSR|S_IWUSR));
1137 if (invocation_file_.get() == -1) {
1138 int err = errno;
1139 Usage("Unable to open invocation file '%s' for writing due to %s.",
1140 args.Get(M::InvocationFile)->c_str(), strerror(err));
1141 }
1142 }
1143 AssignIfExists(args, M::CopyDexFiles, ©_dex_files_);
1144
1145 AssignTrueIfExists(args, M::MultiImage, &have_multi_image_arg_);
1146 AssignIfExists(args, M::MultiImage, &compiler_options_->multi_image_);
1147
1148 if (args.Exists(M::ForceDeterminism)) {
1149 force_determinism_ = true;
1150 }
1151 AssignTrueIfExists(args, M::CompileIndividually, &compile_individually_);
1152
1153 if (args.Exists(M::Base)) {
1154 ParseBase(*args.Get(M::Base));
1155 }
1156 if (args.Exists(M::TargetInstructionSetVariant)) {
1157 ParseInstructionSetVariant(*args.Get(M::TargetInstructionSetVariant), parser_options.get());
1158 }
1159 if (args.Exists(M::TargetInstructionSetFeatures)) {
1160 ParseInstructionSetFeatures(*args.Get(M::TargetInstructionSetFeatures), parser_options.get());
1161 }
1162 if (args.Exists(M::ClassLoaderContext)) {
1163 std::string class_loader_context_arg = *args.Get(M::ClassLoaderContext);
1164 class_loader_context_ = ClassLoaderContext::Create(class_loader_context_arg);
1165 if (class_loader_context_ == nullptr) {
1166 Usage("Option --class-loader-context has an incorrect format: %s",
1167 class_loader_context_arg.c_str());
1168 }
1169 if (args.Exists(M::ClassLoaderContextFds)) {
1170 std::string str_fds_arg = *args.Get(M::ClassLoaderContextFds);
1171 std::vector<std::string> str_fds = android::base::Split(str_fds_arg, ":");
1172 for (const std::string& str_fd : str_fds) {
1173 class_loader_context_fds_.push_back(std::stoi(str_fd, nullptr, 0));
1174 if (class_loader_context_fds_.back() < 0) {
1175 Usage("Option --class-loader-context-fds has incorrect format: %s",
1176 str_fds_arg.c_str());
1177 }
1178 }
1179 }
1180 if (args.Exists(M::StoredClassLoaderContext)) {
1181 const std::string stored_context_arg = *args.Get(M::StoredClassLoaderContext);
1182 stored_class_loader_context_ = ClassLoaderContext::Create(stored_context_arg);
1183 if (stored_class_loader_context_ == nullptr) {
1184 Usage("Option --stored-class-loader-context has an incorrect format: %s",
1185 stored_context_arg.c_str());
1186 } else if (class_loader_context_->VerifyClassLoaderContextMatch(
1187 stored_context_arg,
1188 /*verify_names*/ false,
1189 /*verify_checksums*/ false) != ClassLoaderContext::VerificationResult::kVerifies) {
1190 Usage(
1191 "Option --stored-class-loader-context '%s' mismatches --class-loader-context '%s'",
1192 stored_context_arg.c_str(),
1193 class_loader_context_arg.c_str());
1194 }
1195 }
1196 } else if (args.Exists(M::StoredClassLoaderContext)) {
1197 Usage("Option --stored-class-loader-context should only be used if "
1198 "--class-loader-context is also specified");
1199 }
1200
1201 if (args.Exists(M::UpdatableBcpPackagesFile)) {
1202 LOG(WARNING)
1203 << "Option --updatable-bcp-packages-file is deprecated and no longer takes effect";
1204 }
1205
1206 if (args.Exists(M::UpdatableBcpPackagesFd)) {
1207 LOG(WARNING) << "Option --updatable-bcp-packages-fd is deprecated and no longer takes effect";
1208 }
1209
1210 if (args.Exists(M::ForceJitZygote)) {
1211 if (!parser_options->boot_image_filename.empty()) {
1212 Usage("Option --boot-image and --force-jit-zygote cannot be specified together");
1213 }
1214 parser_options->boot_image_filename = GetJitZygoteBootImageLocation();
1215 }
1216
1217 // If we have a profile, change the default compiler filter to speed-profile
1218 // before reading compiler options.
1219 static_assert(CompilerFilter::kDefaultCompilerFilter == CompilerFilter::kSpeed);
1220 DCHECK_EQ(compiler_options_->GetCompilerFilter(), CompilerFilter::kSpeed);
1221 if (HasProfileInput()) {
1222 compiler_options_->SetCompilerFilter(CompilerFilter::kSpeedProfile);
1223 }
1224
1225 if (!ReadCompilerOptions(args, compiler_options_.get(), &error_msg)) {
1226 Usage(error_msg.c_str());
1227 }
1228
1229 if (!compiler_options_->GetDumpCfgFileName().empty() && thread_count_ != 1) {
1230 LOG(INFO) << "Since we are dumping the CFG to " << compiler_options_->GetDumpCfgFileName()
1231 << ", we override thread number to 1 to have determinism. It was " << thread_count_
1232 << ".";
1233 thread_count_ = 1;
1234 }
1235
1236 PaletteShouldReportDex2oatCompilation(&should_report_dex2oat_compilation_);
1237 AssignTrueIfExists(args, M::ForcePaletteCompilationHooks, &should_report_dex2oat_compilation_);
1238
1239 ProcessOptions(parser_options.get());
1240 }
1241
1242 // Check whether the oat output files are writable, and open them for later. Also open a swap
1243 // file, if a name is given.
OpenFile()1244 bool OpenFile() {
1245 // Prune non-existent dex files now so that we don't create empty oat files for multi-image.
1246 PruneNonExistentDexFiles();
1247
1248 // Expand oat and image filenames for boot image and boot image extension.
1249 // This is mostly for multi-image but single-image also needs some processing.
1250 if (IsBootImage() || IsBootImageExtension()) {
1251 ExpandOatAndImageFilenames();
1252 }
1253
1254 // OAT and VDEX file handling
1255 if (oat_fd_ == -1) {
1256 DCHECK(!oat_filenames_.empty());
1257 for (const std::string& oat_filename : oat_filenames_) {
1258 std::unique_ptr<File> oat_file(OS::CreateEmptyFile(oat_filename.c_str()));
1259 if (oat_file == nullptr) {
1260 PLOG(ERROR) << "Failed to create oat file: " << oat_filename;
1261 return false;
1262 }
1263 if (fchmod(oat_file->Fd(), 0644) != 0) {
1264 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_filename;
1265 oat_file->Erase();
1266 return false;
1267 }
1268 oat_files_.push_back(std::move(oat_file));
1269 DCHECK_EQ(input_vdex_fd_, -1);
1270 if (!input_vdex_.empty()) {
1271 std::string error_msg;
1272 input_vdex_file_ = VdexFile::Open(input_vdex_,
1273 /* writable */ false,
1274 /* low_4gb */ false,
1275 &error_msg);
1276 }
1277
1278 DCHECK_EQ(output_vdex_fd_, -1);
1279 std::string vdex_filename = output_vdex_.empty() ?
1280 ReplaceFileExtension(oat_filename, kVdexExtension) :
1281 output_vdex_;
1282 if (vdex_filename == input_vdex_ && output_vdex_.empty()) {
1283 use_existing_vdex_ = true;
1284 std::unique_ptr<File> vdex_file(OS::OpenFileForReading(vdex_filename.c_str()));
1285 vdex_files_.push_back(std::move(vdex_file));
1286 } else {
1287 std::unique_ptr<File> vdex_file(OS::CreateEmptyFile(vdex_filename.c_str()));
1288 if (vdex_file == nullptr) {
1289 PLOG(ERROR) << "Failed to open vdex file: " << vdex_filename;
1290 return false;
1291 }
1292 if (fchmod(vdex_file->Fd(), 0644) != 0) {
1293 PLOG(ERROR) << "Failed to make vdex file world readable: " << vdex_filename;
1294 vdex_file->Erase();
1295 return false;
1296 }
1297 vdex_files_.push_back(std::move(vdex_file));
1298 }
1299 }
1300 } else {
1301 std::unique_ptr<File> oat_file(
1302 new File(DupCloexec(oat_fd_), oat_location_, /* check_usage */ true));
1303 if (!oat_file->IsOpened()) {
1304 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
1305 return false;
1306 }
1307 if (oat_file->SetLength(0) != 0) {
1308 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
1309 oat_file->Erase();
1310 return false;
1311 }
1312 oat_files_.push_back(std::move(oat_file));
1313
1314 if (input_vdex_fd_ != -1) {
1315 struct stat s;
1316 int rc = TEMP_FAILURE_RETRY(fstat(input_vdex_fd_, &s));
1317 if (rc == -1) {
1318 PLOG(WARNING) << "Failed getting length of vdex file";
1319 } else {
1320 std::string error_msg;
1321 input_vdex_file_ = VdexFile::Open(input_vdex_fd_,
1322 s.st_size,
1323 "vdex",
1324 /* writable */ false,
1325 /* low_4gb */ false,
1326 &error_msg);
1327 // If there's any problem with the passed vdex, just warn and proceed
1328 // without it.
1329 if (input_vdex_file_ == nullptr) {
1330 PLOG(WARNING) << "Failed opening vdex file: " << error_msg;
1331 }
1332 }
1333 }
1334
1335 DCHECK_NE(output_vdex_fd_, -1);
1336 std::string vdex_location = ReplaceFileExtension(oat_location_, kVdexExtension);
1337 if (input_vdex_file_ != nullptr && output_vdex_fd_ == input_vdex_fd_) {
1338 use_existing_vdex_ = true;
1339 }
1340
1341 std::unique_ptr<File> vdex_file(new File(DupCloexec(output_vdex_fd_),
1342 vdex_location,
1343 /* check_usage= */ true,
1344 /* read_only_mode= */ use_existing_vdex_));
1345 if (!vdex_file->IsOpened()) {
1346 PLOG(ERROR) << "Failed to create vdex file: " << vdex_location;
1347 return false;
1348 }
1349
1350 if (!use_existing_vdex_) {
1351 if (vdex_file->SetLength(0) != 0) {
1352 PLOG(ERROR) << "Truncating vdex file " << vdex_location << " failed.";
1353 vdex_file->Erase();
1354 return false;
1355 }
1356 }
1357 vdex_files_.push_back(std::move(vdex_file));
1358
1359 oat_filenames_.push_back(oat_location_);
1360 }
1361
1362 if (dm_fd_ != -1 || !dm_file_location_.empty()) {
1363 std::string error_msg;
1364 if (dm_fd_ != -1) {
1365 dm_file_.reset(ZipArchive::OpenFromFd(dm_fd_, "DexMetadata", &error_msg));
1366 } else {
1367 dm_file_.reset(ZipArchive::Open(dm_file_location_.c_str(), &error_msg));
1368 }
1369 if (dm_file_ == nullptr) {
1370 LOG(WARNING) << "Could not open DexMetadata archive " << error_msg;
1371 }
1372 }
1373
1374 // If we have a dm file and a vdex file, we (arbitrarily) pick the vdex file.
1375 // In theory the files should be the same.
1376 if (dm_file_ != nullptr) {
1377 if (input_vdex_file_ == nullptr) {
1378 input_vdex_file_ = VdexFile::OpenFromDm(dm_file_location_, *dm_file_);
1379 if (input_vdex_file_ != nullptr) {
1380 VLOG(verifier) << "Doing fast verification with vdex from DexMetadata archive";
1381 }
1382 } else {
1383 LOG(INFO) << "Ignoring vdex file in dex metadata due to vdex file already being passed";
1384 }
1385 }
1386
1387 // Swap file handling
1388 //
1389 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file
1390 // that we can use for swap.
1391 //
1392 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We
1393 // will immediately unlink to satisfy the swap fd assumption.
1394 if (swap_fd_ == -1 && !swap_file_name_.empty()) {
1395 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str()));
1396 if (swap_file.get() == nullptr) {
1397 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_;
1398 return false;
1399 }
1400 swap_fd_ = swap_file->Release();
1401 unlink(swap_file_name_.c_str());
1402 }
1403
1404 return true;
1405 }
1406
EraseOutputFiles()1407 void EraseOutputFiles() {
1408 for (auto& files : { &vdex_files_, &oat_files_ }) {
1409 for (size_t i = 0; i < files->size(); ++i) {
1410 auto& file = (*files)[i];
1411 if (file != nullptr) {
1412 if (!file->ReadOnlyMode()) {
1413 file->Erase();
1414 }
1415 file.reset();
1416 }
1417 }
1418 }
1419 }
1420
LoadImageClassDescriptors()1421 void LoadImageClassDescriptors() {
1422 if (!IsImage()) {
1423 return;
1424 }
1425 HashSet<std::string> image_classes;
1426 if (DoProfileGuidedOptimizations()) {
1427 // TODO: The following comment looks outdated or misplaced.
1428 // Filter out class path classes since we don't want to include these in the image.
1429 image_classes = profile_compilation_info_->GetClassDescriptors(
1430 compiler_options_->dex_files_for_oat_file_);
1431 VLOG(compiler) << "Loaded " << image_classes.size()
1432 << " image class descriptors from profile";
1433 } else if (compiler_options_->IsBootImage() || compiler_options_->IsBootImageExtension()) {
1434 // If we are compiling a boot image but no profile is provided, include all classes in the
1435 // image. This is to match pre-boot image extension work where we would load all boot image
1436 // extension classes at startup.
1437 for (const DexFile* dex_file : compiler_options_->dex_files_for_oat_file_) {
1438 for (uint32_t i = 0; i < dex_file->NumClassDefs(); i++) {
1439 const dex::ClassDef& class_def = dex_file->GetClassDef(i);
1440 const char* descriptor = dex_file->GetClassDescriptor(class_def);
1441 image_classes.insert(descriptor);
1442 }
1443 }
1444 }
1445 if (VLOG_IS_ON(compiler)) {
1446 for (const std::string& s : image_classes) {
1447 LOG(INFO) << "Image class " << s;
1448 }
1449 }
1450 compiler_options_->image_classes_ = std::move(image_classes);
1451 }
1452
1453 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
1454 // boot class path.
Setup()1455 dex2oat::ReturnCode Setup() {
1456 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
1457
1458 if (!PrepareDirtyObjects()) {
1459 return dex2oat::ReturnCode::kOther;
1460 }
1461
1462 if (!PreparePreloadedClasses()) {
1463 return dex2oat::ReturnCode::kOther;
1464 }
1465
1466 callbacks_.reset(new QuickCompilerCallbacks(
1467 // For class verification purposes, boot image extension is the same as boot image.
1468 (IsBootImage() || IsBootImageExtension())
1469 ? CompilerCallbacks::CallbackMode::kCompileBootImage
1470 : CompilerCallbacks::CallbackMode::kCompileApp));
1471
1472 RuntimeArgumentMap runtime_options;
1473 if (!PrepareRuntimeOptions(&runtime_options, callbacks_.get())) {
1474 return dex2oat::ReturnCode::kOther;
1475 }
1476
1477 CreateOatWriters();
1478 if (!AddDexFileSources()) {
1479 return dex2oat::ReturnCode::kOther;
1480 }
1481
1482 {
1483 TimingLogger::ScopedTiming t_dex("Writing and opening dex files", timings_);
1484 for (size_t i = 0, size = oat_writers_.size(); i != size; ++i) {
1485 // Unzip or copy dex files straight to the oat file.
1486 std::vector<MemMap> opened_dex_files_map;
1487 std::vector<std::unique_ptr<const DexFile>> opened_dex_files;
1488 // No need to verify the dex file when we have a vdex file, which means it was already
1489 // verified.
1490 const bool verify =
1491 (input_vdex_file_ == nullptr) && !compiler_options_->AssumeDexFilesAreVerified();
1492 if (!oat_writers_[i]->WriteAndOpenDexFiles(
1493 vdex_files_[i].get(),
1494 verify,
1495 use_existing_vdex_,
1496 copy_dex_files_,
1497 &opened_dex_files_map,
1498 &opened_dex_files)) {
1499 return dex2oat::ReturnCode::kOther;
1500 }
1501 dex_files_per_oat_file_.push_back(MakeNonOwningPointerVector(opened_dex_files));
1502 for (MemMap& map : opened_dex_files_map) {
1503 opened_dex_files_maps_.push_back(std::move(map));
1504 }
1505 for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files) {
1506 dex_file_oat_index_map_.insert(std::make_pair(dex_file.get(), i));
1507 opened_dex_files_.push_back(std::move(dex_file));
1508 }
1509 }
1510 }
1511
1512 compiler_options_->dex_files_for_oat_file_ = MakeNonOwningPointerVector(opened_dex_files_);
1513 const std::vector<const DexFile*>& dex_files = compiler_options_->dex_files_for_oat_file_;
1514
1515 if (!ValidateInputVdexChecksums()) {
1516 return dex2oat::ReturnCode::kOther;
1517 }
1518
1519 // Check if we need to downgrade the compiler-filter for size reasons.
1520 // Note: This does not affect the compiler filter already stored in the key-value
1521 // store which is used for determining whether the oat file is up to date,
1522 // together with the boot class path locations and checksums stored below.
1523 CompilerFilter::Filter original_compiler_filter = compiler_options_->GetCompilerFilter();
1524 if (!IsBootImage() && !IsBootImageExtension() && IsVeryLarge(dex_files)) {
1525 // Disable app image to make sure dex2oat unloading is enabled.
1526 compiler_options_->image_type_ = CompilerOptions::ImageType::kNone;
1527
1528 // If we need to downgrade the compiler-filter for size reasons, do that early before we read
1529 // it below for creating verification callbacks.
1530 if (!CompilerFilter::IsAsGoodAs(kLargeAppFilter, compiler_options_->GetCompilerFilter())) {
1531 LOG(INFO) << "Very large app, downgrading to verify.";
1532 compiler_options_->SetCompilerFilter(kLargeAppFilter);
1533 }
1534 }
1535
1536 if (CompilerFilter::IsAnyCompilationEnabled(compiler_options_->GetCompilerFilter()) ||
1537 IsImage()) {
1538 // Only modes with compilation or image generation require verification results.
1539 verification_results_.reset(new VerificationResults());
1540 callbacks_->SetVerificationResults(verification_results_.get());
1541 }
1542
1543 if (IsBootImage() || IsBootImageExtension()) {
1544 // For boot image or boot image extension, pass opened dex files to the Runtime::Create().
1545 // Note: Runtime acquires ownership of these dex files.
1546 runtime_options.Set(RuntimeArgumentMap::BootClassPathDexList, &opened_dex_files_);
1547 }
1548 if (!CreateRuntime(std::move(runtime_options))) {
1549 return dex2oat::ReturnCode::kCreateRuntime;
1550 }
1551 if (runtime_->GetHeap()->GetBootImageSpaces().empty() &&
1552 (IsBootImageExtension() || IsAppImage())) {
1553 LOG(WARNING) << "Cannot create "
1554 << (IsBootImageExtension() ? "boot image extension" : "app image")
1555 << " without a primary boot image.";
1556 compiler_options_->image_type_ = CompilerOptions::ImageType::kNone;
1557 }
1558 ArrayRef<const DexFile* const> bcp_dex_files(runtime_->GetClassLinker()->GetBootClassPath());
1559 if (IsBootImage() || IsBootImageExtension()) {
1560 // Check boot class path dex files and, if compiling an extension, the images it depends on.
1561 if ((IsBootImage() && bcp_dex_files.size() != dex_files.size()) ||
1562 (IsBootImageExtension() && bcp_dex_files.size() <= dex_files.size())) {
1563 LOG(ERROR) << "Unexpected number of boot class path dex files for boot image or extension, "
1564 << bcp_dex_files.size() << (IsBootImage() ? " != " : " <= ") << dex_files.size();
1565 return dex2oat::ReturnCode::kOther;
1566 }
1567 if (!std::equal(dex_files.begin(), dex_files.end(), bcp_dex_files.end() - dex_files.size())) {
1568 LOG(ERROR) << "Boot class path dex files do not end with the compiled dex files.";
1569 return dex2oat::ReturnCode::kOther;
1570 }
1571 size_t bcp_df_pos = 0u;
1572 size_t bcp_df_end = bcp_dex_files.size();
1573 for (const std::string& bcp_location : runtime_->GetBootClassPathLocations()) {
1574 if (bcp_df_pos == bcp_df_end || bcp_dex_files[bcp_df_pos]->GetLocation() != bcp_location) {
1575 LOG(ERROR) << "Missing dex file for boot class component " << bcp_location;
1576 return dex2oat::ReturnCode::kOther;
1577 }
1578 CHECK(!DexFileLoader::IsMultiDexLocation(bcp_dex_files[bcp_df_pos]->GetLocation()));
1579 ++bcp_df_pos;
1580 while (bcp_df_pos != bcp_df_end &&
1581 DexFileLoader::IsMultiDexLocation(bcp_dex_files[bcp_df_pos]->GetLocation())) {
1582 ++bcp_df_pos;
1583 }
1584 }
1585 if (bcp_df_pos != bcp_df_end) {
1586 LOG(ERROR) << "Unexpected dex file in boot class path "
1587 << bcp_dex_files[bcp_df_pos]->GetLocation();
1588 return dex2oat::ReturnCode::kOther;
1589 }
1590 auto lacks_image = [](const DexFile* df) {
1591 if (kIsDebugBuild && df->GetOatDexFile() != nullptr) {
1592 const OatFile* oat_file = df->GetOatDexFile()->GetOatFile();
1593 CHECK(oat_file != nullptr);
1594 const auto& image_spaces = Runtime::Current()->GetHeap()->GetBootImageSpaces();
1595 CHECK(std::any_of(image_spaces.begin(),
1596 image_spaces.end(),
1597 [=](const ImageSpace* space) {
1598 return oat_file == space->GetOatFile();
1599 }));
1600 }
1601 return df->GetOatDexFile() == nullptr;
1602 };
1603 if (std::any_of(bcp_dex_files.begin(), bcp_dex_files.end() - dex_files.size(), lacks_image)) {
1604 LOG(ERROR) << "Missing required boot image(s) for boot image extension.";
1605 return dex2oat::ReturnCode::kOther;
1606 }
1607 }
1608
1609 if (!compilation_reason_.empty()) {
1610 key_value_store_->Put(OatHeader::kCompilationReasonKey, compilation_reason_);
1611 }
1612
1613 Runtime* runtime = Runtime::Current();
1614
1615 if (IsBootImage()) {
1616 // If we're compiling the boot image, store the boot classpath into the Key-Value store.
1617 // We use this when loading the boot image.
1618 key_value_store_->Put(OatHeader::kBootClassPathKey, android::base::Join(dex_locations_, ':'));
1619 } else if (IsBootImageExtension()) {
1620 // Validate the boot class path and record the dependency on the loaded boot images.
1621 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1622 std::string full_bcp = android::base::Join(runtime->GetBootClassPathLocations(), ':');
1623 std::string extension_part = ":" + android::base::Join(dex_locations_, ':');
1624 if (!full_bcp.ends_with(extension_part)) {
1625 LOG(ERROR) << "Full boot class path does not end with extension parts, full: " << full_bcp
1626 << ", extension: " << extension_part.substr(1u);
1627 return dex2oat::ReturnCode::kOther;
1628 }
1629 std::string bcp_dependency = full_bcp.substr(0u, full_bcp.size() - extension_part.size());
1630 key_value_store_->Put(OatHeader::kBootClassPathKey, bcp_dependency);
1631 ArrayRef<const DexFile* const> bcp_dex_files_dependency =
1632 bcp_dex_files.SubArray(/*pos=*/ 0u, bcp_dex_files.size() - dex_files.size());
1633 ArrayRef<ImageSpace* const> image_spaces(runtime->GetHeap()->GetBootImageSpaces());
1634 key_value_store_->Put(
1635 OatHeader::kBootClassPathChecksumsKey,
1636 gc::space::ImageSpace::GetBootClassPathChecksums(image_spaces, bcp_dex_files_dependency));
1637 } else {
1638 if (CompilerFilter::DependsOnImageChecksum(original_compiler_filter)) {
1639 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1640 key_value_store_->Put(OatHeader::kBootClassPathKey,
1641 android::base::Join(runtime->GetBootClassPathLocations(), ':'));
1642 ArrayRef<ImageSpace* const> image_spaces(runtime->GetHeap()->GetBootImageSpaces());
1643 key_value_store_->Put(
1644 OatHeader::kBootClassPathChecksumsKey,
1645 gc::space::ImageSpace::GetBootClassPathChecksums(image_spaces, bcp_dex_files));
1646 }
1647
1648 // Open dex files for class path.
1649
1650 if (class_loader_context_ == nullptr) {
1651 // If no context was specified use the default one (which is an empty PathClassLoader).
1652 class_loader_context_ = ClassLoaderContext::Default();
1653 }
1654
1655 DCHECK_EQ(oat_writers_.size(), 1u);
1656
1657 // Note: Ideally we would reject context where the source dex files are also
1658 // specified in the classpath (as it doesn't make sense). However this is currently
1659 // needed for non-prebuild tests and benchmarks which expects on the fly compilation.
1660 // Also, for secondary dex files we do not have control on the actual classpath.
1661 // Instead of aborting, remove all the source location from the context classpaths.
1662 if (class_loader_context_->RemoveLocationsFromClassPaths(
1663 oat_writers_[0]->GetSourceLocations())) {
1664 LOG(WARNING) << "The source files to be compiled are also in the classpath.";
1665 }
1666
1667 // We need to open the dex files before encoding the context in the oat file.
1668 // (because the encoding adds the dex checksum...)
1669 // TODO(calin): consider redesigning this so we don't have to open the dex files before
1670 // creating the actual class loader.
1671 if (!class_loader_context_->OpenDexFiles(classpath_dir_,
1672 class_loader_context_fds_)) {
1673 // Do not abort if we couldn't open files from the classpath. They might be
1674 // apks without dex files and right now are opening flow will fail them.
1675 LOG(WARNING) << "Failed to open classpath dex files";
1676 }
1677
1678 // Store the class loader context in the oat header.
1679 // TODO: deprecate this since store_class_loader_context should be enough to cover the users
1680 // of classpath_dir as well.
1681 std::string class_path_key =
1682 class_loader_context_->EncodeContextForOatFile(classpath_dir_,
1683 stored_class_loader_context_.get());
1684 key_value_store_->Put(OatHeader::kClassPathKey, class_path_key);
1685 }
1686
1687 if (IsBootImage() ||
1688 IsBootImageExtension() ||
1689 CompilerFilter::DependsOnImageChecksum(original_compiler_filter)) {
1690 std::string versions =
1691 apex_versions_argument_.empty() ? runtime->GetApexVersions() : apex_versions_argument_;
1692 key_value_store_->Put(OatHeader::kApexVersionsKey, versions);
1693 }
1694
1695 // Now that we have adjusted whether we generate an image, encode it in the
1696 // key/value store.
1697 key_value_store_->Put(OatHeader::kRequiresImage, compiler_options_->IsGeneratingImage());
1698
1699 // Now that we have finalized key_value_store_, start writing the .rodata section.
1700 // Among other things, this creates type lookup tables that speed up the compilation.
1701 {
1702 TimingLogger::ScopedTiming t_dex("Starting .rodata", timings_);
1703 rodata_.reserve(oat_writers_.size());
1704 for (size_t i = 0, size = oat_writers_.size(); i != size; ++i) {
1705 rodata_.push_back(elf_writers_[i]->StartRoData());
1706 if (!oat_writers_[i]->StartRoData(dex_files_per_oat_file_[i],
1707 rodata_.back(),
1708 (i == 0u) ? key_value_store_.get() : nullptr)) {
1709 return dex2oat::ReturnCode::kOther;
1710 }
1711 }
1712 }
1713
1714 // We had to postpone the swap decision till now, as this is the point when we actually
1715 // know about the dex files we're going to use.
1716
1717 // Make sure that we didn't create the driver, yet.
1718 CHECK(driver_ == nullptr);
1719 // If we use a swap file, ensure we are above the threshold to make it necessary.
1720 if (swap_fd_ != -1) {
1721 if (!UseSwap(IsBootImage() || IsBootImageExtension(), dex_files)) {
1722 close(swap_fd_);
1723 swap_fd_ = -1;
1724 VLOG(compiler) << "Decided to run without swap.";
1725 } else {
1726 LOG(INFO) << "Large app, accepted running with swap.";
1727 }
1728 }
1729 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that.
1730
1731 if (!IsBootImage() && !IsBootImageExtension()) {
1732 constexpr bool kSaveDexInput = false;
1733 if (kSaveDexInput) {
1734 SaveDexInput();
1735 }
1736 }
1737
1738 // Setup VerifierDeps for compilation and report if we fail to parse the data.
1739 if (input_vdex_file_ != nullptr) {
1740 TimingLogger::ScopedTiming t_dex("Parse Verifier Deps", timings_);
1741 std::unique_ptr<verifier::VerifierDeps> verifier_deps(
1742 new verifier::VerifierDeps(dex_files, /*output_only=*/ false));
1743 if (!verifier_deps->ParseStoredData(dex_files, input_vdex_file_->GetVerifierDepsData())) {
1744 return dex2oat::ReturnCode::kOther;
1745 }
1746 // We can do fast verification.
1747 callbacks_->SetVerifierDeps(verifier_deps.release());
1748 } else {
1749 // Create the main VerifierDeps, here instead of in the compiler since we want to aggregate
1750 // the results for all the dex files, not just the results for the current dex file.
1751 callbacks_->SetVerifierDeps(new verifier::VerifierDeps(dex_files));
1752 }
1753
1754 return dex2oat::ReturnCode::kNoFailure;
1755 }
1756
1757 // Validates that the input vdex checksums match the source dex checksums.
1758 // Note that this is only effective and relevant if the input_vdex_file does not
1759 // contain a dex section (e.g. when they come from .dm files).
1760 // If the input vdex does contain dex files, the dex files will be opened from there
1761 // and so this check is redundant.
ValidateInputVdexChecksums()1762 bool ValidateInputVdexChecksums() {
1763 if (input_vdex_file_ == nullptr) {
1764 // Nothing to validate
1765 return true;
1766 }
1767 if (input_vdex_file_->GetNumberOfDexFiles()
1768 != compiler_options_->dex_files_for_oat_file_.size()) {
1769 LOG(ERROR) << "Vdex file contains a different number of dex files than the source. "
1770 << " vdex_num=" << input_vdex_file_->GetNumberOfDexFiles()
1771 << " dex_source_num=" << compiler_options_->dex_files_for_oat_file_.size();
1772 return false;
1773 }
1774
1775 for (size_t i = 0; i < compiler_options_->dex_files_for_oat_file_.size(); i++) {
1776 uint32_t dex_source_checksum =
1777 compiler_options_->dex_files_for_oat_file_[i]->GetLocationChecksum();
1778 uint32_t vdex_checksum = input_vdex_file_->GetLocationChecksum(i);
1779 if (dex_source_checksum != vdex_checksum) {
1780 LOG(ERROR) << "Vdex file checksum different than source dex checksum for position " << i
1781 << std::hex
1782 << " vdex_checksum=0x" << vdex_checksum
1783 << " dex_source_checksum=0x" << dex_source_checksum
1784 << std::dec;
1785 return false;
1786 }
1787 }
1788 return true;
1789 }
1790
1791 // If we need to keep the oat file open for the image writer.
ShouldKeepOatFileOpen() const1792 bool ShouldKeepOatFileOpen() const {
1793 return IsImage() && oat_fd_ != File::kInvalidFd;
1794 }
1795
1796 // Doesn't return the class loader since it's not meant to be used for image compilation.
CompileDexFilesIndividually()1797 void CompileDexFilesIndividually() {
1798 CHECK(!IsImage()) << "Not supported with image";
1799 for (const DexFile* dex_file : compiler_options_->dex_files_for_oat_file_) {
1800 std::vector<const DexFile*> dex_files(1u, dex_file);
1801 VLOG(compiler) << "Compiling " << dex_file->GetLocation();
1802 jobject class_loader = CompileDexFiles(dex_files);
1803 CHECK(class_loader != nullptr);
1804 ScopedObjectAccess soa(Thread::Current());
1805 // Unload class loader to free RAM.
1806 jweak weak_class_loader = soa.Env()->GetVm()->AddWeakGlobalRef(
1807 soa.Self(),
1808 soa.Decode<mirror::ClassLoader>(class_loader));
1809 soa.Env()->GetVm()->DeleteGlobalRef(soa.Self(), class_loader);
1810 runtime_->GetHeap()->CollectGarbage(/* clear_soft_references */ true);
1811 ObjPtr<mirror::ClassLoader> decoded_weak = soa.Decode<mirror::ClassLoader>(weak_class_loader);
1812 if (decoded_weak != nullptr) {
1813 LOG(FATAL) << "Failed to unload class loader, path from root set: "
1814 << runtime_->GetHeap()->GetVerification()->FirstPathFromRootSet(decoded_weak);
1815 }
1816 VLOG(compiler) << "Unloaded classloader";
1817 }
1818 }
1819
ShouldCompileDexFilesIndividually() const1820 bool ShouldCompileDexFilesIndividually() const {
1821 // Compile individually if we are allowed to, and
1822 // 1. not building an image, and
1823 // 2. not verifying a vdex file, and
1824 // 3. using multidex, and
1825 // 4. not doing any AOT compilation.
1826 // This means no-vdex verify will use the individual compilation
1827 // mode (to reduce RAM used by the compiler).
1828 return compile_individually_ &&
1829 (!IsImage() && !use_existing_vdex_ &&
1830 compiler_options_->dex_files_for_oat_file_.size() > 1 &&
1831 !CompilerFilter::IsAotCompilationEnabled(compiler_options_->GetCompilerFilter()));
1832 }
1833
GetCombinedChecksums() const1834 uint32_t GetCombinedChecksums() const {
1835 uint32_t combined_checksums = 0u;
1836 for (const DexFile* dex_file : compiler_options_->GetDexFilesForOatFile()) {
1837 combined_checksums ^= dex_file->GetLocationChecksum();
1838 }
1839 return combined_checksums;
1840 }
1841
1842 // Set up and create the compiler driver and then invoke it to compile all the dex files.
Compile()1843 jobject Compile() REQUIRES(!Locks::mutator_lock_) {
1844 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
1845
1846 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1847
1848 // Find the dex files we should not inline from.
1849 std::vector<std::string> no_inline_filters;
1850 Split(no_inline_from_string_, ',', &no_inline_filters);
1851
1852 // For now, on the host always have core-oj removed.
1853 const std::string core_oj = "core-oj";
1854 if (!kIsTargetBuild && !ContainsElement(no_inline_filters, core_oj)) {
1855 if (force_allow_oj_inlines_) {
1856 LOG(ERROR) << "Inlines allowed from core-oj! FOR TESTING USE ONLY! DO NOT DISTRIBUTE"
1857 << " BINARIES BUILT WITH THIS OPTION!";
1858 } else {
1859 no_inline_filters.push_back(core_oj);
1860 }
1861 }
1862
1863 if (!no_inline_filters.empty()) {
1864 std::vector<const DexFile*> class_path_files;
1865 if (!IsBootImage() && !IsBootImageExtension()) {
1866 // The class loader context is used only for apps.
1867 class_path_files = class_loader_context_->FlattenOpenedDexFiles();
1868 }
1869
1870 const std::vector<const DexFile*>& dex_files = compiler_options_->dex_files_for_oat_file_;
1871 std::vector<const DexFile*> no_inline_from_dex_files;
1872 const std::vector<const DexFile*>* dex_file_vectors[] = {
1873 &class_linker->GetBootClassPath(),
1874 &class_path_files,
1875 &dex_files
1876 };
1877 for (const std::vector<const DexFile*>* dex_file_vector : dex_file_vectors) {
1878 for (const DexFile* dex_file : *dex_file_vector) {
1879 for (const std::string& filter : no_inline_filters) {
1880 // Use dex_file->GetLocation() rather than dex_file->GetBaseLocation(). This
1881 // allows tests to specify <test-dexfile>!classes2.dex if needed but if the
1882 // base location passes the `starts_with()` test, so do all extra locations.
1883 std::string dex_location = dex_file->GetLocation();
1884 if (filter.find('/') == std::string::npos) {
1885 // The filter does not contain the path. Remove the path from dex_location as well.
1886 size_t last_slash = dex_file->GetLocation().rfind('/');
1887 if (last_slash != std::string::npos) {
1888 dex_location = dex_location.substr(last_slash + 1);
1889 }
1890 }
1891
1892 if (dex_location.starts_with(filter)) {
1893 VLOG(compiler) << "Disabling inlining from " << dex_file->GetLocation();
1894 no_inline_from_dex_files.push_back(dex_file);
1895 break;
1896 }
1897 }
1898 }
1899 }
1900 if (!no_inline_from_dex_files.empty()) {
1901 compiler_options_->no_inline_from_.swap(no_inline_from_dex_files);
1902 }
1903 }
1904 compiler_options_->profile_compilation_info_ = profile_compilation_info_.get();
1905
1906 driver_.reset(new CompilerDriver(compiler_options_.get(),
1907 verification_results_.get(),
1908 thread_count_,
1909 swap_fd_));
1910
1911 driver_->PrepareDexFilesForOatFile(timings_);
1912
1913 if (!IsBootImage() && !IsBootImageExtension()) {
1914 driver_->SetClasspathDexFiles(class_loader_context_->FlattenOpenedDexFiles());
1915 }
1916
1917 const bool compile_individually = ShouldCompileDexFilesIndividually();
1918 if (compile_individually) {
1919 // Set the compiler driver in the callbacks so that we can avoid re-verification.
1920 // Only set the compiler filter if we are doing separate compilation since there is a bit
1921 // of overhead when checking if a class was previously verified.
1922 callbacks_->SetDoesClassUnloading(true, driver_.get());
1923 }
1924
1925 // Setup vdex for compilation.
1926 const std::vector<const DexFile*>& dex_files = compiler_options_->dex_files_for_oat_file_;
1927 // To allow initialization of classes that construct ThreadLocal objects in class initializer,
1928 // re-initialize the ThreadLocal.nextHashCode to a new object that's not in the boot image.
1929 ThreadLocalHashOverride thread_local_hash_override(
1930 /*apply=*/ !IsBootImage(), /*initial_value=*/ 123456789u ^ GetCombinedChecksums());
1931
1932 // Invoke the compilation.
1933 if (compile_individually) {
1934 CompileDexFilesIndividually();
1935 // Return a null classloader since we already freed released it.
1936 return nullptr;
1937 }
1938 return CompileDexFiles(dex_files);
1939 }
1940
1941 // Create the class loader, use it to compile, and return.
CompileDexFiles(const std::vector<const DexFile * > & dex_files)1942 jobject CompileDexFiles(const std::vector<const DexFile*>& dex_files) {
1943 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
1944
1945 jobject class_loader = nullptr;
1946 if (!IsBootImage() && !IsBootImageExtension()) {
1947 class_loader =
1948 class_loader_context_->CreateClassLoader(compiler_options_->GetDexFilesForOatFile());
1949 }
1950 if (!IsBootImage()) {
1951 callbacks_->SetDexFiles(&dex_files);
1952
1953 // We need to set this after we create the class loader so that the runtime can access
1954 // the hidden fields of the well known class loaders.
1955 if (!public_sdk_.empty()) {
1956 std::string error_msg;
1957 std::unique_ptr<SdkChecker> sdk_checker(SdkChecker::Create(public_sdk_, &error_msg));
1958 if (sdk_checker != nullptr) {
1959 AotClassLinker* aot_class_linker = down_cast<AotClassLinker*>(class_linker);
1960 aot_class_linker->SetSdkChecker(std::move(sdk_checker));
1961 } else {
1962 LOG(FATAL) << "Failed to create SdkChecker with dex files "
1963 << public_sdk_ << " Error: " << error_msg;
1964 UNREACHABLE();
1965 }
1966 }
1967 }
1968 if (IsAppImage()) {
1969 AotClassLinker::SetAppImageDexFiles(&compiler_options_->GetDexFilesForOatFile());
1970 }
1971
1972 // Register dex caches and key them to the class loader so that they only unload when the
1973 // class loader unloads.
1974 for (const auto& dex_file : dex_files) {
1975 ScopedObjectAccess soa(Thread::Current());
1976 // Registering the dex cache adds a strong root in the class loader that prevents the dex
1977 // cache from being unloaded early.
1978 ObjPtr<mirror::DexCache> dex_cache = class_linker->RegisterDexFile(
1979 *dex_file,
1980 soa.Decode<mirror::ClassLoader>(class_loader));
1981 if (dex_cache == nullptr) {
1982 soa.Self()->AssertPendingException();
1983 LOG(FATAL) << "Failed to register dex file " << dex_file->GetLocation() << " "
1984 << soa.Self()->GetException()->Dump();
1985 }
1986 }
1987 driver_->InitializeThreadPools();
1988 driver_->PreCompile(class_loader,
1989 dex_files,
1990 timings_,
1991 &compiler_options_->image_classes_);
1992 callbacks_->SetVerificationResults(nullptr); // Should not be needed anymore.
1993 driver_->CompileAll(class_loader, dex_files, timings_);
1994 driver_->FreeThreadPools();
1995 return class_loader;
1996 }
1997
1998 // Notes on the interleaving of creating the images and oat files to
1999 // ensure the references between the two are correct.
2000 //
2001 // Currently we have a memory layout that looks something like this:
2002 //
2003 // +--------------+
2004 // | images |
2005 // +--------------+
2006 // | oat files |
2007 // +--------------+
2008 // | alloc spaces |
2009 // +--------------+
2010 //
2011 // There are several constraints on the loading of the images and oat files.
2012 //
2013 // 1. The images are expected to be loaded at an absolute address and
2014 // contain Objects with absolute pointers within the images.
2015 //
2016 // 2. There are absolute pointers from Methods in the images to their
2017 // code in the oat files.
2018 //
2019 // 3. There are absolute pointers from the code in the oat files to Methods
2020 // in the images.
2021 //
2022 // 4. There are absolute pointers from code in the oat files to other code
2023 // in the oat files.
2024 //
2025 // To get this all correct, we go through several steps.
2026 //
2027 // 1. We prepare offsets for all data in the oat files and calculate
2028 // the oat data size and code size. During this stage, we also set
2029 // oat code offsets in methods for use by the image writer.
2030 //
2031 // 2. We prepare offsets for the objects in the images and calculate
2032 // the image sizes.
2033 //
2034 // 3. We create the oat files. Originally this was just our own proprietary
2035 // file but now it is contained within an ELF dynamic object (aka an .so
2036 // file). Since we know the image sizes and oat data sizes and code sizes we
2037 // can prepare the ELF headers and we then know the ELF memory segment
2038 // layout and we can now resolve all references. The compiler provides
2039 // LinkerPatch information in each CompiledMethod and we resolve these,
2040 // using the layout information and image object locations provided by
2041 // image writer, as we're writing the method code.
2042 //
2043 // 4. We create the image files. They need to know where the oat files
2044 // will be loaded after itself. Originally oat files were simply
2045 // memory mapped so we could predict where their contents were based
2046 // on the file size. Now that they are ELF files, we need to inspect
2047 // the ELF files to understand the in memory segment layout including
2048 // where the oat header is located within.
2049 // TODO: We could just remember this information from step 3.
2050 //
2051 // 5. We fixup the ELF program headers so that dlopen will try to
2052 // load the .so at the desired location at runtime by offsetting the
2053 // Elf32_Phdr.p_vaddr values by the desired base address.
2054 // TODO: Do this in step 3. We already know the layout there.
2055 //
2056 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
2057 // are done by the CreateImageFile() below.
2058
2059 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
2060 // ImageWriter, if necessary.
2061 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
2062 // case (when the file will be explicitly erased).
WriteOutputFiles(jobject class_loader)2063 bool WriteOutputFiles(jobject class_loader) {
2064 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
2065
2066 // Sync the data to the file, in case we did dex2dex transformations.
2067 for (MemMap& map : opened_dex_files_maps_) {
2068 if (!map.Sync()) {
2069 PLOG(ERROR) << "Failed to Sync() dex2dex output. Map: " << map.GetName();
2070 return false;
2071 }
2072 }
2073
2074 if (IsImage()) {
2075 if (!IsBootImage()) {
2076 DCHECK_EQ(image_base_, 0u);
2077 gc::Heap* const heap = Runtime::Current()->GetHeap();
2078 image_base_ = heap->GetBootImagesStartAddress() + heap->GetBootImagesSize();
2079 }
2080 VLOG(compiler) << "Image base=" << reinterpret_cast<void*>(image_base_);
2081
2082 image_writer_.reset(new linker::ImageWriter(*compiler_options_,
2083 image_base_,
2084 image_storage_mode_,
2085 oat_filenames_,
2086 dex_file_oat_index_map_,
2087 class_loader,
2088 dirty_image_objects_.get()));
2089
2090 // We need to prepare method offsets in the image address space for resolving linker patches.
2091 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
2092 if (!image_writer_->PrepareImageAddressSpace(timings_)) {
2093 LOG(ERROR) << "Failed to prepare image address space.";
2094 return false;
2095 }
2096 }
2097
2098 // Initialize the writers with the compiler driver, image writer, and their
2099 // dex files. The writers were created without those being there yet.
2100 for (size_t i = 0, size = oat_files_.size(); i != size; ++i) {
2101 std::unique_ptr<linker::OatWriter>& oat_writer = oat_writers_[i];
2102 std::vector<const DexFile*>& dex_files = dex_files_per_oat_file_[i];
2103 oat_writer->Initialize(
2104 driver_.get(), verification_results_.get(), image_writer_.get(), dex_files);
2105 }
2106
2107 if (!use_existing_vdex_) {
2108 TimingLogger::ScopedTiming t2("dex2oat Write VDEX", timings_);
2109 DCHECK(IsBootImage() || IsBootImageExtension() || oat_files_.size() == 1u);
2110 verifier::VerifierDeps* verifier_deps = callbacks_->GetVerifierDeps();
2111 for (size_t i = 0, size = oat_files_.size(); i != size; ++i) {
2112 File* vdex_file = vdex_files_[i].get();
2113 if (!oat_writers_[i]->FinishVdexFile(vdex_file, verifier_deps)) {
2114 LOG(ERROR) << "Failed to finish VDEX file " << vdex_file->GetPath();
2115 return false;
2116 }
2117 }
2118 }
2119
2120 {
2121 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
2122 linker::MultiOatRelativePatcher patcher(compiler_options_->GetInstructionSet(),
2123 compiler_options_->GetInstructionSetFeatures(),
2124 driver_->GetCompiledMethodStorage());
2125 for (size_t i = 0, size = oat_files_.size(); i != size; ++i) {
2126 std::unique_ptr<linker::ElfWriter>& elf_writer = elf_writers_[i];
2127 std::unique_ptr<linker::OatWriter>& oat_writer = oat_writers_[i];
2128
2129 oat_writer->PrepareLayout(&patcher);
2130 elf_writer->PrepareDynamicSection(oat_writer->GetOatHeader().GetExecutableOffset(),
2131 oat_writer->GetCodeSize(),
2132 oat_writer->GetDataImgRelRoSize(),
2133 oat_writer->GetDataImgRelRoAppImageOffset(),
2134 oat_writer->GetBssSize(),
2135 oat_writer->GetBssMethodsOffset(),
2136 oat_writer->GetBssRootsOffset(),
2137 oat_writer->GetVdexSize());
2138 if (IsImage()) {
2139 // Update oat layout.
2140 DCHECK(image_writer_ != nullptr);
2141 DCHECK_LT(i, oat_filenames_.size());
2142 image_writer_->UpdateOatFileLayout(i,
2143 elf_writer->GetLoadedSize(),
2144 oat_writer->GetOatDataOffset(),
2145 oat_writer->GetOatSize());
2146 }
2147 }
2148
2149 for (size_t i = 0, size = oat_files_.size(); i != size; ++i) {
2150 std::unique_ptr<File>& oat_file = oat_files_[i];
2151 std::unique_ptr<linker::ElfWriter>& elf_writer = elf_writers_[i];
2152 std::unique_ptr<linker::OatWriter>& oat_writer = oat_writers_[i];
2153
2154 // We need to mirror the layout of the ELF file in the compressed debug-info.
2155 // Therefore PrepareDebugInfo() relies on the SetLoadedSectionSizes() call further above.
2156 debug::DebugInfo debug_info = oat_writer->GetDebugInfo(); // Keep the variable alive.
2157 // This will perform the compression on background thread while we do other I/O below.
2158 // If we hit any ERROR path below, the destructor of this variable will wait for the
2159 // task to finish (since it accesses the 'debug_info' above and other 'Dex2Oat' data).
2160 std::unique_ptr<ThreadPool> compression_job = elf_writer->PrepareDebugInfo(debug_info);
2161
2162 OutputStream* rodata = rodata_[i];
2163 DCHECK(rodata != nullptr);
2164 if (!oat_writer->WriteRodata(rodata)) {
2165 LOG(ERROR) << "Failed to write .rodata section to the ELF file " << oat_file->GetPath();
2166 return false;
2167 }
2168 elf_writer->EndRoData(rodata);
2169 rodata = nullptr;
2170
2171 OutputStream* text = elf_writer->StartText();
2172 if (!oat_writer->WriteCode(text)) {
2173 LOG(ERROR) << "Failed to write .text section to the ELF file " << oat_file->GetPath();
2174 return false;
2175 }
2176 elf_writer->EndText(text);
2177
2178 if (oat_writer->GetDataImgRelRoSize() != 0u) {
2179 OutputStream* data_img_rel_ro = elf_writer->StartDataImgRelRo();
2180 if (!oat_writer->WriteDataImgRelRo(data_img_rel_ro)) {
2181 LOG(ERROR) << "Failed to write .data.img.rel.ro section to the ELF file "
2182 << oat_file->GetPath();
2183 return false;
2184 }
2185 elf_writer->EndDataImgRelRo(data_img_rel_ro);
2186 }
2187
2188 if (!oat_writer->WriteHeader(elf_writer->GetStream())) {
2189 LOG(ERROR) << "Failed to write oat header to the ELF file " << oat_file->GetPath();
2190 return false;
2191 }
2192
2193 if (IsImage()) {
2194 // Update oat header information.
2195 DCHECK(image_writer_ != nullptr);
2196 DCHECK_LT(i, oat_filenames_.size());
2197 image_writer_->UpdateOatFileHeader(i, oat_writer->GetOatHeader());
2198 }
2199
2200 elf_writer->WriteDynamicSection();
2201 elf_writer->WriteDebugInfo(oat_writer->GetDebugInfo());
2202
2203 if (!elf_writer->End()) {
2204 LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath();
2205 return false;
2206 }
2207
2208 if (!FlushOutputFile(&vdex_files_[i]) || !FlushOutputFile(&oat_files_[i])) {
2209 return false;
2210 }
2211
2212 VLOG(compiler) << "Oat file written successfully: " << oat_filenames_[i];
2213
2214 oat_writer.reset();
2215 // We may still need the ELF writer later for stripping.
2216 }
2217 }
2218
2219 return true;
2220 }
2221
2222 // If we are compiling an image, invoke the image creation routine. Else just skip.
HandleImage()2223 bool HandleImage() {
2224 if (IsImage()) {
2225 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
2226 if (!CreateImageFile()) {
2227 return false;
2228 }
2229 VLOG(compiler) << "Images written successfully";
2230 }
2231 return true;
2232 }
2233
2234 // Copy the full oat files to symbols directory and then strip the originals.
CopyOatFilesToSymbolsDirectoryAndStrip()2235 bool CopyOatFilesToSymbolsDirectoryAndStrip() {
2236 for (size_t i = 0; i < oat_unstripped_.size(); ++i) {
2237 // If we don't want to strip in place, copy from stripped location to unstripped location.
2238 // We need to strip after image creation because FixupElf needs to use .strtab.
2239 if (oat_unstripped_[i] != oat_filenames_[i]) {
2240 DCHECK(oat_files_[i].get() != nullptr && oat_files_[i]->IsOpened());
2241
2242 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
2243 std::unique_ptr<File>& in = oat_files_[i];
2244 int64_t in_length = in->GetLength();
2245 if (in_length < 0) {
2246 PLOG(ERROR) << "Failed to get the length of oat file: " << in->GetPath();
2247 return false;
2248 }
2249 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_unstripped_[i].c_str()));
2250 if (out == nullptr) {
2251 PLOG(ERROR) << "Failed to open oat file for writing: " << oat_unstripped_[i];
2252 return false;
2253 }
2254 if (!out->Copy(in.get(), 0, in_length)) {
2255 PLOG(ERROR) << "Failed to copy oat file to file: " << out->GetPath();
2256 return false;
2257 }
2258 if (out->FlushCloseOrErase() != 0) {
2259 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_unstripped_[i];
2260 return false;
2261 }
2262 VLOG(compiler) << "Oat file copied successfully (unstripped): " << oat_unstripped_[i];
2263
2264 if (strip_) {
2265 TimingLogger::ScopedTiming t2("dex2oat OatFile strip", timings_);
2266 if (!elf_writers_[i]->StripDebugInfo()) {
2267 PLOG(ERROR) << "Failed strip oat file: " << in->GetPath();
2268 return false;
2269 }
2270 }
2271 }
2272 }
2273 return true;
2274 }
2275
FlushOutputFile(std::unique_ptr<File> * file)2276 bool FlushOutputFile(std::unique_ptr<File>* file) {
2277 if ((file->get() != nullptr) && !file->get()->ReadOnlyMode()) {
2278 if (file->get()->Flush() != 0) {
2279 PLOG(ERROR) << "Failed to flush output file: " << file->get()->GetPath();
2280 return false;
2281 }
2282 }
2283 return true;
2284 }
2285
FlushCloseOutputFile(File * file)2286 bool FlushCloseOutputFile(File* file) {
2287 if ((file != nullptr) && !file->ReadOnlyMode()) {
2288 if (file->FlushCloseOrErase() != 0) {
2289 PLOG(ERROR) << "Failed to flush and close output file: " << file->GetPath();
2290 return false;
2291 }
2292 }
2293 return true;
2294 }
2295
FlushOutputFiles()2296 bool FlushOutputFiles() {
2297 TimingLogger::ScopedTiming t2("dex2oat Flush Output Files", timings_);
2298 for (auto& files : { &vdex_files_, &oat_files_ }) {
2299 for (size_t i = 0; i < files->size(); ++i) {
2300 if (!FlushOutputFile(&(*files)[i])) {
2301 return false;
2302 }
2303 }
2304 }
2305 return true;
2306 }
2307
FlushCloseOutputFiles()2308 bool FlushCloseOutputFiles() {
2309 bool result = true;
2310 for (auto& files : { &vdex_files_, &oat_files_ }) {
2311 for (size_t i = 0; i < files->size(); ++i) {
2312 result &= FlushCloseOutputFile((*files)[i].get());
2313 }
2314 }
2315 return result;
2316 }
2317
DumpTiming()2318 void DumpTiming() {
2319 if (compiler_options_->GetDumpTimings() ||
2320 (kIsDebugBuild && timings_->GetTotalNs() > MsToNs(1000))) {
2321 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
2322 }
2323 }
2324
IsImage() const2325 bool IsImage() const {
2326 return IsAppImage() || IsBootImage() || IsBootImageExtension();
2327 }
2328
IsAppImage() const2329 bool IsAppImage() const {
2330 return compiler_options_->IsAppImage();
2331 }
2332
IsBootImage() const2333 bool IsBootImage() const {
2334 return compiler_options_->IsBootImage();
2335 }
2336
IsBootImageExtension() const2337 bool IsBootImageExtension() const {
2338 return compiler_options_->IsBootImageExtension();
2339 }
2340
IsHost() const2341 bool IsHost() const {
2342 return is_host_;
2343 }
2344
HasProfileInput() const2345 bool HasProfileInput() const { return !profile_file_fds_.empty() || !profile_files_.empty(); }
2346
2347 // Must be called after the profile is loaded.
DoProfileGuidedOptimizations() const2348 bool DoProfileGuidedOptimizations() const {
2349 DCHECK(!HasProfileInput() || profile_load_attempted_)
2350 << "The profile has to be loaded before we can decided "
2351 << "if we do profile guided optimizations";
2352 return profile_compilation_info_ != nullptr && !profile_compilation_info_->IsEmpty();
2353 }
2354
DoOatLayoutOptimizations() const2355 bool DoOatLayoutOptimizations() const {
2356 return DoProfileGuidedOptimizations();
2357 }
2358
LoadProfile()2359 bool LoadProfile() {
2360 DCHECK(HasProfileInput());
2361 profile_load_attempted_ = true;
2362 // TODO(calin): We should be using the runtime arena pool (instead of the
2363 // default profile arena). However the setup logic is messy and needs
2364 // cleaning up before that (e.g. the oat writers are created before the
2365 // runtime).
2366 bool for_boot_image = IsBootImage() || IsBootImageExtension();
2367 profile_compilation_info_.reset(new ProfileCompilationInfo(for_boot_image));
2368
2369 // Cleanup profile compilation info if we encounter any error when reading profiles.
2370 auto cleanup = android::base::ScopeGuard([&]() { profile_compilation_info_.reset(nullptr); });
2371
2372 // 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::vector<std::unique_ptr<File>> profile_files;
2376 if (!profile_file_fds_.empty()) {
2377 for (int fd : profile_file_fds_) {
2378 profile_files.push_back(std::make_unique<File>(DupCloexec(fd),
2379 "profile",
2380 /*check_usage=*/ false,
2381 /*read_only_mode=*/ true));
2382 }
2383 } else {
2384 for (const std::string& file : profile_files_) {
2385 profile_files.emplace_back(OS::OpenFileForReading(file.c_str()));
2386 if (profile_files.back().get() == nullptr) {
2387 PLOG(ERROR) << "Cannot open profiles";
2388 return false;
2389 }
2390 }
2391 }
2392
2393 std::map<std::string, uint32_t> old_profile_keys, new_profile_keys;
2394 auto filter_fn = [&](const std::string& profile_key, uint32_t checksum) {
2395 auto it = old_profile_keys.find(profile_key);
2396 if (it != old_profile_keys.end() && it->second != checksum) {
2397 // Filter out this entry. We have already loaded data for the same profile key with a
2398 // different checksum from an earlier profile file.
2399 return false;
2400 }
2401 // Insert the new profile key and checksum.
2402 // Note: If the profile contains the same key with different checksums, this insertion fails
2403 // but we still return `true` and let the `ProfileCompilationInfo::Load()` report an error.
2404 new_profile_keys.insert(std::make_pair(profile_key, checksum));
2405 return true;
2406 };
2407 for (const std::unique_ptr<File>& profile_file : profile_files) {
2408 if (!profile_compilation_info_->Load(profile_file->Fd(),
2409 /*merge_classes=*/ true,
2410 filter_fn)) {
2411 return false;
2412 }
2413 old_profile_keys.merge(new_profile_keys);
2414 new_profile_keys.clear();
2415 }
2416
2417 cleanup.Disable();
2418 return true;
2419 }
2420
2421 // If we're asked to speed-profile the app but we have no profile, or the profile
2422 // is empty, change the filter to verify, and the image_type to none.
2423 // A speed-profile compilation without profile data is equivalent to verify and
2424 // this change will increase the precision of the telemetry data.
UpdateCompilerOptionsBasedOnProfile()2425 void UpdateCompilerOptionsBasedOnProfile() {
2426 if (!DoProfileGuidedOptimizations() &&
2427 compiler_options_->GetCompilerFilter() == CompilerFilter::kSpeedProfile) {
2428 VLOG(compiler) << "Changing compiler filter to verify from speed-profile "
2429 << "because of empty or non existing profile";
2430
2431 compiler_options_->SetCompilerFilter(CompilerFilter::kVerify);
2432
2433 // Note that we could reset the image_type to CompilerOptions::ImageType::kNone
2434 // to prevent an app image generation.
2435 // However, if we were pass an image file we would essentially leave the image
2436 // file empty (possibly triggering some harmless errors when we try to load it).
2437 //
2438 // Letting the image_type_ be determined by whether or not we passed an image
2439 // file will at least write the appropriate header making it an empty but valid
2440 // image.
2441 }
2442 }
2443
2444 class ScopedDex2oatReporting {
2445 public:
ScopedDex2oatReporting(const Dex2Oat & dex2oat)2446 explicit ScopedDex2oatReporting(const Dex2Oat& dex2oat) :
2447 should_report_(dex2oat.should_report_dex2oat_compilation_) {
2448 if (should_report_) {
2449 if (dex2oat.zip_fd_ != -1) {
2450 zip_dup_fd_.reset(DupCloexecOrError(dex2oat.zip_fd_));
2451 if (zip_dup_fd_ < 0) {
2452 return;
2453 }
2454 }
2455 int image_fd = dex2oat.IsAppImage() ? dex2oat.app_image_fd_ : dex2oat.image_fd_;
2456 if (image_fd != -1) {
2457 image_dup_fd_.reset(DupCloexecOrError(image_fd));
2458 if (image_dup_fd_ < 0) {
2459 return;
2460 }
2461 }
2462 oat_dup_fd_.reset(DupCloexecOrError(dex2oat.oat_fd_));
2463 if (oat_dup_fd_ < 0) {
2464 return;
2465 }
2466 vdex_dup_fd_.reset(DupCloexecOrError(dex2oat.output_vdex_fd_));
2467 if (vdex_dup_fd_ < 0) {
2468 return;
2469 }
2470 PaletteNotifyStartDex2oatCompilation(zip_dup_fd_,
2471 image_dup_fd_,
2472 oat_dup_fd_,
2473 vdex_dup_fd_);
2474 }
2475 error_reporting_ = false;
2476 }
2477
~ScopedDex2oatReporting()2478 ~ScopedDex2oatReporting() {
2479 if (!error_reporting_) {
2480 if (should_report_) {
2481 PaletteNotifyEndDex2oatCompilation(zip_dup_fd_,
2482 image_dup_fd_,
2483 oat_dup_fd_,
2484 vdex_dup_fd_);
2485 }
2486 }
2487 }
2488
ErrorReporting() const2489 bool ErrorReporting() const { return error_reporting_; }
2490
2491 private:
DupCloexecOrError(int fd)2492 int DupCloexecOrError(int fd) {
2493 int dup_fd = DupCloexec(fd);
2494 if (dup_fd < 0) {
2495 LOG(ERROR) << "Error dup'ing a file descriptor " << strerror(errno);
2496 error_reporting_ = true;
2497 }
2498 return dup_fd;
2499 }
2500 android::base::unique_fd oat_dup_fd_;
2501 android::base::unique_fd vdex_dup_fd_;
2502 android::base::unique_fd zip_dup_fd_;
2503 android::base::unique_fd image_dup_fd_;
2504 bool error_reporting_ = false;
2505 bool should_report_;
2506 };
2507
2508 private:
UseSwap(bool is_image,const std::vector<const DexFile * > & dex_files)2509 bool UseSwap(bool is_image, const std::vector<const DexFile*>& dex_files) {
2510 if (is_image) {
2511 // Don't use swap, we know generation should succeed, and we don't want to slow it down.
2512 return false;
2513 }
2514 if (dex_files.size() < min_dex_files_for_swap_) {
2515 // If there are less dex files than the threshold, assume it's gonna be fine.
2516 return false;
2517 }
2518 size_t dex_files_size = 0;
2519 for (const auto* dex_file : dex_files) {
2520 dex_files_size += dex_file->GetHeader().file_size_;
2521 }
2522 return dex_files_size >= min_dex_file_cumulative_size_for_swap_;
2523 }
2524
IsVeryLarge(const std::vector<const DexFile * > & dex_files)2525 bool IsVeryLarge(const std::vector<const DexFile*>& dex_files) {
2526 size_t dex_files_size = 0;
2527 for (const auto* dex_file : dex_files) {
2528 dex_files_size += dex_file->GetHeader().file_size_;
2529 }
2530 return dex_files_size >= very_large_threshold_;
2531 }
2532
PrepareDirtyObjects()2533 bool PrepareDirtyObjects() {
2534 if (!dirty_image_objects_fds_.empty()) {
2535 dirty_image_objects_ = std::make_unique<std::vector<std::string>>();
2536 for (int fd : dirty_image_objects_fds_) {
2537 if (!ReadCommentedInputFromFd(fd, nullptr, dirty_image_objects_.get())) {
2538 LOG(ERROR) << "Failed to create list of dirty objects from fd " << fd;
2539 return false;
2540 }
2541 }
2542 // Close since we won't need it again.
2543 for (int fd : dirty_image_objects_fds_) {
2544 close(fd);
2545 }
2546 dirty_image_objects_fds_.clear();
2547 } else if (!dirty_image_objects_filenames_.empty()) {
2548 dirty_image_objects_ = std::make_unique<std::vector<std::string>>();
2549 for (const std::string& file : dirty_image_objects_filenames_) {
2550 if (!ReadCommentedInputFromFile(file.c_str(), nullptr, dirty_image_objects_.get())) {
2551 LOG(ERROR) << "Failed to create list of dirty objects from '" << file << "'";
2552 return false;
2553 }
2554 }
2555 }
2556 return true;
2557 }
2558
PreparePreloadedClasses()2559 bool PreparePreloadedClasses() {
2560 if (!preloaded_classes_fds_.empty()) {
2561 for (int fd : preloaded_classes_fds_) {
2562 if (!ReadCommentedInputFromFd(fd, nullptr, &compiler_options_->preloaded_classes_)) {
2563 return false;
2564 }
2565 }
2566 } else {
2567 for (const std::string& file : preloaded_classes_files_) {
2568 if (!ReadCommentedInputFromFile(
2569 file.c_str(), nullptr, &compiler_options_->preloaded_classes_)) {
2570 return false;
2571 }
2572 }
2573 }
2574 return true;
2575 }
2576
PruneNonExistentDexFiles()2577 void PruneNonExistentDexFiles() {
2578 DCHECK_EQ(dex_filenames_.size(), dex_locations_.size());
2579 size_t kept = 0u;
2580 for (size_t i = 0, size = dex_filenames_.size(); i != size; ++i) {
2581 // Keep if the file exist, or is passed as FD.
2582 if (!OS::FileExists(dex_filenames_[i].c_str()) && i >= dex_fds_.size()) {
2583 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filenames_[i] << "'";
2584 } else {
2585 if (kept != i) {
2586 dex_filenames_[kept] = dex_filenames_[i];
2587 dex_locations_[kept] = dex_locations_[i];
2588 }
2589 ++kept;
2590 }
2591 }
2592 dex_filenames_.resize(kept);
2593 dex_locations_.resize(kept);
2594 }
2595
AddDexFileSources()2596 bool AddDexFileSources() {
2597 TimingLogger::ScopedTiming t2("AddDexFileSources", timings_);
2598 if (input_vdex_file_ != nullptr && input_vdex_file_->HasDexSection()) {
2599 DCHECK_EQ(oat_writers_.size(), 1u);
2600 const std::string& name = zip_location_.empty() ? dex_locations_[0] : zip_location_;
2601 DCHECK(!name.empty());
2602 if (!oat_writers_[0]->AddVdexDexFilesSource(*input_vdex_file_.get(), name.c_str())) {
2603 return false;
2604 }
2605 } else if (zip_fd_ != -1) {
2606 DCHECK_EQ(oat_writers_.size(), 1u);
2607 if (!oat_writers_[0]->AddDexFileSource(File(zip_fd_, /* check_usage */ false),
2608 zip_location_.c_str())) {
2609 return false;
2610 }
2611 } else {
2612 DCHECK_EQ(dex_filenames_.size(), dex_locations_.size());
2613 DCHECK_GE(oat_writers_.size(), 1u);
2614
2615 bool use_dex_fds = !dex_fds_.empty();
2616 if (use_dex_fds) {
2617 DCHECK_EQ(dex_fds_.size(), dex_filenames_.size());
2618 }
2619
2620 bool is_multi_image = oat_writers_.size() > 1u;
2621 if (is_multi_image) {
2622 DCHECK_EQ(oat_writers_.size(), dex_filenames_.size());
2623 }
2624
2625 for (size_t i = 0; i != dex_filenames_.size(); ++i) {
2626 int oat_index = is_multi_image ? i : 0;
2627 auto oat_writer = oat_writers_[oat_index].get();
2628
2629 if (use_dex_fds) {
2630 if (!oat_writer->AddDexFileSource(File(dex_fds_[i], /* check_usage */ false),
2631 dex_locations_[i].c_str())) {
2632 return false;
2633 }
2634 } else {
2635 if (!oat_writer->AddDexFileSource(dex_filenames_[i].c_str(),
2636 dex_locations_[i].c_str())) {
2637 return false;
2638 }
2639 }
2640 }
2641 }
2642 return true;
2643 }
2644
CreateOatWriters()2645 void CreateOatWriters() {
2646 TimingLogger::ScopedTiming t2("CreateOatWriters", timings_);
2647 elf_writers_.reserve(oat_files_.size());
2648 oat_writers_.reserve(oat_files_.size());
2649 for (const std::unique_ptr<File>& oat_file : oat_files_) {
2650 elf_writers_.emplace_back(linker::CreateElfWriterQuick(*compiler_options_, oat_file.get()));
2651 elf_writers_.back()->Start();
2652 bool do_oat_writer_layout = DoOatLayoutOptimizations();
2653 oat_writers_.emplace_back(new linker::OatWriter(
2654 *compiler_options_,
2655 timings_,
2656 do_oat_writer_layout ? profile_compilation_info_.get() : nullptr));
2657 }
2658 }
2659
SaveDexInput()2660 void SaveDexInput() {
2661 const std::vector<const DexFile*>& dex_files = compiler_options_->dex_files_for_oat_file_;
2662 for (size_t i = 0, size = dex_files.size(); i != size; ++i) {
2663 const DexFile* dex_file = dex_files[i];
2664 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
2665 getpid(), i));
2666 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
2667 if (tmp_file.get() == nullptr) {
2668 PLOG(ERROR) << "Failed to open file " << tmp_file_name
2669 << ". Try: adb shell chmod 777 /data/local/tmp";
2670 continue;
2671 }
2672 // This is just dumping files for debugging. Ignore errors, and leave remnants.
2673 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
2674 UNUSED(tmp_file->Flush());
2675 UNUSED(tmp_file->Close());
2676 LOG(INFO) << "Wrote input to " << tmp_file_name;
2677 }
2678 }
2679
PrepareRuntimeOptions(RuntimeArgumentMap * runtime_options,QuickCompilerCallbacks * callbacks)2680 bool PrepareRuntimeOptions(RuntimeArgumentMap* runtime_options,
2681 QuickCompilerCallbacks* callbacks) {
2682 RuntimeOptions raw_options;
2683 if (IsBootImage()) {
2684 std::string boot_class_path = "-Xbootclasspath:";
2685 boot_class_path += android::base::Join(dex_filenames_, ':');
2686 raw_options.push_back(std::make_pair(boot_class_path, nullptr));
2687 std::string boot_class_path_locations = "-Xbootclasspath-locations:";
2688 boot_class_path_locations += android::base::Join(dex_locations_, ':');
2689 raw_options.push_back(std::make_pair(boot_class_path_locations, nullptr));
2690 } else {
2691 std::string boot_image_option = "-Ximage:";
2692 boot_image_option += boot_image_filename_;
2693 raw_options.push_back(std::make_pair(boot_image_option, nullptr));
2694 }
2695 for (size_t i = 0; i < runtime_args_.size(); i++) {
2696 raw_options.push_back(std::make_pair(runtime_args_[i], nullptr));
2697 }
2698
2699 raw_options.push_back(std::make_pair("compilercallbacks", callbacks));
2700 raw_options.push_back(
2701 std::make_pair("imageinstructionset",
2702 GetInstructionSetString(compiler_options_->GetInstructionSet())));
2703
2704 // Never allow implicit image compilation.
2705 raw_options.push_back(std::make_pair("-Xnoimage-dex2oat", nullptr));
2706 // Disable libsigchain. We don't don't need it during compilation and it prevents us
2707 // from getting a statically linked version of dex2oat (because of dlsym and RTLD_NEXT).
2708 raw_options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
2709 // Disable Hspace compaction to save heap size virtual space.
2710 // Only need disable Hspace for OOM becasue background collector is equal to
2711 // foreground collector by default for dex2oat.
2712 raw_options.push_back(std::make_pair("-XX:DisableHSpaceCompactForOOM", nullptr));
2713
2714 if (!Runtime::ParseOptions(raw_options, false, runtime_options)) {
2715 LOG(ERROR) << "Failed to parse runtime options";
2716 return false;
2717 }
2718 return true;
2719 }
2720
2721 // Create a runtime necessary for compilation.
CreateRuntime(RuntimeArgumentMap && runtime_options)2722 bool CreateRuntime(RuntimeArgumentMap&& runtime_options) {
2723 // To make identity hashcode deterministic, set a seed based on the dex file checksums.
2724 // That makes the seed also most likely different for different inputs, for example
2725 // for primary boot image and different extensions that could be loaded together.
2726 mirror::Object::SetHashCodeSeed(987654321u ^ GetCombinedChecksums());
2727
2728 TimingLogger::ScopedTiming t_runtime("Create runtime", timings_);
2729 if (!Runtime::Create(std::move(runtime_options))) {
2730 LOG(ERROR) << "Failed to create runtime";
2731 return false;
2732 }
2733
2734 // Runtime::Init will rename this thread to be "main". Prefer "dex2oat" so that "top" and
2735 // "ps -a" don't change to non-descript "main."
2736 SetThreadName(kIsDebugBuild ? "dex2oatd" : "dex2oat");
2737
2738 runtime_.reset(Runtime::Current());
2739 runtime_->SetInstructionSet(compiler_options_->GetInstructionSet());
2740 for (uint32_t i = 0; i < static_cast<uint32_t>(CalleeSaveType::kLastCalleeSaveType); ++i) {
2741 CalleeSaveType type = CalleeSaveType(i);
2742 if (!runtime_->HasCalleeSaveMethod(type)) {
2743 runtime_->SetCalleeSaveMethod(runtime_->CreateCalleeSaveMethod(), type);
2744 }
2745 }
2746
2747 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
2748 // set up.
2749 interpreter::UnstartedRuntime::Initialize();
2750
2751 Thread* self = Thread::Current();
2752 runtime_->GetClassLinker()->RunEarlyRootClinits(self);
2753 InitializeIntrinsics();
2754 runtime_->RunRootClinits(self);
2755
2756 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
2757 // Runtime::Start, give it away now so that we don't starve GC.
2758 self->TransitionFromRunnableToSuspended(ThreadState::kNative);
2759
2760 WatchDog::SetRuntime(runtime_.get());
2761
2762 return true;
2763 }
2764
2765 // Let the ImageWriter write the image files. If we do not compile PIC, also fix up the oat files.
CreateImageFile()2766 bool CreateImageFile()
2767 REQUIRES(!Locks::mutator_lock_) {
2768 CHECK(image_writer_ != nullptr);
2769 if (IsAppImage()) {
2770 DCHECK(image_filenames_.empty());
2771 if (app_image_fd_ != -1) {
2772 image_filenames_.push_back(StringPrintf("FileDescriptor[%d]", app_image_fd_));
2773 } else {
2774 image_filenames_.push_back(app_image_file_name_);
2775 }
2776 }
2777 if (image_fd_ != -1) {
2778 DCHECK(image_filenames_.empty());
2779 image_filenames_.push_back(StringPrintf("FileDescriptor[%d]", image_fd_));
2780 }
2781 if (!image_writer_->Write(IsAppImage() ? app_image_fd_ : image_fd_,
2782 image_filenames_,
2783 IsAppImage() ? 1u : dex_locations_.size())) {
2784 LOG(ERROR) << "Failure during image file creation";
2785 return false;
2786 }
2787
2788 // We need the OatDataBegin entries.
2789 dchecked_vector<uintptr_t> oat_data_begins;
2790 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
2791 oat_data_begins.push_back(image_writer_->GetOatDataBegin(i));
2792 }
2793 // Destroy ImageWriter.
2794 image_writer_.reset();
2795
2796 return true;
2797 }
2798
2799 template <typename T>
ReadCommentedInputFromFile(const char * input_filename,std::function<std::string (const char *)> * process,T * output)2800 static bool ReadCommentedInputFromFile(
2801 const char* input_filename, std::function<std::string(const char*)>* process, T* output) {
2802 auto input_file = std::unique_ptr<FILE, decltype(&fclose)>{fopen(input_filename, "re"), fclose};
2803 if (!input_file) {
2804 LOG(ERROR) << "Failed to open input file " << input_filename;
2805 return false;
2806 }
2807 ReadCommentedInputStream<T>(input_file.get(), process, output);
2808 return true;
2809 }
2810
2811 template <typename T>
ReadCommentedInputFromFd(int input_fd,std::function<std::string (const char *)> * process,T * output)2812 static bool ReadCommentedInputFromFd(
2813 int input_fd, std::function<std::string(const char*)>* process, T* output) {
2814 auto input_file = std::unique_ptr<FILE, decltype(&fclose)>{fdopen(input_fd, "r"), fclose};
2815 if (!input_file) {
2816 LOG(ERROR) << "Failed to re-open input fd from /prof/self/fd/" << input_fd;
2817 return false;
2818 }
2819 ReadCommentedInputStream<T>(input_file.get(), process, output);
2820 return true;
2821 }
2822
2823 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
2824 // the given function.
2825 template <typename T>
ReadCommentedInputFromFile(const char * input_filename,std::function<std::string (const char *)> * process)2826 static std::unique_ptr<T> ReadCommentedInputFromFile(
2827 const char* input_filename, std::function<std::string(const char*)>* process) {
2828 std::unique_ptr<T> output(new T());
2829 ReadCommentedInputFromFile(input_filename, process, output.get());
2830 return output;
2831 }
2832
2833 // Read lines from the given fd, dropping comments and empty lines. Post-process each line with
2834 // the given function.
2835 template <typename T>
ReadCommentedInputFromFd(int input_fd,std::function<std::string (const char *)> * process)2836 static std::unique_ptr<T> ReadCommentedInputFromFd(
2837 int input_fd, std::function<std::string(const char*)>* process) {
2838 std::unique_ptr<T> output(new T());
2839 ReadCommentedInputFromFd(input_fd, process, output.get());
2840 return output;
2841 }
2842
2843 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
2844 // with the given function.
ReadCommentedInputStream(std::FILE * in_stream,std::function<std::string (const char *)> * process,T * output)2845 template <typename T> static void ReadCommentedInputStream(
2846 std::FILE* in_stream,
2847 std::function<std::string(const char*)>* process,
2848 T* output) {
2849 char* line = nullptr;
2850 size_t line_alloc = 0;
2851 ssize_t len = 0;
2852 while ((len = getline(&line, &line_alloc, in_stream)) > 0) {
2853 if (line[0] == '\0' || line[0] == '#' || line[0] == '\n') {
2854 continue;
2855 }
2856 if (line[len - 1] == '\n') {
2857 line[len - 1] = '\0';
2858 }
2859 if (process != nullptr) {
2860 std::string descriptor((*process)(line));
2861 output->insert(output->end(), descriptor);
2862 } else {
2863 output->insert(output->end(), line);
2864 }
2865 }
2866 free(line);
2867 }
2868
LogCompletionTime()2869 void LogCompletionTime() {
2870 // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there
2871 // is no image, there won't be a Runtime::Current().
2872 // Note: driver creation can fail when loading an invalid dex file.
2873 LOG(INFO) << "dex2oat took "
2874 << PrettyDuration(NanoTime() - start_ns_)
2875 << " (" << PrettyDuration(ProcessCpuNanoTime() - start_cputime_ns_) << " cpu)"
2876 << " (threads: " << thread_count_ << ") "
2877 << ((Runtime::Current() != nullptr && driver_ != nullptr) ?
2878 driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) :
2879 "");
2880 }
2881
StripIsaFrom(const char * image_filename,InstructionSet isa)2882 std::string StripIsaFrom(const char* image_filename, InstructionSet isa) {
2883 std::string res(image_filename);
2884 size_t last_slash = res.rfind('/');
2885 if (last_slash == std::string::npos || last_slash == 0) {
2886 return res;
2887 }
2888 size_t penultimate_slash = res.rfind('/', last_slash - 1);
2889 if (penultimate_slash == std::string::npos) {
2890 return res;
2891 }
2892 // Check that the string in-between is the expected one.
2893 if (res.substr(penultimate_slash + 1, last_slash - penultimate_slash - 1) !=
2894 GetInstructionSetString(isa)) {
2895 LOG(WARNING) << "Unexpected string when trying to strip isa: " << res;
2896 return res;
2897 }
2898 return res.substr(0, penultimate_slash) + res.substr(last_slash);
2899 }
2900
2901 std::unique_ptr<CompilerOptions> compiler_options_;
2902
2903 std::unique_ptr<OatKeyValueStore> key_value_store_;
2904
2905 std::unique_ptr<VerificationResults> verification_results_;
2906
2907 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
2908
2909 std::unique_ptr<Runtime> runtime_;
2910
2911 // The spec describing how the class loader should be setup for compilation.
2912 std::unique_ptr<ClassLoaderContext> class_loader_context_;
2913
2914 // Optional list of file descriptors corresponding to dex file locations in
2915 // flattened `class_loader_context_`.
2916 std::vector<int> class_loader_context_fds_;
2917
2918 // The class loader context stored in the oat file. May be equal to class_loader_context_.
2919 std::unique_ptr<ClassLoaderContext> stored_class_loader_context_;
2920
2921 size_t thread_count_;
2922 std::vector<int32_t> cpu_set_;
2923 uint64_t start_ns_;
2924 uint64_t start_cputime_ns_;
2925 std::unique_ptr<WatchDog> watchdog_;
2926 std::vector<std::unique_ptr<File>> oat_files_;
2927 std::vector<std::unique_ptr<File>> vdex_files_;
2928 std::string oat_location_;
2929 std::vector<std::string> oat_filenames_;
2930 std::vector<std::string> oat_unstripped_;
2931 bool strip_;
2932 int oat_fd_;
2933 int input_vdex_fd_;
2934 int output_vdex_fd_;
2935 std::string input_vdex_;
2936 std::string output_vdex_;
2937 std::unique_ptr<VdexFile> input_vdex_file_;
2938 int dm_fd_;
2939 std::string dm_file_location_;
2940 std::unique_ptr<ZipArchive> dm_file_;
2941 std::vector<std::string> dex_filenames_;
2942 std::vector<std::string> dex_locations_;
2943 std::vector<int> dex_fds_;
2944 int zip_fd_;
2945 std::string zip_location_;
2946 std::string boot_image_filename_;
2947 std::vector<const char*> runtime_args_;
2948 std::vector<std::string> image_filenames_;
2949 int image_fd_;
2950 bool have_multi_image_arg_;
2951 uintptr_t image_base_;
2952 ImageHeader::StorageMode image_storage_mode_;
2953 const char* passes_to_run_filename_;
2954 std::vector<std::string> dirty_image_objects_filenames_;
2955 std::vector<int> dirty_image_objects_fds_;
2956 std::unique_ptr<std::vector<std::string>> dirty_image_objects_;
2957 std::unique_ptr<std::vector<std::string>> passes_to_run_;
2958 bool is_host_;
2959 std::string android_root_;
2960 std::string no_inline_from_string_;
2961 bool force_allow_oj_inlines_ = false;
2962
2963 std::vector<std::unique_ptr<linker::ElfWriter>> elf_writers_;
2964 std::vector<std::unique_ptr<linker::OatWriter>> oat_writers_;
2965 std::vector<OutputStream*> rodata_;
2966 std::vector<std::unique_ptr<OutputStream>> vdex_out_;
2967 std::unique_ptr<linker::ImageWriter> image_writer_;
2968 std::unique_ptr<CompilerDriver> driver_;
2969
2970 std::vector<MemMap> opened_dex_files_maps_;
2971 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
2972
2973 bool avoid_storing_invocation_;
2974 android::base::unique_fd invocation_file_;
2975 std::string swap_file_name_;
2976 int swap_fd_;
2977 size_t min_dex_files_for_swap_ = kDefaultMinDexFilesForSwap;
2978 size_t min_dex_file_cumulative_size_for_swap_ = kDefaultMinDexFileCumulativeSizeForSwap;
2979 size_t very_large_threshold_ = std::numeric_limits<size_t>::max();
2980 std::string app_image_file_name_;
2981 int app_image_fd_;
2982 std::vector<std::string> profile_files_;
2983 std::vector<int> profile_file_fds_;
2984 std::vector<std::string> preloaded_classes_files_;
2985 std::vector<int> preloaded_classes_fds_;
2986 std::unique_ptr<ProfileCompilationInfo> profile_compilation_info_;
2987 TimingLogger* timings_;
2988 std::vector<std::vector<const DexFile*>> dex_files_per_oat_file_;
2989 HashMap<const DexFile*, size_t> dex_file_oat_index_map_;
2990
2991 // Backing storage.
2992 std::forward_list<std::string> char_backing_storage_;
2993
2994 // See CompilerOptions.force_determinism_.
2995 bool force_determinism_;
2996 // See CompilerOptions.crash_on_linkage_violation_.
2997 bool check_linkage_conditions_;
2998 // See CompilerOptions.crash_on_linkage_violation_.
2999 bool crash_on_linkage_violation_;
3000
3001 // Directory of relative classpaths.
3002 std::string classpath_dir_;
3003
3004 // Whether the given input vdex is also the output.
3005 bool use_existing_vdex_ = false;
3006
3007 // By default, copy the dex to the vdex file only if dex files are
3008 // compressed in APK.
3009 linker::CopyOption copy_dex_files_ = linker::CopyOption::kOnlyIfCompressed;
3010
3011 // The reason for invoking the compiler.
3012 std::string compilation_reason_;
3013
3014 // Whether to force individual compilation.
3015 bool compile_individually_;
3016
3017 // The classpath that determines if a given symbol should be resolved at compile time or not.
3018 std::string public_sdk_;
3019
3020 // The apex versions of jars in the boot classpath. Set through command line
3021 // argument.
3022 std::string apex_versions_argument_;
3023
3024 // Whether or we attempted to load the profile (if given).
3025 bool profile_load_attempted_;
3026
3027 // Whether PaletteNotify{Start,End}Dex2oatCompilation should be called.
3028 bool should_report_dex2oat_compilation_;
3029
3030 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
3031 };
3032
b13564922()3033 static void b13564922() {
3034 #if defined(__linux__) && defined(__arm__)
3035 int major, minor;
3036 struct utsname uts;
3037 if (uname(&uts) != -1 &&
3038 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
3039 ((major < 3) || ((major == 3) && (minor < 4)))) {
3040 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
3041 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
3042 int old_personality = personality(0xffffffff);
3043 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
3044 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
3045 if (new_personality == -1) {
3046 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
3047 }
3048 }
3049 }
3050 #endif
3051 }
3052
3053 class ScopedGlobalRef {
3054 public:
ScopedGlobalRef(jobject obj)3055 explicit ScopedGlobalRef(jobject obj) : obj_(obj) {}
~ScopedGlobalRef()3056 ~ScopedGlobalRef() {
3057 if (obj_ != nullptr) {
3058 ScopedObjectAccess soa(Thread::Current());
3059 soa.Env()->GetVm()->DeleteGlobalRef(soa.Self(), obj_);
3060 }
3061 }
3062
3063 private:
3064 jobject obj_;
3065 };
3066
DoCompilation(Dex2Oat & dex2oat)3067 static dex2oat::ReturnCode DoCompilation(Dex2Oat& dex2oat) REQUIRES(!Locks::mutator_lock_) {
3068 Locks::mutator_lock_->AssertNotHeld(Thread::Current());
3069 dex2oat.LoadImageClassDescriptors();
3070 jobject class_loader = dex2oat.Compile();
3071 // Keep the class loader that was used for compilation live for the rest of the compilation
3072 // process.
3073 ScopedGlobalRef global_ref(class_loader);
3074
3075 if (!dex2oat.WriteOutputFiles(class_loader)) {
3076 dex2oat.EraseOutputFiles();
3077 return dex2oat::ReturnCode::kOther;
3078 }
3079
3080 // Flush output files. Keep them open as we might still modify them later (strip them).
3081 if (!dex2oat.FlushOutputFiles()) {
3082 dex2oat.EraseOutputFiles();
3083 return dex2oat::ReturnCode::kOther;
3084 }
3085
3086 // Creates the boot.art and patches the oat files.
3087 if (!dex2oat.HandleImage()) {
3088 return dex2oat::ReturnCode::kOther;
3089 }
3090
3091 // When given --host, finish early without stripping.
3092 if (dex2oat.IsHost()) {
3093 if (!dex2oat.FlushCloseOutputFiles()) {
3094 return dex2oat::ReturnCode::kOther;
3095 }
3096 dex2oat.DumpTiming();
3097 return dex2oat::ReturnCode::kNoFailure;
3098 }
3099
3100 // Copy stripped to unstripped location, if necessary. This will implicitly flush & close the
3101 // stripped versions. If this is given, we expect to be able to open writable files by name.
3102 if (!dex2oat.CopyOatFilesToSymbolsDirectoryAndStrip()) {
3103 return dex2oat::ReturnCode::kOther;
3104 }
3105
3106 // FlushClose again, as stripping might have re-opened the oat files.
3107 if (!dex2oat.FlushCloseOutputFiles()) {
3108 return dex2oat::ReturnCode::kOther;
3109 }
3110
3111 dex2oat.DumpTiming();
3112 return dex2oat::ReturnCode::kNoFailure;
3113 }
3114
Dex2oat(int argc,char ** argv)3115 static dex2oat::ReturnCode Dex2oat(int argc, char** argv) {
3116 b13564922();
3117
3118 TimingLogger timings("compiler", false, false);
3119
3120 // Allocate `dex2oat` on the heap instead of on the stack, as Clang
3121 // might produce a stack frame too large for this function or for
3122 // functions inlining it (such as main), that would not fit the
3123 // requirements of the `-Wframe-larger-than` option.
3124 std::unique_ptr<Dex2Oat> dex2oat = std::make_unique<Dex2Oat>(&timings);
3125
3126 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
3127 dex2oat->ParseArgs(argc, argv);
3128
3129 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap, vdex and profiles.
3130
3131 // If needed, process profile information for profile guided compilation.
3132 // This operation involves I/O.
3133 if (dex2oat->HasProfileInput()) {
3134 if (!dex2oat->LoadProfile()) {
3135 LOG(ERROR) << "Failed to process profile file";
3136 return dex2oat::ReturnCode::kOther;
3137 }
3138 }
3139
3140 // Check if we need to update any of the compiler options (such as the filter)
3141 // and do it before anything else (so that the other operations have a true
3142 // view of the state).
3143 dex2oat->UpdateCompilerOptionsBasedOnProfile();
3144
3145 // Insert the compiler options in the key value store.
3146 // We have to do this after we altered any incoming arguments
3147 // (such as the compiler filter).
3148 dex2oat->InsertCompileOptions(argc, argv);
3149
3150 // Check early that the result of compilation can be written
3151 if (!dex2oat->OpenFile()) {
3152 // Flush close so that the File Guard checks don't fail the assertions.
3153 dex2oat->FlushCloseOutputFiles();
3154 return dex2oat::ReturnCode::kOther;
3155 }
3156
3157 // Print the complete line when any of the following is true:
3158 // 1) Debug build
3159 // 2) Compiling an image
3160 // 3) Compiling with --host
3161 // 4) Compiling on the host (not a target build)
3162 // Otherwise, print a stripped command line.
3163 if (kIsDebugBuild ||
3164 dex2oat->IsBootImage() || dex2oat->IsBootImageExtension() ||
3165 dex2oat->IsHost() ||
3166 !kIsTargetBuild) {
3167 LOG(INFO) << CommandLine();
3168 } else {
3169 LOG(INFO) << StrippedCommandLine();
3170 }
3171
3172 Dex2Oat::ScopedDex2oatReporting sdr(*dex2oat.get());
3173
3174 if (sdr.ErrorReporting()) {
3175 dex2oat->EraseOutputFiles();
3176 return dex2oat::ReturnCode::kOther;
3177 }
3178
3179 dex2oat::ReturnCode setup_code = dex2oat->Setup();
3180 if (setup_code != dex2oat::ReturnCode::kNoFailure) {
3181 dex2oat->EraseOutputFiles();
3182 return setup_code;
3183 }
3184
3185 // TODO: Due to the cyclic dependencies, profile loading and verifying are
3186 // being done separately. Refactor and place the two next to each other.
3187 // If verification fails, we don't abort the compilation and instead log an
3188 // error.
3189 // TODO(b/62602192, b/65260586): We should consider aborting compilation when
3190 // the profile verification fails.
3191 // Note: If dex2oat fails, installd will remove the oat files causing the app
3192 // to fallback to apk with possible in-memory extraction. We want to avoid
3193 // that, and thus we're lenient towards profile corruptions.
3194 if (dex2oat->DoProfileGuidedOptimizations()) {
3195 dex2oat->VerifyProfileData();
3196 }
3197
3198 // Helps debugging on device. Can be used to determine which dalvikvm instance invoked a dex2oat
3199 // instance. Used by tools/bisection_search/bisection_search.py.
3200 VLOG(compiler) << "Running dex2oat (parent PID = " << getppid() << ")";
3201
3202 dex2oat::ReturnCode result = DoCompilation(*dex2oat);
3203
3204 return result;
3205 }
3206 } // namespace art
3207
main(int argc,char ** argv)3208 int main(int argc, char** argv) {
3209 int result = static_cast<int>(art::Dex2oat(argc, argv));
3210 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
3211 // time (bug 10645725) unless we're a debug or instrumented build or running on a memory tool.
3212 // Note: The Dex2Oat class should not destruct the runtime in this case.
3213 if (!art::kIsDebugBuild && !art::kIsPGOInstrumentation && !art::kRunningOnMemoryTool) {
3214 art::FastExit(result);
3215 }
3216 return result;
3217 }
3218