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