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