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