• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "runtime.h"
18 
19 #include <optional>
20 #include <utility>
21 
22 #ifdef __linux__
23 #include <sys/prctl.h>
24 #endif
25 
26 #include <fcntl.h>
27 #include <signal.h>
28 #include <sys/mount.h>
29 #include <sys/syscall.h>
30 
31 #if defined(__APPLE__)
32 #include <crt_externs.h>  // for _NSGetEnviron
33 #endif
34 
35 #include <android-base/properties.h>
36 #include <android-base/strings.h>
37 #include <string.h>
38 
39 #include <cstdio>
40 #include <cstdlib>
41 #include <limits>
42 #include <thread>
43 #include <unordered_set>
44 #include <vector>
45 
46 #include "arch/arm/registers_arm.h"
47 #include "arch/arm64/registers_arm64.h"
48 #include "arch/context.h"
49 #include "arch/instruction_set_features.h"
50 #include "arch/x86/registers_x86.h"
51 #include "arch/x86_64/registers_x86_64.h"
52 #include "art_field-inl.h"
53 #include "art_method-inl.h"
54 #include "asm_support.h"
55 #include "base/aborting.h"
56 #include "base/arena_allocator.h"
57 #include "base/atomic.h"
58 #include "base/dumpable.h"
59 #include "base/file_utils.h"
60 #include "base/flags.h"
61 #include "base/malloc_arena_pool.h"
62 #include "base/mem_map_arena_pool.h"
63 #include "base/memory_tool.h"
64 #include "base/mutex.h"
65 #include "base/os.h"
66 #include "base/pointer_size.h"
67 #include "base/quasi_atomic.h"
68 #include "base/sdk_version.h"
69 #include "base/stl_util.h"
70 #include "base/systrace.h"
71 #include "base/unix_file/fd_file.h"
72 #include "base/utils.h"
73 #include "class_linker-inl.h"
74 #include "class_root-inl.h"
75 #include "compiler_callbacks.h"
76 #include "debugger.h"
77 #include "dex/art_dex_file_loader.h"
78 #include "dex/dex_file_loader.h"
79 #include "entrypoints/entrypoint_utils-inl.h"
80 #include "entrypoints/runtime_asm_entrypoints.h"
81 #include "experimental_flags.h"
82 #include "fault_handler.h"
83 #include "gc/accounting/card_table-inl.h"
84 #include "gc/heap.h"
85 #include "gc/scoped_gc_critical_section.h"
86 #include "gc/space/image_space.h"
87 #include "gc/space/space-inl.h"
88 #include "gc/system_weak.h"
89 #include "gc/task_processor.h"
90 #include "handle_scope-inl.h"
91 #include "hidden_api.h"
92 #include "indirect_reference_table.h"
93 #include "instrumentation.h"
94 #include "intern_table-inl.h"
95 #include "interpreter/interpreter.h"
96 #include "jit/jit.h"
97 #include "jit/jit_code_cache.h"
98 #include "jit/profile_saver.h"
99 #include "jni/java_vm_ext.h"
100 #include "jni/jni_id_manager.h"
101 #include "jni_id_type.h"
102 #include "linear_alloc.h"
103 #include "memory_representation.h"
104 #include "metrics/statsd.h"
105 #include "mirror/array.h"
106 #include "mirror/class-alloc-inl.h"
107 #include "mirror/class-inl.h"
108 #include "mirror/class_ext.h"
109 #include "mirror/class_loader-inl.h"
110 #include "mirror/emulated_stack_frame.h"
111 #include "mirror/field.h"
112 #include "mirror/method.h"
113 #include "mirror/method_handle_impl.h"
114 #include "mirror/method_handles_lookup.h"
115 #include "mirror/method_type.h"
116 #include "mirror/stack_trace_element.h"
117 #include "mirror/throwable.h"
118 #include "mirror/var_handle.h"
119 #include "monitor.h"
120 #include "native/dalvik_system_BaseDexClassLoader.h"
121 #include "native/dalvik_system_DexFile.h"
122 #include "native/dalvik_system_VMDebug.h"
123 #include "native/dalvik_system_VMRuntime.h"
124 #include "native/dalvik_system_VMStack.h"
125 #include "native/dalvik_system_ZygoteHooks.h"
126 #include "native/java_lang_Class.h"
127 #include "native/java_lang_Object.h"
128 #include "native/java_lang_StackStreamFactory.h"
129 #include "native/java_lang_String.h"
130 #include "native/java_lang_StringFactory.h"
131 #include "native/java_lang_System.h"
132 #include "native/java_lang_Thread.h"
133 #include "native/java_lang_Throwable.h"
134 #include "native/java_lang_VMClassLoader.h"
135 #include "native/java_lang_invoke_MethodHandle.h"
136 #include "native/java_lang_invoke_MethodHandleImpl.h"
137 #include "native/java_lang_ref_FinalizerReference.h"
138 #include "native/java_lang_ref_Reference.h"
139 #include "native/java_lang_reflect_Array.h"
140 #include "native/java_lang_reflect_Constructor.h"
141 #include "native/java_lang_reflect_Executable.h"
142 #include "native/java_lang_reflect_Field.h"
143 #include "native/java_lang_reflect_Method.h"
144 #include "native/java_lang_reflect_Parameter.h"
145 #include "native/java_lang_reflect_Proxy.h"
146 #include "native/java_util_concurrent_atomic_AtomicLong.h"
147 #include "native/jdk_internal_misc_Unsafe.h"
148 #include "native/libcore_io_Memory.h"
149 #include "native/libcore_util_CharsetUtils.h"
150 #include "native/org_apache_harmony_dalvik_ddmc_DdmServer.h"
151 #include "native/org_apache_harmony_dalvik_ddmc_DdmVmInternal.h"
152 #include "native/sun_misc_Unsafe.h"
153 #include "native_bridge_art_interface.h"
154 #include "native_stack_dump.h"
155 #include "nativehelper/scoped_local_ref.h"
156 #include "nterp_helpers.h"
157 #include "oat/elf_file.h"
158 #include "oat/image-inl.h"
159 #include "oat/oat.h"
160 #include "oat/oat_file_manager.h"
161 #include "oat/oat_quick_method_header.h"
162 #include "object_callbacks.h"
163 #include "odr_statslog/odr_statslog.h"
164 #include "parsed_options.h"
165 #include "quick/quick_method_frame_info.h"
166 #include "reflection.h"
167 #include "runtime_callbacks.h"
168 #include "runtime_common.h"
169 #include "runtime_image.h"
170 #include "runtime_intrinsics.h"
171 #include "runtime_options.h"
172 #include "scoped_thread_state_change-inl.h"
173 #include "sigchain.h"
174 #include "signal_catcher.h"
175 #include "signal_set.h"
176 #include "thread.h"
177 #include "thread_list.h"
178 #include "ti/agent.h"
179 #include "trace.h"
180 #include "vdex_file.h"
181 #include "verifier/class_verifier.h"
182 #include "well_known_classes-inl.h"
183 
184 #ifdef ART_TARGET_ANDROID
185 #include <android/api-level.h>
186 #include <android/set_abort_message.h>
187 #include "com_android_apex.h"
188 namespace apex = com::android::apex;
189 
190 #endif
191 
192 // Static asserts to check the values of generated assembly-support macros.
193 #define ASM_DEFINE(NAME, EXPR) static_assert((NAME) == (EXPR), "Unexpected value of " #NAME);
194 #include "asm_defines.def"
195 #undef ASM_DEFINE
196 
197 namespace art HIDDEN {
198 
199 // If a signal isn't handled properly, enable a handler that attempts to dump the Java stack.
200 static constexpr bool kEnableJavaStackTraceHandler = false;
201 // Tuned by compiling GmsCore under perf and measuring time spent in DescriptorEquals for class
202 // linking.
203 static constexpr double kLowMemoryMinLoadFactor = 0.5;
204 static constexpr double kLowMemoryMaxLoadFactor = 0.8;
205 static constexpr double kNormalMinLoadFactor = 0.4;
206 static constexpr double kNormalMaxLoadFactor = 0.7;
207 
208 #ifdef ART_PAGE_SIZE_AGNOSTIC
209 // Declare the constant as ALWAYS_HIDDEN to ensure it isn't visible from outside libart.so.
210 const size_t PageSize::value_ ALWAYS_HIDDEN = GetPageSizeSlow();
211 PageSize gPageSize ALWAYS_HIDDEN;
212 #endif
213 
214 Runtime* Runtime::instance_ = nullptr;
215 
216 struct TraceConfig {
217   Trace::TraceMode trace_mode;
218   TraceOutputMode trace_output_mode;
219   std::string trace_file;
220   size_t trace_file_size;
221   TraceClockSource clock_source;
222 };
223 
224 extern bool ShouldUseGenerationalGC();
225 
226 namespace {
227 
228 #ifdef __APPLE__
GetEnviron()229 inline char** GetEnviron() {
230   // When Google Test is built as a framework on MacOS X, the environ variable
231   // is unavailable. Apple's documentation (man environ) recommends using
232   // _NSGetEnviron() instead.
233   return *_NSGetEnviron();
234 }
235 #else
236 // Some POSIX platforms expect you to declare environ. extern "C" makes
237 // it reside in the global namespace.
238 EXPORT extern "C" char** environ;
239 inline char** GetEnviron() { return environ; }
240 #endif
241 
CheckConstants()242 void CheckConstants() {
243   CHECK_EQ(mirror::Array::kFirstElementOffset, mirror::Array::FirstElementOffset());
244 }
245 
246 }  // namespace
247 
Runtime()248 Runtime::Runtime()
249     : resolution_method_(nullptr),
250       imt_conflict_method_(nullptr),
251       imt_unimplemented_method_(nullptr),
252       instruction_set_(InstructionSet::kNone),
253       compiler_callbacks_(nullptr),
254       is_zygote_(false),
255       is_primary_zygote_(false),
256       is_system_server_(false),
257       must_relocate_(false),
258       is_concurrent_gc_enabled_(true),
259       is_explicit_gc_disabled_(false),
260       is_eagerly_release_explicit_gc_disabled_(false),
261       image_dex2oat_enabled_(true),
262       default_stack_size_(0),
263       heap_(nullptr),
264       max_spins_before_thin_lock_inflation_(Monitor::kDefaultMaxSpinsBeforeThinLockInflation),
265       monitor_list_(nullptr),
266       monitor_pool_(nullptr),
267       thread_list_(nullptr),
268       intern_table_(nullptr),
269       class_linker_(nullptr),
270       signal_catcher_(nullptr),
271       java_vm_(nullptr),
272       thread_pool_ref_count_(0u),
273       fault_message_(nullptr),
274       threads_being_born_(0),
275       shutdown_cond_(new ConditionVariable("Runtime shutdown", *Locks::runtime_shutdown_lock_)),
276       shutting_down_(false),
277       shutting_down_started_(false),
278       started_(false),
279       finished_starting_(false),
280       vfprintf_(nullptr),
281       exit_(nullptr),
282       abort_(nullptr),
283       stats_enabled_(false),
284       is_running_on_memory_tool_(kRunningOnMemoryTool),
285       instrumentation_(new instrumentation::Instrumentation()),
286       main_thread_group_(nullptr),
287       system_thread_group_(nullptr),
288       system_class_loader_(nullptr),
289       dump_gc_performance_on_shutdown_(false),
290       active_transaction_(false),
291       verify_(verifier::VerifyMode::kNone),
292       target_sdk_version_(static_cast<uint32_t>(SdkVersion::kUnset)),
293       compat_framework_(),
294       implicit_null_checks_(false),
295       implicit_so_checks_(false),
296       implicit_suspend_checks_(false),
297       no_sig_chain_(false),
298       force_native_bridge_(false),
299       is_native_bridge_loaded_(false),
300       is_native_debuggable_(false),
301       async_exceptions_thrown_(false),
302       non_standard_exits_enabled_(false),
303       runtime_debug_state_(RuntimeDebugState::kNonJavaDebuggable),
304       monitor_timeout_enable_(false),
305       monitor_timeout_ns_(0),
306       zygote_max_failed_boots_(0),
307       experimental_flags_(ExperimentalFlags::kNone),
308       oat_file_manager_(nullptr),
309       is_low_memory_mode_(false),
310       madvise_willneed_total_dex_size_(0),
311       madvise_willneed_odex_filesize_(0),
312       madvise_willneed_art_filesize_(0),
313       safe_mode_(false),
314       hidden_api_policy_(hiddenapi::EnforcementPolicy::kDisabled),
315       core_platform_api_policy_(hiddenapi::EnforcementPolicy::kDisabled),
316       test_api_policy_(hiddenapi::EnforcementPolicy::kDisabled),
317       dedupe_hidden_api_warnings_(true),
318       hidden_api_access_event_log_rate_(0),
319       dump_native_stack_on_sig_quit_(true),
320       // Initially assume we perceive jank in case the process state is never updated.
321       process_state_(kProcessStateJankPerceptible),
322       zygote_no_threads_(false),
323       verifier_logging_threshold_ms_(100),
324       verifier_missing_kthrow_fatal_(false),
325       perfetto_hprof_enabled_(false),
326       perfetto_javaheapprof_enabled_(false),
327       out_of_memory_error_hook_(nullptr) {
328   static_assert(Runtime::kCalleeSaveSize ==
329                     static_cast<uint32_t>(CalleeSaveType::kLastCalleeSaveType), "Unexpected size");
330   CheckConstants();
331 
332   std::fill(callee_save_methods_, callee_save_methods_ + arraysize(callee_save_methods_), 0u);
333   interpreter::CheckInterpreterAsmConstants();
334   callbacks_.reset(new RuntimeCallbacks());
335   for (size_t i = 0; i <= static_cast<size_t>(DeoptimizationKind::kLast); ++i) {
336     deoptimization_counts_[i] = 0u;
337   }
338 }
339 
~Runtime()340 Runtime::~Runtime() {
341   ScopedTrace trace("Runtime shutdown");
342   if (is_native_bridge_loaded_) {
343     UnloadNativeBridge();
344   }
345 
346   Thread* self = Thread::Current();
347   const bool attach_shutdown_thread = self == nullptr;
348   if (attach_shutdown_thread) {
349     // We can only create a peer if the runtime is actually started. This is only not true during
350     // some tests. If there is extreme memory pressure the allocation of the thread peer can fail.
351     // In this case we will just try again without allocating a peer so that shutdown can continue.
352     // Very few things are actually capable of distinguishing between the peer & peerless states so
353     // this should be fine.
354     // Running callbacks is prone to deadlocks in libjdwp tests that need an event handler lock to
355     // process any event. We also need to enter a GCCriticalSection when processing certain events
356     // (for ex: removing the last breakpoint). These two restrictions together make the tear down
357     // of the jdwp tests deadlock prone if we fail to finish Thread::Attach callback.
358     // (TODO:b/251163712) Remove this once we update deopt manager to not use GCCriticalSection.
359     bool thread_attached = AttachCurrentThread("Shutdown thread",
360                                                /* as_daemon= */ false,
361                                                GetSystemThreadGroup(),
362                                                /* create_peer= */ IsStarted(),
363                                                /* should_run_callbacks= */ false);
364     if (UNLIKELY(!thread_attached)) {
365       LOG(WARNING) << "Failed to attach shutdown thread. Trying again without a peer.";
366       CHECK(AttachCurrentThread("Shutdown thread (no java peer)",
367                                 /* as_daemon= */   false,
368                                 /* thread_group=*/ nullptr,
369                                 /* create_peer= */ false));
370     }
371     self = Thread::Current();
372   } else {
373     LOG(WARNING) << "Current thread not detached in Runtime shutdown";
374   }
375 
376   if (dump_gc_performance_on_shutdown_) {
377     heap_->CalculatePreGcWeightedAllocatedBytes();
378     uint64_t process_cpu_end_time = ProcessCpuNanoTime();
379     ScopedLogSeverity sls(LogSeverity::INFO);
380     // This can't be called from the Heap destructor below because it
381     // could call RosAlloc::InspectAll() which needs the thread_list
382     // to be still alive.
383     heap_->DumpGcPerformanceInfo(LOG_STREAM(INFO));
384 
385     uint64_t process_cpu_time = process_cpu_end_time - heap_->GetProcessCpuStartTime();
386     uint64_t gc_cpu_time = heap_->GetTotalGcCpuTime();
387     float ratio = static_cast<float>(gc_cpu_time) / process_cpu_time;
388     LOG_STREAM(INFO) << "GC CPU time " << PrettyDuration(gc_cpu_time)
389         << " out of process CPU time " << PrettyDuration(process_cpu_time)
390         << " (" << ratio << ")"
391         << "\n";
392     double pre_gc_weighted_allocated_bytes =
393         heap_->GetPreGcWeightedAllocatedBytes() / process_cpu_time;
394     // Here we don't use process_cpu_time for normalization, because VM shutdown is not a real
395     // GC. Both numerator and denominator take into account until the end of the last GC,
396     // instead of the whole process life time like pre_gc_weighted_allocated_bytes.
397     double post_gc_weighted_allocated_bytes =
398         heap_->GetPostGcWeightedAllocatedBytes() /
399           (heap_->GetPostGCLastProcessCpuTime() - heap_->GetProcessCpuStartTime());
400 
401     LOG_STREAM(INFO) << "Average bytes allocated at GC start, weighted by CPU time between GCs: "
402         << static_cast<uint64_t>(pre_gc_weighted_allocated_bytes)
403         << " (" <<  PrettySize(pre_gc_weighted_allocated_bytes)  << ")";
404     LOG_STREAM(INFO) << "Average bytes allocated at GC end, weighted by CPU time between GCs: "
405         << static_cast<uint64_t>(post_gc_weighted_allocated_bytes)
406         << " (" <<  PrettySize(post_gc_weighted_allocated_bytes)  << ")"
407         << "\n";
408   }
409 
410   // Wait for the workers of thread pools to be created since there can't be any
411   // threads attaching during shutdown.
412   WaitForThreadPoolWorkersToStart();
413   if (jit_ != nullptr) {
414     jit_->WaitForWorkersToBeCreated();
415     // Stop the profile saver thread before marking the runtime as shutting down.
416     // The saver will try to dump the profiles before being sopped and that
417     // requires holding the mutator lock.
418     jit_->StopProfileSaver();
419     // Delete thread pool before the thread list since we don't want to wait forever on the
420     // JIT compiler threads. Also this should be run before marking the runtime
421     // as shutting down as some tasks may require mutator access.
422     jit_->DeleteThreadPool();
423   }
424   if (oat_file_manager_ != nullptr) {
425     oat_file_manager_->WaitForWorkersToBeCreated();
426   }
427   // Disable GC before deleting the thread-pool and shutting down runtime as it
428   // restricts attaching new threads.
429   heap_->DisableGCForShutdown();
430   heap_->WaitForWorkersToBeCreated();
431   // Make sure to let the GC complete if it is running.
432   heap_->WaitForGcToComplete(gc::kGcCauseBackground, self);
433 
434   // Shutdown any trace before SetShuttingDown. Trace uses thread pool workers to flush entries
435   // and we want to make sure they are fully created. Threads cannot attach while shutting down.
436   Trace::Shutdown();
437 
438   {
439     ScopedTrace trace2("Wait for shutdown cond");
440     MutexLock mu(self, *Locks::runtime_shutdown_lock_);
441     shutting_down_started_ = true;
442     while (threads_being_born_ > 0) {
443       shutdown_cond_->Wait(self);
444     }
445     SetShuttingDown();
446   }
447   // Shutdown and wait for the daemons.
448   CHECK(self != nullptr);
449   if (IsFinishedStarting()) {
450     ScopedTrace trace2("Waiting for Daemons");
451     self->ClearException();
452     ScopedObjectAccess soa(self);
453     WellKnownClasses::java_lang_Daemons_stop->InvokeStatic<'V'>(self);
454   }
455 
456   // Report death. Clients may require a working thread, still, so do it before GC completes and
457   // all non-daemon threads are done.
458   {
459     ScopedObjectAccess soa(self);
460     callbacks_->NextRuntimePhase(RuntimePhaseCallback::RuntimePhase::kDeath);
461   }
462 
463   // Delete thread pools before detaching the current thread in case tasks
464   // getting deleted need to have access to Thread::Current.
465   heap_->DeleteThreadPool();
466   if (oat_file_manager_ != nullptr) {
467     oat_file_manager_->DeleteThreadPool();
468   }
469   DeleteThreadPool();
470   CHECK(thread_pool_ == nullptr);
471 
472   if (attach_shutdown_thread) {
473     DetachCurrentThread(/* should_run_callbacks= */ false);
474     self = nullptr;
475   }
476 
477   // Make sure our internal threads are dead before we start tearing down things they're using.
478   GetRuntimeCallbacks()->StopDebugger();
479   // Deletion ordering is tricky. Null out everything we've deleted.
480   delete signal_catcher_;
481   signal_catcher_ = nullptr;
482 
483   // Shutdown metrics reporting.
484   metrics_reporter_.reset();
485 
486   // Make sure all other non-daemon threads have terminated, and all daemon threads are suspended.
487   // Also wait for daemon threads to quiesce, so that in addition to being "suspended", they
488   // no longer access monitor and thread list data structures. We leak user daemon threads
489   // themselves, since we have no mechanism for shutting them down.
490   {
491     ScopedTrace trace2("Delete thread list");
492     thread_list_->ShutDown();
493   }
494 
495   // TODO Maybe do some locking.
496   for (auto& agent : agents_) {
497     agent->Unload();
498   }
499 
500   // TODO Maybe do some locking
501   for (auto& plugin : plugins_) {
502     plugin.Unload();
503   }
504 
505   // Finally delete the thread list.
506   // Thread_list_ can be accessed by "suspended" threads, e.g. in InflateThinLocked.
507   // We assume that by this point, we've waited long enough for things to quiesce.
508   delete thread_list_;
509   thread_list_ = nullptr;
510 
511   // Delete the JIT after thread list to ensure that there is no remaining threads which could be
512   // accessing the instrumentation when we delete it.
513   if (jit_ != nullptr) {
514     VLOG(jit) << "Deleting jit";
515     jit_.reset(nullptr);
516     jit_code_cache_.reset(nullptr);
517   }
518 
519   // Shutdown the fault manager if it was initialized.
520   fault_manager.Shutdown();
521 
522   ScopedTrace trace2("Delete state");
523   delete monitor_list_;
524   monitor_list_ = nullptr;
525   delete monitor_pool_;
526   monitor_pool_ = nullptr;
527   delete class_linker_;
528   class_linker_ = nullptr;
529   delete small_lrt_allocator_;
530   small_lrt_allocator_ = nullptr;
531   delete heap_;
532   heap_ = nullptr;
533   delete intern_table_;
534   intern_table_ = nullptr;
535   delete oat_file_manager_;
536   oat_file_manager_ = nullptr;
537   Thread::Shutdown();
538   QuasiAtomic::Shutdown();
539 
540   // Destroy allocators before shutting down the MemMap because they may use it.
541   java_vm_.reset();
542   linear_alloc_.reset();
543   delete ReleaseStartupLinearAlloc();
544   linear_alloc_arena_pool_.reset();
545   arena_pool_.reset();
546   jit_arena_pool_.reset();
547   protected_fault_page_.Reset();
548   MemMap::Shutdown();
549 
550   // TODO: acquire a static mutex on Runtime to avoid racing.
551   CHECK(instance_ == nullptr || instance_ == this);
552   instance_ = nullptr;
553 
554   // Well-known classes must be deleted or it is impossible to successfully start another Runtime
555   // instance. We rely on a small initialization order issue in Runtime::Start() that requires
556   // elements of WellKnownClasses to be null, see b/65500943.
557   WellKnownClasses::Clear();
558 
559 #ifdef ART_PAGE_SIZE_AGNOSTIC
560   // This is added to ensure no test is able to access gPageSize prior to initializing Runtime just
561   // because a Runtime instance was created (and subsequently destroyed) by another test.
562   gPageSize.DisallowAccess();
563 #endif
564 }
565 
566 struct AbortState {
Dumpart::AbortState567   void Dump(std::ostream& os) const {
568     if (gAborting > 1) {
569       os << "Runtime aborting --- recursively, so no thread-specific detail!\n";
570       DumpRecursiveAbort(os);
571       return;
572     }
573     gAborting++;
574     os << "Runtime aborting...\n";
575     if (Runtime::Current() == nullptr) {
576       os << "(Runtime does not yet exist!)\n";
577       DumpNativeStack(os, GetTid(), "  native: ", nullptr);
578       return;
579     }
580     Thread* self = Thread::Current();
581 
582     // Dump all threads first and then the aborting thread. While this is counter the logical flow,
583     // it improves the chance of relevant data surviving in the Android logs.
584 
585     DumpAllThreads(os, self);
586 
587     if (self == nullptr) {
588       os << "(Aborting thread was not attached to runtime!)\n";
589       DumpNativeStack(os, GetTid(), "  native: ", nullptr);
590     } else {
591       os << "Aborting thread:\n";
592       if (Locks::mutator_lock_->IsExclusiveHeld(self) || Locks::mutator_lock_->IsSharedHeld(self)) {
593         DumpThread(os, self);
594       } else {
595         if (Locks::mutator_lock_->SharedTryLock(self)) {
596           DumpThread(os, self);
597           Locks::mutator_lock_->SharedUnlock(self);
598         }
599       }
600     }
601   }
602 
603   // No thread-safety analysis as we do explicitly test for holding the mutator lock.
DumpThreadart::AbortState604   void DumpThread(std::ostream& os, Thread* self) const NO_THREAD_SAFETY_ANALYSIS {
605     DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self) || Locks::mutator_lock_->IsSharedHeld(self));
606     self->Dump(os);
607     if (self->IsExceptionPending()) {
608       mirror::Throwable* exception = self->GetException();
609       os << "Pending exception " << exception->Dump();
610     }
611   }
612 
DumpAllThreadsart::AbortState613   void DumpAllThreads(std::ostream& os, Thread* self) const {
614     Runtime* runtime = Runtime::Current();
615     if (runtime != nullptr) {
616       ThreadList* thread_list = runtime->GetThreadList();
617       if (thread_list != nullptr) {
618         // Dump requires ThreadListLock and ThreadSuspendCountLock to not be held (they will be
619         // grabbed).
620         // TODO(b/134167395): Change Dump to work with the locks held, and have a loop with timeout
621         //                    acquiring the locks.
622         bool tll_already_held = Locks::thread_list_lock_->IsExclusiveHeld(self);
623         bool tscl_already_held = Locks::thread_suspend_count_lock_->IsExclusiveHeld(self);
624         if (tll_already_held || tscl_already_held) {
625           os << "Skipping all-threads dump as locks are held:"
626              << (tll_already_held ? "" : " thread_list_lock")
627              << (tscl_already_held ? "" : " thread_suspend_count_lock")
628              << "\n";
629           return;
630         }
631         bool ml_already_exlusively_held = Locks::mutator_lock_->IsExclusiveHeld(self);
632         if (ml_already_exlusively_held) {
633           os << "Skipping all-threads dump as mutator lock is exclusively held.";
634           return;
635         }
636         bool ml_already_held = Locks::mutator_lock_->IsSharedHeld(self);
637         if (!ml_already_held) {
638           os << "Dumping all threads without mutator lock held\n";
639         }
640         os << "All threads:\n";
641         thread_list->Dump(os);
642       }
643     }
644   }
645 
646   // For recursive aborts.
DumpRecursiveAbortart::AbortState647   void DumpRecursiveAbort(std::ostream& os) const NO_THREAD_SAFETY_ANALYSIS {
648     // The only thing we'll attempt is dumping the native stack of the current thread. We will only
649     // try this if we haven't exceeded an arbitrary amount of recursions, to recover and actually
650     // die.
651     // Note: as we're using a global counter for the recursive abort detection, there is a potential
652     //       race here and it is not OK to just print when the counter is "2" (one from
653     //       Runtime::Abort(), one from previous Dump() call). Use a number that seems large enough.
654     static constexpr size_t kOnlyPrintWhenRecursionLessThan = 100u;
655     if (gAborting < kOnlyPrintWhenRecursionLessThan) {
656       gAborting++;
657       DumpNativeStack(os, GetTid());
658     }
659   }
660 };
661 
SetAbortMessage(const char * msg)662 void Runtime::SetAbortMessage(const char* msg) {
663   auto old_value = gAborting.fetch_add(1);  // set before taking any locks
664 
665   // Only set the first abort message.
666   if (old_value == 0) {
667 #ifdef ART_TARGET_ANDROID
668     android_set_abort_message(msg);
669 #endif
670     // Set the runtime fault message in case our unexpected-signal code will run.
671     Runtime* current = Runtime::Current();
672     if (current != nullptr) {
673       current->SetFaultMessage(msg);
674     }
675   }
676 }
677 
Abort(const char * msg)678 void Runtime::Abort(const char* msg) {
679   SetAbortMessage(msg);
680 
681   // May be coming from an unattached thread.
682   if (Thread::Current() == nullptr) {
683     Runtime* current = Runtime::Current();
684     if (current != nullptr && current->IsStarted() && !current->IsShuttingDownUnsafe()) {
685       // We do not flag this to the unexpected-signal handler so that that may dump the stack.
686       abort();
687       UNREACHABLE();
688     }
689   }
690 
691   {
692     // Ensure that we don't have multiple threads trying to abort at once,
693     // which would result in significantly worse diagnostics.
694     ScopedThreadStateChange tsc(Thread::Current(), ThreadState::kNativeForAbort);
695     Locks::abort_lock_->ExclusiveLock(Thread::Current());
696   }
697 
698   // Get any pending output out of the way.
699   fflush(nullptr);
700 
701   // Many people have difficulty distinguish aborts from crashes,
702   // so be explicit.
703   // Note: use cerr on the host to print log lines immediately, so we get at least some output
704   //       in case of recursive aborts. We lose annotation with the source file and line number
705   //       here, which is a minor issue. The same is significantly more complicated on device,
706   //       which is why we ignore the issue there.
707   AbortState state;
708   if (kIsTargetBuild) {
709     LOG(FATAL_WITHOUT_ABORT) << Dumpable<AbortState>(state);
710   } else {
711     std::cerr << Dumpable<AbortState>(state);
712   }
713 
714   // Sometimes we dump long messages, and the Android abort message only retains the first line.
715   // In those cases, just log the message again, to avoid logcat limits.
716   if (msg != nullptr && strchr(msg, '\n') != nullptr) {
717     LOG(FATAL_WITHOUT_ABORT) << msg;
718   }
719 
720   FlagRuntimeAbort();
721 
722   // Call the abort hook if we have one.
723   if (Runtime::Current() != nullptr && Runtime::Current()->abort_ != nullptr) {
724     LOG(FATAL_WITHOUT_ABORT) << "Calling abort hook...";
725     Runtime::Current()->abort_();
726     // notreached
727     LOG(FATAL_WITHOUT_ABORT) << "Unexpectedly returned from abort hook!";
728   }
729 
730   abort();
731   // notreached
732 }
733 
734 /**
735  * Update entrypoints of methods before the first fork. This
736  * helps sharing pages where ArtMethods are allocated between the zygote and
737  * forked apps.
738  */
739 class UpdateMethodsPreFirstForkVisitor : public ClassVisitor {
740  public:
UpdateMethodsPreFirstForkVisitor(ClassLinker * class_linker)741   explicit UpdateMethodsPreFirstForkVisitor(ClassLinker* class_linker)
742       : class_linker_(class_linker),
743         can_use_nterp_(interpreter::CanRuntimeUseNterp()) {}
744 
operator ()(ObjPtr<mirror::Class> klass)745   bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
746     bool is_initialized = klass->IsVisiblyInitialized();
747     for (ArtMethod& method : klass->GetDeclaredMethods(kRuntimePointerSize)) {
748       if (!is_initialized && method.NeedsClinitCheckBeforeCall() && can_use_nterp_) {
749         const void* existing = method.GetEntryPointFromQuickCompiledCode();
750         if (class_linker_->IsQuickResolutionStub(existing) && CanMethodUseNterp(&method)) {
751           method.SetEntryPointFromQuickCompiledCode(interpreter::GetNterpWithClinitEntryPoint());
752         }
753       }
754     }
755     return true;
756   }
757 
758  private:
759   ClassLinker* const class_linker_;
760   const bool can_use_nterp_;
761 
762   DISALLOW_COPY_AND_ASSIGN(UpdateMethodsPreFirstForkVisitor);
763 };
764 
765 // Wait until the kernel thinks we are single-threaded again.
WaitUntilSingleThreaded()766 static void WaitUntilSingleThreaded() {
767 #if defined(__linux__)
768   // Read num_threads field from /proc/self/stat, avoiding higher-level IO libraries that may
769   // break atomicity of the read.
770   static constexpr size_t kNumTries = 2000;
771   static constexpr size_t kNumThreadsIndex = 20;
772   static constexpr size_t BUF_SIZE = 500;
773   static constexpr size_t BUF_PRINT_SIZE = 150;  // Only log this much on failure to limit length.
774   static_assert(BUF_SIZE > BUF_PRINT_SIZE);
775   char buf[BUF_SIZE];
776   size_t bytes_read = 0;
777   uint64_t millis = 0;
778   for (size_t tries = 0; tries < kNumTries; ++tries) {
779     bytes_read = GetOsThreadStat(getpid(), buf, BUF_SIZE);
780     CHECK_NE(bytes_read, 0u);
781     size_t pos = 0;
782     while (pos < bytes_read && buf[pos++] != ')') {}
783     ++pos;
784     // We're now positioned at the beginning of the third field. Don't count blanks embedded in
785     // second (command) field.
786     size_t blanks_seen = 2;
787     while (pos < bytes_read && blanks_seen < kNumThreadsIndex - 1) {
788       if (buf[pos++] == ' ') {
789         ++blanks_seen;
790       }
791     }
792     CHECK(pos < bytes_read - 2);
793     // pos is first character of num_threads field.
794     CHECK_EQ(buf[pos + 1], ' ');  // We never have more than single-digit threads here.
795     if (buf[pos] == '1') {
796       return;  //  num_threads == 1; success.
797     }
798     if (millis == 0) {
799       millis = MilliTime();
800     }
801     usleep(tries < 10 ? 1000 : 2000);
802   }
803   buf[std::min(BUF_PRINT_SIZE, bytes_read)] = '\0';  // Truncate buf before printing.
804   LOG(ERROR) << "Not single threaded: bytes_read = " << bytes_read << " stat contents = \"" << buf
805              << "...\"";
806   LOG(ERROR) << "Other threads' abbreviated stats: " << GetOtherThreadOsStats();
807   bytes_read = GetOsThreadStat(getpid(), buf, BUF_PRINT_SIZE);
808   CHECK_NE(bytes_read, 0u);
809   LOG(ERROR) << "After re-read: bytes_read = " << bytes_read << " stat contents = \"" << buf
810              << "...\"";
811   LOG(FATAL) << "Failed to reach single-threaded state: wait_time = " << MilliTime() - millis;
812 #else  // Not Linux; shouldn't matter, but this has a high probability of working slowly.
813   usleep(20'000);
814 #endif
815 }
816 
PreZygoteFork()817 void Runtime::PreZygoteFork() {
818   if (GetJit() != nullptr) {
819     GetJit()->PreZygoteFork();
820   }
821   // All other threads have already been joined, but they may not have finished
822   // removing themselves from the thread list. Wait until the other threads have completely
823   // finished, and are no longer in the thread list.
824   // TODO: Since the threads Unregister() themselves before exiting, the first wait should be
825   // unnecessary. But since we're reading from a /proc entry that's concurrently changing, for
826   // now we play this as safe as possible.
827   ThreadList* tl = GetThreadList();
828   {
829     Thread* self = Thread::Current();
830     MutexLock mu(self, *Locks::thread_list_lock_);
831     tl->WaitForUnregisterToComplete(self);
832     if (kIsDebugBuild) {
833       auto list = tl->GetList();
834       if (list.size() != 1) {
835         for (Thread* t : list) {
836           std::string name;
837           t->GetThreadName(name);
838           LOG(ERROR) << "Remaining pre-fork thread: " << name;
839         }
840       }
841     }
842     CHECK_EQ(tl->Size(), 1u);
843     // And then wait until the kernel thinks the threads are gone.
844     WaitUntilSingleThreaded();
845   }
846 
847   if (!heap_->HasZygoteSpace()) {
848     Thread* self = Thread::Current();
849     // This is the first fork. Update ArtMethods in the boot classpath now to
850     // avoid having forked apps dirty the memory.
851 
852     // Ensure we call FixupStaticTrampolines on all methods that are
853     // initialized.
854     class_linker_->MakeInitializedClassesVisiblyInitialized(self, /*wait=*/ true);
855 
856     ScopedObjectAccess soa(self);
857     UpdateMethodsPreFirstForkVisitor visitor(class_linker_);
858     class_linker_->VisitClasses(&visitor);
859   }
860   heap_->PreZygoteFork();
861   PreZygoteForkNativeBridge();
862 }
863 
PostZygoteFork()864 void Runtime::PostZygoteFork() {
865   jit::Jit* jit = GetJit();
866   if (jit != nullptr) {
867     jit->PostZygoteFork();
868     // Ensure that the threads in the JIT pool have been created with the right
869     // priority.
870     if (kIsDebugBuild && jit->GetThreadPool() != nullptr) {
871       jit->GetThreadPool()->CheckPthreadPriority(
872           IsZygote() ? jit->GetZygoteThreadPoolPthreadPriority()
873                      : jit->GetThreadPoolPthreadPriority());
874     }
875   }
876   // Reset all stats.
877   ResetStats(0xFFFFFFFF);
878 }
879 
CallExitHook(jint status)880 void Runtime::CallExitHook(jint status) {
881   if (exit_ != nullptr) {
882     ScopedThreadStateChange tsc(Thread::Current(), ThreadState::kNative);
883     exit_(status);
884     LOG(WARNING) << "Exit hook returned instead of exiting!";
885   }
886 }
887 
SweepSystemWeaks(IsMarkedVisitor * visitor)888 void Runtime::SweepSystemWeaks(IsMarkedVisitor* visitor) {
889   // Userfaultfd compaction updates weak intern-table page-by-page via
890   // LinearAlloc.
891   if (!GetHeap()->IsPerformingUffdCompaction()) {
892     GetInternTable()->SweepInternTableWeaks(visitor);
893   }
894   GetMonitorList()->SweepMonitorList(visitor);
895   GetJavaVM()->SweepJniWeakGlobals(visitor);
896   GetHeap()->SweepAllocationRecords(visitor);
897   // Sweep JIT tables only if the GC is moving as in other cases the entries are
898   // not updated.
899   if (GetJit() != nullptr && GetHeap()->IsMovingGc()) {
900     // Visit JIT literal tables. Objects in these tables are classes and strings
901     // and only classes can be affected by class unloading. The strings always
902     // stay alive as they are strongly interned.
903     // TODO: Move this closer to CleanupClassLoaders, to avoid blocking weak accesses
904     // from mutators. See b/32167580.
905     GetJit()->GetCodeCache()->SweepRootTables(visitor);
906   }
907 
908   // All other generic system-weak holders.
909   for (gc::AbstractSystemWeakHolder* holder : system_weak_holders_) {
910     holder->Sweep(visitor);
911   }
912 }
913 
ParseOptions(const RuntimeOptions & raw_options,bool ignore_unrecognized,RuntimeArgumentMap * runtime_options)914 bool Runtime::ParseOptions(const RuntimeOptions& raw_options,
915                            bool ignore_unrecognized,
916                            RuntimeArgumentMap* runtime_options) {
917   Locks::Init();
918   InitLogging(/* argv= */ nullptr, Abort);  // Calls Locks::Init() as a side effect.
919   bool parsed = ParsedOptions::Parse(raw_options, ignore_unrecognized, runtime_options);
920   if (!parsed) {
921     LOG(ERROR) << "Failed to parse options";
922     return false;
923   }
924   return true;
925 }
926 
927 // Callback to check whether it is safe to call Abort (e.g., to use a call to
928 // LOG(FATAL)).  It is only safe to call Abort if the runtime has been created,
929 // properly initialized, and has not shut down.
IsSafeToCallAbort()930 static bool IsSafeToCallAbort() NO_THREAD_SAFETY_ANALYSIS {
931   Runtime* runtime = Runtime::Current();
932   return runtime != nullptr && runtime->IsStarted() && !runtime->IsShuttingDownLocked();
933 }
934 
AddGeneratedCodeRange(const void * start,size_t size)935 void Runtime::AddGeneratedCodeRange(const void* start, size_t size) {
936   if (HandlesSignalsInCompiledCode()) {
937     fault_manager.AddGeneratedCodeRange(start, size);
938   }
939 }
940 
RemoveGeneratedCodeRange(const void * start,size_t size)941 void Runtime::RemoveGeneratedCodeRange(const void* start, size_t size) {
942   if (HandlesSignalsInCompiledCode()) {
943     fault_manager.RemoveGeneratedCodeRange(start, size);
944   }
945 }
946 
Create(RuntimeArgumentMap && runtime_options)947 bool Runtime::Create(RuntimeArgumentMap&& runtime_options) {
948   // TODO: acquire a static mutex on Runtime to avoid racing.
949   if (Runtime::instance_ != nullptr) {
950     return false;
951   }
952   instance_ = new Runtime;
953   Locks::SetClientCallback(IsSafeToCallAbort);
954   if (!instance_->Init(std::move(runtime_options))) {
955     // TODO: Currently deleting the instance will abort the runtime on destruction. Now This will
956     // leak memory, instead. Fix the destructor. b/19100793.
957     // delete instance_;
958     instance_ = nullptr;
959     return false;
960   }
961   return true;
962 }
963 
Create(const RuntimeOptions & raw_options,bool ignore_unrecognized)964 bool Runtime::Create(const RuntimeOptions& raw_options, bool ignore_unrecognized) {
965   RuntimeArgumentMap runtime_options;
966   return ParseOptions(raw_options, ignore_unrecognized, &runtime_options) &&
967       Create(std::move(runtime_options));
968 }
969 
CreateSystemClassLoader(Runtime * runtime)970 static jobject CreateSystemClassLoader(Runtime* runtime) {
971   if (runtime->IsAotCompiler() && !runtime->GetCompilerCallbacks()->IsBootImage()) {
972     return nullptr;
973   }
974 
975   ScopedObjectAccess soa(Thread::Current());
976   ClassLinker* cl = runtime->GetClassLinker();
977   auto pointer_size = cl->GetImagePointerSize();
978 
979   ObjPtr<mirror::Class> class_loader_class = GetClassRoot<mirror::ClassLoader>(cl);
980   DCHECK(class_loader_class->IsInitialized());  // Class roots have been initialized.
981 
982   ArtMethod* getSystemClassLoader = class_loader_class->FindClassMethod(
983       "getSystemClassLoader", "()Ljava/lang/ClassLoader;", pointer_size);
984   CHECK(getSystemClassLoader != nullptr);
985   CHECK(getSystemClassLoader->IsStatic());
986 
987   ObjPtr<mirror::Object> system_class_loader = getSystemClassLoader->InvokeStatic<'L'>(soa.Self());
988   CHECK(system_class_loader != nullptr)
989       << (soa.Self()->IsExceptionPending() ? soa.Self()->GetException()->Dump() : "<null>");
990 
991   ScopedAssertNoThreadSuspension sants(__FUNCTION__);
992   jobject g_system_class_loader =
993       runtime->GetJavaVM()->AddGlobalRef(soa.Self(), system_class_loader);
994   soa.Self()->SetClassLoaderOverride(g_system_class_loader);
995 
996   ObjPtr<mirror::Class> thread_class = WellKnownClasses::java_lang_Thread.Get();
997   ArtField* contextClassLoader =
998       thread_class->FindDeclaredInstanceField("contextClassLoader", "Ljava/lang/ClassLoader;");
999   CHECK(contextClassLoader != nullptr);
1000 
1001   // We can't run in a transaction yet.
1002   contextClassLoader->SetObject<false>(soa.Self()->GetPeer(), system_class_loader);
1003 
1004   return g_system_class_loader;
1005 }
1006 
GetCompilerExecutable() const1007 std::string Runtime::GetCompilerExecutable() const {
1008   if (!compiler_executable_.empty()) {
1009     return compiler_executable_;
1010   }
1011   std::string compiler_executable = GetArtBinDir() + "/dex2oat";
1012   if (kIsDebugBuild) {
1013     compiler_executable += 'd';
1014   }
1015   if (kIsTargetBuild) {
1016     compiler_executable += Is64BitInstructionSet(kRuntimeISA) ? "64" : "32";
1017   }
1018   return compiler_executable;
1019 }
1020 
RunRootClinits(Thread * self)1021 void Runtime::RunRootClinits(Thread* self) {
1022   class_linker_->RunRootClinits(self);
1023 
1024   GcRoot<mirror::Throwable>* exceptions[] = {
1025       &pre_allocated_OutOfMemoryError_when_throwing_exception_,
1026       // &pre_allocated_OutOfMemoryError_when_throwing_oome_,             // Same class as above.
1027       // &pre_allocated_OutOfMemoryError_when_handling_stack_overflow_,   // Same class as above.
1028       &pre_allocated_NoClassDefFoundError_,
1029   };
1030   for (GcRoot<mirror::Throwable>* exception : exceptions) {
1031     StackHandleScope<1> hs(self);
1032     Handle<mirror::Class> klass = hs.NewHandle<mirror::Class>(exception->Read()->GetClass());
1033     class_linker_->EnsureInitialized(self, klass, true, true);
1034     self->AssertNoPendingException();
1035   }
1036 }
1037 
Start()1038 bool Runtime::Start() {
1039   VLOG(startup) << "Runtime::Start entering";
1040 
1041   CHECK(!no_sig_chain_) << "A started runtime should have sig chain enabled";
1042 
1043   // If a debug host build, disable ptrace restriction for debugging and test timeout thread dump.
1044   // Only 64-bit as prctl() may fail in 32 bit userspace on a 64-bit kernel.
1045 #if defined(__linux__) && !defined(ART_TARGET_ANDROID) && defined(__x86_64__)
1046   if (kIsDebugBuild) {
1047     if (prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY) != 0) {
1048       PLOG(WARNING) << "Failed setting PR_SET_PTRACER to PR_SET_PTRACER_ANY";
1049     }
1050   }
1051 #endif
1052 
1053   // Restore main thread state to kNative as expected by native code.
1054   Thread* self = Thread::Current();
1055 
1056   started_ = true;
1057 
1058   // Before running any clinit, set up the native methods provided by the runtime itself.
1059   RegisterRuntimeNativeMethods(self->GetJniEnv());
1060 
1061   class_linker_->RunEarlyRootClinits(self);
1062   InitializeIntrinsics();
1063 
1064   self->TransitionFromRunnableToSuspended(ThreadState::kNative);
1065 
1066   // InitNativeMethods needs to be after started_ so that the classes
1067   // it touches will have methods linked to the oat file if necessary.
1068   {
1069     ScopedTrace trace2("InitNativeMethods");
1070     InitNativeMethods();
1071   }
1072 
1073   // InitializeCorePlatformApiPrivateFields() needs to be called after well known class
1074   // initializtion in InitNativeMethods().
1075   art::hiddenapi::InitializeCorePlatformApiPrivateFields();
1076 
1077   // Initialize well known thread group values that may be accessed threads while attaching.
1078   InitThreadGroups(self);
1079 
1080   Thread::FinishStartup();
1081 
1082   // Create the JIT either if we have to use JIT compilation or save profiling info. This is
1083   // done after FinishStartup as the JIT pool needs Java thread peers, which require the main
1084   // ThreadGroup to exist.
1085   //
1086   // TODO(calin): We use the JIT class as a proxy for JIT compilation and for
1087   // recoding profiles. Maybe we should consider changing the name to be more clear it's
1088   // not only about compiling. b/28295073.
1089   if (jit_options_->UseJitCompilation() || jit_options_->GetSaveProfilingInfo()) {
1090     CreateJit();
1091 #ifdef ADDRESS_SANITIZER
1092     // (b/238730394): In older implementations of sanitizer + glibc there is a race between
1093     // pthread_create and dlopen that could cause a deadlock. pthread_create interceptor in ASAN
1094     // uses dl_pthread_iterator with a callback that could request a dl_load_lock via call to
1095     // __tls_get_addr [1]. dl_pthread_iterate would already hold dl_load_lock so this could cause a
1096     // deadlock. __tls_get_addr needs a dl_load_lock only when there is a dlopen happening in
1097     // parallel. As a workaround we wait for the pthread_create (i.e JIT thread pool creation) to
1098     // finish before going to the next phase. Creating a system class loader could need a dlopen so
1099     // we wait here till threads are initialized.
1100     // [1] https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/sanitizer_common/sanitizer_linux_libcdep.cpp#L408
1101     // See this for more context: https://reviews.llvm.org/D98926
1102     // TODO(b/238730394): Revisit this workaround once we migrate to musl libc.
1103     if (jit_ != nullptr) {
1104       jit_->GetThreadPool()->WaitForWorkersToBeCreated();
1105     }
1106 #endif
1107   }
1108 
1109   // Send the start phase event. We have to wait till here as this is when the main thread peer
1110   // has just been generated, important root clinits have been run and JNI is completely functional.
1111   {
1112     ScopedObjectAccess soa(self);
1113     callbacks_->NextRuntimePhase(RuntimePhaseCallback::RuntimePhase::kStart);
1114   }
1115 
1116   system_class_loader_ = CreateSystemClassLoader(this);
1117 
1118   if (!is_zygote_) {
1119     if (is_native_bridge_loaded_) {
1120       PreInitializeNativeBridge(".");
1121     }
1122     NativeBridgeAction action = force_native_bridge_
1123         ? NativeBridgeAction::kInitialize
1124         : NativeBridgeAction::kUnload;
1125     InitNonZygoteOrPostFork(self->GetJniEnv(),
1126                             /* is_system_server= */ false,
1127                             /* is_child_zygote= */ false,
1128                             action,
1129                             GetInstructionSetString(kRuntimeISA));
1130   }
1131 
1132   {
1133     ScopedObjectAccess soa(self);
1134     StartDaemonThreads();
1135     self->GetJniEnv()->AssertLocalsEmpty();
1136 
1137     // Send the initialized phase event. Send it after starting the Daemon threads so that agents
1138     // cannot delay the daemon threads from starting forever.
1139     callbacks_->NextRuntimePhase(RuntimePhaseCallback::RuntimePhase::kInit);
1140     self->GetJniEnv()->AssertLocalsEmpty();
1141   }
1142 
1143   VLOG(startup) << "Runtime::Start exiting";
1144   finished_starting_ = true;
1145 
1146   if (trace_config_.get() != nullptr && trace_config_->trace_file != "") {
1147     ScopedThreadStateChange tsc(self, ThreadState::kWaitingForMethodTracingStart);
1148     int flags = 0;
1149     if (trace_config_->clock_source == TraceClockSource::kDual) {
1150       flags = Trace::TraceFlag::kTraceClockSourceWallClock |
1151               Trace::TraceFlag::kTraceClockSourceThreadCpu;
1152     } else if (trace_config_->clock_source == TraceClockSource::kWall) {
1153       flags = Trace::TraceFlag::kTraceClockSourceWallClock;
1154     } else if (TraceClockSource::kThreadCpu == trace_config_->clock_source) {
1155       flags = Trace::TraceFlag::kTraceClockSourceThreadCpu;
1156     } else {
1157       LOG(ERROR) << "Unexpected clock source";
1158     }
1159     Trace::Start(trace_config_->trace_file.c_str(),
1160                  static_cast<int>(trace_config_->trace_file_size),
1161                  flags,
1162                  trace_config_->trace_output_mode,
1163                  trace_config_->trace_mode,
1164                  0);
1165   }
1166 
1167   // In case we have a profile path passed as a command line argument,
1168   // register the current class path for profiling now. Note that we cannot do
1169   // this before we create the JIT and having it here is the most convenient way.
1170   // This is used when testing profiles with dalvikvm command as there is no
1171   // framework to register the dex files for profiling.
1172   if (jit_.get() != nullptr && jit_options_->GetSaveProfilingInfo() &&
1173       !jit_options_->GetProfileSaverOptions().GetProfilePath().empty()) {
1174     std::vector<std::string> dex_filenames;
1175     Split(class_path_string_, ':', &dex_filenames);
1176 
1177     // We pass "" as the package name because at this point we don't know it. It could be the
1178     // Zygote or it could be a dalvikvm cmd line execution. The package name will be re-set during
1179     // post-fork or during RegisterAppInfo.
1180     //
1181     // Also, it's ok to pass "" to the ref profile filename. It indicates we don't have
1182     // a reference profile.
1183     RegisterAppInfo(
1184         /*package_name=*/ "",
1185         dex_filenames,
1186         jit_options_->GetProfileSaverOptions().GetProfilePath(),
1187         /*ref_profile_filename=*/ "",
1188         kVMRuntimePrimaryApk);
1189   }
1190 
1191   return true;
1192 }
1193 
EndThreadBirth()1194 void Runtime::EndThreadBirth() REQUIRES(Locks::runtime_shutdown_lock_) {
1195   DCHECK_GT(threads_being_born_, 0U);
1196   threads_being_born_--;
1197   if (shutting_down_started_ && threads_being_born_ == 0) {
1198     shutdown_cond_->Broadcast(Thread::Current());
1199   }
1200 }
1201 
InitNonZygoteOrPostFork(JNIEnv * env,bool is_system_server,bool is_child_zygote,NativeBridgeAction action,const char * isa,bool profile_system_server)1202 void Runtime::InitNonZygoteOrPostFork(
1203     JNIEnv* env,
1204     bool is_system_server,
1205     // This is true when we are initializing a child-zygote. It requires
1206     // native bridge initialization to be able to run guest native code in
1207     // doPreload().
1208     bool is_child_zygote,
1209     NativeBridgeAction action,
1210     const char* isa,
1211     bool profile_system_server) {
1212   if (is_native_bridge_loaded_) {
1213     switch (action) {
1214       case NativeBridgeAction::kUnload:
1215         UnloadNativeBridge();
1216         is_native_bridge_loaded_ = false;
1217         break;
1218       case NativeBridgeAction::kInitialize:
1219         InitializeNativeBridge(env, isa);
1220         break;
1221     }
1222   }
1223 
1224   if (is_child_zygote) {
1225     // If creating a child-zygote we only initialize native bridge. The rest of
1226     // runtime post-fork logic would spin up threads for Binder and JDWP.
1227     // Instead, the Java side of the child process will call a static main in a
1228     // class specified by the parent.
1229     return;
1230   }
1231 
1232   DCHECK(!IsZygote());
1233 
1234   if (is_system_server) {
1235     // Register the system server code paths.
1236     // TODO: Ideally this should be done by the VMRuntime#RegisterAppInfo. However, right now
1237     // the method is only called when we set up the profile. It should be called all the time
1238     // (simillar to the apps). Once that's done this manual registration can be removed.
1239     const char* system_server_classpath = getenv("SYSTEMSERVERCLASSPATH");
1240     if (system_server_classpath == nullptr || (strlen(system_server_classpath) == 0)) {
1241       LOG(WARNING) << "System server class path not set";
1242     } else {
1243       std::vector<std::string> jars = android::base::Split(system_server_classpath, ":");
1244       app_info_.RegisterAppInfo("android",
1245                                 jars,
1246                                 /*profile_output_filename=*/ "",
1247                                 /*ref_profile_filename=*/ "",
1248                                 AppInfo::CodeType::kPrimaryApk);
1249     }
1250 
1251     // Set the system server package name to "android".
1252     // This is used to tell the difference between samples provided by system server
1253     // and samples generated by other apps when processing boot image profiles.
1254     SetProcessPackageName("android");
1255     if (profile_system_server) {
1256       jit_options_->SetWaitForJitNotificationsToSaveProfile(false);
1257       VLOG(profiler) << "Enabling system server profiles";
1258     }
1259   }
1260 
1261   // Create the thread pool for loading app images.
1262   // Avoid creating the runtime thread pool for system server since it will not be used and would
1263   // waste memory.
1264   if (!is_system_server &&
1265       android::base::GetBoolProperty("dalvik.vm.parallel-image-loading", false)) {
1266     ScopedTrace timing("CreateThreadPool");
1267     constexpr size_t kStackSize = 64 * KB;
1268     constexpr size_t kMaxRuntimeWorkers = 4u;
1269     const size_t num_workers =
1270         std::min(static_cast<size_t>(std::thread::hardware_concurrency()), kMaxRuntimeWorkers);
1271     MutexLock mu(Thread::Current(), *Locks::runtime_thread_pool_lock_);
1272     CHECK(thread_pool_ == nullptr);
1273     thread_pool_.reset(
1274         ThreadPool::Create("Runtime", num_workers, /*create_peers=*/false, kStackSize));
1275     thread_pool_->StartWorkers(Thread::Current());
1276   }
1277 
1278   // Reset the gc performance data and metrics at zygote fork so that the events from
1279   // before fork aren't attributed to an app.
1280   heap_->ResetGcPerformanceInfo();
1281   GetMetrics()->Reset();
1282 
1283   if (AreMetricsInitialized()) {
1284     // Now that we know if we are an app or system server, reload the metrics reporter config
1285     // in case there are any difference.
1286     metrics::ReportingConfig metrics_config =
1287         metrics::ReportingConfig::FromFlags(is_system_server);
1288 
1289     metrics_reporter_->ReloadConfig(metrics_config);
1290 
1291     metrics::SessionData session_data{metrics::SessionData::CreateDefault()};
1292     // Start the session id from 1 to avoid clashes with the default value.
1293     // (better for debugability)
1294     session_data.session_id = GetRandomNumber<int64_t>(1, std::numeric_limits<int64_t>::max());
1295     // TODO: set session_data.compilation_reason and session_data.compiler_filter
1296     metrics_reporter_->MaybeStartBackgroundThread(session_data);
1297     // Also notify about any updates to the app info.
1298     metrics_reporter_->NotifyAppInfoUpdated(&app_info_);
1299   }
1300 
1301   StartSignalCatcher();
1302 
1303   ScopedObjectAccess soa(Thread::Current());
1304   if (IsPerfettoHprofEnabled() &&
1305       (Dbg::IsJdwpAllowed() || IsProfileable() || IsProfileableFromShell() || IsJavaDebuggable() ||
1306        Runtime::Current()->IsSystemServer())) {
1307     std::string err;
1308     ScopedTrace tr("perfetto_hprof init.");
1309     ScopedThreadSuspension sts(Thread::Current(), ThreadState::kNative);
1310     if (!EnsurePerfettoPlugin(&err)) {
1311       LOG(WARNING) << "Failed to load perfetto_hprof: " << err;
1312     }
1313   }
1314   if (IsPerfettoJavaHeapStackProfEnabled() &&
1315       (Dbg::IsJdwpAllowed() || IsProfileable() || IsProfileableFromShell() || IsJavaDebuggable() ||
1316        Runtime::Current()->IsSystemServer())) {
1317     // Marker used for dev tracing similar to above markers.
1318     ScopedTrace tr("perfetto_javaheapprof init.");
1319   }
1320   if (Runtime::Current()->IsSystemServer()) {
1321     std::string err;
1322     ScopedTrace tr("odrefresh and device stats logging");
1323     ScopedThreadSuspension sts(Thread::Current(), ThreadState::kNative);
1324     // Report stats if available. This should be moved into ART Services when they are ready.
1325     if (!odrefresh::UploadStatsIfAvailable(&err)) {
1326       LOG(WARNING) << "Failed to upload odrefresh metrics: " << err;
1327     }
1328     metrics::ReportDeviceMetrics();
1329   }
1330 
1331   if (LIKELY(automatically_set_jni_ids_indirection_) && CanSetJniIdType()) {
1332     if (IsJavaDebuggable()) {
1333       SetJniIdType(JniIdType::kIndices);
1334     } else {
1335       SetJniIdType(JniIdType::kPointer);
1336     }
1337   }
1338   ATraceIntegerValue(
1339       "profilebootclasspath",
1340       static_cast<int>(jit_options_->GetProfileSaverOptions().GetProfileBootClassPath()));
1341   // Start the JDWP thread. If the command-line debugger flags specified "suspend=y",
1342   // this will pause the runtime (in the internal debugger implementation), so we probably want
1343   // this to come last.
1344   GetRuntimeCallbacks()->StartDebugger();
1345 }
1346 
StartSignalCatcher()1347 void Runtime::StartSignalCatcher() {
1348   if (!is_zygote_) {
1349     signal_catcher_ = new SignalCatcher();
1350   }
1351 }
1352 
IsShuttingDown(Thread * self)1353 bool Runtime::IsShuttingDown(Thread* self) {
1354   MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1355   return IsShuttingDownLocked();
1356 }
1357 
StartDaemonThreads()1358 void Runtime::StartDaemonThreads() {
1359   ScopedTrace trace(__FUNCTION__);
1360   VLOG(startup) << "Runtime::StartDaemonThreads entering";
1361 
1362   Thread* self = Thread::Current();
1363 
1364   DCHECK_EQ(self->GetState(), ThreadState::kRunnable);
1365 
1366   WellKnownClasses::java_lang_Daemons_start->InvokeStatic<'V'>(self);
1367   if (UNLIKELY(self->IsExceptionPending())) {
1368     LOG(FATAL) << "Error starting java.lang.Daemons: " << self->GetException()->Dump();
1369   }
1370 
1371   VLOG(startup) << "Runtime::StartDaemonThreads exiting";
1372 }
1373 
OpenBootDexFiles(ArrayRef<const std::string> dex_filenames,ArrayRef<const std::string> dex_locations,ArrayRef<File> dex_files,std::vector<std::unique_ptr<const DexFile>> * out_dex_files)1374 static size_t OpenBootDexFiles(ArrayRef<const std::string> dex_filenames,
1375                                ArrayRef<const std::string> dex_locations,
1376                                ArrayRef<File> dex_files,
1377                                std::vector<std::unique_ptr<const DexFile>>* out_dex_files) {
1378   DCHECK(out_dex_files != nullptr) << "OpenDexFiles: out-param is nullptr";
1379   size_t failure_count = 0;
1380   for (size_t i = 0; i < dex_filenames.size(); i++) {
1381     const char* dex_filename = dex_filenames[i].c_str();
1382     const char* dex_location = dex_locations[i].c_str();
1383     File noFile;
1384     File* file = i < dex_files.size() ? &dex_files[i] : &noFile;
1385     static constexpr bool kVerifyChecksum = true;
1386     std::string error_msg;
1387     if (!OS::FileExists(dex_filename) && file->IsValid()) {
1388       LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
1389       continue;
1390     }
1391     bool verify = Runtime::Current()->IsVerificationEnabled();
1392     ArtDexFileLoader dex_file_loader(dex_filename, file, dex_location);
1393     if (!dex_file_loader.Open(verify, kVerifyChecksum, &error_msg, out_dex_files)) {
1394       LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "' / fd " << file->Fd()
1395                    << ": " << error_msg;
1396       ++failure_count;
1397     }
1398     if (file->IsValid()) {
1399       bool close_ok = file->Close();
1400       DCHECK(close_ok) << dex_filename;
1401     }
1402   }
1403   return failure_count;
1404 }
1405 
SetSentinel(ObjPtr<mirror::Object> sentinel)1406 void Runtime::SetSentinel(ObjPtr<mirror::Object> sentinel) {
1407   CHECK(sentinel_.Read() == nullptr);
1408   CHECK(sentinel != nullptr);
1409   CHECK(!heap_->IsMovableObject(sentinel));
1410   sentinel_ = GcRoot<mirror::Object>(sentinel);
1411 }
1412 
GetSentinel()1413 GcRoot<mirror::Object> Runtime::GetSentinel() {
1414   return sentinel_;
1415 }
1416 
CreatePreAllocatedException(Thread * self,Runtime * runtime,GcRoot<mirror::Throwable> * exception,const char * exception_class_descriptor,const char * msg)1417 static inline void CreatePreAllocatedException(Thread* self,
1418                                                Runtime* runtime,
1419                                                GcRoot<mirror::Throwable>* exception,
1420                                                const char* exception_class_descriptor,
1421                                                const char* msg)
1422     REQUIRES_SHARED(Locks::mutator_lock_) {
1423   DCHECK_EQ(self, Thread::Current());
1424   ClassLinker* class_linker = runtime->GetClassLinker();
1425   // Allocate an object without initializing the class to allow non-trivial Throwable.<clinit>().
1426   ObjPtr<mirror::Class> klass = class_linker->FindSystemClass(self, exception_class_descriptor);
1427   CHECK(klass != nullptr);
1428   gc::AllocatorType allocator_type = runtime->GetHeap()->GetCurrentAllocator();
1429   ObjPtr<mirror::Throwable> exception_object = ObjPtr<mirror::Throwable>::DownCast(
1430       klass->Alloc(self, allocator_type));
1431   CHECK(exception_object != nullptr);
1432   *exception = GcRoot<mirror::Throwable>(exception_object);
1433   // Initialize the "detailMessage" field.
1434   ObjPtr<mirror::String> message = mirror::String::AllocFromModifiedUtf8(self, msg);
1435   CHECK(message != nullptr);
1436   ObjPtr<mirror::Class> throwable = GetClassRoot<mirror::Throwable>(class_linker);
1437   ArtField* detailMessageField =
1438       throwable->FindDeclaredInstanceField("detailMessage", "Ljava/lang/String;");
1439   CHECK(detailMessageField != nullptr);
1440   detailMessageField->SetObject</* kTransactionActive= */ false>(exception->Read(), message);
1441 }
1442 
CreatePreAllocatedExceptions(Thread * self)1443 inline void Runtime::CreatePreAllocatedExceptions(Thread* self) {
1444   // Pre-allocate an OutOfMemoryError for the case when we fail to
1445   // allocate the exception to be thrown.
1446   CreatePreAllocatedException(self,
1447                               this,
1448                               &pre_allocated_OutOfMemoryError_when_throwing_exception_,
1449                               "Ljava/lang/OutOfMemoryError;",
1450                               "OutOfMemoryError thrown while trying to throw an exception; "
1451                               "no stack trace available");
1452   // Pre-allocate an OutOfMemoryError for the double-OOME case.
1453   CreatePreAllocatedException(self,
1454                               this,
1455                               &pre_allocated_OutOfMemoryError_when_throwing_oome_,
1456                               "Ljava/lang/OutOfMemoryError;",
1457                               "OutOfMemoryError thrown while trying to throw OutOfMemoryError; "
1458                               "no stack trace available");
1459   // Pre-allocate an OutOfMemoryError for the case when we fail to
1460   // allocate while handling a stack overflow.
1461   CreatePreAllocatedException(self,
1462                               this,
1463                               &pre_allocated_OutOfMemoryError_when_handling_stack_overflow_,
1464                               "Ljava/lang/OutOfMemoryError;",
1465                               "OutOfMemoryError thrown while trying to handle a stack overflow; "
1466                               "no stack trace available");
1467   // Pre-allocate a NoClassDefFoundError for the common case of failing to find a system class
1468   // ahead of checking the application's class loader.
1469   CreatePreAllocatedException(self,
1470                               this,
1471                               &pre_allocated_NoClassDefFoundError_,
1472                               "Ljava/lang/NoClassDefFoundError;",
1473                               "Class not found using the boot class loader; "
1474                               "no stack trace available");
1475 }
1476 
GetApexVersions(ArrayRef<const std::string> boot_class_path_locations)1477 std::string Runtime::GetApexVersions(ArrayRef<const std::string> boot_class_path_locations) {
1478   std::vector<std::string_view> bcp_apexes;
1479   for (std::string_view jar : boot_class_path_locations) {
1480     std::string_view apex = ApexNameFromLocation(jar);
1481     if (!apex.empty()) {
1482       bcp_apexes.push_back(apex);
1483     }
1484   }
1485   static const char* kApexFileName = "/apex/apex-info-list.xml";
1486   // Start with empty markers.
1487   std::string empty_apex_versions(bcp_apexes.size(), '/');
1488   // When running on host or chroot, we just use empty markers.
1489   if (!kIsTargetBuild || !OS::FileExists(kApexFileName)) {
1490     return empty_apex_versions;
1491   }
1492 #ifdef ART_TARGET_ANDROID
1493   if (access(kApexFileName, R_OK) != 0) {
1494     PLOG(WARNING) << "Failed to read " << kApexFileName;
1495     return empty_apex_versions;
1496   }
1497   auto info_list = apex::readApexInfoList(kApexFileName);
1498   if (!info_list.has_value()) {
1499     LOG(WARNING) << "Failed to parse " << kApexFileName;
1500     return empty_apex_versions;
1501   }
1502 
1503   std::string result;
1504   std::map<std::string_view, const apex::ApexInfo*> apex_infos;
1505   for (const apex::ApexInfo& info : info_list->getApexInfo()) {
1506     if (info.getIsActive()) {
1507       apex_infos.emplace(info.getModuleName(), &info);
1508     }
1509   }
1510   for (const std::string_view& str : bcp_apexes) {
1511     auto info = apex_infos.find(str);
1512     if (info == apex_infos.end() || info->second->getIsFactory()) {
1513       result += '/';
1514     } else {
1515       // In case lastUpdateMillis field is populated in apex-info-list.xml, we
1516       // prefer to use it as version scheme. If the field is missing we
1517       // fallback to the version code of the APEX.
1518       uint64_t version = info->second->hasLastUpdateMillis()
1519           ? info->second->getLastUpdateMillis()
1520           : info->second->getVersionCode();
1521       android::base::StringAppendF(&result, "/%" PRIu64, version);
1522     }
1523   }
1524   return result;
1525 #else
1526   return empty_apex_versions;  // Not an Android build.
1527 #endif
1528 }
1529 
InitializeApexVersions()1530 void Runtime::InitializeApexVersions() {
1531   apex_versions_ =
1532       GetApexVersions(ArrayRef<const std::string>(Runtime::Current()->GetBootClassPathLocations()));
1533 }
1534 
ReloadAllFlags(const std::string & caller)1535 void Runtime::ReloadAllFlags(const std::string& caller) {
1536   FlagBase::ReloadAllFlags(caller);
1537 }
1538 
FileFdsToFileObjects(std::vector<int> && fds)1539 static std::vector<File> FileFdsToFileObjects(std::vector<int>&& fds) {
1540   std::vector<File> files;
1541   files.reserve(fds.size());
1542   for (int fd : fds) {
1543     files.push_back(File(fd, /*check_usage=*/false));
1544   }
1545   return files;
1546 }
1547 
GetThreadSuspendTimeout(const RuntimeArgumentMap * runtime_options)1548 inline static uint64_t GetThreadSuspendTimeout(const RuntimeArgumentMap* runtime_options) {
1549   auto suspend_timeout_opt = runtime_options->GetOptional(RuntimeArgumentMap::ThreadSuspendTimeout);
1550   return suspend_timeout_opt.has_value() ?
1551              suspend_timeout_opt.value().GetNanoseconds() :
1552              ThreadList::kDefaultThreadSuspendTimeout *
1553                  android::base::GetIntProperty("ro.hw_timeout_multiplier", 1);
1554 }
1555 
Init(RuntimeArgumentMap && runtime_options_in)1556 bool Runtime::Init(RuntimeArgumentMap&& runtime_options_in) {
1557   // (b/30160149): protect subprocesses from modifications to LD_LIBRARY_PATH, etc.
1558   // Take a snapshot of the environment at the time the runtime was created, for use by Exec, etc.
1559   env_snapshot_.TakeSnapshot();
1560 
1561 #ifdef ART_PAGE_SIZE_AGNOSTIC
1562   gPageSize.AllowAccess();
1563 #endif
1564 
1565   using Opt = RuntimeArgumentMap;
1566   Opt runtime_options(std::move(runtime_options_in));
1567   ScopedTrace trace(__FUNCTION__);
1568   CHECK_EQ(static_cast<size_t>(sysconf(_SC_PAGE_SIZE)), gPageSize);
1569 
1570   // Reload all the flags value (from system properties and device configs).
1571   ReloadAllFlags(__FUNCTION__);
1572 
1573   deny_art_apex_data_files_ = runtime_options.Exists(Opt::DenyArtApexDataFiles);
1574   if (deny_art_apex_data_files_) {
1575     // We will run slower without those files if the system has taken an ART APEX update.
1576     LOG(WARNING) << "ART APEX data files are untrusted.";
1577   }
1578 
1579   // Early override for logging output.
1580   if (runtime_options.Exists(Opt::UseStderrLogger)) {
1581     android::base::SetLogger(android::base::StderrLogger);
1582   }
1583 
1584   MemMap::Init();
1585 
1586   verifier_missing_kthrow_fatal_ = runtime_options.GetOrDefault(Opt::VerifierMissingKThrowFatal);
1587   force_java_zygote_fork_loop_ = runtime_options.GetOrDefault(Opt::ForceJavaZygoteForkLoop);
1588   perfetto_hprof_enabled_ = runtime_options.GetOrDefault(Opt::PerfettoHprof);
1589   perfetto_javaheapprof_enabled_ = runtime_options.GetOrDefault(Opt::PerfettoJavaHeapStackProf);
1590 
1591   // Try to reserve a dedicated fault page. This is allocated for clobbered registers and sentinels.
1592   // If we cannot reserve it, log a warning.
1593   // Note: We allocate this first to have a good chance of grabbing the page. The address (0xebad..)
1594   //       is out-of-the-way enough that it should not collide with boot image mapping.
1595   // Note: Don't request an error message. That will lead to a maps dump in the case of failure,
1596   //       leading to logspam.
1597   {
1598     const uintptr_t sentinel_addr =
1599         RoundDown(static_cast<uintptr_t>(Context::kBadGprBase), gPageSize);
1600     protected_fault_page_ = MemMap::MapAnonymous("Sentinel fault page",
1601                                                  reinterpret_cast<uint8_t*>(sentinel_addr),
1602                                                  gPageSize,
1603                                                  PROT_NONE,
1604                                                  /*low_4gb=*/ true,
1605                                                  /*reuse=*/ false,
1606                                                  /*reservation=*/ nullptr,
1607                                                  /*error_msg=*/ nullptr);
1608     if (!protected_fault_page_.IsValid()) {
1609       LOG(WARNING) << "Could not reserve sentinel fault page";
1610     } else if (reinterpret_cast<uintptr_t>(protected_fault_page_.Begin()) != sentinel_addr) {
1611       LOG(WARNING) << "Could not reserve sentinel fault page at the right address.";
1612       protected_fault_page_.Reset();
1613     }
1614   }
1615 
1616   VLOG(startup) << "Runtime::Init -verbose:startup enabled";
1617 
1618   QuasiAtomic::Startup();
1619 
1620   oat_file_manager_ = new OatFileManager();
1621 
1622   jni_id_manager_.reset(new jni::JniIdManager());
1623 
1624   Thread::SetSensitiveThreadHook(runtime_options.GetOrDefault(Opt::HookIsSensitiveThread));
1625   Monitor::Init(runtime_options.GetOrDefault(Opt::LockProfThreshold),
1626                 runtime_options.GetOrDefault(Opt::StackDumpLockProfThreshold));
1627 
1628   image_locations_ = runtime_options.ReleaseOrDefault(Opt::Image);
1629 
1630   SetInstructionSet(runtime_options.GetOrDefault(Opt::ImageInstructionSet));
1631   boot_class_path_ = runtime_options.ReleaseOrDefault(Opt::BootClassPath);
1632   boot_class_path_locations_ = runtime_options.ReleaseOrDefault(Opt::BootClassPathLocations);
1633   DCHECK(boot_class_path_locations_.empty() ||
1634          boot_class_path_locations_.size() == boot_class_path_.size());
1635   if (boot_class_path_.empty()) {
1636     LOG(ERROR) << "Boot classpath is empty";
1637     return false;
1638   }
1639 
1640   boot_class_path_files_ =
1641       FileFdsToFileObjects(runtime_options.ReleaseOrDefault(Opt::BootClassPathFds));
1642   if (!boot_class_path_files_.empty() && boot_class_path_files_.size() != boot_class_path_.size()) {
1643     LOG(ERROR) << "Number of FDs specified in -Xbootclasspathfds must match the number of JARs in "
1644                << "-Xbootclasspath.";
1645     return false;
1646   }
1647 
1648   boot_class_path_image_files_ =
1649       FileFdsToFileObjects(runtime_options.ReleaseOrDefault(Opt::BootClassPathImageFds));
1650   boot_class_path_vdex_files_ =
1651       FileFdsToFileObjects(runtime_options.ReleaseOrDefault(Opt::BootClassPathVdexFds));
1652   boot_class_path_oat_files_ =
1653       FileFdsToFileObjects(runtime_options.ReleaseOrDefault(Opt::BootClassPathOatFds));
1654   CHECK(boot_class_path_image_files_.empty() ||
1655         boot_class_path_image_files_.size() == boot_class_path_.size());
1656   CHECK(boot_class_path_vdex_files_.empty() ||
1657         boot_class_path_vdex_files_.size() == boot_class_path_.size());
1658   CHECK(boot_class_path_oat_files_.empty() ||
1659         boot_class_path_oat_files_.size() == boot_class_path_.size());
1660 
1661   class_path_string_ = runtime_options.ReleaseOrDefault(Opt::ClassPath);
1662   properties_ = runtime_options.ReleaseOrDefault(Opt::PropertiesList);
1663 
1664   compiler_callbacks_ = runtime_options.GetOrDefault(Opt::CompilerCallbacksPtr);
1665   must_relocate_ = runtime_options.GetOrDefault(Opt::Relocate);
1666   is_zygote_ = runtime_options.Exists(Opt::Zygote);
1667   is_primary_zygote_ = runtime_options.Exists(Opt::PrimaryZygote);
1668   is_explicit_gc_disabled_ = runtime_options.Exists(Opt::DisableExplicitGC);
1669   is_eagerly_release_explicit_gc_disabled_ =
1670       runtime_options.Exists(Opt::DisableEagerlyReleaseExplicitGC);
1671   image_dex2oat_enabled_ = runtime_options.GetOrDefault(Opt::ImageDex2Oat);
1672   dump_native_stack_on_sig_quit_ = runtime_options.GetOrDefault(Opt::DumpNativeStackOnSigQuit);
1673   allow_in_memory_compilation_ = runtime_options.Exists(Opt::AllowInMemoryCompilation);
1674 
1675   if (is_zygote_ || runtime_options.Exists(Opt::OnlyUseTrustedOatFiles)) {
1676     oat_file_manager_->SetOnlyUseTrustedOatFiles();
1677   }
1678 
1679   vfprintf_ = runtime_options.GetOrDefault(Opt::HookVfprintf);
1680   exit_ = runtime_options.GetOrDefault(Opt::HookExit);
1681   abort_ = runtime_options.GetOrDefault(Opt::HookAbort);
1682 
1683   default_stack_size_ = runtime_options.GetOrDefault(Opt::StackSize);
1684 
1685   compiler_executable_ = runtime_options.ReleaseOrDefault(Opt::Compiler);
1686   compiler_options_ = runtime_options.ReleaseOrDefault(Opt::CompilerOptions);
1687   for (const std::string& option : Runtime::Current()->GetCompilerOptions()) {
1688     if (option == "--debuggable") {
1689       SetRuntimeDebugState(RuntimeDebugState::kJavaDebuggableAtInit);
1690       break;
1691     }
1692   }
1693   image_compiler_options_ = runtime_options.ReleaseOrDefault(Opt::ImageCompilerOptions);
1694 
1695   finalizer_timeout_ms_ = runtime_options.GetOrDefault(Opt::FinalizerTimeoutMs);
1696   max_spins_before_thin_lock_inflation_ =
1697       runtime_options.GetOrDefault(Opt::MaxSpinsBeforeThinLockInflation);
1698 
1699   monitor_list_ = new MonitorList;
1700   monitor_pool_ = MonitorPool::Create();
1701   thread_list_ = new ThreadList(GetThreadSuspendTimeout(&runtime_options));
1702   intern_table_ = new InternTable;
1703 
1704   monitor_timeout_enable_ = runtime_options.GetOrDefault(Opt::MonitorTimeoutEnable);
1705   int monitor_timeout_ms = runtime_options.GetOrDefault(Opt::MonitorTimeout);
1706   if (monitor_timeout_ms < Monitor::kMonitorTimeoutMinMs) {
1707     LOG(WARNING) << "Monitor timeout too short: Increasing";
1708     monitor_timeout_ms = Monitor::kMonitorTimeoutMinMs;
1709   }
1710   if (monitor_timeout_ms >= Monitor::kMonitorTimeoutMaxMs) {
1711     LOG(WARNING) << "Monitor timeout too long: Decreasing";
1712     monitor_timeout_ms = Monitor::kMonitorTimeoutMaxMs - 1;
1713   }
1714   monitor_timeout_ns_ = MsToNs(monitor_timeout_ms);
1715 
1716   verify_ = runtime_options.GetOrDefault(Opt::Verify);
1717 
1718   target_sdk_version_ = runtime_options.GetOrDefault(Opt::TargetSdkVersion);
1719 
1720   // Set hidden API enforcement policy. The checks are disabled by default and
1721   // we only enable them if:
1722   // (a) runtime was started with a command line flag that enables the checks, or
1723   // (b) Zygote forked a new process that is not exempt (see ZygoteHooks).
1724   hidden_api_policy_ = runtime_options.GetOrDefault(Opt::HiddenApiPolicy);
1725   DCHECK_IMPLIES(is_zygote_, hidden_api_policy_ == hiddenapi::EnforcementPolicy::kDisabled);
1726 
1727   // Set core platform API enforcement policy. The checks are disabled by default and
1728   // can be enabled with a command line flag. AndroidRuntime will pass the flag if
1729   // a system property is set.
1730   core_platform_api_policy_ = runtime_options.GetOrDefault(Opt::CorePlatformApiPolicy);
1731   if (core_platform_api_policy_ != hiddenapi::EnforcementPolicy::kDisabled) {
1732     LOG(INFO) << "Core platform API reporting enabled, enforcing="
1733         << (core_platform_api_policy_ == hiddenapi::EnforcementPolicy::kEnabled ? "true" : "false");
1734   }
1735 
1736   // Dex2Oat's Runtime does not need the signal chain or the fault handler
1737   // and it passes the `NoSigChain` option to `Runtime` to indicate this.
1738   no_sig_chain_ = runtime_options.Exists(Opt::NoSigChain);
1739   force_native_bridge_ = runtime_options.Exists(Opt::ForceNativeBridge);
1740 
1741   Split(runtime_options.GetOrDefault(Opt::CpuAbiList), ',', &cpu_abilist_);
1742 
1743   fingerprint_ = runtime_options.ReleaseOrDefault(Opt::Fingerprint);
1744 
1745   if (runtime_options.GetOrDefault(Opt::Interpret)) {
1746     GetInstrumentation()->ForceInterpretOnly();
1747   }
1748 
1749   zygote_max_failed_boots_ = runtime_options.GetOrDefault(Opt::ZygoteMaxFailedBoots);
1750   experimental_flags_ = runtime_options.GetOrDefault(Opt::Experimental);
1751   is_low_memory_mode_ = runtime_options.Exists(Opt::LowMemoryMode);
1752   madvise_willneed_total_dex_size_ = runtime_options.GetOrDefault(Opt::MadviseWillNeedVdexFileSize);
1753   madvise_willneed_odex_filesize_ = runtime_options.GetOrDefault(Opt::MadviseWillNeedOdexFileSize);
1754   madvise_willneed_art_filesize_ = runtime_options.GetOrDefault(Opt::MadviseWillNeedArtFileSize);
1755 
1756   jni_ids_indirection_ = runtime_options.GetOrDefault(Opt::OpaqueJniIds);
1757   automatically_set_jni_ids_indirection_ =
1758       runtime_options.GetOrDefault(Opt::AutoPromoteOpaqueJniIds);
1759 
1760   plugins_ = runtime_options.ReleaseOrDefault(Opt::Plugins);
1761   agent_specs_ = runtime_options.ReleaseOrDefault(Opt::AgentPath);
1762   // TODO Add back in -agentlib
1763   // for (auto lib : runtime_options.ReleaseOrDefault(Opt::AgentLib)) {
1764   //   agents_.push_back(lib);
1765   // }
1766 
1767   float foreground_heap_growth_multiplier;
1768   if (is_low_memory_mode_ && !runtime_options.Exists(Opt::ForegroundHeapGrowthMultiplier)) {
1769     // If low memory mode, use 1.0 as the multiplier by default.
1770     foreground_heap_growth_multiplier = 1.0f;
1771   } else {
1772     // Extra added to the default heap growth multiplier for concurrent GC
1773     // compaction algorithms. This is done for historical reasons.
1774     // TODO: remove when we revisit heap configurations.
1775     foreground_heap_growth_multiplier =
1776         runtime_options.GetOrDefault(Opt::ForegroundHeapGrowthMultiplier) + 1.0f;
1777   }
1778   XGcOption xgc_option = runtime_options.GetOrDefault(Opt::GcOption);
1779 
1780   // Generational CC collection is currently only compatible with Baker read barriers.
1781   bool use_generational_gc = (kUseBakerReadBarrier || gUseUserfaultfd) &&
1782                              xgc_option.generational_gc && ShouldUseGenerationalGC();
1783 
1784   // Cache the apex versions.
1785   InitializeApexVersions();
1786 
1787   BackgroundGcOption background_gc =
1788       gUseReadBarrier ? BackgroundGcOption(gc::kCollectorTypeCCBackground) :
1789                         (gUseUserfaultfd ? BackgroundGcOption(gc::kCollectorTypeCMCBackground) :
1790                                            runtime_options.GetOrDefault(Opt::BackgroundGc));
1791 
1792   heap_ = new gc::Heap(runtime_options.GetOrDefault(Opt::MemoryInitialSize),
1793                        runtime_options.GetOrDefault(Opt::HeapGrowthLimit),
1794                        runtime_options.GetOrDefault(Opt::HeapMinFree),
1795                        runtime_options.GetOrDefault(Opt::HeapMaxFree),
1796                        runtime_options.GetOrDefault(Opt::HeapTargetUtilization),
1797                        foreground_heap_growth_multiplier,
1798                        runtime_options.GetOrDefault(Opt::StopForNativeAllocs),
1799                        runtime_options.GetOrDefault(Opt::MemoryMaximumSize),
1800                        runtime_options.GetOrDefault(Opt::NonMovingSpaceCapacity),
1801                        GetBootClassPath(),
1802                        GetBootClassPathLocations(),
1803                        GetBootClassPathFiles(),
1804                        GetBootClassPathImageFiles(),
1805                        GetBootClassPathVdexFiles(),
1806                        GetBootClassPathOatFiles(),
1807                        image_locations_,
1808                        instruction_set_,
1809                        // Override the collector type to CC if the read barrier config.
1810                        gUseReadBarrier ? gc::kCollectorTypeCC : xgc_option.collector_type_,
1811                        background_gc,
1812                        runtime_options.GetOrDefault(Opt::LargeObjectSpace),
1813                        runtime_options.GetOrDefault(Opt::LargeObjectThreshold),
1814                        runtime_options.GetOrDefault(Opt::ParallelGCThreads),
1815                        runtime_options.GetOrDefault(Opt::ConcGCThreads),
1816                        runtime_options.Exists(Opt::LowMemoryMode),
1817                        runtime_options.GetOrDefault(Opt::LongPauseLogThreshold),
1818                        runtime_options.GetOrDefault(Opt::LongGCLogThreshold),
1819                        runtime_options.Exists(Opt::IgnoreMaxFootprint),
1820                        runtime_options.GetOrDefault(Opt::AlwaysLogExplicitGcs),
1821                        runtime_options.GetOrDefault(Opt::UseTLAB),
1822                        xgc_option.verify_pre_gc_heap_,
1823                        xgc_option.verify_pre_sweeping_heap_,
1824                        xgc_option.verify_post_gc_heap_,
1825                        xgc_option.verify_pre_gc_rosalloc_,
1826                        xgc_option.verify_pre_sweeping_rosalloc_,
1827                        xgc_option.verify_post_gc_rosalloc_,
1828                        xgc_option.gcstress_,
1829                        xgc_option.measure_,
1830                        runtime_options.GetOrDefault(Opt::EnableHSpaceCompactForOOM),
1831                        use_generational_gc,
1832                        runtime_options.GetOrDefault(Opt::HSpaceCompactForOOMMinIntervalsMs),
1833                        runtime_options.Exists(Opt::DumpRegionInfoBeforeGC),
1834                        runtime_options.Exists(Opt::DumpRegionInfoAfterGC));
1835 
1836   dump_gc_performance_on_shutdown_ = runtime_options.Exists(Opt::DumpGCPerformanceOnShutdown);
1837 
1838   bool has_explicit_jdwp_options = runtime_options.Get(Opt::JdwpOptions) != nullptr;
1839   jdwp_options_ = runtime_options.GetOrDefault(Opt::JdwpOptions);
1840   jdwp_provider_ = CanonicalizeJdwpProvider(runtime_options.GetOrDefault(Opt::JdwpProvider),
1841                                             IsJavaDebuggable());
1842   switch (jdwp_provider_) {
1843     case JdwpProvider::kNone: {
1844       VLOG(jdwp) << "Disabling all JDWP support.";
1845       if (!jdwp_options_.empty()) {
1846         bool has_transport = jdwp_options_.find("transport") != std::string::npos;
1847         std::string adb_connection_args =
1848             std::string("  -XjdwpProvider:adbconnection -XjdwpOptions:") + jdwp_options_;
1849         if (has_explicit_jdwp_options) {
1850           LOG(WARNING) << "Jdwp options given when jdwp is disabled! You probably want to enable "
1851                       << "jdwp with one of:" << std::endl
1852                       << "  -Xplugin:libopenjdkjvmti" << (kIsDebugBuild ? "d" : "") << ".so "
1853                       << "-agentpath:libjdwp.so=" << jdwp_options_ << std::endl
1854                       << (has_transport ? "" : adb_connection_args);
1855         }
1856       }
1857       break;
1858     }
1859     case JdwpProvider::kAdbConnection: {
1860       constexpr const char* plugin_name = kIsDebugBuild ? "libadbconnectiond.so"
1861                                                         : "libadbconnection.so";
1862       plugins_.push_back(Plugin::Create(plugin_name));
1863       break;
1864     }
1865     case JdwpProvider::kUnset: {
1866       LOG(FATAL) << "Illegal jdwp provider " << jdwp_provider_ << " was not filtered out!";
1867     }
1868   }
1869   callbacks_->AddThreadLifecycleCallback(Dbg::GetThreadLifecycleCallback());
1870 
1871   jit_options_.reset(jit::JitOptions::CreateFromRuntimeArguments(runtime_options));
1872   if (IsAotCompiler()) {
1873     // If we are already the compiler at this point, we must be dex2oat. Don't create the jit in
1874     // this case.
1875     // If runtime_options doesn't have UseJIT set to true then CreateFromRuntimeArguments returns
1876     // null and we don't create the jit.
1877     jit_options_->SetUseJitCompilation(false);
1878     jit_options_->SetSaveProfilingInfo(false);
1879   }
1880 
1881   // Use MemMap arena pool for jit, malloc otherwise. Malloc arenas are faster to allocate but
1882   // can't be trimmed as easily.
1883   const bool use_malloc = IsAotCompiler();
1884   if (use_malloc) {
1885     arena_pool_.reset(new MallocArenaPool());
1886     jit_arena_pool_.reset(new MallocArenaPool());
1887   } else {
1888     arena_pool_.reset(new MemMapArenaPool(/* low_4gb= */ false));
1889     jit_arena_pool_.reset(new MemMapArenaPool(/* low_4gb= */ false, "CompilerMetadata"));
1890   }
1891 
1892   // For 64 bit compilers, it needs to be in low 4GB in the case where we are cross compiling for a
1893   // 32 bit target. In this case, we have 32 bit pointers in the dex cache arrays which can't hold
1894   // when we have 64 bit ArtMethod pointers.
1895   const bool low_4gb = IsAotCompiler() && Is64BitInstructionSet(kRuntimeISA);
1896   if (gUseUserfaultfd) {
1897     linear_alloc_arena_pool_.reset(new GcVisitedArenaPool(low_4gb, IsZygote()));
1898   } else if (low_4gb) {
1899     linear_alloc_arena_pool_.reset(new MemMapArenaPool(low_4gb));
1900   }
1901   linear_alloc_.reset(CreateLinearAlloc());
1902   startup_linear_alloc_.store(CreateLinearAlloc(), std::memory_order_relaxed);
1903 
1904   small_lrt_allocator_ = new jni::SmallLrtAllocator();
1905 
1906   BlockSignals();
1907   InitPlatformSignalHandlers();
1908 
1909   // Change the implicit checks flags based on runtime architecture.
1910   switch (kRuntimeQuickCodeISA) {
1911     case InstructionSet::kArm64:
1912       implicit_suspend_checks_ = true;
1913       FALLTHROUGH_INTENDED;
1914     case InstructionSet::kArm:
1915     case InstructionSet::kThumb2:
1916     case InstructionSet::kRiscv64:
1917     case InstructionSet::kX86:
1918     case InstructionSet::kX86_64:
1919       implicit_null_checks_ = true;
1920       // Historical note: Installing stack protection was not playing well with Valgrind.
1921       implicit_so_checks_ = true;
1922       break;
1923     default:
1924       // Keep the defaults.
1925       break;
1926   }
1927 
1928 #ifdef ART_USE_RESTRICTED_MODE
1929   // TODO(Simulator): support signal handling and implicit checks.
1930   implicit_suspend_checks_ = false;
1931   implicit_null_checks_ = false;
1932 #endif  // ART_USE_RESTRICTED_MODE
1933 
1934   fault_manager.Init(!no_sig_chain_);
1935   if (!no_sig_chain_) {
1936     if (HandlesSignalsInCompiledCode()) {
1937       // These need to be in a specific order.  The null point check handler must be
1938       // after the suspend check and stack overflow check handlers.
1939       //
1940       // Note: the instances attach themselves to the fault manager and are handled by it. The
1941       //       manager will delete the instance on Shutdown().
1942       if (implicit_suspend_checks_) {
1943         new SuspensionHandler(&fault_manager);
1944       }
1945 
1946       if (implicit_so_checks_) {
1947         new StackOverflowHandler(&fault_manager);
1948       }
1949 
1950       if (implicit_null_checks_) {
1951         new NullPointerHandler(&fault_manager);
1952       }
1953 
1954       if (kEnableJavaStackTraceHandler) {
1955         new JavaStackTraceHandler(&fault_manager);
1956       }
1957 
1958       if (interpreter::CanRuntimeUseNterp()) {
1959         // Nterp code can use signal handling just like the compiled managed code.
1960         OatQuickMethodHeader* nterp_header = OatQuickMethodHeader::NterpMethodHeader;
1961         fault_manager.AddGeneratedCodeRange(nterp_header->GetCode(), nterp_header->GetCodeSize());
1962       }
1963     }
1964   }
1965 
1966   verifier_logging_threshold_ms_ = runtime_options.GetOrDefault(Opt::VerifierLoggingThreshold);
1967 
1968   std::string error_msg;
1969   java_vm_ = JavaVMExt::Create(this, runtime_options, &error_msg);
1970   if (java_vm_.get() == nullptr) {
1971     LOG(ERROR) << "Could not initialize JavaVMExt: " << error_msg;
1972     return false;
1973   }
1974 
1975   // Add the JniEnv handler.
1976   // TODO Refactor this stuff.
1977   java_vm_->AddEnvironmentHook(JNIEnvExt::GetEnvHandler);
1978 
1979   Thread::Startup();
1980 
1981   // ClassLinker needs an attached thread, but we can't fully attach a thread without creating
1982   // objects. We can't supply a thread group yet; it will be fixed later. Since we are the main
1983   // thread, we do not get a java peer.
1984   Thread* self = Thread::Attach("main", false, nullptr, false, /* should_run_callbacks= */ true);
1985   CHECK_EQ(self->GetThreadId(), ThreadList::kMainThreadId);
1986   CHECK(self != nullptr);
1987 
1988   self->SetIsRuntimeThread(IsAotCompiler());
1989 
1990   // Set us to runnable so tools using a runtime can allocate and GC by default
1991   self->TransitionFromSuspendedToRunnable();
1992 
1993   // Now we're attached, we can take the heap locks and validate the heap.
1994   GetHeap()->EnableObjectValidation();
1995 
1996   CHECK_GE(GetHeap()->GetContinuousSpaces().size(), 1U);
1997 
1998   if (UNLIKELY(IsAotCompiler())) {
1999     class_linker_ = compiler_callbacks_->CreateAotClassLinker(intern_table_);
2000   } else {
2001     class_linker_ = new ClassLinker(
2002         intern_table_,
2003         runtime_options.GetOrDefault(Opt::FastClassNotFoundException));
2004   }
2005   if (GetHeap()->HasBootImageSpace()) {
2006     bool result = class_linker_->InitFromBootImage(&error_msg);
2007     if (!result) {
2008       LOG(ERROR) << "Could not initialize from image: " << error_msg;
2009       return false;
2010     }
2011     if (kIsDebugBuild) {
2012       for (auto image_space : GetHeap()->GetBootImageSpaces()) {
2013         image_space->VerifyImageAllocations();
2014       }
2015     }
2016     {
2017       ScopedTrace trace2("AddImageStringsToTable");
2018       for (gc::space::ImageSpace* image_space : heap_->GetBootImageSpaces()) {
2019         GetInternTable()->AddImageStringsToTable(image_space, VoidFunctor());
2020       }
2021     }
2022 
2023     const size_t total_components = gc::space::ImageSpace::GetNumberOfComponents(
2024         ArrayRef<gc::space::ImageSpace* const>(heap_->GetBootImageSpaces()));
2025     if (total_components != GetBootClassPath().size()) {
2026       // The boot image did not contain all boot class path components. Load the rest.
2027       CHECK_LT(total_components, GetBootClassPath().size());
2028       size_t start = total_components;
2029       DCHECK_LT(start, GetBootClassPath().size());
2030       std::vector<std::unique_ptr<const DexFile>> extra_boot_class_path;
2031       if (runtime_options.Exists(Opt::BootClassPathDexList)) {
2032         extra_boot_class_path.swap(*runtime_options.GetOrDefault(Opt::BootClassPathDexList));
2033       } else {
2034         ArrayRef<File> bcp_files = start < GetBootClassPathFiles().size() ?
2035                                        ArrayRef<File>(GetBootClassPathFiles()).SubArray(start) :
2036                                        ArrayRef<File>();
2037         OpenBootDexFiles(ArrayRef<const std::string>(GetBootClassPath()).SubArray(start),
2038                          ArrayRef<const std::string>(GetBootClassPathLocations()).SubArray(start),
2039                          bcp_files,
2040                          &extra_boot_class_path);
2041       }
2042       class_linker_->AddExtraBootDexFiles(self, std::move(extra_boot_class_path));
2043     }
2044     if (IsJavaDebuggable() || jit_options_->GetProfileSaverOptions().GetProfileBootClassPath()) {
2045       // Deoptimize the boot image if debuggable  as the code may have been compiled non-debuggable.
2046       // Also deoptimize if we are profiling the boot class path.
2047       ScopedThreadSuspension sts(self, ThreadState::kNative);
2048       ScopedSuspendAll ssa(__FUNCTION__);
2049       DeoptimizeBootImage();
2050     }
2051   } else {
2052     std::vector<std::unique_ptr<const DexFile>> boot_class_path;
2053     if (runtime_options.Exists(Opt::BootClassPathDexList)) {
2054       boot_class_path.swap(*runtime_options.GetOrDefault(Opt::BootClassPathDexList));
2055     } else {
2056       OpenBootDexFiles(ArrayRef<const std::string>(GetBootClassPath()),
2057                        ArrayRef<const std::string>(GetBootClassPathLocations()),
2058                        ArrayRef<File>(GetBootClassPathFiles()),
2059                        &boot_class_path);
2060     }
2061     if (!class_linker_->InitWithoutImage(std::move(boot_class_path), &error_msg)) {
2062       LOG(ERROR) << "Could not initialize without image: " << error_msg;
2063       return false;
2064     }
2065 
2066     // TODO: Should we move the following to InitWithoutImage?
2067     SetInstructionSet(instruction_set_);
2068     for (uint32_t i = 0; i < kCalleeSaveSize; i++) {
2069       CalleeSaveType type = CalleeSaveType(i);
2070       if (!HasCalleeSaveMethod(type)) {
2071         SetCalleeSaveMethod(CreateCalleeSaveMethod(), type);
2072       }
2073     }
2074   }
2075 
2076   // Now that the boot image space is set, cache the boot classpath checksums,
2077   // to be used when validating oat files.
2078   ArrayRef<gc::space::ImageSpace* const> image_spaces(GetHeap()->GetBootImageSpaces());
2079   ArrayRef<const DexFile* const> bcp_dex_files(GetClassLinker()->GetBootClassPath());
2080   boot_class_path_checksums_ = gc::space::ImageSpace::GetBootClassPathChecksums(image_spaces,
2081                                                                                 bcp_dex_files);
2082 
2083   CHECK(class_linker_ != nullptr);
2084 
2085   if (runtime_options.Exists(Opt::MethodTrace)) {
2086     trace_config_.reset(new TraceConfig());
2087     trace_config_->trace_file = runtime_options.ReleaseOrDefault(Opt::MethodTraceFile);
2088     trace_config_->trace_file_size = runtime_options.ReleaseOrDefault(Opt::MethodTraceFileSize);
2089     trace_config_->trace_mode = Trace::TraceMode::kMethodTracing;
2090     trace_config_->trace_output_mode = runtime_options.Exists(Opt::MethodTraceStreaming) ?
2091                                            TraceOutputMode::kStreaming :
2092                                            TraceOutputMode::kFile;
2093     trace_config_->clock_source = runtime_options.GetOrDefault(Opt::MethodTraceClock);
2094   }
2095 
2096   if (GetHeap()->HasBootImageSpace()) {
2097     const ImageHeader& image_header = GetHeap()->GetBootImageSpaces()[0]->GetImageHeader();
2098     ObjPtr<mirror::ObjectArray<mirror::Object>> boot_image_live_objects =
2099         ObjPtr<mirror::ObjectArray<mirror::Object>>::DownCast(
2100             image_header.GetImageRoot(ImageHeader::kBootImageLiveObjects));
2101     pre_allocated_OutOfMemoryError_when_throwing_exception_ = GcRoot<mirror::Throwable>(
2102         boot_image_live_objects->Get(ImageHeader::kOomeWhenThrowingException)->AsThrowable());
2103     DCHECK(pre_allocated_OutOfMemoryError_when_throwing_exception_.Read()->GetClass()
2104                ->DescriptorEquals("Ljava/lang/OutOfMemoryError;"));
2105     pre_allocated_OutOfMemoryError_when_throwing_oome_ = GcRoot<mirror::Throwable>(
2106         boot_image_live_objects->Get(ImageHeader::kOomeWhenThrowingOome)->AsThrowable());
2107     DCHECK(pre_allocated_OutOfMemoryError_when_throwing_oome_.Read()->GetClass()
2108                ->DescriptorEquals("Ljava/lang/OutOfMemoryError;"));
2109     pre_allocated_OutOfMemoryError_when_handling_stack_overflow_ = GcRoot<mirror::Throwable>(
2110         boot_image_live_objects->Get(ImageHeader::kOomeWhenHandlingStackOverflow)->AsThrowable());
2111     DCHECK(pre_allocated_OutOfMemoryError_when_handling_stack_overflow_.Read()->GetClass()
2112                ->DescriptorEquals("Ljava/lang/OutOfMemoryError;"));
2113     pre_allocated_NoClassDefFoundError_ = GcRoot<mirror::Throwable>(
2114         boot_image_live_objects->Get(ImageHeader::kNoClassDefFoundError)->AsThrowable());
2115     DCHECK(pre_allocated_NoClassDefFoundError_.Read()->GetClass()
2116                ->DescriptorEquals("Ljava/lang/NoClassDefFoundError;"));
2117   } else {
2118     CreatePreAllocatedExceptions(self);
2119   }
2120 
2121   // Class-roots are setup, we can now finish initializing the JniIdManager.
2122   GetJniIdManager()->Init(self);
2123 
2124   // Initialize metrics only for the Zygote process or
2125   // if explicitly enabled via command line argument.
2126   if (IsZygote() || gFlags.MetricsForceEnable.GetValue()) {
2127     LOG(INFO) << "Initializing ART runtime metrics";
2128     InitMetrics();
2129   }
2130 
2131   // Runtime initialization is largely done now.
2132   // We load plugins first since that can modify the runtime state slightly.
2133   // Load all plugins
2134   {
2135     // The init method of plugins expect the state of the thread to be non runnable.
2136     ScopedThreadSuspension sts(self, ThreadState::kNative);
2137     for (auto& plugin : plugins_) {
2138       std::string err;
2139       if (!plugin.Load(&err)) {
2140         LOG(FATAL) << plugin << " failed to load: " << err;
2141       }
2142     }
2143   }
2144 
2145   // Look for a native bridge.
2146   //
2147   // The intended flow here is, in the case of a running system:
2148   //
2149   // Runtime::Init() (zygote):
2150   //   LoadNativeBridge -> dlopen from cmd line parameter.
2151   //  |
2152   //  V
2153   // Runtime::Start() (zygote):
2154   //   No-op wrt native bridge.
2155   //  |
2156   //  | start app
2157   //  V
2158   // DidForkFromZygote(action)
2159   //   action = kUnload -> dlclose native bridge.
2160   //   action = kInitialize -> initialize library
2161   //
2162   //
2163   // The intended flow here is, in the case of a simple dalvikvm call:
2164   //
2165   // Runtime::Init():
2166   //   LoadNativeBridge -> dlopen from cmd line parameter.
2167   //  |
2168   //  V
2169   // Runtime::Start():
2170   //   DidForkFromZygote(kInitialize) -> try to initialize any native bridge given.
2171   //   No-op wrt native bridge.
2172   {
2173     std::string native_bridge_file_name = runtime_options.ReleaseOrDefault(Opt::NativeBridge);
2174     is_native_bridge_loaded_ = LoadNativeBridge(native_bridge_file_name);
2175   }
2176 
2177   // Startup agents
2178   // TODO Maybe we should start a new thread to run these on. Investigate RI behavior more.
2179   for (auto& agent_spec : agent_specs_) {
2180     // TODO Check err
2181     int res = 0;
2182     std::string err = "";
2183     ti::LoadError error;
2184     std::unique_ptr<ti::Agent> agent = agent_spec.Load(&res, &error, &err);
2185 
2186     if (agent != nullptr) {
2187       agents_.push_back(std::move(agent));
2188       continue;
2189     }
2190 
2191     switch (error) {
2192       case ti::LoadError::kInitializationError:
2193         LOG(FATAL) << "Unable to initialize agent!";
2194         UNREACHABLE();
2195 
2196       case ti::LoadError::kLoadingError:
2197         LOG(ERROR) << "Unable to load an agent: " << err;
2198         continue;
2199 
2200       case ti::LoadError::kNoError:
2201         break;
2202     }
2203     LOG(FATAL) << "Unreachable";
2204     UNREACHABLE();
2205   }
2206   {
2207     ScopedObjectAccess soa(self);
2208     callbacks_->NextRuntimePhase(RuntimePhaseCallback::RuntimePhase::kInitialAgents);
2209   }
2210 
2211   if (IsZygote() && IsPerfettoHprofEnabled()) {
2212     constexpr const char* plugin_name = kIsDebugBuild ?
2213         "libperfetto_hprofd.so" : "libperfetto_hprof.so";
2214     // Load eagerly in Zygote to improve app startup times. This will make
2215     // subsequent dlopens for the library no-ops.
2216     dlopen(plugin_name, RTLD_NOW | RTLD_LOCAL);
2217   }
2218 
2219   VLOG(startup) << "Runtime::Init exiting";
2220 
2221   return true;
2222 }
2223 
InitMetrics()2224 void Runtime::InitMetrics() {
2225   metrics::ReportingConfig metrics_config = metrics::ReportingConfig::FromFlags();
2226   metrics_reporter_ = metrics::MetricsReporter::Create(metrics_config, this);
2227 }
2228 
RequestMetricsReport(bool synchronous)2229 void Runtime::RequestMetricsReport(bool synchronous) {
2230   if (AreMetricsInitialized()) {
2231     metrics_reporter_->RequestMetricsReport(synchronous);
2232   }
2233 }
2234 
EnsurePluginLoaded(const char * plugin_name,std::string * error_msg)2235 bool Runtime::EnsurePluginLoaded(const char* plugin_name, std::string* error_msg) {
2236   // Is the plugin already loaded?
2237   for (const Plugin& p : plugins_) {
2238     if (p.GetLibrary() == plugin_name) {
2239       return true;
2240     }
2241   }
2242   Plugin new_plugin = Plugin::Create(plugin_name);
2243 
2244   if (!new_plugin.Load(error_msg)) {
2245     return false;
2246   }
2247   plugins_.push_back(std::move(new_plugin));
2248   return true;
2249 }
2250 
EnsurePerfettoPlugin(std::string * error_msg)2251 bool Runtime::EnsurePerfettoPlugin(std::string* error_msg) {
2252   constexpr const char* plugin_name = kIsDebugBuild ?
2253     "libperfetto_hprofd.so" : "libperfetto_hprof.so";
2254   return EnsurePluginLoaded(plugin_name, error_msg);
2255 }
2256 
EnsureJvmtiPlugin(Runtime * runtime,std::string * error_msg)2257 static bool EnsureJvmtiPlugin(Runtime* runtime,
2258                               std::string* error_msg) {
2259   // TODO Rename Dbg::IsJdwpAllowed is IsDebuggingAllowed.
2260   DCHECK(Dbg::IsJdwpAllowed() || !runtime->IsJavaDebuggable())
2261       << "Being debuggable requires that jdwp (i.e. debugging) is allowed.";
2262   // Is the process debuggable? Otherwise, do not attempt to load the plugin unless we are
2263   // specifically allowed.
2264   if (!Dbg::IsJdwpAllowed()) {
2265     *error_msg = "Process is not allowed to load openjdkjvmti plugin. Process must be debuggable";
2266     return false;
2267   }
2268 
2269   constexpr const char* plugin_name = kIsDebugBuild ? "libopenjdkjvmtid.so" : "libopenjdkjvmti.so";
2270   return runtime->EnsurePluginLoaded(plugin_name, error_msg);
2271 }
2272 
2273 // Attach a new agent and add it to the list of runtime agents
2274 //
2275 // TODO: once we decide on the threading model for agents,
2276 //   revisit this and make sure we're doing this on the right thread
2277 //   (and we synchronize access to any shared data structures like "agents_")
2278 //
AttachAgent(JNIEnv * env,const std::string & agent_arg,jobject class_loader)2279 void Runtime::AttachAgent(JNIEnv* env, const std::string& agent_arg, jobject class_loader) {
2280   std::string error_msg;
2281   if (!EnsureJvmtiPlugin(this, &error_msg)) {
2282     LOG(WARNING) << "Could not load plugin: " << error_msg;
2283     ScopedObjectAccess soa(Thread::Current());
2284     ThrowIOException("%s", error_msg.c_str());
2285     return;
2286   }
2287 
2288   ti::AgentSpec agent_spec(agent_arg);
2289 
2290   int res = 0;
2291   ti::LoadError error;
2292   std::unique_ptr<ti::Agent> agent = agent_spec.Attach(env, class_loader, &res, &error, &error_msg);
2293 
2294   if (agent != nullptr) {
2295     agents_.push_back(std::move(agent));
2296   } else {
2297     LOG(WARNING) << "Agent attach failed (result=" << error << ") : " << error_msg;
2298     ScopedObjectAccess soa(Thread::Current());
2299     ThrowIOException("%s", error_msg.c_str());
2300   }
2301 }
2302 
InitNativeMethods()2303 void Runtime::InitNativeMethods() {
2304   VLOG(startup) << "Runtime::InitNativeMethods entering";
2305   Thread* self = Thread::Current();
2306   JNIEnv* env = self->GetJniEnv();
2307 
2308   // Must be in the kNative state for calling native methods (JNI_OnLoad code).
2309   CHECK_EQ(self->GetState(), ThreadState::kNative);
2310 
2311   // Then set up libjavacore / libopenjdk / libicu_jni ,which are just
2312   // a regular JNI libraries with a regular JNI_OnLoad. Most JNI libraries can
2313   // just use System.loadLibrary, but libcore can't because it's the library
2314   // that implements System.loadLibrary!
2315   //
2316   // By setting calling class to java.lang.Object, the caller location for these
2317   // JNI libs is core-oj.jar in the ART APEX, and hence they are loaded from the
2318   // com_android_art linker namespace.
2319   jclass java_lang_Object;
2320   {
2321     // Use global JNI reference to keep the local references empty. If we allocated a
2322     // local reference here, the `PushLocalFrame(128)` that these internal libraries do
2323     // in their `JNI_OnLoad()` would reserve a lot of unnecessary space due to rounding.
2324     ScopedObjectAccess soa(self);
2325     java_lang_Object = reinterpret_cast<jclass>(
2326         GetJavaVM()->AddGlobalRef(self, GetClassRoot<mirror::Object>(GetClassLinker())));
2327   }
2328 
2329   // libicu_jni has to be initialized before libopenjdk{d} due to runtime dependency from
2330   // libopenjdk{d} to Icu4cMetadata native methods in libicu_jni. See http://b/143888405
2331   {
2332     std::string error_msg;
2333     if (!java_vm_->LoadNativeLibrary(
2334           env, "libicu_jni.so", nullptr, java_lang_Object, &error_msg)) {
2335       LOG(FATAL) << "LoadNativeLibrary failed for \"libicu_jni.so\": " << error_msg;
2336     }
2337   }
2338   {
2339     std::string error_msg;
2340     if (!java_vm_->LoadNativeLibrary(
2341           env, "libjavacore.so", nullptr, java_lang_Object, &error_msg)) {
2342       LOG(FATAL) << "LoadNativeLibrary failed for \"libjavacore.so\": " << error_msg;
2343     }
2344   }
2345   {
2346     constexpr const char* kOpenJdkLibrary = kIsDebugBuild
2347                                                 ? "libopenjdkd.so"
2348                                                 : "libopenjdk.so";
2349     std::string error_msg;
2350     if (!java_vm_->LoadNativeLibrary(
2351           env, kOpenJdkLibrary, nullptr, java_lang_Object, &error_msg)) {
2352       LOG(FATAL) << "LoadNativeLibrary failed for \"" << kOpenJdkLibrary << "\": " << error_msg;
2353     }
2354   }
2355   env->DeleteGlobalRef(java_lang_Object);
2356 
2357   // Initialize well known classes that may invoke runtime native methods.
2358   WellKnownClasses::LateInit(env);
2359 
2360   VLOG(startup) << "Runtime::InitNativeMethods exiting";
2361 }
2362 
ReclaimArenaPoolMemory()2363 void Runtime::ReclaimArenaPoolMemory() {
2364   arena_pool_->LockReclaimMemory();
2365 }
2366 
InitThreadGroups(Thread * self)2367 void Runtime::InitThreadGroups(Thread* self) {
2368   ScopedObjectAccess soa(self);
2369   ArtField* main_thread_group_field = WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup;
2370   ArtField* system_thread_group_field = WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup;
2371   // Note: This is running before `ClassLinker::RunRootClinits()`, so we cannot rely on
2372   // `ThreadGroup` and `Thread` being initialized.
2373   // TODO: Clean up initialization order after all well-known methods are converted to `ArtMethod*`
2374   // (and therefore the `WellKnownClasses::Init()` shall not initialize any classes).
2375   StackHandleScope<2u> hs(self);
2376   Handle<mirror::Class> thread_group_class =
2377       hs.NewHandle(main_thread_group_field->GetDeclaringClass());
2378   bool initialized = GetClassLinker()->EnsureInitialized(
2379       self, thread_group_class, /*can_init_fields=*/ true, /*can_init_parents=*/ true);
2380   CHECK(initialized);
2381   Handle<mirror::Class> thread_class = hs.NewHandle(WellKnownClasses::java_lang_Thread.Get());
2382   initialized = GetClassLinker()->EnsureInitialized(
2383       self, thread_class, /*can_init_fields=*/ true, /*can_init_parents=*/ true);
2384   CHECK(initialized);
2385   main_thread_group_ =
2386       soa.Vm()->AddGlobalRef(self, main_thread_group_field->GetObject(thread_group_class.Get()));
2387   CHECK_IMPLIES(main_thread_group_ == nullptr, IsAotCompiler());
2388   system_thread_group_ =
2389       soa.Vm()->AddGlobalRef(self, system_thread_group_field->GetObject(thread_group_class.Get()));
2390   CHECK_IMPLIES(system_thread_group_ == nullptr, IsAotCompiler());
2391 }
2392 
GetMainThreadGroup() const2393 jobject Runtime::GetMainThreadGroup() const {
2394   CHECK_IMPLIES(main_thread_group_ == nullptr, IsAotCompiler());
2395   return main_thread_group_;
2396 }
2397 
GetSystemThreadGroup() const2398 jobject Runtime::GetSystemThreadGroup() const {
2399   CHECK_IMPLIES(system_thread_group_ == nullptr, IsAotCompiler());
2400   return system_thread_group_;
2401 }
2402 
GetSystemClassLoader() const2403 jobject Runtime::GetSystemClassLoader() const {
2404   CHECK_IMPLIES(system_class_loader_ == nullptr, IsAotCompiler());
2405   return system_class_loader_;
2406 }
2407 
RegisterRuntimeNativeMethods(JNIEnv * env)2408 void Runtime::RegisterRuntimeNativeMethods(JNIEnv* env) {
2409   register_dalvik_system_DexFile(env);
2410   register_dalvik_system_BaseDexClassLoader(env);
2411   register_dalvik_system_VMDebug(env);
2412   real_register_dalvik_system_VMRuntime(env);
2413   register_dalvik_system_VMStack(env);
2414   register_dalvik_system_ZygoteHooks(env);
2415   register_java_lang_Class(env);
2416   register_java_lang_Object(env);
2417   register_java_lang_invoke_MethodHandle(env);
2418   register_java_lang_invoke_MethodHandleImpl(env);
2419   register_java_lang_ref_FinalizerReference(env);
2420   register_java_lang_reflect_Array(env);
2421   register_java_lang_reflect_Constructor(env);
2422   register_java_lang_reflect_Executable(env);
2423   register_java_lang_reflect_Field(env);
2424   register_java_lang_reflect_Method(env);
2425   register_java_lang_reflect_Parameter(env);
2426   register_java_lang_reflect_Proxy(env);
2427   register_java_lang_ref_Reference(env);
2428   register_java_lang_StackStreamFactory(env);
2429   register_java_lang_String(env);
2430   register_java_lang_StringFactory(env);
2431   register_java_lang_System(env);
2432   register_java_lang_Thread(env);
2433   register_java_lang_Throwable(env);
2434   register_java_lang_VMClassLoader(env);
2435   register_java_util_concurrent_atomic_AtomicLong(env);
2436   register_jdk_internal_misc_Unsafe(env);
2437   register_libcore_io_Memory(env);
2438   register_libcore_util_CharsetUtils(env);
2439   register_org_apache_harmony_dalvik_ddmc_DdmServer(env);
2440   register_org_apache_harmony_dalvik_ddmc_DdmVmInternal(env);
2441   register_sun_misc_Unsafe(env);
2442 }
2443 
operator <<(std::ostream & os,const DeoptimizationKind & kind)2444 std::ostream& operator<<(std::ostream& os, const DeoptimizationKind& kind) {
2445   os << GetDeoptimizationKindName(kind);
2446   return os;
2447 }
2448 
DumpDeoptimizations(std::ostream & os)2449 void Runtime::DumpDeoptimizations(std::ostream& os) {
2450   for (size_t i = 0; i <= static_cast<size_t>(DeoptimizationKind::kLast); ++i) {
2451     if (deoptimization_counts_[i] != 0) {
2452       os << "Number of "
2453          << GetDeoptimizationKindName(static_cast<DeoptimizationKind>(i))
2454          << " deoptimizations: "
2455          << deoptimization_counts_[i]
2456          << "\n";
2457     }
2458   }
2459 }
2460 
SigQuitNanoTime() const2461 std::optional<uint64_t> Runtime::SigQuitNanoTime() const {
2462   return signal_catcher_ != nullptr ? signal_catcher_->SigQuitNanoTime() : std::nullopt;
2463 }
2464 
DumpForSigQuit(std::ostream & os)2465 void Runtime::DumpForSigQuit(std::ostream& os) {
2466   // Print backtraces first since they are important do diagnose ANRs,
2467   // and ANRs can often be trimmed to limit upload size.
2468   thread_list_->DumpForSigQuit(os);
2469   GetClassLinker()->DumpForSigQuit(os);
2470   GetInternTable()->DumpForSigQuit(os);
2471   GetJavaVM()->DumpForSigQuit(os);
2472   GetHeap()->DumpForSigQuit(os);
2473   oat_file_manager_->DumpForSigQuit(os);
2474   if (GetJit() != nullptr) {
2475     GetJit()->DumpForSigQuit(os);
2476   } else {
2477     os << "Running non JIT\n";
2478   }
2479   DumpDeoptimizations(os);
2480   TrackedAllocators::Dump(os);
2481   GetMetrics()->DumpForSigQuit(os);
2482   os << "\n";
2483 
2484   BaseMutex::DumpAll(os);
2485 
2486   // Inform anyone else who is interested in SigQuit.
2487   {
2488     ScopedObjectAccess soa(Thread::Current());
2489     callbacks_->SigQuit();
2490   }
2491 }
2492 
DumpLockHolders(std::ostream & os)2493 void Runtime::DumpLockHolders(std::ostream& os) {
2494   pid_t mutator_lock_owner = Locks::mutator_lock_->GetExclusiveOwnerTid();
2495   pid_t thread_list_lock_owner = GetThreadList()->GetLockOwner();
2496   pid_t classes_lock_owner = GetClassLinker()->GetClassesLockOwner();
2497   pid_t dex_lock_owner = GetClassLinker()->GetDexLockOwner();
2498   if ((mutator_lock_owner | thread_list_lock_owner | classes_lock_owner | dex_lock_owner) != 0) {
2499     os << "Mutator lock exclusive owner tid: " << mutator_lock_owner << "\n"
2500        << "ThreadList lock owner tid: " << thread_list_lock_owner << "\n"
2501        << "ClassLinker classes lock owner tid: " << classes_lock_owner << "\n"
2502        << "ClassLinker dex lock owner tid: " << dex_lock_owner << "\n";
2503   }
2504 }
2505 
SetStatsEnabled(bool new_state)2506 void Runtime::SetStatsEnabled(bool new_state) {
2507   Thread* self = Thread::Current();
2508   MutexLock mu(self, *Locks::instrument_entrypoints_lock_);
2509   if (new_state == true) {
2510     GetStats()->Clear(~0);
2511     // TODO: wouldn't it make more sense to clear _all_ threads' stats?
2512     self->GetStats()->Clear(~0);
2513     if (stats_enabled_ != new_state) {
2514       GetInstrumentation()->InstrumentQuickAllocEntryPointsLocked();
2515     }
2516   } else if (stats_enabled_ != new_state) {
2517     GetInstrumentation()->UninstrumentQuickAllocEntryPointsLocked();
2518   }
2519   stats_enabled_ = new_state;
2520 }
2521 
ResetStats(int kinds)2522 void Runtime::ResetStats(int kinds) {
2523   GetStats()->Clear(kinds & 0xffff);
2524   // TODO: wouldn't it make more sense to clear _all_ threads' stats?
2525   Thread::Current()->GetStats()->Clear(kinds >> 16);
2526 }
2527 
GetStat(int kind)2528 uint64_t Runtime::GetStat(int kind) {
2529   RuntimeStats* stats;
2530   if (kind < (1<<16)) {
2531     stats = GetStats();
2532   } else {
2533     stats = Thread::Current()->GetStats();
2534     kind >>= 16;
2535   }
2536   switch (kind) {
2537   case KIND_ALLOCATED_OBJECTS:
2538     return stats->allocated_objects;
2539   case KIND_ALLOCATED_BYTES:
2540     return stats->allocated_bytes;
2541   case KIND_FREED_OBJECTS:
2542     return stats->freed_objects;
2543   case KIND_FREED_BYTES:
2544     return stats->freed_bytes;
2545   case KIND_GC_INVOCATIONS:
2546     return stats->gc_for_alloc_count;
2547   case KIND_CLASS_INIT_COUNT:
2548     return stats->class_init_count;
2549   case KIND_CLASS_INIT_TIME:
2550     return stats->class_init_time_ns;
2551   case KIND_EXT_ALLOCATED_OBJECTS:
2552   case KIND_EXT_ALLOCATED_BYTES:
2553   case KIND_EXT_FREED_OBJECTS:
2554   case KIND_EXT_FREED_BYTES:
2555     return 0;  // backward compatibility
2556   default:
2557     LOG(FATAL) << "Unknown statistic " << kind;
2558     UNREACHABLE();
2559   }
2560 }
2561 
BlockSignals()2562 void Runtime::BlockSignals() {
2563   SignalSet signals;
2564   signals.Add(SIGPIPE);
2565   // SIGQUIT is used to dump the runtime's state (including stack traces).
2566   signals.Add(SIGQUIT);
2567   // SIGUSR1 is used to initiate a GC.
2568   signals.Add(SIGUSR1);
2569   signals.Block();
2570 }
2571 
AttachCurrentThread(const char * thread_name,bool as_daemon,jobject thread_group,bool create_peer,bool should_run_callbacks)2572 bool Runtime::AttachCurrentThread(const char* thread_name, bool as_daemon, jobject thread_group,
2573                                   bool create_peer, bool should_run_callbacks) {
2574   ScopedTrace trace(__FUNCTION__);
2575   Thread* self = Thread::Attach(thread_name,
2576                                 as_daemon,
2577                                 thread_group,
2578                                 create_peer,
2579                                 should_run_callbacks);
2580   // Run ThreadGroup.add to notify the group that this thread is now started.
2581   if (self != nullptr && create_peer && !IsAotCompiler()) {
2582     ScopedObjectAccess soa(self);
2583     self->NotifyThreadGroup(soa, thread_group);
2584   }
2585   return self != nullptr;
2586 }
2587 
DetachCurrentThread(bool should_run_callbacks)2588 void Runtime::DetachCurrentThread(bool should_run_callbacks) {
2589   ScopedTrace trace(__FUNCTION__);
2590   Thread* self = Thread::Current();
2591   if (self == nullptr) {
2592     LOG(FATAL) << "attempting to detach thread that is not attached";
2593   }
2594   if (self->HasManagedStack()) {
2595     LOG(FATAL) << *Thread::Current() << " attempting to detach while still running code";
2596   }
2597   thread_list_->Unregister(self, should_run_callbacks);
2598 }
2599 
GetPreAllocatedOutOfMemoryErrorWhenThrowingException()2600 mirror::Throwable* Runtime::GetPreAllocatedOutOfMemoryErrorWhenThrowingException() {
2601   mirror::Throwable* oome = pre_allocated_OutOfMemoryError_when_throwing_exception_.Read();
2602   if (oome == nullptr) {
2603     LOG(ERROR) << "Failed to return pre-allocated OOME-when-throwing-exception";
2604   }
2605   return oome;
2606 }
2607 
GetPreAllocatedOutOfMemoryErrorWhenThrowingOOME()2608 mirror::Throwable* Runtime::GetPreAllocatedOutOfMemoryErrorWhenThrowingOOME() {
2609   mirror::Throwable* oome = pre_allocated_OutOfMemoryError_when_throwing_oome_.Read();
2610   if (oome == nullptr) {
2611     LOG(ERROR) << "Failed to return pre-allocated OOME-when-throwing-OOME";
2612   }
2613   return oome;
2614 }
2615 
GetPreAllocatedOutOfMemoryErrorWhenHandlingStackOverflow()2616 mirror::Throwable* Runtime::GetPreAllocatedOutOfMemoryErrorWhenHandlingStackOverflow() {
2617   mirror::Throwable* oome = pre_allocated_OutOfMemoryError_when_handling_stack_overflow_.Read();
2618   if (oome == nullptr) {
2619     LOG(ERROR) << "Failed to return pre-allocated OOME-when-handling-stack-overflow";
2620   }
2621   return oome;
2622 }
2623 
GetPreAllocatedNoClassDefFoundError()2624 mirror::Throwable* Runtime::GetPreAllocatedNoClassDefFoundError() {
2625   mirror::Throwable* ncdfe = pre_allocated_NoClassDefFoundError_.Read();
2626   if (ncdfe == nullptr) {
2627     LOG(ERROR) << "Failed to return pre-allocated NoClassDefFoundError";
2628   }
2629   return ncdfe;
2630 }
2631 
VisitConstantRoots(RootVisitor * visitor)2632 void Runtime::VisitConstantRoots(RootVisitor* visitor) {
2633   // Visiting the roots of these ArtMethods is not currently required since all the GcRoots are
2634   // null.
2635   BufferedRootVisitor<16> buffered_visitor(visitor, RootInfo(kRootVMInternal));
2636   const PointerSize pointer_size = GetClassLinker()->GetImagePointerSize();
2637   if (HasResolutionMethod()) {
2638     resolution_method_->VisitRoots(buffered_visitor, pointer_size);
2639   }
2640   if (HasImtConflictMethod()) {
2641     imt_conflict_method_->VisitRoots(buffered_visitor, pointer_size);
2642   }
2643   if (imt_unimplemented_method_ != nullptr) {
2644     imt_unimplemented_method_->VisitRoots(buffered_visitor, pointer_size);
2645   }
2646   for (uint32_t i = 0; i < kCalleeSaveSize; ++i) {
2647     auto* m = reinterpret_cast<ArtMethod*>(callee_save_methods_[i]);
2648     if (m != nullptr) {
2649       m->VisitRoots(buffered_visitor, pointer_size);
2650     }
2651   }
2652 }
2653 
VisitConcurrentRoots(RootVisitor * visitor,VisitRootFlags flags)2654 void Runtime::VisitConcurrentRoots(RootVisitor* visitor, VisitRootFlags flags) {
2655   // Userfaultfd compaction updates intern-tables and class-tables page-by-page
2656   // via LinearAlloc. So don't visit them here.
2657   if (GetHeap()->IsPerformingUffdCompaction()) {
2658     class_linker_->VisitRoots(visitor, flags, /*visit_class_roots=*/false);
2659   } else {
2660     intern_table_->VisitRoots(visitor, flags);
2661     class_linker_->VisitRoots(visitor, flags, /*visit_class_roots=*/true);
2662   }
2663   jni_id_manager_->VisitRoots(visitor);
2664   heap_->VisitAllocationRecords(visitor);
2665   if (jit_ != nullptr) {
2666     jit_->VisitRoots(visitor);
2667   }
2668   if ((flags & kVisitRootFlagNewRoots) == 0) {
2669     // Guaranteed to have no new roots in the constant roots.
2670     VisitConstantRoots(visitor);
2671   }
2672 }
2673 
VisitNonThreadRoots(RootVisitor * visitor)2674 void Runtime::VisitNonThreadRoots(RootVisitor* visitor) {
2675   java_vm_->VisitRoots(visitor);
2676   sentinel_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
2677   pre_allocated_OutOfMemoryError_when_throwing_exception_
2678       .VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
2679   pre_allocated_OutOfMemoryError_when_throwing_oome_
2680       .VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
2681   pre_allocated_OutOfMemoryError_when_handling_stack_overflow_
2682       .VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
2683   pre_allocated_NoClassDefFoundError_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
2684   VisitImageRoots(visitor);
2685   class_linker_->VisitTransactionRoots(visitor);
2686 }
2687 
VisitNonConcurrentRoots(RootVisitor * visitor,VisitRootFlags flags)2688 void Runtime::VisitNonConcurrentRoots(RootVisitor* visitor, VisitRootFlags flags) {
2689   VisitThreadRoots(visitor, flags);
2690   VisitNonThreadRoots(visitor);
2691 }
2692 
VisitThreadRoots(RootVisitor * visitor,VisitRootFlags flags)2693 void Runtime::VisitThreadRoots(RootVisitor* visitor, VisitRootFlags flags) {
2694   thread_list_->VisitRoots(visitor, flags);
2695 }
2696 
VisitRoots(RootVisitor * visitor,VisitRootFlags flags)2697 void Runtime::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
2698   VisitNonConcurrentRoots(visitor, flags);
2699   VisitConcurrentRoots(visitor, flags);
2700 }
2701 
VisitReflectiveTargets(ReflectiveValueVisitor * visitor)2702 void Runtime::VisitReflectiveTargets(ReflectiveValueVisitor *visitor) {
2703   thread_list_->VisitReflectiveTargets(visitor);
2704   heap_->VisitReflectiveTargets(visitor);
2705   jni_id_manager_->VisitReflectiveTargets(visitor);
2706   callbacks_->VisitReflectiveTargets(visitor);
2707 }
2708 
VisitImageRoots(RootVisitor * visitor)2709 void Runtime::VisitImageRoots(RootVisitor* visitor) {
2710   // We only confirm that image roots are unchanged.
2711   if (kIsDebugBuild) {
2712     for (auto* space : GetHeap()->GetContinuousSpaces()) {
2713       if (space->IsImageSpace()) {
2714         auto* image_space = space->AsImageSpace();
2715         const auto& image_header = image_space->GetImageHeader();
2716         for (int32_t i = 0, size = image_header.GetImageRoots()->GetLength(); i != size; ++i) {
2717           mirror::Object* obj =
2718               image_header.GetImageRoot(static_cast<ImageHeader::ImageRoot>(i)).Ptr();
2719           if (obj != nullptr) {
2720             mirror::Object* after_obj = obj;
2721             visitor->VisitRoot(&after_obj, RootInfo(kRootStickyClass));
2722             CHECK_EQ(after_obj, obj);
2723           }
2724         }
2725       }
2726     }
2727   }
2728 }
2729 
CreateRuntimeMethod(ClassLinker * class_linker,LinearAlloc * linear_alloc)2730 static ArtMethod* CreateRuntimeMethod(ClassLinker* class_linker, LinearAlloc* linear_alloc)
2731     REQUIRES_SHARED(Locks::mutator_lock_) {
2732   const PointerSize image_pointer_size = class_linker->GetImagePointerSize();
2733   const size_t method_alignment = ArtMethod::Alignment(image_pointer_size);
2734   const size_t method_size = ArtMethod::Size(image_pointer_size);
2735   LengthPrefixedArray<ArtMethod>* method_array = class_linker->AllocArtMethodArray(
2736       Thread::Current(),
2737       linear_alloc,
2738       1);
2739   ArtMethod* method = &method_array->At(0, method_size, method_alignment);
2740   CHECK(method != nullptr);
2741   method->SetDexMethodIndex(dex::kDexNoIndex);
2742   CHECK(method->IsRuntimeMethod());
2743   return method;
2744 }
2745 
CreateImtConflictMethod(LinearAlloc * linear_alloc)2746 ArtMethod* Runtime::CreateImtConflictMethod(LinearAlloc* linear_alloc) {
2747   ClassLinker* const class_linker = GetClassLinker();
2748   ArtMethod* method = CreateRuntimeMethod(class_linker, linear_alloc);
2749   // When compiling, the code pointer will get set later when the image is loaded.
2750   const PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set_);
2751   if (IsAotCompiler()) {
2752     method->SetEntryPointFromQuickCompiledCodePtrSize(nullptr, pointer_size);
2753   } else {
2754     method->SetEntryPointFromQuickCompiledCode(GetQuickImtConflictStub());
2755   }
2756   // Create empty conflict table.
2757   method->SetImtConflictTable(class_linker->CreateImtConflictTable(/*count=*/0u, linear_alloc),
2758                               pointer_size);
2759   return method;
2760 }
2761 
SetImtConflictMethod(ArtMethod * method)2762 void Runtime::SetImtConflictMethod(ArtMethod* method) {
2763   CHECK(method != nullptr);
2764   CHECK(method->IsRuntimeMethod());
2765   imt_conflict_method_ = method;
2766 }
2767 
CreateResolutionMethod()2768 ArtMethod* Runtime::CreateResolutionMethod() {
2769   auto* method = CreateRuntimeMethod(GetClassLinker(), GetLinearAlloc());
2770   // When compiling, the code pointer will get set later when the image is loaded.
2771   if (IsAotCompiler()) {
2772     PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set_);
2773     method->SetEntryPointFromQuickCompiledCodePtrSize(nullptr, pointer_size);
2774     method->SetEntryPointFromJniPtrSize(nullptr, pointer_size);
2775   } else {
2776     method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
2777     method->SetEntryPointFromJni(GetJniDlsymLookupCriticalStub());
2778   }
2779   return method;
2780 }
2781 
CreateCalleeSaveMethod()2782 ArtMethod* Runtime::CreateCalleeSaveMethod() {
2783   auto* method = CreateRuntimeMethod(GetClassLinker(), GetLinearAlloc());
2784   PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set_);
2785   method->SetEntryPointFromQuickCompiledCodePtrSize(nullptr, pointer_size);
2786   DCHECK_NE(instruction_set_, InstructionSet::kNone);
2787   DCHECK(method->IsRuntimeMethod());
2788   return method;
2789 }
2790 
DisallowNewSystemWeaks()2791 void Runtime::DisallowNewSystemWeaks() {
2792   CHECK(!gUseReadBarrier);
2793   monitor_list_->DisallowNewMonitors();
2794   intern_table_->ChangeWeakRootState(gc::kWeakRootStateNoReadsOrWrites);
2795   java_vm_->DisallowNewWeakGlobals();
2796   heap_->DisallowNewAllocationRecords();
2797   if (GetJit() != nullptr) {
2798     GetJit()->GetCodeCache()->DisallowInlineCacheAccess();
2799   }
2800 
2801   // All other generic system-weak holders.
2802   for (gc::AbstractSystemWeakHolder* holder : system_weak_holders_) {
2803     holder->Disallow();
2804   }
2805 }
2806 
AllowNewSystemWeaks()2807 void Runtime::AllowNewSystemWeaks() {
2808   CHECK(!gUseReadBarrier);
2809   monitor_list_->AllowNewMonitors();
2810   intern_table_->ChangeWeakRootState(gc::kWeakRootStateNormal);  // TODO: Do this in the sweeping.
2811   java_vm_->AllowNewWeakGlobals();
2812   heap_->AllowNewAllocationRecords();
2813   if (GetJit() != nullptr) {
2814     GetJit()->GetCodeCache()->AllowInlineCacheAccess();
2815   }
2816 
2817   // All other generic system-weak holders.
2818   for (gc::AbstractSystemWeakHolder* holder : system_weak_holders_) {
2819     holder->Allow();
2820   }
2821 }
2822 
BroadcastForNewSystemWeaks(bool broadcast_for_checkpoint)2823 void Runtime::BroadcastForNewSystemWeaks(bool broadcast_for_checkpoint) {
2824   // This is used for the read barrier case that uses the thread-local
2825   // Thread::GetWeakRefAccessEnabled() flag and the checkpoint while weak ref access is disabled
2826   // (see ThreadList::RunCheckpoint).
2827   monitor_list_->BroadcastForNewMonitors();
2828   intern_table_->BroadcastForNewInterns();
2829   java_vm_->BroadcastForNewWeakGlobals();
2830   heap_->BroadcastForNewAllocationRecords();
2831   if (GetJit() != nullptr) {
2832     GetJit()->GetCodeCache()->BroadcastForInlineCacheAccess();
2833   }
2834 
2835   // All other generic system-weak holders.
2836   for (gc::AbstractSystemWeakHolder* holder : system_weak_holders_) {
2837     holder->Broadcast(broadcast_for_checkpoint);
2838   }
2839 }
2840 
SetInstructionSet(InstructionSet instruction_set)2841 void Runtime::SetInstructionSet(InstructionSet instruction_set) {
2842   instruction_set_ = instruction_set;
2843   switch (instruction_set) {
2844     case InstructionSet::kThumb2:
2845       // kThumb2 is the same as kArm, use the canonical value.
2846       instruction_set_ = InstructionSet::kArm;
2847       break;
2848     case InstructionSet::kArm:
2849     case InstructionSet::kArm64:
2850     case InstructionSet::kRiscv64:
2851     case InstructionSet::kX86:
2852     case InstructionSet::kX86_64:
2853       break;
2854     default:
2855       UNIMPLEMENTED(FATAL) << instruction_set_;
2856       UNREACHABLE();
2857   }
2858 }
2859 
ClearInstructionSet()2860 void Runtime::ClearInstructionSet() {
2861   instruction_set_ = InstructionSet::kNone;
2862 }
2863 
SetCalleeSaveMethod(ArtMethod * method,CalleeSaveType type)2864 void Runtime::SetCalleeSaveMethod(ArtMethod* method, CalleeSaveType type) {
2865   DCHECK_LT(static_cast<uint32_t>(type), kCalleeSaveSize);
2866   CHECK(method != nullptr);
2867   callee_save_methods_[static_cast<size_t>(type)] = reinterpret_cast<uintptr_t>(method);
2868 }
2869 
ClearCalleeSaveMethods()2870 void Runtime::ClearCalleeSaveMethods() {
2871   for (size_t i = 0; i < kCalleeSaveSize; ++i) {
2872     callee_save_methods_[i] = reinterpret_cast<uintptr_t>(nullptr);
2873   }
2874 }
2875 
RegisterAppInfo(const std::string & package_name,const std::vector<std::string> & code_paths,const std::string & profile_output_filename,const std::string & ref_profile_filename,int32_t code_type)2876 void Runtime::RegisterAppInfo(const std::string& package_name,
2877                               const std::vector<std::string>& code_paths,
2878                               const std::string& profile_output_filename,
2879                               const std::string& ref_profile_filename,
2880                               int32_t code_type) {
2881   app_info_.RegisterAppInfo(
2882       package_name,
2883       code_paths,
2884       profile_output_filename,
2885       ref_profile_filename,
2886       AppInfo::FromVMRuntimeConstants(code_type));
2887 
2888   if (AreMetricsInitialized()) {
2889     metrics_reporter_->NotifyAppInfoUpdated(&app_info_);
2890   }
2891 
2892   if (jit_.get() == nullptr) {
2893     // We are not JITing. Nothing to do.
2894     return;
2895   }
2896 
2897   VLOG(profiler) << "Register app with " << profile_output_filename
2898       << " " << android::base::Join(code_paths, ':');
2899   VLOG(profiler) << "Reference profile is: " << ref_profile_filename;
2900 
2901   if (profile_output_filename.empty()) {
2902     LOG(WARNING) << "JIT profile information will not be recorded: profile filename is empty.";
2903     return;
2904   }
2905   if (code_paths.empty()) {
2906     LOG(WARNING) << "JIT profile information will not be recorded: code paths is empty.";
2907     return;
2908   }
2909 
2910   // Framework calls this method for all split APKs. Ignore the calls for the ones with no dex code
2911   // so that we don't unnecessarily create profiles for them or write bootclasspath profiling info
2912   // to those profiles.
2913   bool has_code = false;
2914   for (const std::string& path : code_paths) {
2915     std::string error_msg;
2916     std::optional<uint32_t> checksum;
2917     std::vector<std::string> dex_locations;
2918     DexFileLoader loader(path);
2919     if (!loader.GetMultiDexChecksum(&checksum, &error_msg)) {
2920       LOG(WARNING) << error_msg;
2921       continue;
2922     }
2923     if (checksum.has_value()) {
2924       has_code = true;
2925       break;
2926     }
2927   }
2928   if (!has_code) {
2929     VLOG(profiler) << ART_FORMAT(
2930         "JIT profile information will not be recorded: no dex code in '{}'.",
2931         android::base::Join(code_paths, ','));
2932     return;
2933   }
2934 
2935   jit_->StartProfileSaver(profile_output_filename,
2936                           code_paths,
2937                           ref_profile_filename,
2938                           AppInfo::FromVMRuntimeConstants(code_type));
2939 }
2940 
SetFaultMessage(const std::string & message)2941 void Runtime::SetFaultMessage(const std::string& message) {
2942   std::string* new_msg = new std::string(message);
2943   std::string* cur_msg = fault_message_.exchange(new_msg);
2944   delete cur_msg;
2945 }
2946 
GetFaultMessage()2947 std::string Runtime::GetFaultMessage() {
2948   // Retrieve the message. Temporarily replace with null so that SetFaultMessage will not delete
2949   // the string in parallel.
2950   std::string* cur_msg = fault_message_.exchange(nullptr);
2951 
2952   // Make a copy of the string.
2953   std::string ret = cur_msg == nullptr ? "" : *cur_msg;
2954 
2955   // Put the message back if it hasn't been updated.
2956   std::string* null_str = nullptr;
2957   if (!fault_message_.compare_exchange_strong(null_str, cur_msg)) {
2958     // Already replaced.
2959     delete cur_msg;
2960   }
2961 
2962   return ret;
2963 }
2964 
AddCurrentRuntimeFeaturesAsDex2OatArguments(std::vector<std::string> * argv) const2965 void Runtime::AddCurrentRuntimeFeaturesAsDex2OatArguments(std::vector<std::string>* argv)
2966     const {
2967   if (GetInstrumentation()->InterpretOnly()) {
2968     argv->push_back("--compiler-filter=verify");
2969   }
2970 
2971   // Make the dex2oat instruction set match that of the launching runtime. If we have multiple
2972   // architecture support, dex2oat may be compiled as a different instruction-set than that
2973   // currently being executed.
2974   std::string instruction_set("--instruction-set=");
2975   // The dex2oat instruction set should match the runtime's target ISA.
2976   instruction_set += GetInstructionSetString(kRuntimeQuickCodeISA);
2977   argv->push_back(instruction_set);
2978 
2979   if (InstructionSetFeatures::IsRuntimeDetectionSupported()) {
2980     argv->push_back("--instruction-set-features=runtime");
2981   } else {
2982     std::unique_ptr<const InstructionSetFeatures> features(
2983         InstructionSetFeatures::FromCppDefines());
2984     std::string feature_string("--instruction-set-features=");
2985     feature_string += features->GetFeatureString();
2986     argv->push_back(feature_string);
2987   }
2988 }
2989 
CreateJit()2990 void Runtime::CreateJit() {
2991   DCHECK(jit_code_cache_ == nullptr);
2992   DCHECK(jit_ == nullptr);
2993   if (kIsDebugBuild && GetInstrumentation()->IsForcedInterpretOnly()) {
2994     DCHECK(!jit_options_->UseJitCompilation());
2995   }
2996 
2997   if (!jit_options_->UseJitCompilation() && !jit_options_->GetSaveProfilingInfo()) {
2998     return;
2999   }
3000 
3001   if (IsSafeMode()) {
3002     LOG(INFO) << "Not creating JIT because of SafeMode.";
3003     return;
3004   }
3005 
3006   std::string error_msg;
3007   bool profiling_only = !jit_options_->UseJitCompilation();
3008   jit_code_cache_.reset(jit::JitCodeCache::Create(profiling_only,
3009                                                   /*rwx_memory_allowed=*/ true,
3010                                                   IsZygote(),
3011                                                   &error_msg));
3012   if (jit_code_cache_.get() == nullptr) {
3013     LOG(WARNING) << "Failed to create JIT Code Cache: " << error_msg;
3014     return;
3015   }
3016 
3017   jit_ = jit::Jit::Create(jit_code_cache_.get(), jit_options_.get());
3018   jit_->CreateThreadPool();
3019 }
3020 
CanRelocate() const3021 bool Runtime::CanRelocate() const {
3022   return !IsAotCompiler();
3023 }
3024 
IsCompilingBootImage() const3025 bool Runtime::IsCompilingBootImage() const {
3026   return IsCompiler() && compiler_callbacks_->IsBootImage();
3027 }
3028 
SetResolutionMethod(ArtMethod * method)3029 void Runtime::SetResolutionMethod(ArtMethod* method) {
3030   CHECK(method != nullptr);
3031   CHECK(method->IsRuntimeMethod()) << method;
3032   resolution_method_ = method;
3033 }
3034 
SetImtUnimplementedMethod(ArtMethod * method)3035 void Runtime::SetImtUnimplementedMethod(ArtMethod* method) {
3036   CHECK(method != nullptr);
3037   CHECK(method->IsRuntimeMethod());
3038   imt_unimplemented_method_ = method;
3039 }
3040 
FixupConflictTables()3041 void Runtime::FixupConflictTables() {
3042   // We can only do this after the class linker is created.
3043   const PointerSize pointer_size = GetClassLinker()->GetImagePointerSize();
3044   if (imt_unimplemented_method_->GetImtConflictTable(pointer_size) == nullptr) {
3045     imt_unimplemented_method_->SetImtConflictTable(
3046         ClassLinker::CreateImtConflictTable(/*count=*/0u, GetLinearAlloc(), pointer_size),
3047         pointer_size);
3048   }
3049   if (imt_conflict_method_->GetImtConflictTable(pointer_size) == nullptr) {
3050     imt_conflict_method_->SetImtConflictTable(
3051           ClassLinker::CreateImtConflictTable(/*count=*/0u, GetLinearAlloc(), pointer_size),
3052           pointer_size);
3053   }
3054 }
3055 
DisableVerifier()3056 void Runtime::DisableVerifier() {
3057   verify_ = verifier::VerifyMode::kNone;
3058 }
3059 
IsVerificationEnabled() const3060 bool Runtime::IsVerificationEnabled() const {
3061   return verify_ == verifier::VerifyMode::kEnable ||
3062       verify_ == verifier::VerifyMode::kSoftFail;
3063 }
3064 
IsVerificationSoftFail() const3065 bool Runtime::IsVerificationSoftFail() const {
3066   return verify_ == verifier::VerifyMode::kSoftFail;
3067 }
3068 
IsAsyncDeoptimizeable(ArtMethod * method,uintptr_t code) const3069 bool Runtime::IsAsyncDeoptimizeable(ArtMethod* method, uintptr_t code) const {
3070   if (OatQuickMethodHeader::NterpMethodHeader != nullptr) {
3071     if (OatQuickMethodHeader::NterpMethodHeader->Contains(code)) {
3072       return true;
3073     }
3074   }
3075 
3076   // We only support async deopt (ie the compiled code is not explicitly asking for
3077   // deopt, but something else like the debugger) in debuggable JIT code.
3078   // We could look at the oat file where `code` is being defined,
3079   // and check whether it's been compiled debuggable, but we decided to
3080   // only rely on the JIT for debuggable apps.
3081   // The JIT-zygote is not debuggable so we need to be sure to exclude code from the non-private
3082   // region as well.
3083   if (GetJit() != nullptr &&
3084       GetJit()->GetCodeCache()->PrivateRegionContainsPc(reinterpret_cast<const void*>(code))) {
3085     // If the code is JITed code then check if it was compiled as debuggable.
3086     const OatQuickMethodHeader* header = method->GetOatQuickMethodHeader(code);
3087     return CodeInfo::IsDebuggable(header->GetOptimizedCodeInfoPtr());
3088   }
3089 
3090   return false;
3091 }
3092 
3093 
CreateLinearAlloc()3094 LinearAlloc* Runtime::CreateLinearAlloc() {
3095   ArenaPool* pool = linear_alloc_arena_pool_.get();
3096   return pool != nullptr
3097       ? new LinearAlloc(pool, gUseUserfaultfd)
3098       : new LinearAlloc(arena_pool_.get(), /*track_allocs=*/ false);
3099 }
3100 
3101 class Runtime::SetupLinearAllocForZygoteFork : public AllocatorVisitor {
3102  public:
SetupLinearAllocForZygoteFork(Thread * self)3103   explicit SetupLinearAllocForZygoteFork(Thread* self) : self_(self) {}
3104 
Visit(LinearAlloc * alloc)3105   bool Visit(LinearAlloc* alloc) override {
3106     alloc->SetupForPostZygoteFork(self_);
3107     return true;
3108   }
3109 
3110  private:
3111   Thread* self_;
3112 };
3113 
SetupLinearAllocForPostZygoteFork(Thread * self)3114 void Runtime::SetupLinearAllocForPostZygoteFork(Thread* self) {
3115   if (gUseUserfaultfd) {
3116     // Setup all the linear-allocs out there for post-zygote fork. This will
3117     // basically force the arena allocator to ask for a new arena for the next
3118     // allocation. All arenas allocated from now on will be in the userfaultfd
3119     // visited space.
3120     if (GetLinearAlloc() != nullptr) {
3121       GetLinearAlloc()->SetupForPostZygoteFork(self);
3122     }
3123     if (GetStartupLinearAlloc() != nullptr) {
3124       GetStartupLinearAlloc()->SetupForPostZygoteFork(self);
3125     }
3126     {
3127       Locks::mutator_lock_->AssertNotHeld(self);
3128       ReaderMutexLock mu2(self, *Locks::mutator_lock_);
3129       ReaderMutexLock mu3(self, *Locks::classlinker_classes_lock_);
3130       SetupLinearAllocForZygoteFork visitor(self);
3131       GetClassLinker()->VisitAllocators(&visitor);
3132     }
3133     static_cast<GcVisitedArenaPool*>(GetLinearAllocArenaPool())->SetupPostZygoteMode();
3134   }
3135 }
3136 
GetHashTableMinLoadFactor() const3137 double Runtime::GetHashTableMinLoadFactor() const {
3138   return is_low_memory_mode_ ? kLowMemoryMinLoadFactor : kNormalMinLoadFactor;
3139 }
3140 
GetHashTableMaxLoadFactor() const3141 double Runtime::GetHashTableMaxLoadFactor() const {
3142   return is_low_memory_mode_ ? kLowMemoryMaxLoadFactor : kNormalMaxLoadFactor;
3143 }
3144 
UpdateProcessState(ProcessState process_state)3145 void Runtime::UpdateProcessState(ProcessState process_state) {
3146   ProcessState old_process_state = process_state_;
3147   process_state_ = process_state;
3148   GetHeap()->UpdateProcessState(old_process_state, process_state);
3149 }
3150 
RegisterSensitiveThread() const3151 void Runtime::RegisterSensitiveThread() const {
3152   Thread::SetJitSensitiveThread();
3153 }
3154 
3155 // Returns true if JIT compilations are enabled. GetJit() will be not null in this case.
UseJitCompilation() const3156 bool Runtime::UseJitCompilation() const {
3157   return (jit_ != nullptr) && jit_->UseJitCompilation();
3158 }
3159 
TakeSnapshot()3160 void Runtime::EnvSnapshot::TakeSnapshot() {
3161   char** env = GetEnviron();
3162   for (size_t i = 0; env[i] != nullptr; ++i) {
3163     name_value_pairs_.emplace_back(new std::string(env[i]));
3164   }
3165   // The strings in name_value_pairs_ retain ownership of the c_str, but we assign pointers
3166   // for quick use by GetSnapshot.  This avoids allocation and copying cost at Exec.
3167   c_env_vector_.reset(new char*[name_value_pairs_.size() + 1]);
3168   for (size_t i = 0; env[i] != nullptr; ++i) {
3169     c_env_vector_[i] = const_cast<char*>(name_value_pairs_[i]->c_str());
3170   }
3171   c_env_vector_[name_value_pairs_.size()] = nullptr;
3172 }
3173 
GetSnapshot() const3174 char** Runtime::EnvSnapshot::GetSnapshot() const {
3175   return c_env_vector_.get();
3176 }
3177 
AddSystemWeakHolder(gc::AbstractSystemWeakHolder * holder)3178 void Runtime::AddSystemWeakHolder(gc::AbstractSystemWeakHolder* holder) {
3179   gc::ScopedGCCriticalSection gcs(Thread::Current(),
3180                                   gc::kGcCauseAddRemoveSystemWeakHolder,
3181                                   gc::kCollectorTypeAddRemoveSystemWeakHolder);
3182   // Note: The ScopedGCCriticalSection also ensures that the rest of the function is in
3183   //       a critical section.
3184   system_weak_holders_.push_back(holder);
3185 }
3186 
RemoveSystemWeakHolder(gc::AbstractSystemWeakHolder * holder)3187 void Runtime::RemoveSystemWeakHolder(gc::AbstractSystemWeakHolder* holder) {
3188   gc::ScopedGCCriticalSection gcs(Thread::Current(),
3189                                   gc::kGcCauseAddRemoveSystemWeakHolder,
3190                                   gc::kCollectorTypeAddRemoveSystemWeakHolder);
3191   auto it = std::find(system_weak_holders_.begin(), system_weak_holders_.end(), holder);
3192   if (it != system_weak_holders_.end()) {
3193     system_weak_holders_.erase(it);
3194   }
3195 }
3196 
GetRuntimeCallbacks()3197 RuntimeCallbacks* Runtime::GetRuntimeCallbacks() {
3198   return callbacks_.get();
3199 }
3200 
3201 // Used to update boot image to not use AOT code. This is used when transitioning the runtime to
3202 // java debuggable. This visitor re-initializes the entry points without using AOT code. This also
3203 // disables shared hotness counters so the necessary methods can be JITed more efficiently.
3204 class DeoptimizeBootImageClassVisitor : public ClassVisitor {
3205  public:
DeoptimizeBootImageClassVisitor(instrumentation::Instrumentation * instrumentation)3206   explicit DeoptimizeBootImageClassVisitor(instrumentation::Instrumentation* instrumentation)
3207       : instrumentation_(instrumentation) {}
3208 
operator ()(ObjPtr<mirror::Class> klass)3209   bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES(Locks::mutator_lock_) {
3210     DCHECK(Locks::mutator_lock_->IsExclusiveHeld(Thread::Current()));
3211     auto pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
3212     for (auto& m : klass->GetMethods(pointer_size)) {
3213       const void* code = m.GetEntryPointFromQuickCompiledCode();
3214       if (!m.IsInvokable()) {
3215         continue;
3216       }
3217       // For java debuggable runtimes we also deoptimize native methods. For other cases (boot
3218       // image profiling) we don't need to deoptimize native methods. If this changes also
3219       // update Instrumentation::CanUseAotCode.
3220       bool deoptimize_native_methods = Runtime::Current()->IsJavaDebuggable();
3221       if (Runtime::Current()->GetHeap()->IsInBootImageOatFile(code) &&
3222           (!m.IsNative() || deoptimize_native_methods) &&
3223           !m.IsProxyMethod()) {
3224         instrumentation_->ReinitializeMethodsCode(&m);
3225       }
3226 
3227       if (Runtime::Current()->GetJit() != nullptr &&
3228           Runtime::Current()->GetJit()->GetCodeCache()->IsInZygoteExecSpace(code) &&
3229           (!m.IsNative() || deoptimize_native_methods)) {
3230         DCHECK(!m.IsProxyMethod());
3231         instrumentation_->ReinitializeMethodsCode(&m);
3232       }
3233 
3234       if (m.IsPreCompiled()) {
3235         // Precompilation is incompatible with debuggable, so clear the flag
3236         // and update the entrypoint in case it has been compiled.
3237         m.ClearPreCompiled();
3238         instrumentation_->ReinitializeMethodsCode(&m);
3239       }
3240 
3241       // Clear MemorySharedAccessFlags so the boot class methods can be JITed better.
3242       m.ClearMemorySharedMethod();
3243     }
3244     return true;
3245   }
3246 
3247  private:
3248   instrumentation::Instrumentation* const instrumentation_;
3249 };
3250 
SetRuntimeDebugState(RuntimeDebugState state)3251 void Runtime::SetRuntimeDebugState(RuntimeDebugState state) {
3252   if (state != RuntimeDebugState::kJavaDebuggableAtInit) {
3253     // We never change the state if we started as a debuggable runtime.
3254     DCHECK(runtime_debug_state_ != RuntimeDebugState::kJavaDebuggableAtInit);
3255   }
3256   runtime_debug_state_ = state;
3257 }
3258 
DeoptimizeBootImage()3259 void Runtime::DeoptimizeBootImage() {
3260   // If we've already started and we are setting this runtime to debuggable,
3261   // we patch entry points of methods in boot image to interpreter bridge, as
3262   // boot image code may be AOT compiled as not debuggable.
3263   DeoptimizeBootImageClassVisitor visitor(GetInstrumentation());
3264   GetClassLinker()->VisitClasses(&visitor);
3265   jit::Jit* jit = GetJit();
3266   if (jit != nullptr) {
3267     // Code previously compiled may not be compiled debuggable.
3268     jit->GetCodeCache()->TransitionToDebuggable();
3269   }
3270 }
3271 
ScopedThreadPoolUsage()3272 Runtime::ScopedThreadPoolUsage::ScopedThreadPoolUsage()
3273     : thread_pool_(Runtime::Current()->AcquireThreadPool()) {}
3274 
~ScopedThreadPoolUsage()3275 Runtime::ScopedThreadPoolUsage::~ScopedThreadPoolUsage() {
3276   Runtime::Current()->ReleaseThreadPool();
3277 }
3278 
DeleteThreadPool()3279 bool Runtime::DeleteThreadPool() {
3280   // Make sure workers are started to prevent thread shutdown errors.
3281   WaitForThreadPoolWorkersToStart();
3282   std::unique_ptr<ThreadPool> thread_pool;
3283   {
3284     MutexLock mu(Thread::Current(), *Locks::runtime_thread_pool_lock_);
3285     if (thread_pool_ref_count_ == 0) {
3286       thread_pool = std::move(thread_pool_);
3287     }
3288   }
3289   return thread_pool != nullptr;
3290 }
3291 
AcquireThreadPool()3292 ThreadPool* Runtime::AcquireThreadPool() {
3293   MutexLock mu(Thread::Current(), *Locks::runtime_thread_pool_lock_);
3294   ++thread_pool_ref_count_;
3295   return thread_pool_.get();
3296 }
3297 
ReleaseThreadPool()3298 void Runtime::ReleaseThreadPool() {
3299   MutexLock mu(Thread::Current(), *Locks::runtime_thread_pool_lock_);
3300   CHECK_GT(thread_pool_ref_count_, 0u);
3301   --thread_pool_ref_count_;
3302 }
3303 
WaitForThreadPoolWorkersToStart()3304 void Runtime::WaitForThreadPoolWorkersToStart() {
3305   // Need to make sure workers are created before deleting the pool.
3306   ScopedThreadPoolUsage stpu;
3307   if (stpu.GetThreadPool() != nullptr) {
3308     stpu.GetThreadPool()->WaitForWorkersToBeCreated();
3309   }
3310 }
3311 
ResetStartupCompleted()3312 void Runtime::ResetStartupCompleted() {
3313   startup_completed_.store(false, std::memory_order_seq_cst);
3314 }
3315 
NotifyStartupCompleted()3316 bool Runtime::NotifyStartupCompleted() {
3317   DCHECK(!IsZygote());
3318   bool expected = false;
3319   if (!startup_completed_.compare_exchange_strong(expected, true, std::memory_order_seq_cst)) {
3320     // Right now NotifyStartupCompleted will be called up to twice, once from profiler and up to
3321     // once externally. For this reason there are no asserts.
3322     return false;
3323   }
3324 
3325   VLOG(startup) << app_info_;
3326 
3327   ProfileSaver::NotifyStartupCompleted();
3328 
3329   if (AreMetricsInitialized()) {
3330     metrics_reporter_->NotifyStartupCompleted();
3331   }
3332   return true;
3333 }
3334 
NotifyDexFileLoaded()3335 void Runtime::NotifyDexFileLoaded() {
3336   if (AreMetricsInitialized()) {
3337     metrics_reporter_->NotifyAppInfoUpdated(&app_info_);
3338   }
3339 }
3340 
GetStartupCompleted() const3341 bool Runtime::GetStartupCompleted() const {
3342   return startup_completed_.load(std::memory_order_seq_cst);
3343 }
3344 
SetSignalHookDebuggable(bool value)3345 void Runtime::SetSignalHookDebuggable(bool value) {
3346   SkipAddSignalHandler(value);
3347 }
3348 
SetJniIdType(JniIdType t)3349 void Runtime::SetJniIdType(JniIdType t) {
3350   CHECK(CanSetJniIdType()) << "Not allowed to change id type!";
3351   if (t == GetJniIdType()) {
3352     return;
3353   }
3354   jni_ids_indirection_ = t;
3355   JNIEnvExt::ResetFunctionTable();
3356   WellKnownClasses::HandleJniIdTypeChange(Thread::Current()->GetJniEnv());
3357 }
3358 
IsSystemServerProfiled() const3359 bool Runtime::IsSystemServerProfiled() const {
3360   return IsSystemServer() && jit_options_->GetSaveProfilingInfo();
3361 }
3362 
GetOatFilesExecutable() const3363 bool Runtime::GetOatFilesExecutable() const {
3364   return !IsAotCompiler() && !IsSystemServerProfiled();
3365 }
3366 
MadviseFileForRange(size_t madvise_size_limit_bytes,size_t map_size_bytes,const uint8_t * map_begin,const uint8_t * map_end,const std::string & file_name)3367 void Runtime::MadviseFileForRange(size_t madvise_size_limit_bytes,
3368                                   size_t map_size_bytes,
3369                                   const uint8_t* map_begin,
3370                                   const uint8_t* map_end,
3371                                   const std::string& file_name) {
3372   map_begin = AlignDown(map_begin, gPageSize);
3373   map_size_bytes = RoundUp(map_size_bytes, gPageSize);
3374 #ifdef ART_TARGET_ANDROID
3375   // Short-circuit the madvise optimization for background processes. This
3376   // avoids IO and memory contention with foreground processes, particularly
3377   // those involving app startup.
3378   // Note: We can only safely short-circuit the madvise on T+, as it requires
3379   // the framework to always immediately notify ART of process states.
3380   static const int kApiLevel = android_get_device_api_level();
3381   const bool accurate_process_state_at_startup = kApiLevel >= __ANDROID_API_T__;
3382   if (accurate_process_state_at_startup) {
3383     const Runtime* runtime = Runtime::Current();
3384     if (runtime != nullptr && !runtime->InJankPerceptibleProcessState()) {
3385       return;
3386     }
3387   }
3388 #endif  // ART_TARGET_ANDROID
3389 
3390   // Ideal blockTransferSize for madvising files (128KiB)
3391   static constexpr size_t kIdealIoTransferSizeBytes = 128*1024;
3392 
3393   size_t target_size_bytes = std::min<size_t>(map_size_bytes, madvise_size_limit_bytes);
3394 
3395   if (target_size_bytes > 0) {
3396     ScopedTrace madvising_trace("madvising "
3397                                 + file_name
3398                                 + " size="
3399                                 + std::to_string(target_size_bytes));
3400 
3401     // Based on requested size (target_size_bytes)
3402     const uint8_t* target_pos = map_begin + target_size_bytes;
3403 
3404     // Clamp endOfFile if its past map_end
3405     if (target_pos > map_end) {
3406       target_pos = map_end;
3407     }
3408 
3409     // Madvise the whole file up to target_pos in chunks of
3410     // kIdealIoTransferSizeBytes (to MADV_WILLNEED)
3411     // Note:
3412     // madvise(MADV_WILLNEED) will prefetch max(fd readahead size, optimal
3413     // block size for device) per call, hence the need for chunks. (128KB is a
3414     // good default.)
3415     for (const uint8_t* madvise_start = map_begin;
3416          madvise_start < target_pos;
3417          madvise_start += kIdealIoTransferSizeBytes) {
3418       void* madvise_addr = const_cast<void*>(reinterpret_cast<const void*>(madvise_start));
3419       size_t madvise_length = std::min(kIdealIoTransferSizeBytes,
3420                                        static_cast<size_t>(target_pos - madvise_start));
3421       int status = madvise(madvise_addr, madvise_length, MADV_WILLNEED);
3422       // In case of error we stop madvising rest of the file
3423       if (status < 0) {
3424         LOG(ERROR) << "Failed to madvise file " << file_name
3425                    << " for size:" << map_size_bytes
3426                    << ": " << strerror(errno);
3427         break;
3428       }
3429     }
3430   }
3431 }
3432 
3433 // Return whether a boot image has a profile. This means we'll need to pre-JIT
3434 // methods in that profile for performance.
HasImageWithProfile() const3435 bool Runtime::HasImageWithProfile() const {
3436   for (gc::space::ImageSpace* space : GetHeap()->GetBootImageSpaces()) {
3437     if (!space->GetProfileFiles().empty()) {
3438       return true;
3439     }
3440   }
3441   return false;
3442 }
3443 
AppendToBootClassPath(const std::string & filename,const std::string & location)3444 void Runtime::AppendToBootClassPath(const std::string& filename, const std::string& location) {
3445   DCHECK(!DexFileLoader::IsMultiDexLocation(filename));
3446   boot_class_path_.push_back(filename);
3447   if (!boot_class_path_locations_.empty()) {
3448     DCHECK(!DexFileLoader::IsMultiDexLocation(location));
3449     boot_class_path_locations_.push_back(location);
3450   }
3451 }
3452 
AppendToBootClassPath(const std::string & filename,const std::string & location,const std::vector<std::unique_ptr<const art::DexFile>> & dex_files)3453 void Runtime::AppendToBootClassPath(
3454     const std::string& filename,
3455     const std::string& location,
3456     const std::vector<std::unique_ptr<const art::DexFile>>& dex_files) {
3457   AppendToBootClassPath(filename, location);
3458   ScopedObjectAccess soa(Thread::Current());
3459   for (const std::unique_ptr<const art::DexFile>& dex_file : dex_files) {
3460     // The first element must not be at a multi-dex location, while other elements must be.
3461     DCHECK_NE(DexFileLoader::IsMultiDexLocation(dex_file->GetLocation()),
3462               dex_file.get() == dex_files.begin()->get());
3463     GetClassLinker()->AppendToBootClassPath(Thread::Current(), dex_file.get());
3464   }
3465 }
3466 
AppendToBootClassPath(const std::string & filename,const std::string & location,const std::vector<const art::DexFile * > & dex_files)3467 void Runtime::AppendToBootClassPath(const std::string& filename,
3468                                     const std::string& location,
3469                                     const std::vector<const art::DexFile*>& dex_files) {
3470   AppendToBootClassPath(filename, location);
3471   ScopedObjectAccess soa(Thread::Current());
3472   for (const art::DexFile* dex_file : dex_files) {
3473     // The first element must not be at a multi-dex location, while other elements must be.
3474     DCHECK_NE(DexFileLoader::IsMultiDexLocation(dex_file->GetLocation()),
3475               dex_file == *dex_files.begin());
3476     GetClassLinker()->AppendToBootClassPath(Thread::Current(), dex_file);
3477   }
3478 }
3479 
AppendToBootClassPath(const std::string & filename,const std::string & location,const std::vector<std::pair<const art::DexFile *,ObjPtr<mirror::DexCache>>> & dex_files_and_cache)3480 void Runtime::AppendToBootClassPath(
3481     const std::string& filename,
3482     const std::string& location,
3483     const std::vector<std::pair<const art::DexFile*, ObjPtr<mirror::DexCache>>>&
3484         dex_files_and_cache) {
3485   AppendToBootClassPath(filename, location);
3486   ScopedObjectAccess soa(Thread::Current());
3487   for (const auto& [dex_file, dex_cache] : dex_files_and_cache) {
3488     // The first element must not be at a multi-dex location, while other elements must be.
3489     DCHECK_NE(DexFileLoader::IsMultiDexLocation(dex_file->GetLocation()),
3490               dex_file == dex_files_and_cache.begin()->first);
3491     GetClassLinker()->AppendToBootClassPath(dex_file, dex_cache);
3492   }
3493 }
3494 
AddExtraBootDexFiles(const std::string & filename,const std::string & location,std::vector<std::unique_ptr<const art::DexFile>> && dex_files)3495 void Runtime::AddExtraBootDexFiles(const std::string& filename,
3496                                    const std::string& location,
3497                                    std::vector<std::unique_ptr<const art::DexFile>>&& dex_files) {
3498   AppendToBootClassPath(filename, location);
3499   ScopedObjectAccess soa(Thread::Current());
3500   if (kIsDebugBuild) {
3501     for (const std::unique_ptr<const art::DexFile>& dex_file : dex_files) {
3502       // The first element must not be at a multi-dex location, while other elements must be.
3503       DCHECK_NE(DexFileLoader::IsMultiDexLocation(dex_file->GetLocation()),
3504                 dex_file.get() == dex_files.begin()->get());
3505     }
3506   }
3507   GetClassLinker()->AddExtraBootDexFiles(Thread::Current(), std::move(dex_files));
3508 }
3509 
DCheckNoTransactionCheckAllowed()3510 void Runtime::DCheckNoTransactionCheckAllowed() {
3511   if (kIsDebugBuild) {
3512     Thread* self = Thread::Current();
3513     if (self != nullptr) {
3514       self->AssertNoTransactionCheckAllowed();
3515     }
3516   }
3517 }
3518 
3519 }  // namespace art
3520