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