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