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