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