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