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 // sys/mount.h has to come before linux/fs.h due to redefinition of MS_RDONLY, MS_BIND, etc
20 #include <sys/mount.h>
21 #ifdef __linux__
22 #include <linux/fs.h>
23 #include <sys/prctl.h>
24 #endif
25 
26 #include <fcntl.h>
27 #include <signal.h>
28 #include <sys/syscall.h>
29 
30 #if defined(__APPLE__)
31 #include <crt_externs.h>  // for _NSGetEnviron
32 #endif
33 
34 #include <cstdio>
35 #include <cstdlib>
36 #include <limits>
37 #include <thread>
38 #include <unordered_set>
39 #include <vector>
40 
41 #include "android-base/strings.h"
42 
43 #include "aot_class_linker.h"
44 #include "arch/arm/registers_arm.h"
45 #include "arch/arm64/registers_arm64.h"
46 #include "arch/context.h"
47 #include "arch/instruction_set_features.h"
48 #include "arch/x86/registers_x86.h"
49 #include "arch/x86_64/registers_x86_64.h"
50 #include "art_field-inl.h"
51 #include "art_method-inl.h"
52 #include "asm_support.h"
53 #include "base/aborting.h"
54 #include "base/arena_allocator.h"
55 #include "base/atomic.h"
56 #include "base/dumpable.h"
57 #include "base/enums.h"
58 #include "base/file_utils.h"
59 #include "base/malloc_arena_pool.h"
60 #include "base/mem_map_arena_pool.h"
61 #include "base/memory_tool.h"
62 #include "base/mutex.h"
63 #include "base/os.h"
64 #include "base/quasi_atomic.h"
65 #include "base/sdk_version.h"
66 #include "base/stl_util.h"
67 #include "base/systrace.h"
68 #include "base/unix_file/fd_file.h"
69 #include "base/utils.h"
70 #include "class_linker-inl.h"
71 #include "class_root.h"
72 #include "compiler_callbacks.h"
73 #include "debugger.h"
74 #include "dex/art_dex_file_loader.h"
75 #include "dex/dex_file_loader.h"
76 #include "elf_file.h"
77 #include "entrypoints/runtime_asm_entrypoints.h"
78 #include "experimental_flags.h"
79 #include "fault_handler.h"
80 #include "gc/accounting/card_table-inl.h"
81 #include "gc/heap.h"
82 #include "gc/scoped_gc_critical_section.h"
83 #include "gc/space/image_space.h"
84 #include "gc/space/space-inl.h"
85 #include "gc/system_weak.h"
86 #include "gc/task_processor.h"
87 #include "handle_scope-inl.h"
88 #include "hidden_api.h"
89 #include "image-inl.h"
90 #include "instrumentation.h"
91 #include "intern_table-inl.h"
92 #include "interpreter/interpreter.h"
93 #include "jit/jit.h"
94 #include "jit/jit_code_cache.h"
95 #include "jit/profile_saver.h"
96 #include "jni/java_vm_ext.h"
97 #include "jni/jni_id_manager.h"
98 #include "jni_id_type.h"
99 #include "linear_alloc.h"
100 #include "memory_representation.h"
101 #include "mirror/array.h"
102 #include "mirror/class-alloc-inl.h"
103 #include "mirror/class-inl.h"
104 #include "mirror/class_ext.h"
105 #include "mirror/class_loader-inl.h"
106 #include "mirror/emulated_stack_frame.h"
107 #include "mirror/field.h"
108 #include "mirror/method.h"
109 #include "mirror/method_handle_impl.h"
110 #include "mirror/method_handles_lookup.h"
111 #include "mirror/method_type.h"
112 #include "mirror/stack_trace_element.h"
113 #include "mirror/throwable.h"
114 #include "mirror/var_handle.h"
115 #include "monitor.h"
116 #include "native/dalvik_system_DexFile.h"
117 #include "native/dalvik_system_BaseDexClassLoader.h"
118 #include "native/dalvik_system_VMDebug.h"
119 #include "native/dalvik_system_VMRuntime.h"
120 #include "native/dalvik_system_VMStack.h"
121 #include "native/dalvik_system_ZygoteHooks.h"
122 #include "native/java_lang_Class.h"
123 #include "native/java_lang_Object.h"
124 #include "native/java_lang_String.h"
125 #include "native/java_lang_StringFactory.h"
126 #include "native/java_lang_System.h"
127 #include "native/java_lang_Thread.h"
128 #include "native/java_lang_Throwable.h"
129 #include "native/java_lang_VMClassLoader.h"
130 #include "native/java_lang_invoke_MethodHandleImpl.h"
131 #include "native/java_lang_ref_FinalizerReference.h"
132 #include "native/java_lang_ref_Reference.h"
133 #include "native/java_lang_reflect_Array.h"
134 #include "native/java_lang_reflect_Constructor.h"
135 #include "native/java_lang_reflect_Executable.h"
136 #include "native/java_lang_reflect_Field.h"
137 #include "native/java_lang_reflect_Method.h"
138 #include "native/java_lang_reflect_Parameter.h"
139 #include "native/java_lang_reflect_Proxy.h"
140 #include "native/java_util_concurrent_atomic_AtomicLong.h"
141 #include "native/libcore_util_CharsetUtils.h"
142 #include "native/org_apache_harmony_dalvik_ddmc_DdmServer.h"
143 #include "native/org_apache_harmony_dalvik_ddmc_DdmVmInternal.h"
144 #include "native/sun_misc_Unsafe.h"
145 #include "native_bridge_art_interface.h"
146 #include "native_stack_dump.h"
147 #include "nativehelper/scoped_local_ref.h"
148 #include "oat.h"
149 #include "oat_file.h"
150 #include "oat_file_manager.h"
151 #include "oat_quick_method_header.h"
152 #include "object_callbacks.h"
153 #include "parsed_options.h"
154 #include "quick/quick_method_frame_info.h"
155 #include "reflection.h"
156 #include "runtime_callbacks.h"
157 #include "runtime_common.h"
158 #include "runtime_intrinsics.h"
159 #include "runtime_options.h"
160 #include "scoped_thread_state_change-inl.h"
161 #include "sigchain.h"
162 #include "signal_catcher.h"
163 #include "signal_set.h"
164 #include "thread.h"
165 #include "thread_list.h"
166 #include "ti/agent.h"
167 #include "trace.h"
168 #include "transaction.h"
169 #include "vdex_file.h"
170 #include "verifier/class_verifier.h"
171 #include "well_known_classes.h"
172 
173 #ifdef ART_TARGET_ANDROID
174 #include <android/set_abort_message.h>
175 #endif
176 
177 // Static asserts to check the values of generated assembly-support macros.
178 #define ASM_DEFINE(NAME, EXPR) static_assert((NAME) == (EXPR), "Unexpected value of " #NAME);
179 #include "asm_defines.def"
180 #undef ASM_DEFINE
181 
182 namespace art {
183 
184 // If a signal isn't handled properly, enable a handler that attempts to dump the Java stack.
185 static constexpr bool kEnableJavaStackTraceHandler = false;
186 // Tuned by compiling GmsCore under perf and measuring time spent in DescriptorEquals for class
187 // linking.
188 static constexpr double kLowMemoryMinLoadFactor = 0.5;
189 static constexpr double kLowMemoryMaxLoadFactor = 0.8;
190 static constexpr double kNormalMinLoadFactor = 0.4;
191 static constexpr double kNormalMaxLoadFactor = 0.7;
192 
193 // Extra added to the default heap growth multiplier. Used to adjust the GC ergonomics for the read
194 // barrier config.
195 static constexpr double kExtraDefaultHeapGrowthMultiplier = kUseReadBarrier ? 1.0 : 0.0;
196 
197 Runtime* Runtime::instance_ = nullptr;
198 
199 struct TraceConfig {
200   Trace::TraceMode trace_mode;
201   Trace::TraceOutputMode trace_output_mode;
202   std::string trace_file;
203   size_t trace_file_size;
204 };
205 
206 namespace {
207 
208 #ifdef __APPLE__
GetEnviron()209 inline char** GetEnviron() {
210   // When Google Test is built as a framework on MacOS X, the environ variable
211   // is unavailable. Apple's documentation (man environ) recommends using
212   // _NSGetEnviron() instead.
213   return *_NSGetEnviron();
214 }
215 #else
216 // Some POSIX platforms expect you to declare environ. extern "C" makes
217 // it reside in the global namespace.
218 extern "C" char** environ;
219 inline char** GetEnviron() { return environ; }
220 #endif
221 
CheckConstants()222 void CheckConstants() {
223   CHECK_EQ(mirror::Array::kFirstElementOffset, mirror::Array::FirstElementOffset());
224 }
225 
226 }  // namespace
227 
Runtime()228 Runtime::Runtime()
229     : resolution_method_(nullptr),
230       imt_conflict_method_(nullptr),
231       imt_unimplemented_method_(nullptr),
232       instruction_set_(InstructionSet::kNone),
233       compiler_callbacks_(nullptr),
234       is_zygote_(false),
235       is_primary_zygote_(false),
236       is_system_server_(false),
237       must_relocate_(false),
238       is_concurrent_gc_enabled_(true),
239       is_explicit_gc_disabled_(false),
240       image_dex2oat_enabled_(true),
241       default_stack_size_(0),
242       heap_(nullptr),
243       max_spins_before_thin_lock_inflation_(Monitor::kDefaultMaxSpinsBeforeThinLockInflation),
244       monitor_list_(nullptr),
245       monitor_pool_(nullptr),
246       thread_list_(nullptr),
247       intern_table_(nullptr),
248       class_linker_(nullptr),
249       signal_catcher_(nullptr),
250       java_vm_(nullptr),
251       thread_pool_ref_count_(0u),
252       fault_message_(nullptr),
253       threads_being_born_(0),
254       shutdown_cond_(new ConditionVariable("Runtime shutdown", *Locks::runtime_shutdown_lock_)),
255       shutting_down_(false),
256       shutting_down_started_(false),
257       started_(false),
258       finished_starting_(false),
259       vfprintf_(nullptr),
260       exit_(nullptr),
261       abort_(nullptr),
262       stats_enabled_(false),
263       is_running_on_memory_tool_(kRunningOnMemoryTool),
264       instrumentation_(),
265       main_thread_group_(nullptr),
266       system_thread_group_(nullptr),
267       system_class_loader_(nullptr),
268       dump_gc_performance_on_shutdown_(false),
269       preinitialization_transactions_(),
270       verify_(verifier::VerifyMode::kNone),
271       allow_dex_file_fallback_(true),
272       target_sdk_version_(static_cast<uint32_t>(SdkVersion::kUnset)),
273       implicit_null_checks_(false),
274       implicit_so_checks_(false),
275       implicit_suspend_checks_(false),
276       no_sig_chain_(false),
277       force_native_bridge_(false),
278       is_native_bridge_loaded_(false),
279       is_native_debuggable_(false),
280       async_exceptions_thrown_(false),
281       non_standard_exits_enabled_(false),
282       is_java_debuggable_(false),
283       zygote_max_failed_boots_(0),
284       experimental_flags_(ExperimentalFlags::kNone),
285       oat_file_manager_(nullptr),
286       is_low_memory_mode_(false),
287       safe_mode_(false),
288       hidden_api_policy_(hiddenapi::EnforcementPolicy::kDisabled),
289       core_platform_api_policy_(hiddenapi::EnforcementPolicy::kDisabled),
290       test_api_policy_(hiddenapi::EnforcementPolicy::kDisabled),
291       dedupe_hidden_api_warnings_(true),
292       hidden_api_access_event_log_rate_(0),
293       dump_native_stack_on_sig_quit_(true),
294       pruned_dalvik_cache_(false),
295       // Initially assume we perceive jank in case the process state is never updated.
296       process_state_(kProcessStateJankPerceptible),
297       zygote_no_threads_(false),
298       verifier_logging_threshold_ms_(100),
299       verifier_missing_kthrow_fatal_(false),
300       perfetto_hprof_enabled_(false) {
301   static_assert(Runtime::kCalleeSaveSize ==
302                     static_cast<uint32_t>(CalleeSaveType::kLastCalleeSaveType), "Unexpected size");
303   CheckConstants();
304 
305   std::fill(callee_save_methods_, callee_save_methods_ + arraysize(callee_save_methods_), 0u);
306   interpreter::CheckInterpreterAsmConstants();
307   callbacks_.reset(new RuntimeCallbacks());
308   for (size_t i = 0; i <= static_cast<size_t>(DeoptimizationKind::kLast); ++i) {
309     deoptimization_counts_[i] = 0u;
310   }
311 }
312 
~Runtime()313 Runtime::~Runtime() {
314   ScopedTrace trace("Runtime shutdown");
315   if (is_native_bridge_loaded_) {
316     UnloadNativeBridge();
317   }
318 
319   Thread* self = Thread::Current();
320   const bool attach_shutdown_thread = self == nullptr;
321   if (attach_shutdown_thread) {
322     // We can only create a peer if the runtime is actually started. This is only not true during
323     // some tests. If there is extreme memory pressure the allocation of the thread peer can fail.
324     // In this case we will just try again without allocating a peer so that shutdown can continue.
325     // Very few things are actually capable of distinguishing between the peer & peerless states so
326     // this should be fine.
327     bool thread_attached = AttachCurrentThread("Shutdown thread",
328                                                /* as_daemon= */ false,
329                                                GetSystemThreadGroup(),
330                                                /* create_peer= */ IsStarted());
331     if (UNLIKELY(!thread_attached)) {
332       LOG(WARNING) << "Failed to attach shutdown thread. Trying again without a peer.";
333       CHECK(AttachCurrentThread("Shutdown thread (no java peer)",
334                                 /* as_daemon= */   false,
335                                 /* thread_group=*/ nullptr,
336                                 /* create_peer= */ false));
337     }
338     self = Thread::Current();
339   } else {
340     LOG(WARNING) << "Current thread not detached in Runtime shutdown";
341   }
342 
343   if (dump_gc_performance_on_shutdown_) {
344     heap_->CalculatePreGcWeightedAllocatedBytes();
345     uint64_t process_cpu_end_time = ProcessCpuNanoTime();
346     ScopedLogSeverity sls(LogSeverity::INFO);
347     // This can't be called from the Heap destructor below because it
348     // could call RosAlloc::InspectAll() which needs the thread_list
349     // to be still alive.
350     heap_->DumpGcPerformanceInfo(LOG_STREAM(INFO));
351 
352     uint64_t process_cpu_time = process_cpu_end_time - heap_->GetProcessCpuStartTime();
353     uint64_t gc_cpu_time = heap_->GetTotalGcCpuTime();
354     float ratio = static_cast<float>(gc_cpu_time) / process_cpu_time;
355     LOG_STREAM(INFO) << "GC CPU time " << PrettyDuration(gc_cpu_time)
356         << " out of process CPU time " << PrettyDuration(process_cpu_time)
357         << " (" << ratio << ")"
358         << "\n";
359     double pre_gc_weighted_allocated_bytes =
360         heap_->GetPreGcWeightedAllocatedBytes() / process_cpu_time;
361     // Here we don't use process_cpu_time for normalization, because VM shutdown is not a real
362     // GC. Both numerator and denominator take into account until the end of the last GC,
363     // instead of the whole process life time like pre_gc_weighted_allocated_bytes.
364     double post_gc_weighted_allocated_bytes =
365         heap_->GetPostGcWeightedAllocatedBytes() /
366           (heap_->GetPostGCLastProcessCpuTime() - heap_->GetProcessCpuStartTime());
367 
368     LOG_STREAM(INFO) << "Average bytes allocated at GC start, weighted by CPU time between GCs: "
369         << static_cast<uint64_t>(pre_gc_weighted_allocated_bytes)
370         << " (" <<  PrettySize(pre_gc_weighted_allocated_bytes)  << ")";
371     LOG_STREAM(INFO) << "Average bytes allocated at GC end, weighted by CPU time between GCs: "
372         << static_cast<uint64_t>(post_gc_weighted_allocated_bytes)
373         << " (" <<  PrettySize(post_gc_weighted_allocated_bytes)  << ")"
374         << "\n";
375   }
376 
377   // Wait for the workers of thread pools to be created since there can't be any
378   // threads attaching during shutdown.
379   WaitForThreadPoolWorkersToStart();
380   if (jit_ != nullptr) {
381     jit_->WaitForWorkersToBeCreated();
382     // Stop the profile saver thread before marking the runtime as shutting down.
383     // The saver will try to dump the profiles before being sopped and that
384     // requires holding the mutator lock.
385     jit_->StopProfileSaver();
386     // Delete thread pool before the thread list since we don't want to wait forever on the
387     // JIT compiler threads. Also this should be run before marking the runtime
388     // as shutting down as some tasks may require mutator access.
389     jit_->DeleteThreadPool();
390   }
391   if (oat_file_manager_ != nullptr) {
392     oat_file_manager_->WaitForWorkersToBeCreated();
393   }
394 
395   {
396     ScopedTrace trace2("Wait for shutdown cond");
397     MutexLock mu(self, *Locks::runtime_shutdown_lock_);
398     shutting_down_started_ = true;
399     while (threads_being_born_ > 0) {
400       shutdown_cond_->Wait(self);
401     }
402     shutting_down_ = true;
403   }
404   // Shutdown and wait for the daemons.
405   CHECK(self != nullptr);
406   if (IsFinishedStarting()) {
407     ScopedTrace trace2("Waiting for Daemons");
408     self->ClearException();
409     self->GetJniEnv()->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
410                                             WellKnownClasses::java_lang_Daemons_stop);
411   }
412 
413   // Shutdown any trace running.
414   Trace::Shutdown();
415 
416   // Report death. Clients may require a working thread, still, so do it before GC completes and
417   // all non-daemon threads are done.
418   {
419     ScopedObjectAccess soa(self);
420     callbacks_->NextRuntimePhase(RuntimePhaseCallback::RuntimePhase::kDeath);
421   }
422 
423   if (attach_shutdown_thread) {
424     DetachCurrentThread();
425     self = nullptr;
426   }
427 
428   // Make sure to let the GC complete if it is running.
429   heap_->WaitForGcToComplete(gc::kGcCauseBackground, self);
430   heap_->DeleteThreadPool();
431   if (oat_file_manager_ != nullptr) {
432     oat_file_manager_->DeleteThreadPool();
433   }
434   DeleteThreadPool();
435   CHECK(thread_pool_ == nullptr);
436 
437   // Make sure our internal threads are dead before we start tearing down things they're using.
438   GetRuntimeCallbacks()->StopDebugger();
439   // Deletion ordering is tricky. Null out everything we've deleted.
440   delete signal_catcher_;
441   signal_catcher_ = nullptr;
442 
443   // Make sure all other non-daemon threads have terminated, and all daemon threads are suspended.
444   // Also wait for daemon threads to quiesce, so that in addition to being "suspended", they
445   // no longer access monitor and thread list data structures. We leak user daemon threads
446   // themselves, since we have no mechanism for shutting them down.
447   {
448     ScopedTrace trace2("Delete thread list");
449     thread_list_->ShutDown();
450   }
451 
452   // TODO Maybe do some locking.
453   for (auto& agent : agents_) {
454     agent->Unload();
455   }
456 
457   // TODO Maybe do some locking
458   for (auto& plugin : plugins_) {
459     plugin.Unload();
460   }
461 
462   // Finally delete the thread list.
463   // Thread_list_ can be accessed by "suspended" threads, e.g. in InflateThinLocked.
464   // We assume that by this point, we've waited long enough for things to quiesce.
465   delete thread_list_;
466   thread_list_ = nullptr;
467 
468   // Delete the JIT after thread list to ensure that there is no remaining threads which could be
469   // accessing the instrumentation when we delete it.
470   if (jit_ != nullptr) {
471     VLOG(jit) << "Deleting jit";
472     jit_.reset(nullptr);
473     jit_code_cache_.reset(nullptr);
474   }
475 
476   // Shutdown the fault manager if it was initialized.
477   fault_manager.Shutdown();
478 
479   ScopedTrace trace2("Delete state");
480   delete monitor_list_;
481   monitor_list_ = nullptr;
482   delete monitor_pool_;
483   monitor_pool_ = nullptr;
484   delete class_linker_;
485   class_linker_ = nullptr;
486   delete heap_;
487   heap_ = nullptr;
488   delete intern_table_;
489   intern_table_ = nullptr;
490   delete oat_file_manager_;
491   oat_file_manager_ = nullptr;
492   Thread::Shutdown();
493   QuasiAtomic::Shutdown();
494   verifier::ClassVerifier::Shutdown();
495 
496   // Destroy allocators before shutting down the MemMap because they may use it.
497   java_vm_.reset();
498   linear_alloc_.reset();
499   low_4gb_arena_pool_.reset();
500   arena_pool_.reset();
501   jit_arena_pool_.reset();
502   protected_fault_page_.Reset();
503   MemMap::Shutdown();
504 
505   // TODO: acquire a static mutex on Runtime to avoid racing.
506   CHECK(instance_ == nullptr || instance_ == this);
507   instance_ = nullptr;
508 
509   // Well-known classes must be deleted or it is impossible to successfully start another Runtime
510   // instance. We rely on a small initialization order issue in Runtime::Start() that requires
511   // elements of WellKnownClasses to be null, see b/65500943.
512   WellKnownClasses::Clear();
513 }
514 
515 struct AbortState {
Dumpart::AbortState516   void Dump(std::ostream& os) const {
517     if (gAborting > 1) {
518       os << "Runtime aborting --- recursively, so no thread-specific detail!\n";
519       DumpRecursiveAbort(os);
520       return;
521     }
522     gAborting++;
523     os << "Runtime aborting...\n";
524     if (Runtime::Current() == nullptr) {
525       os << "(Runtime does not yet exist!)\n";
526       DumpNativeStack(os, GetTid(), nullptr, "  native: ", nullptr);
527       return;
528     }
529     Thread* self = Thread::Current();
530 
531     // Dump all threads first and then the aborting thread. While this is counter the logical flow,
532     // it improves the chance of relevant data surviving in the Android logs.
533 
534     DumpAllThreads(os, self);
535 
536     if (self == nullptr) {
537       os << "(Aborting thread was not attached to runtime!)\n";
538       DumpNativeStack(os, GetTid(), nullptr, "  native: ", nullptr);
539     } else {
540       os << "Aborting thread:\n";
541       if (Locks::mutator_lock_->IsExclusiveHeld(self) || Locks::mutator_lock_->IsSharedHeld(self)) {
542         DumpThread(os, self);
543       } else {
544         if (Locks::mutator_lock_->SharedTryLock(self)) {
545           DumpThread(os, self);
546           Locks::mutator_lock_->SharedUnlock(self);
547         }
548       }
549     }
550   }
551 
552   // No thread-safety analysis as we do explicitly test for holding the mutator lock.
DumpThreadart::AbortState553   void DumpThread(std::ostream& os, Thread* self) const NO_THREAD_SAFETY_ANALYSIS {
554     DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self) || Locks::mutator_lock_->IsSharedHeld(self));
555     self->Dump(os);
556     if (self->IsExceptionPending()) {
557       mirror::Throwable* exception = self->GetException();
558       os << "Pending exception " << exception->Dump();
559     }
560   }
561 
DumpAllThreadsart::AbortState562   void DumpAllThreads(std::ostream& os, Thread* self) const {
563     Runtime* runtime = Runtime::Current();
564     if (runtime != nullptr) {
565       ThreadList* thread_list = runtime->GetThreadList();
566       if (thread_list != nullptr) {
567         // Dump requires ThreadListLock and ThreadSuspendCountLock to not be held (they will be
568         // grabbed).
569         // TODO(b/134167395): Change Dump to work with the locks held, and have a loop with timeout
570         //                    acquiring the locks.
571         bool tll_already_held = Locks::thread_list_lock_->IsExclusiveHeld(self);
572         bool tscl_already_held = Locks::thread_suspend_count_lock_->IsExclusiveHeld(self);
573         if (tll_already_held || tscl_already_held) {
574           os << "Skipping all-threads dump as locks are held:"
575              << (tll_already_held ? "" : " thread_list_lock")
576              << (tscl_already_held ? "" : " thread_suspend_count_lock")
577              << "\n";
578           return;
579         }
580         bool ml_already_exlusively_held = Locks::mutator_lock_->IsExclusiveHeld(self);
581         if (ml_already_exlusively_held) {
582           os << "Skipping all-threads dump as mutator lock is exclusively held.";
583           return;
584         }
585         bool ml_already_held = Locks::mutator_lock_->IsSharedHeld(self);
586         if (!ml_already_held) {
587           os << "Dumping all threads without mutator lock held\n";
588         }
589         os << "All threads:\n";
590         thread_list->Dump(os);
591       }
592     }
593   }
594 
595   // For recursive aborts.
DumpRecursiveAbortart::AbortState596   void DumpRecursiveAbort(std::ostream& os) const NO_THREAD_SAFETY_ANALYSIS {
597     // The only thing we'll attempt is dumping the native stack of the current thread. We will only
598     // try this if we haven't exceeded an arbitrary amount of recursions, to recover and actually
599     // die.
600     // Note: as we're using a global counter for the recursive abort detection, there is a potential
601     //       race here and it is not OK to just print when the counter is "2" (one from
602     //       Runtime::Abort(), one from previous Dump() call). Use a number that seems large enough.
603     static constexpr size_t kOnlyPrintWhenRecursionLessThan = 100u;
604     if (gAborting < kOnlyPrintWhenRecursionLessThan) {
605       gAborting++;
606       DumpNativeStack(os, GetTid());
607     }
608   }
609 };
610 
Abort(const char * msg)611 void Runtime::Abort(const char* msg) {
612   auto old_value = gAborting.fetch_add(1);  // set before taking any locks
613 
614   // Only set the first abort message.
615   if (old_value == 0) {
616 #ifdef ART_TARGET_ANDROID
617     android_set_abort_message(msg);
618 #else
619     // Set the runtime fault message in case our unexpected-signal code will run.
620     Runtime* current = Runtime::Current();
621     if (current != nullptr) {
622       current->SetFaultMessage(msg);
623     }
624 #endif
625   }
626 
627   // May be coming from an unattached thread.
628   if (Thread::Current() == nullptr) {
629     Runtime* current = Runtime::Current();
630     if (current != nullptr && current->IsStarted() && !current->IsShuttingDown(nullptr)) {
631       // We do not flag this to the unexpected-signal handler so that that may dump the stack.
632       abort();
633       UNREACHABLE();
634     }
635   }
636 
637   {
638     // Ensure that we don't have multiple threads trying to abort at once,
639     // which would result in significantly worse diagnostics.
640     ScopedThreadStateChange tsc(Thread::Current(), kNativeForAbort);
641     Locks::abort_lock_->ExclusiveLock(Thread::Current());
642   }
643 
644   // Get any pending output out of the way.
645   fflush(nullptr);
646 
647   // Many people have difficulty distinguish aborts from crashes,
648   // so be explicit.
649   // Note: use cerr on the host to print log lines immediately, so we get at least some output
650   //       in case of recursive aborts. We lose annotation with the source file and line number
651   //       here, which is a minor issue. The same is significantly more complicated on device,
652   //       which is why we ignore the issue there.
653   AbortState state;
654   if (kIsTargetBuild) {
655     LOG(FATAL_WITHOUT_ABORT) << Dumpable<AbortState>(state);
656   } else {
657     std::cerr << Dumpable<AbortState>(state);
658   }
659 
660   // Sometimes we dump long messages, and the Android abort message only retains the first line.
661   // In those cases, just log the message again, to avoid logcat limits.
662   if (msg != nullptr && strchr(msg, '\n') != nullptr) {
663     LOG(FATAL_WITHOUT_ABORT) << msg;
664   }
665 
666   FlagRuntimeAbort();
667 
668   // Call the abort hook if we have one.
669   if (Runtime::Current() != nullptr && Runtime::Current()->abort_ != nullptr) {
670     LOG(FATAL_WITHOUT_ABORT) << "Calling abort hook...";
671     Runtime::Current()->abort_();
672     // notreached
673     LOG(FATAL_WITHOUT_ABORT) << "Unexpectedly returned from abort hook!";
674   }
675 
676   abort();
677   // notreached
678 }
679 
PreZygoteFork()680 void Runtime::PreZygoteFork() {
681   if (GetJit() != nullptr) {
682     GetJit()->PreZygoteFork();
683   }
684   heap_->PreZygoteFork();
685   PreZygoteForkNativeBridge();
686 }
687 
PostZygoteFork()688 void Runtime::PostZygoteFork() {
689   if (GetJit() != nullptr) {
690     GetJit()->PostZygoteFork();
691   }
692   // Reset all stats.
693   ResetStats(0xFFFFFFFF);
694 }
695 
CallExitHook(jint status)696 void Runtime::CallExitHook(jint status) {
697   if (exit_ != nullptr) {
698     ScopedThreadStateChange tsc(Thread::Current(), kNative);
699     exit_(status);
700     LOG(WARNING) << "Exit hook returned instead of exiting!";
701   }
702 }
703 
SweepSystemWeaks(IsMarkedVisitor * visitor)704 void Runtime::SweepSystemWeaks(IsMarkedVisitor* visitor) {
705   GetInternTable()->SweepInternTableWeaks(visitor);
706   GetMonitorList()->SweepMonitorList(visitor);
707   GetJavaVM()->SweepJniWeakGlobals(visitor);
708   GetHeap()->SweepAllocationRecords(visitor);
709   if (GetJit() != nullptr) {
710     // Visit JIT literal tables. Objects in these tables are classes and strings
711     // and only classes can be affected by class unloading. The strings always
712     // stay alive as they are strongly interned.
713     // TODO: Move this closer to CleanupClassLoaders, to avoid blocking weak accesses
714     // from mutators. See b/32167580.
715     GetJit()->GetCodeCache()->SweepRootTables(visitor);
716   }
717   thread_list_->SweepInterpreterCaches(visitor);
718 
719   // All other generic system-weak holders.
720   for (gc::AbstractSystemWeakHolder* holder : system_weak_holders_) {
721     holder->Sweep(visitor);
722   }
723 }
724 
ParseOptions(const RuntimeOptions & raw_options,bool ignore_unrecognized,RuntimeArgumentMap * runtime_options)725 bool Runtime::ParseOptions(const RuntimeOptions& raw_options,
726                            bool ignore_unrecognized,
727                            RuntimeArgumentMap* runtime_options) {
728   Locks::Init();
729   InitLogging(/* argv= */ nullptr, Abort);  // Calls Locks::Init() as a side effect.
730   bool parsed = ParsedOptions::Parse(raw_options, ignore_unrecognized, runtime_options);
731   if (!parsed) {
732     LOG(ERROR) << "Failed to parse options";
733     return false;
734   }
735   return true;
736 }
737 
738 // Callback to check whether it is safe to call Abort (e.g., to use a call to
739 // LOG(FATAL)).  It is only safe to call Abort if the runtime has been created,
740 // properly initialized, and has not shut down.
IsSafeToCallAbort()741 static bool IsSafeToCallAbort() NO_THREAD_SAFETY_ANALYSIS {
742   Runtime* runtime = Runtime::Current();
743   return runtime != nullptr && runtime->IsStarted() && !runtime->IsShuttingDownLocked();
744 }
745 
Create(RuntimeArgumentMap && runtime_options)746 bool Runtime::Create(RuntimeArgumentMap&& runtime_options) {
747   // TODO: acquire a static mutex on Runtime to avoid racing.
748   if (Runtime::instance_ != nullptr) {
749     return false;
750   }
751   instance_ = new Runtime;
752   Locks::SetClientCallback(IsSafeToCallAbort);
753   if (!instance_->Init(std::move(runtime_options))) {
754     // TODO: Currently deleting the instance will abort the runtime on destruction. Now This will
755     // leak memory, instead. Fix the destructor. b/19100793.
756     // delete instance_;
757     instance_ = nullptr;
758     return false;
759   }
760   return true;
761 }
762 
Create(const RuntimeOptions & raw_options,bool ignore_unrecognized)763 bool Runtime::Create(const RuntimeOptions& raw_options, bool ignore_unrecognized) {
764   RuntimeArgumentMap runtime_options;
765   return ParseOptions(raw_options, ignore_unrecognized, &runtime_options) &&
766       Create(std::move(runtime_options));
767 }
768 
CreateSystemClassLoader(Runtime * runtime)769 static jobject CreateSystemClassLoader(Runtime* runtime) {
770   if (runtime->IsAotCompiler() && !runtime->GetCompilerCallbacks()->IsBootImage()) {
771     return nullptr;
772   }
773 
774   ScopedObjectAccess soa(Thread::Current());
775   ClassLinker* cl = Runtime::Current()->GetClassLinker();
776   auto pointer_size = cl->GetImagePointerSize();
777 
778   StackHandleScope<2> hs(soa.Self());
779   Handle<mirror::Class> class_loader_class(
780       hs.NewHandle(soa.Decode<mirror::Class>(WellKnownClasses::java_lang_ClassLoader)));
781   CHECK(cl->EnsureInitialized(soa.Self(), class_loader_class, true, true));
782 
783   ArtMethod* getSystemClassLoader = class_loader_class->FindClassMethod(
784       "getSystemClassLoader", "()Ljava/lang/ClassLoader;", pointer_size);
785   CHECK(getSystemClassLoader != nullptr);
786   CHECK(getSystemClassLoader->IsStatic());
787 
788   JValue result = InvokeWithJValues(soa,
789                                     nullptr,
790                                     getSystemClassLoader,
791                                     nullptr);
792   JNIEnv* env = soa.Self()->GetJniEnv();
793   ScopedLocalRef<jobject> system_class_loader(env, soa.AddLocalReference<jobject>(result.GetL()));
794   CHECK(system_class_loader.get() != nullptr);
795 
796   soa.Self()->SetClassLoaderOverride(system_class_loader.get());
797 
798   Handle<mirror::Class> thread_class(
799       hs.NewHandle(soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread)));
800   CHECK(cl->EnsureInitialized(soa.Self(), thread_class, true, true));
801 
802   ArtField* contextClassLoader =
803       thread_class->FindDeclaredInstanceField("contextClassLoader", "Ljava/lang/ClassLoader;");
804   CHECK(contextClassLoader != nullptr);
805 
806   // We can't run in a transaction yet.
807   contextClassLoader->SetObject<false>(
808       soa.Self()->GetPeer(),
809       soa.Decode<mirror::ClassLoader>(system_class_loader.get()).Ptr());
810 
811   return env->NewGlobalRef(system_class_loader.get());
812 }
813 
GetCompilerExecutable() const814 std::string Runtime::GetCompilerExecutable() const {
815   if (!compiler_executable_.empty()) {
816     return compiler_executable_;
817   }
818   std::string compiler_executable = GetArtBinDir() + "/dex2oat";
819   if (kIsDebugBuild) {
820     compiler_executable += 'd';
821   }
822   if (kIsTargetBuild) {
823     compiler_executable += Is64BitInstructionSet(kRuntimeISA) ? "64" : "32";
824   }
825   return compiler_executable;
826 }
827 
RunRootClinits(Thread * self)828 void Runtime::RunRootClinits(Thread* self) {
829   class_linker_->RunRootClinits(self);
830 
831   GcRoot<mirror::Throwable>* exceptions[] = {
832       &pre_allocated_OutOfMemoryError_when_throwing_exception_,
833       // &pre_allocated_OutOfMemoryError_when_throwing_oome_,             // Same class as above.
834       // &pre_allocated_OutOfMemoryError_when_handling_stack_overflow_,   // Same class as above.
835       &pre_allocated_NoClassDefFoundError_,
836   };
837   for (GcRoot<mirror::Throwable>* exception : exceptions) {
838     StackHandleScope<1> hs(self);
839     Handle<mirror::Class> klass = hs.NewHandle<mirror::Class>(exception->Read()->GetClass());
840     class_linker_->EnsureInitialized(self, klass, true, true);
841     self->AssertNoPendingException();
842   }
843 }
844 
Start()845 bool Runtime::Start() {
846   VLOG(startup) << "Runtime::Start entering";
847 
848   CHECK(!no_sig_chain_) << "A started runtime should have sig chain enabled";
849 
850   // If a debug host build, disable ptrace restriction for debugging and test timeout thread dump.
851   // Only 64-bit as prctl() may fail in 32 bit userspace on a 64-bit kernel.
852 #if defined(__linux__) && !defined(ART_TARGET_ANDROID) && defined(__x86_64__)
853   if (kIsDebugBuild) {
854     if (prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY) != 0) {
855       PLOG(WARNING) << "Failed setting PR_SET_PTRACER to PR_SET_PTRACER_ANY";
856     }
857   }
858 #endif
859 
860   // Restore main thread state to kNative as expected by native code.
861   Thread* self = Thread::Current();
862 
863   self->TransitionFromRunnableToSuspended(kNative);
864 
865   DoAndMaybeSwitchInterpreter([=](){ started_ = true; });
866 
867   if (!IsImageDex2OatEnabled() || !GetHeap()->HasBootImageSpace()) {
868     ScopedObjectAccess soa(self);
869     StackHandleScope<3> hs(soa.Self());
870 
871     ObjPtr<mirror::ObjectArray<mirror::Class>> class_roots = GetClassLinker()->GetClassRoots();
872     auto class_class(hs.NewHandle<mirror::Class>(GetClassRoot<mirror::Class>(class_roots)));
873     auto string_class(hs.NewHandle<mirror::Class>(GetClassRoot<mirror::String>(class_roots)));
874     auto field_class(hs.NewHandle<mirror::Class>(GetClassRoot<mirror::Field>(class_roots)));
875 
876     class_linker_->EnsureInitialized(soa.Self(), class_class, true, true);
877     class_linker_->EnsureInitialized(soa.Self(), string_class, true, true);
878     self->AssertNoPendingException();
879     // Field class is needed for register_java_net_InetAddress in libcore, b/28153851.
880     class_linker_->EnsureInitialized(soa.Self(), field_class, true, true);
881     self->AssertNoPendingException();
882   }
883 
884   // InitNativeMethods needs to be after started_ so that the classes
885   // it touches will have methods linked to the oat file if necessary.
886   {
887     ScopedTrace trace2("InitNativeMethods");
888     InitNativeMethods();
889   }
890 
891   // IntializeIntrinsics needs to be called after the WellKnownClasses::Init in InitNativeMethods
892   // because in checking the invocation types of intrinsic methods ArtMethod::GetInvokeType()
893   // needs the SignaturePolymorphic annotation class which is initialized in WellKnownClasses::Init.
894   InitializeIntrinsics();
895 
896   // InitializeCorePlatformApiPrivateFields() needs to be called after well known class
897   // initializtion in InitNativeMethods().
898   art::hiddenapi::InitializeCorePlatformApiPrivateFields();
899 
900   // Initialize well known thread group values that may be accessed threads while attaching.
901   InitThreadGroups(self);
902 
903   Thread::FinishStartup();
904 
905   // Create the JIT either if we have to use JIT compilation or save profiling info. This is
906   // done after FinishStartup as the JIT pool needs Java thread peers, which require the main
907   // ThreadGroup to exist.
908   //
909   // TODO(calin): We use the JIT class as a proxy for JIT compilation and for
910   // recoding profiles. Maybe we should consider changing the name to be more clear it's
911   // not only about compiling. b/28295073.
912   if (jit_options_->UseJitCompilation() || jit_options_->GetSaveProfilingInfo()) {
913     // Try to load compiler pre zygote to reduce PSS. b/27744947
914     std::string error_msg;
915     if (!jit::Jit::LoadCompilerLibrary(&error_msg)) {
916       LOG(WARNING) << "Failed to load JIT compiler with error " << error_msg;
917     }
918     CreateJitCodeCache(/*rwx_memory_allowed=*/true);
919     CreateJit();
920   }
921 
922   // Send the start phase event. We have to wait till here as this is when the main thread peer
923   // has just been generated, important root clinits have been run and JNI is completely functional.
924   {
925     ScopedObjectAccess soa(self);
926     callbacks_->NextRuntimePhase(RuntimePhaseCallback::RuntimePhase::kStart);
927   }
928 
929   system_class_loader_ = CreateSystemClassLoader(this);
930 
931   if (!is_zygote_) {
932     if (is_native_bridge_loaded_) {
933       PreInitializeNativeBridge(".");
934     }
935     NativeBridgeAction action = force_native_bridge_
936         ? NativeBridgeAction::kInitialize
937         : NativeBridgeAction::kUnload;
938     InitNonZygoteOrPostFork(self->GetJniEnv(),
939                             /* is_system_server= */ false,
940                             /* is_child_zygote= */ false,
941                             action,
942                             GetInstructionSetString(kRuntimeISA));
943   }
944 
945   StartDaemonThreads();
946 
947   // Make sure the environment is still clean (no lingering local refs from starting daemon
948   // threads).
949   {
950     ScopedObjectAccess soa(self);
951     self->GetJniEnv()->AssertLocalsEmpty();
952   }
953 
954   // Send the initialized phase event. Send it after starting the Daemon threads so that agents
955   // cannot delay the daemon threads from starting forever.
956   {
957     ScopedObjectAccess soa(self);
958     callbacks_->NextRuntimePhase(RuntimePhaseCallback::RuntimePhase::kInit);
959   }
960 
961   {
962     ScopedObjectAccess soa(self);
963     self->GetJniEnv()->AssertLocalsEmpty();
964   }
965 
966   VLOG(startup) << "Runtime::Start exiting";
967   finished_starting_ = true;
968 
969   if (trace_config_.get() != nullptr && trace_config_->trace_file != "") {
970     ScopedThreadStateChange tsc(self, kWaitingForMethodTracingStart);
971     Trace::Start(trace_config_->trace_file.c_str(),
972                  static_cast<int>(trace_config_->trace_file_size),
973                  0,
974                  trace_config_->trace_output_mode,
975                  trace_config_->trace_mode,
976                  0);
977   }
978 
979   // In case we have a profile path passed as a command line argument,
980   // register the current class path for profiling now. Note that we cannot do
981   // this before we create the JIT and having it here is the most convenient way.
982   // This is used when testing profiles with dalvikvm command as there is no
983   // framework to register the dex files for profiling.
984   if (jit_.get() != nullptr && jit_options_->GetSaveProfilingInfo() &&
985       !jit_options_->GetProfileSaverOptions().GetProfilePath().empty()) {
986     std::vector<std::string> dex_filenames;
987     Split(class_path_string_, ':', &dex_filenames);
988     RegisterAppInfo(dex_filenames, jit_options_->GetProfileSaverOptions().GetProfilePath());
989   }
990 
991   return true;
992 }
993 
EndThreadBirth()994 void Runtime::EndThreadBirth() REQUIRES(Locks::runtime_shutdown_lock_) {
995   DCHECK_GT(threads_being_born_, 0U);
996   threads_being_born_--;
997   if (shutting_down_started_ && threads_being_born_ == 0) {
998     shutdown_cond_->Broadcast(Thread::Current());
999   }
1000 }
1001 
InitNonZygoteOrPostFork(JNIEnv * env,bool is_system_server,bool is_child_zygote,NativeBridgeAction action,const char * isa,bool profile_system_server)1002 void Runtime::InitNonZygoteOrPostFork(
1003     JNIEnv* env,
1004     bool is_system_server,
1005     // This is true when we are initializing a child-zygote. It requires
1006     // native bridge initialization to be able to run guest native code in
1007     // doPreload().
1008     bool is_child_zygote,
1009     NativeBridgeAction action,
1010     const char* isa,
1011     bool profile_system_server) {
1012   if (is_native_bridge_loaded_) {
1013     switch (action) {
1014       case NativeBridgeAction::kUnload:
1015         UnloadNativeBridge();
1016         is_native_bridge_loaded_ = false;
1017         break;
1018       case NativeBridgeAction::kInitialize:
1019         InitializeNativeBridge(env, isa);
1020         break;
1021     }
1022   }
1023 
1024   if (is_child_zygote) {
1025     // If creating a child-zygote we only initialize native bridge. The rest of
1026     // runtime post-fork logic would spin up threads for Binder and JDWP.
1027     // Instead, the Java side of the child process will call a static main in a
1028     // class specified by the parent.
1029     return;
1030   }
1031 
1032   DCHECK(!IsZygote());
1033 
1034   if (is_system_server && profile_system_server) {
1035     // Set the system server package name to "android".
1036     // This is used to tell the difference between samples provided by system server
1037     // and samples generated by other apps when processing boot image profiles.
1038     SetProcessPackageName("android");
1039     jit_options_->SetWaitForJitNotificationsToSaveProfile(false);
1040     VLOG(profiler) << "Enabling system server profiles";
1041   }
1042 
1043   // Create the thread pools.
1044   heap_->CreateThreadPool();
1045   // Avoid creating the runtime thread pool for system server since it will not be used and would
1046   // waste memory.
1047   if (!is_system_server) {
1048     ScopedTrace timing("CreateThreadPool");
1049     constexpr size_t kStackSize = 64 * KB;
1050     constexpr size_t kMaxRuntimeWorkers = 4u;
1051     const size_t num_workers =
1052         std::min(static_cast<size_t>(std::thread::hardware_concurrency()), kMaxRuntimeWorkers);
1053     MutexLock mu(Thread::Current(), *Locks::runtime_thread_pool_lock_);
1054     CHECK(thread_pool_ == nullptr);
1055     thread_pool_.reset(new ThreadPool("Runtime", num_workers, /*create_peers=*/false, kStackSize));
1056     thread_pool_->StartWorkers(Thread::Current());
1057   }
1058 
1059   // Reset the gc performance data at zygote fork so that the GCs
1060   // before fork aren't attributed to an app.
1061   heap_->ResetGcPerformanceInfo();
1062 
1063   StartSignalCatcher();
1064 
1065   ScopedObjectAccess soa(Thread::Current());
1066   if (IsPerfettoHprofEnabled() &&
1067       (Dbg::IsJdwpAllowed() || IsProfileableFromShell() || IsJavaDebuggable() ||
1068        Runtime::Current()->IsSystemServer())) {
1069     std::string err;
1070     ScopedTrace tr("perfetto_hprof init.");
1071     ScopedThreadSuspension sts(Thread::Current(), ThreadState::kNative);
1072     if (!EnsurePerfettoPlugin(&err)) {
1073       LOG(WARNING) << "Failed to load perfetto_hprof: " << err;
1074     }
1075   }
1076   if (LIKELY(automatically_set_jni_ids_indirection_) && CanSetJniIdType()) {
1077     if (IsJavaDebuggable()) {
1078       SetJniIdType(JniIdType::kIndices);
1079     } else {
1080       SetJniIdType(JniIdType::kPointer);
1081     }
1082   }
1083   // Start the JDWP thread. If the command-line debugger flags specified "suspend=y",
1084   // this will pause the runtime (in the internal debugger implementation), so we probably want
1085   // this to come last.
1086   GetRuntimeCallbacks()->StartDebugger();
1087 }
1088 
StartSignalCatcher()1089 void Runtime::StartSignalCatcher() {
1090   if (!is_zygote_) {
1091     signal_catcher_ = new SignalCatcher();
1092   }
1093 }
1094 
IsShuttingDown(Thread * self)1095 bool Runtime::IsShuttingDown(Thread* self) {
1096   MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1097   return IsShuttingDownLocked();
1098 }
1099 
StartDaemonThreads()1100 void Runtime::StartDaemonThreads() {
1101   ScopedTrace trace(__FUNCTION__);
1102   VLOG(startup) << "Runtime::StartDaemonThreads entering";
1103 
1104   Thread* self = Thread::Current();
1105 
1106   // Must be in the kNative state for calling native methods.
1107   CHECK_EQ(self->GetState(), kNative);
1108 
1109   JNIEnv* env = self->GetJniEnv();
1110   env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1111                             WellKnownClasses::java_lang_Daemons_start);
1112   if (env->ExceptionCheck()) {
1113     env->ExceptionDescribe();
1114     LOG(FATAL) << "Error starting java.lang.Daemons";
1115   }
1116 
1117   VLOG(startup) << "Runtime::StartDaemonThreads exiting";
1118 }
1119 
OpenBootDexFiles(ArrayRef<const std::string> dex_filenames,ArrayRef<const std::string> dex_locations,std::vector<std::unique_ptr<const DexFile>> * dex_files)1120 static size_t OpenBootDexFiles(ArrayRef<const std::string> dex_filenames,
1121                                ArrayRef<const std::string> dex_locations,
1122                                std::vector<std::unique_ptr<const DexFile>>* dex_files) {
1123   DCHECK(dex_files != nullptr) << "OpenDexFiles: out-param is nullptr";
1124   size_t failure_count = 0;
1125   const ArtDexFileLoader dex_file_loader;
1126   for (size_t i = 0; i < dex_filenames.size(); i++) {
1127     const char* dex_filename = dex_filenames[i].c_str();
1128     const char* dex_location = dex_locations[i].c_str();
1129     static constexpr bool kVerifyChecksum = true;
1130     std::string error_msg;
1131     if (!OS::FileExists(dex_filename)) {
1132       LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
1133       continue;
1134     }
1135     bool verify = Runtime::Current()->IsVerificationEnabled();
1136     if (!dex_file_loader.Open(dex_filename,
1137                               dex_location,
1138                               verify,
1139                               kVerifyChecksum,
1140                               &error_msg,
1141                               dex_files)) {
1142       LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
1143       ++failure_count;
1144     }
1145   }
1146   return failure_count;
1147 }
1148 
SetSentinel(ObjPtr<mirror::Object> sentinel)1149 void Runtime::SetSentinel(ObjPtr<mirror::Object> sentinel) {
1150   CHECK(sentinel_.Read() == nullptr);
1151   CHECK(sentinel != nullptr);
1152   CHECK(!heap_->IsMovableObject(sentinel));
1153   sentinel_ = GcRoot<mirror::Object>(sentinel);
1154 }
1155 
GetSentinel()1156 GcRoot<mirror::Object> Runtime::GetSentinel() {
1157   return sentinel_;
1158 }
1159 
CreatePreAllocatedException(Thread * self,Runtime * runtime,GcRoot<mirror::Throwable> * exception,const char * exception_class_descriptor,const char * msg)1160 static inline void CreatePreAllocatedException(Thread* self,
1161                                                Runtime* runtime,
1162                                                GcRoot<mirror::Throwable>* exception,
1163                                                const char* exception_class_descriptor,
1164                                                const char* msg)
1165     REQUIRES_SHARED(Locks::mutator_lock_) {
1166   DCHECK_EQ(self, Thread::Current());
1167   ClassLinker* class_linker = runtime->GetClassLinker();
1168   // Allocate an object without initializing the class to allow non-trivial Throwable.<clinit>().
1169   ObjPtr<mirror::Class> klass = class_linker->FindSystemClass(self, exception_class_descriptor);
1170   CHECK(klass != nullptr);
1171   gc::AllocatorType allocator_type = runtime->GetHeap()->GetCurrentAllocator();
1172   ObjPtr<mirror::Throwable> exception_object = ObjPtr<mirror::Throwable>::DownCast(
1173       klass->Alloc(self, allocator_type));
1174   CHECK(exception_object != nullptr);
1175   *exception = GcRoot<mirror::Throwable>(exception_object);
1176   // Initialize the "detailMessage" field.
1177   ObjPtr<mirror::String> message = mirror::String::AllocFromModifiedUtf8(self, msg);
1178   CHECK(message != nullptr);
1179   ObjPtr<mirror::Class> throwable = GetClassRoot<mirror::Throwable>(class_linker);
1180   ArtField* detailMessageField =
1181       throwable->FindDeclaredInstanceField("detailMessage", "Ljava/lang/String;");
1182   CHECK(detailMessageField != nullptr);
1183   detailMessageField->SetObject</* kTransactionActive= */ false>(exception->Read(), message);
1184 }
1185 
Init(RuntimeArgumentMap && runtime_options_in)1186 bool Runtime::Init(RuntimeArgumentMap&& runtime_options_in) {
1187   // (b/30160149): protect subprocesses from modifications to LD_LIBRARY_PATH, etc.
1188   // Take a snapshot of the environment at the time the runtime was created, for use by Exec, etc.
1189   env_snapshot_.TakeSnapshot();
1190 
1191   using Opt = RuntimeArgumentMap;
1192   Opt runtime_options(std::move(runtime_options_in));
1193   ScopedTrace trace(__FUNCTION__);
1194   CHECK_EQ(sysconf(_SC_PAGE_SIZE), kPageSize);
1195 
1196   // Early override for logging output.
1197   if (runtime_options.Exists(Opt::UseStderrLogger)) {
1198     android::base::SetLogger(android::base::StderrLogger);
1199   }
1200 
1201   MemMap::Init();
1202 
1203   verifier_missing_kthrow_fatal_ = runtime_options.GetOrDefault(Opt::VerifierMissingKThrowFatal);
1204   perfetto_hprof_enabled_ = runtime_options.GetOrDefault(Opt::PerfettoHprof);
1205 
1206   // Try to reserve a dedicated fault page. This is allocated for clobbered registers and sentinels.
1207   // If we cannot reserve it, log a warning.
1208   // Note: We allocate this first to have a good chance of grabbing the page. The address (0xebad..)
1209   //       is out-of-the-way enough that it should not collide with boot image mapping.
1210   // Note: Don't request an error message. That will lead to a maps dump in the case of failure,
1211   //       leading to logspam.
1212   {
1213     constexpr uintptr_t kSentinelAddr =
1214         RoundDown(static_cast<uintptr_t>(Context::kBadGprBase), kPageSize);
1215     protected_fault_page_ = MemMap::MapAnonymous("Sentinel fault page",
1216                                                  reinterpret_cast<uint8_t*>(kSentinelAddr),
1217                                                  kPageSize,
1218                                                  PROT_NONE,
1219                                                  /*low_4gb=*/ true,
1220                                                  /*reuse=*/ false,
1221                                                  /*reservation=*/ nullptr,
1222                                                  /*error_msg=*/ nullptr);
1223     if (!protected_fault_page_.IsValid()) {
1224       LOG(WARNING) << "Could not reserve sentinel fault page";
1225     } else if (reinterpret_cast<uintptr_t>(protected_fault_page_.Begin()) != kSentinelAddr) {
1226       LOG(WARNING) << "Could not reserve sentinel fault page at the right address.";
1227       protected_fault_page_.Reset();
1228     }
1229   }
1230 
1231   VLOG(startup) << "Runtime::Init -verbose:startup enabled";
1232 
1233   QuasiAtomic::Startup();
1234 
1235   oat_file_manager_ = new OatFileManager;
1236 
1237   jni_id_manager_.reset(new jni::JniIdManager);
1238 
1239   Thread::SetSensitiveThreadHook(runtime_options.GetOrDefault(Opt::HookIsSensitiveThread));
1240   Monitor::Init(runtime_options.GetOrDefault(Opt::LockProfThreshold),
1241                 runtime_options.GetOrDefault(Opt::StackDumpLockProfThreshold));
1242 
1243   image_location_ = runtime_options.GetOrDefault(Opt::Image);
1244 
1245   SetInstructionSet(runtime_options.GetOrDefault(Opt::ImageInstructionSet));
1246   boot_class_path_ = runtime_options.ReleaseOrDefault(Opt::BootClassPath);
1247   boot_class_path_locations_ = runtime_options.ReleaseOrDefault(Opt::BootClassPathLocations);
1248   DCHECK(boot_class_path_locations_.empty() ||
1249          boot_class_path_locations_.size() == boot_class_path_.size());
1250   if (boot_class_path_.empty()) {
1251     // Try to extract the boot class path from the system boot image.
1252     if (image_location_.empty()) {
1253       LOG(ERROR) << "Empty boot class path, cannot continue without image.";
1254       return false;
1255     }
1256     std::string system_oat_filename = ImageHeader::GetOatLocationFromImageLocation(
1257         GetSystemImageFilename(image_location_.c_str(), instruction_set_));
1258     std::string system_oat_location = ImageHeader::GetOatLocationFromImageLocation(image_location_);
1259     std::string error_msg;
1260     std::unique_ptr<OatFile> oat_file(OatFile::Open(/*zip_fd=*/ -1,
1261                                                     system_oat_filename,
1262                                                     system_oat_location,
1263                                                     /*executable=*/ false,
1264                                                     /*low_4gb=*/ false,
1265                                                     &error_msg));
1266     if (oat_file == nullptr) {
1267       LOG(ERROR) << "Could not open boot oat file for extracting boot class path: " << error_msg;
1268       return false;
1269     }
1270     const OatHeader& oat_header = oat_file->GetOatHeader();
1271     const char* oat_boot_class_path = oat_header.GetStoreValueByKey(OatHeader::kBootClassPathKey);
1272     if (oat_boot_class_path != nullptr) {
1273       Split(oat_boot_class_path, ':', &boot_class_path_);
1274     }
1275     if (boot_class_path_.empty()) {
1276       LOG(ERROR) << "Boot class path missing from boot image oat file " << oat_file->GetLocation();
1277       return false;
1278     }
1279   }
1280 
1281   class_path_string_ = runtime_options.ReleaseOrDefault(Opt::ClassPath);
1282   properties_ = runtime_options.ReleaseOrDefault(Opt::PropertiesList);
1283 
1284   compiler_callbacks_ = runtime_options.GetOrDefault(Opt::CompilerCallbacksPtr);
1285   must_relocate_ = runtime_options.GetOrDefault(Opt::Relocate);
1286   is_zygote_ = runtime_options.Exists(Opt::Zygote);
1287   is_primary_zygote_ = runtime_options.Exists(Opt::PrimaryZygote);
1288   is_explicit_gc_disabled_ = runtime_options.Exists(Opt::DisableExplicitGC);
1289   image_dex2oat_enabled_ = runtime_options.GetOrDefault(Opt::ImageDex2Oat);
1290   dump_native_stack_on_sig_quit_ = runtime_options.GetOrDefault(Opt::DumpNativeStackOnSigQuit);
1291 
1292   vfprintf_ = runtime_options.GetOrDefault(Opt::HookVfprintf);
1293   exit_ = runtime_options.GetOrDefault(Opt::HookExit);
1294   abort_ = runtime_options.GetOrDefault(Opt::HookAbort);
1295 
1296   default_stack_size_ = runtime_options.GetOrDefault(Opt::StackSize);
1297 
1298   compiler_executable_ = runtime_options.ReleaseOrDefault(Opt::Compiler);
1299   compiler_options_ = runtime_options.ReleaseOrDefault(Opt::CompilerOptions);
1300   for (const std::string& option : Runtime::Current()->GetCompilerOptions()) {
1301     if (option == "--debuggable") {
1302       SetJavaDebuggable(true);
1303       break;
1304     }
1305   }
1306   image_compiler_options_ = runtime_options.ReleaseOrDefault(Opt::ImageCompilerOptions);
1307 
1308   finalizer_timeout_ms_ = runtime_options.GetOrDefault(Opt::FinalizerTimeoutMs);
1309   max_spins_before_thin_lock_inflation_ =
1310       runtime_options.GetOrDefault(Opt::MaxSpinsBeforeThinLockInflation);
1311 
1312   monitor_list_ = new MonitorList;
1313   monitor_pool_ = MonitorPool::Create();
1314   thread_list_ = new ThreadList(runtime_options.GetOrDefault(Opt::ThreadSuspendTimeout));
1315   intern_table_ = new InternTable;
1316 
1317   verify_ = runtime_options.GetOrDefault(Opt::Verify);
1318   allow_dex_file_fallback_ = !runtime_options.Exists(Opt::NoDexFileFallback);
1319 
1320   target_sdk_version_ = runtime_options.GetOrDefault(Opt::TargetSdkVersion);
1321 
1322   // Set hidden API enforcement policy. The checks are disabled by default and
1323   // we only enable them if:
1324   // (a) runtime was started with a command line flag that enables the checks, or
1325   // (b) Zygote forked a new process that is not exempt (see ZygoteHooks).
1326   hidden_api_policy_ = runtime_options.GetOrDefault(Opt::HiddenApiPolicy);
1327   DCHECK(!is_zygote_ || hidden_api_policy_ == hiddenapi::EnforcementPolicy::kDisabled);
1328 
1329   // Set core platform API enforcement policy. The checks are disabled by default and
1330   // can be enabled with a command line flag. AndroidRuntime will pass the flag if
1331   // a system property is set.
1332   core_platform_api_policy_ = runtime_options.GetOrDefault(Opt::CorePlatformApiPolicy);
1333   if (core_platform_api_policy_ != hiddenapi::EnforcementPolicy::kDisabled) {
1334     LOG(INFO) << "Core platform API reporting enabled, enforcing="
1335         << (core_platform_api_policy_ == hiddenapi::EnforcementPolicy::kEnabled ? "true" : "false");
1336   }
1337 
1338   no_sig_chain_ = runtime_options.Exists(Opt::NoSigChain);
1339   force_native_bridge_ = runtime_options.Exists(Opt::ForceNativeBridge);
1340 
1341   Split(runtime_options.GetOrDefault(Opt::CpuAbiList), ',', &cpu_abilist_);
1342 
1343   fingerprint_ = runtime_options.ReleaseOrDefault(Opt::Fingerprint);
1344 
1345   if (runtime_options.GetOrDefault(Opt::Interpret)) {
1346     GetInstrumentation()->ForceInterpretOnly();
1347   }
1348 
1349   zygote_max_failed_boots_ = runtime_options.GetOrDefault(Opt::ZygoteMaxFailedBoots);
1350   experimental_flags_ = runtime_options.GetOrDefault(Opt::Experimental);
1351   is_low_memory_mode_ = runtime_options.Exists(Opt::LowMemoryMode);
1352   madvise_random_access_ = runtime_options.GetOrDefault(Opt::MadviseRandomAccess);
1353 
1354   jni_ids_indirection_ = runtime_options.GetOrDefault(Opt::OpaqueJniIds);
1355   automatically_set_jni_ids_indirection_ =
1356       runtime_options.GetOrDefault(Opt::AutoPromoteOpaqueJniIds);
1357 
1358   plugins_ = runtime_options.ReleaseOrDefault(Opt::Plugins);
1359   agent_specs_ = runtime_options.ReleaseOrDefault(Opt::AgentPath);
1360   // TODO Add back in -agentlib
1361   // for (auto lib : runtime_options.ReleaseOrDefault(Opt::AgentLib)) {
1362   //   agents_.push_back(lib);
1363   // }
1364 
1365   float foreground_heap_growth_multiplier;
1366   if (is_low_memory_mode_ && !runtime_options.Exists(Opt::ForegroundHeapGrowthMultiplier)) {
1367     // If low memory mode, use 1.0 as the multiplier by default.
1368     foreground_heap_growth_multiplier = 1.0f;
1369   } else {
1370     foreground_heap_growth_multiplier =
1371         runtime_options.GetOrDefault(Opt::ForegroundHeapGrowthMultiplier) +
1372             kExtraDefaultHeapGrowthMultiplier;
1373   }
1374   XGcOption xgc_option = runtime_options.GetOrDefault(Opt::GcOption);
1375 
1376   // Generational CC collection is currently only compatible with Baker read barriers.
1377   bool use_generational_cc = kUseBakerReadBarrier && xgc_option.generational_cc;
1378 
1379   image_space_loading_order_ = runtime_options.GetOrDefault(Opt::ImageSpaceLoadingOrder);
1380 
1381   heap_ = new gc::Heap(runtime_options.GetOrDefault(Opt::MemoryInitialSize),
1382                        runtime_options.GetOrDefault(Opt::HeapGrowthLimit),
1383                        runtime_options.GetOrDefault(Opt::HeapMinFree),
1384                        runtime_options.GetOrDefault(Opt::HeapMaxFree),
1385                        runtime_options.GetOrDefault(Opt::HeapTargetUtilization),
1386                        foreground_heap_growth_multiplier,
1387                        runtime_options.GetOrDefault(Opt::StopForNativeAllocs),
1388                        runtime_options.GetOrDefault(Opt::MemoryMaximumSize),
1389                        runtime_options.GetOrDefault(Opt::NonMovingSpaceCapacity),
1390                        GetBootClassPath(),
1391                        GetBootClassPathLocations(),
1392                        image_location_,
1393                        instruction_set_,
1394                        // Override the collector type to CC if the read barrier config.
1395                        kUseReadBarrier ? gc::kCollectorTypeCC : xgc_option.collector_type_,
1396                        kUseReadBarrier ? BackgroundGcOption(gc::kCollectorTypeCCBackground)
1397                                        : runtime_options.GetOrDefault(Opt::BackgroundGc),
1398                        runtime_options.GetOrDefault(Opt::LargeObjectSpace),
1399                        runtime_options.GetOrDefault(Opt::LargeObjectThreshold),
1400                        runtime_options.GetOrDefault(Opt::ParallelGCThreads),
1401                        runtime_options.GetOrDefault(Opt::ConcGCThreads),
1402                        runtime_options.Exists(Opt::LowMemoryMode),
1403                        runtime_options.GetOrDefault(Opt::LongPauseLogThreshold),
1404                        runtime_options.GetOrDefault(Opt::LongGCLogThreshold),
1405                        runtime_options.Exists(Opt::IgnoreMaxFootprint),
1406                        runtime_options.GetOrDefault(Opt::UseTLAB),
1407                        xgc_option.verify_pre_gc_heap_,
1408                        xgc_option.verify_pre_sweeping_heap_,
1409                        xgc_option.verify_post_gc_heap_,
1410                        xgc_option.verify_pre_gc_rosalloc_,
1411                        xgc_option.verify_pre_sweeping_rosalloc_,
1412                        xgc_option.verify_post_gc_rosalloc_,
1413                        xgc_option.gcstress_,
1414                        xgc_option.measure_,
1415                        runtime_options.GetOrDefault(Opt::EnableHSpaceCompactForOOM),
1416                        use_generational_cc,
1417                        runtime_options.GetOrDefault(Opt::HSpaceCompactForOOMMinIntervalsMs),
1418                        runtime_options.Exists(Opt::DumpRegionInfoBeforeGC),
1419                        runtime_options.Exists(Opt::DumpRegionInfoAfterGC),
1420                        image_space_loading_order_);
1421 
1422   if (!heap_->HasBootImageSpace() && !allow_dex_file_fallback_) {
1423     LOG(ERROR) << "Dex file fallback disabled, cannot continue without image.";
1424     return false;
1425   }
1426 
1427   dump_gc_performance_on_shutdown_ = runtime_options.Exists(Opt::DumpGCPerformanceOnShutdown);
1428 
1429   jdwp_options_ = runtime_options.GetOrDefault(Opt::JdwpOptions);
1430   jdwp_provider_ = CanonicalizeJdwpProvider(runtime_options.GetOrDefault(Opt::JdwpProvider),
1431                                             IsJavaDebuggable());
1432   switch (jdwp_provider_) {
1433     case JdwpProvider::kNone: {
1434       VLOG(jdwp) << "Disabling all JDWP support.";
1435       if (!jdwp_options_.empty()) {
1436         bool has_transport = jdwp_options_.find("transport") != std::string::npos;
1437         std::string adb_connection_args =
1438             std::string("  -XjdwpProvider:adbconnection -XjdwpOptions:") + jdwp_options_;
1439         LOG(WARNING) << "Jdwp options given when jdwp is disabled! You probably want to enable "
1440                      << "jdwp with one of:" << std::endl
1441                      << "  -Xplugin:libopenjdkjvmti" << (kIsDebugBuild ? "d" : "") << ".so "
1442                      << "-agentpath:libjdwp.so=" << jdwp_options_ << std::endl
1443                      << (has_transport ? "" : adb_connection_args);
1444       }
1445       break;
1446     }
1447     case JdwpProvider::kAdbConnection: {
1448       constexpr const char* plugin_name = kIsDebugBuild ? "libadbconnectiond.so"
1449                                                         : "libadbconnection.so";
1450       plugins_.push_back(Plugin::Create(plugin_name));
1451       break;
1452     }
1453     case JdwpProvider::kUnset: {
1454       LOG(FATAL) << "Illegal jdwp provider " << jdwp_provider_ << " was not filtered out!";
1455     }
1456   }
1457   callbacks_->AddThreadLifecycleCallback(Dbg::GetThreadLifecycleCallback());
1458 
1459   jit_options_.reset(jit::JitOptions::CreateFromRuntimeArguments(runtime_options));
1460   if (IsAotCompiler()) {
1461     // If we are already the compiler at this point, we must be dex2oat. Don't create the jit in
1462     // this case.
1463     // If runtime_options doesn't have UseJIT set to true then CreateFromRuntimeArguments returns
1464     // null and we don't create the jit.
1465     jit_options_->SetUseJitCompilation(false);
1466     jit_options_->SetSaveProfilingInfo(false);
1467   }
1468 
1469   // Use MemMap arena pool for jit, malloc otherwise. Malloc arenas are faster to allocate but
1470   // can't be trimmed as easily.
1471   const bool use_malloc = IsAotCompiler();
1472   if (use_malloc) {
1473     arena_pool_.reset(new MallocArenaPool());
1474     jit_arena_pool_.reset(new MallocArenaPool());
1475   } else {
1476     arena_pool_.reset(new MemMapArenaPool(/* low_4gb= */ false));
1477     jit_arena_pool_.reset(new MemMapArenaPool(/* low_4gb= */ false, "CompilerMetadata"));
1478   }
1479 
1480   if (IsAotCompiler() && Is64BitInstructionSet(kRuntimeISA)) {
1481     // 4gb, no malloc. Explanation in header.
1482     low_4gb_arena_pool_.reset(new MemMapArenaPool(/* low_4gb= */ true));
1483   }
1484   linear_alloc_.reset(CreateLinearAlloc());
1485 
1486   BlockSignals();
1487   InitPlatformSignalHandlers();
1488 
1489   // Change the implicit checks flags based on runtime architecture.
1490   switch (kRuntimeISA) {
1491     case InstructionSet::kArm:
1492     case InstructionSet::kThumb2:
1493     case InstructionSet::kX86:
1494     case InstructionSet::kArm64:
1495     case InstructionSet::kX86_64:
1496       implicit_null_checks_ = true;
1497       // Historical note: Installing stack protection was not playing well with Valgrind.
1498       implicit_so_checks_ = true;
1499       break;
1500     default:
1501       // Keep the defaults.
1502       break;
1503   }
1504 
1505   if (!no_sig_chain_) {
1506     // Dex2Oat's Runtime does not need the signal chain or the fault handler.
1507     if (implicit_null_checks_ || implicit_so_checks_ || implicit_suspend_checks_) {
1508       fault_manager.Init();
1509 
1510       // These need to be in a specific order.  The null point check handler must be
1511       // after the suspend check and stack overflow check handlers.
1512       //
1513       // Note: the instances attach themselves to the fault manager and are handled by it. The
1514       //       manager will delete the instance on Shutdown().
1515       if (implicit_suspend_checks_) {
1516         new SuspensionHandler(&fault_manager);
1517       }
1518 
1519       if (implicit_so_checks_) {
1520         new StackOverflowHandler(&fault_manager);
1521       }
1522 
1523       if (implicit_null_checks_) {
1524         new NullPointerHandler(&fault_manager);
1525       }
1526 
1527       if (kEnableJavaStackTraceHandler) {
1528         new JavaStackTraceHandler(&fault_manager);
1529       }
1530     }
1531   }
1532 
1533   verifier_logging_threshold_ms_ = runtime_options.GetOrDefault(Opt::VerifierLoggingThreshold);
1534 
1535   std::string error_msg;
1536   java_vm_ = JavaVMExt::Create(this, runtime_options, &error_msg);
1537   if (java_vm_.get() == nullptr) {
1538     LOG(ERROR) << "Could not initialize JavaVMExt: " << error_msg;
1539     return false;
1540   }
1541 
1542   // Add the JniEnv handler.
1543   // TODO Refactor this stuff.
1544   java_vm_->AddEnvironmentHook(JNIEnvExt::GetEnvHandler);
1545 
1546   Thread::Startup();
1547 
1548   // ClassLinker needs an attached thread, but we can't fully attach a thread without creating
1549   // objects. We can't supply a thread group yet; it will be fixed later. Since we are the main
1550   // thread, we do not get a java peer.
1551   Thread* self = Thread::Attach("main", false, nullptr, false);
1552   CHECK_EQ(self->GetThreadId(), ThreadList::kMainThreadId);
1553   CHECK(self != nullptr);
1554 
1555   self->SetIsRuntimeThread(IsAotCompiler());
1556 
1557   // Set us to runnable so tools using a runtime can allocate and GC by default
1558   self->TransitionFromSuspendedToRunnable();
1559 
1560   // Now we're attached, we can take the heap locks and validate the heap.
1561   GetHeap()->EnableObjectValidation();
1562 
1563   CHECK_GE(GetHeap()->GetContinuousSpaces().size(), 1U);
1564 
1565   if (UNLIKELY(IsAotCompiler())) {
1566     class_linker_ = new AotClassLinker(intern_table_);
1567   } else {
1568     class_linker_ = new ClassLinker(
1569         intern_table_,
1570         runtime_options.GetOrDefault(Opt::FastClassNotFoundException));
1571   }
1572   if (GetHeap()->HasBootImageSpace()) {
1573     bool result = class_linker_->InitFromBootImage(&error_msg);
1574     if (!result) {
1575       LOG(ERROR) << "Could not initialize from image: " << error_msg;
1576       return false;
1577     }
1578     if (kIsDebugBuild) {
1579       for (auto image_space : GetHeap()->GetBootImageSpaces()) {
1580         image_space->VerifyImageAllocations();
1581       }
1582     }
1583     {
1584       ScopedTrace trace2("AddImageStringsToTable");
1585       for (gc::space::ImageSpace* image_space : heap_->GetBootImageSpaces()) {
1586         GetInternTable()->AddImageStringsToTable(image_space, VoidFunctor());
1587       }
1588     }
1589     if (heap_->GetBootImageSpaces().size() != GetBootClassPath().size()) {
1590       // The boot image did not contain all boot class path components. Load the rest.
1591       DCHECK_LT(heap_->GetBootImageSpaces().size(), GetBootClassPath().size());
1592       size_t start = heap_->GetBootImageSpaces().size();
1593       DCHECK_LT(start, GetBootClassPath().size());
1594       std::vector<std::unique_ptr<const DexFile>> extra_boot_class_path;
1595       if (runtime_options.Exists(Opt::BootClassPathDexList)) {
1596         extra_boot_class_path.swap(*runtime_options.GetOrDefault(Opt::BootClassPathDexList));
1597       } else {
1598         OpenBootDexFiles(ArrayRef<const std::string>(GetBootClassPath()).SubArray(start),
1599                          ArrayRef<const std::string>(GetBootClassPathLocations()).SubArray(start),
1600                          &extra_boot_class_path);
1601       }
1602       class_linker_->AddExtraBootDexFiles(self, std::move(extra_boot_class_path));
1603     }
1604     if (IsJavaDebuggable() || jit_options_->GetProfileSaverOptions().GetProfileBootClassPath()) {
1605       // Deoptimize the boot image if debuggable  as the code may have been compiled non-debuggable.
1606       // Also deoptimize if we are profiling the boot class path.
1607       ScopedThreadSuspension sts(self, ThreadState::kNative);
1608       ScopedSuspendAll ssa(__FUNCTION__);
1609       DeoptimizeBootImage();
1610     }
1611   } else {
1612     std::vector<std::unique_ptr<const DexFile>> boot_class_path;
1613     if (runtime_options.Exists(Opt::BootClassPathDexList)) {
1614       boot_class_path.swap(*runtime_options.GetOrDefault(Opt::BootClassPathDexList));
1615     } else {
1616       OpenBootDexFiles(ArrayRef<const std::string>(GetBootClassPath()),
1617                        ArrayRef<const std::string>(GetBootClassPathLocations()),
1618                        &boot_class_path);
1619     }
1620     if (!class_linker_->InitWithoutImage(std::move(boot_class_path), &error_msg)) {
1621       LOG(ERROR) << "Could not initialize without image: " << error_msg;
1622       return false;
1623     }
1624 
1625     // TODO: Should we move the following to InitWithoutImage?
1626     SetInstructionSet(instruction_set_);
1627     for (uint32_t i = 0; i < kCalleeSaveSize; i++) {
1628       CalleeSaveType type = CalleeSaveType(i);
1629       if (!HasCalleeSaveMethod(type)) {
1630         SetCalleeSaveMethod(CreateCalleeSaveMethod(), type);
1631       }
1632     }
1633   }
1634 
1635   CHECK(class_linker_ != nullptr);
1636 
1637   verifier::ClassVerifier::Init(class_linker_);
1638 
1639   if (runtime_options.Exists(Opt::MethodTrace)) {
1640     trace_config_.reset(new TraceConfig());
1641     trace_config_->trace_file = runtime_options.ReleaseOrDefault(Opt::MethodTraceFile);
1642     trace_config_->trace_file_size = runtime_options.ReleaseOrDefault(Opt::MethodTraceFileSize);
1643     trace_config_->trace_mode = Trace::TraceMode::kMethodTracing;
1644     trace_config_->trace_output_mode = runtime_options.Exists(Opt::MethodTraceStreaming) ?
1645         Trace::TraceOutputMode::kStreaming :
1646         Trace::TraceOutputMode::kFile;
1647   }
1648 
1649   // TODO: move this to just be an Trace::Start argument
1650   Trace::SetDefaultClockSource(runtime_options.GetOrDefault(Opt::ProfileClock));
1651 
1652   if (GetHeap()->HasBootImageSpace()) {
1653     const ImageHeader& image_header = GetHeap()->GetBootImageSpaces()[0]->GetImageHeader();
1654     ObjPtr<mirror::ObjectArray<mirror::Object>> boot_image_live_objects =
1655         ObjPtr<mirror::ObjectArray<mirror::Object>>::DownCast(
1656             image_header.GetImageRoot(ImageHeader::kBootImageLiveObjects));
1657     pre_allocated_OutOfMemoryError_when_throwing_exception_ = GcRoot<mirror::Throwable>(
1658         boot_image_live_objects->Get(ImageHeader::kOomeWhenThrowingException)->AsThrowable());
1659     DCHECK(pre_allocated_OutOfMemoryError_when_throwing_exception_.Read()->GetClass()
1660                ->DescriptorEquals("Ljava/lang/OutOfMemoryError;"));
1661     pre_allocated_OutOfMemoryError_when_throwing_oome_ = GcRoot<mirror::Throwable>(
1662         boot_image_live_objects->Get(ImageHeader::kOomeWhenThrowingOome)->AsThrowable());
1663     DCHECK(pre_allocated_OutOfMemoryError_when_throwing_oome_.Read()->GetClass()
1664                ->DescriptorEquals("Ljava/lang/OutOfMemoryError;"));
1665     pre_allocated_OutOfMemoryError_when_handling_stack_overflow_ = GcRoot<mirror::Throwable>(
1666         boot_image_live_objects->Get(ImageHeader::kOomeWhenHandlingStackOverflow)->AsThrowable());
1667     DCHECK(pre_allocated_OutOfMemoryError_when_handling_stack_overflow_.Read()->GetClass()
1668                ->DescriptorEquals("Ljava/lang/OutOfMemoryError;"));
1669     pre_allocated_NoClassDefFoundError_ = GcRoot<mirror::Throwable>(
1670         boot_image_live_objects->Get(ImageHeader::kNoClassDefFoundError)->AsThrowable());
1671     DCHECK(pre_allocated_NoClassDefFoundError_.Read()->GetClass()
1672                ->DescriptorEquals("Ljava/lang/NoClassDefFoundError;"));
1673   } else {
1674     // Pre-allocate an OutOfMemoryError for the case when we fail to
1675     // allocate the exception to be thrown.
1676     CreatePreAllocatedException(self,
1677                                 this,
1678                                 &pre_allocated_OutOfMemoryError_when_throwing_exception_,
1679                                 "Ljava/lang/OutOfMemoryError;",
1680                                 "OutOfMemoryError thrown while trying to throw an exception; "
1681                                     "no stack trace available");
1682     // Pre-allocate an OutOfMemoryError for the double-OOME case.
1683     CreatePreAllocatedException(self,
1684                                 this,
1685                                 &pre_allocated_OutOfMemoryError_when_throwing_oome_,
1686                                 "Ljava/lang/OutOfMemoryError;",
1687                                 "OutOfMemoryError thrown while trying to throw OutOfMemoryError; "
1688                                     "no stack trace available");
1689     // Pre-allocate an OutOfMemoryError for the case when we fail to
1690     // allocate while handling a stack overflow.
1691     CreatePreAllocatedException(self,
1692                                 this,
1693                                 &pre_allocated_OutOfMemoryError_when_handling_stack_overflow_,
1694                                 "Ljava/lang/OutOfMemoryError;",
1695                                 "OutOfMemoryError thrown while trying to handle a stack overflow; "
1696                                     "no stack trace available");
1697 
1698     // Pre-allocate a NoClassDefFoundError for the common case of failing to find a system class
1699     // ahead of checking the application's class loader.
1700     CreatePreAllocatedException(self,
1701                                 this,
1702                                 &pre_allocated_NoClassDefFoundError_,
1703                                 "Ljava/lang/NoClassDefFoundError;",
1704                                 "Class not found using the boot class loader; "
1705                                     "no stack trace available");
1706   }
1707 
1708   // Class-roots are setup, we can now finish initializing the JniIdManager.
1709   GetJniIdManager()->Init(self);
1710 
1711   // Runtime initialization is largely done now.
1712   // We load plugins first since that can modify the runtime state slightly.
1713   // Load all plugins
1714   {
1715     // The init method of plugins expect the state of the thread to be non runnable.
1716     ScopedThreadSuspension sts(self, ThreadState::kNative);
1717     for (auto& plugin : plugins_) {
1718       std::string err;
1719       if (!plugin.Load(&err)) {
1720         LOG(FATAL) << plugin << " failed to load: " << err;
1721       }
1722     }
1723   }
1724 
1725   // Look for a native bridge.
1726   //
1727   // The intended flow here is, in the case of a running system:
1728   //
1729   // Runtime::Init() (zygote):
1730   //   LoadNativeBridge -> dlopen from cmd line parameter.
1731   //  |
1732   //  V
1733   // Runtime::Start() (zygote):
1734   //   No-op wrt native bridge.
1735   //  |
1736   //  | start app
1737   //  V
1738   // DidForkFromZygote(action)
1739   //   action = kUnload -> dlclose native bridge.
1740   //   action = kInitialize -> initialize library
1741   //
1742   //
1743   // The intended flow here is, in the case of a simple dalvikvm call:
1744   //
1745   // Runtime::Init():
1746   //   LoadNativeBridge -> dlopen from cmd line parameter.
1747   //  |
1748   //  V
1749   // Runtime::Start():
1750   //   DidForkFromZygote(kInitialize) -> try to initialize any native bridge given.
1751   //   No-op wrt native bridge.
1752   {
1753     std::string native_bridge_file_name = runtime_options.ReleaseOrDefault(Opt::NativeBridge);
1754     is_native_bridge_loaded_ = LoadNativeBridge(native_bridge_file_name);
1755   }
1756 
1757   // Startup agents
1758   // TODO Maybe we should start a new thread to run these on. Investigate RI behavior more.
1759   for (auto& agent_spec : agent_specs_) {
1760     // TODO Check err
1761     int res = 0;
1762     std::string err = "";
1763     ti::LoadError error;
1764     std::unique_ptr<ti::Agent> agent = agent_spec.Load(&res, &error, &err);
1765 
1766     if (agent != nullptr) {
1767       agents_.push_back(std::move(agent));
1768       continue;
1769     }
1770 
1771     switch (error) {
1772       case ti::LoadError::kInitializationError:
1773         LOG(FATAL) << "Unable to initialize agent!";
1774         UNREACHABLE();
1775 
1776       case ti::LoadError::kLoadingError:
1777         LOG(ERROR) << "Unable to load an agent: " << err;
1778         continue;
1779 
1780       case ti::LoadError::kNoError:
1781         break;
1782     }
1783     LOG(FATAL) << "Unreachable";
1784     UNREACHABLE();
1785   }
1786   {
1787     ScopedObjectAccess soa(self);
1788     callbacks_->NextRuntimePhase(RuntimePhaseCallback::RuntimePhase::kInitialAgents);
1789   }
1790 
1791   if (IsZygote() && IsPerfettoHprofEnabled()) {
1792     constexpr const char* plugin_name = kIsDebugBuild ?
1793     "libperfetto_hprofd.so" : "libperfetto_hprof.so";
1794     // Load eagerly in Zygote to improve app startup times. This will make
1795     // subsequent dlopens for the library no-ops.
1796     dlopen(plugin_name, RTLD_NOW | RTLD_LOCAL);
1797   }
1798 
1799   VLOG(startup) << "Runtime::Init exiting";
1800 
1801   // Set OnlyUseSystemOatFiles only after boot classpath has been set up.
1802   if (runtime_options.Exists(Opt::OnlyUseSystemOatFiles)) {
1803     oat_file_manager_->SetOnlyUseSystemOatFiles();
1804   }
1805 
1806   return true;
1807 }
1808 
EnsurePluginLoaded(const char * plugin_name,std::string * error_msg)1809 bool Runtime::EnsurePluginLoaded(const char* plugin_name, std::string* error_msg) {
1810   // Is the plugin already loaded?
1811   for (const Plugin& p : plugins_) {
1812     if (p.GetLibrary() == plugin_name) {
1813       return true;
1814     }
1815   }
1816   Plugin new_plugin = Plugin::Create(plugin_name);
1817 
1818   if (!new_plugin.Load(error_msg)) {
1819     return false;
1820   }
1821   plugins_.push_back(std::move(new_plugin));
1822   return true;
1823 }
1824 
EnsurePerfettoPlugin(std::string * error_msg)1825 bool Runtime::EnsurePerfettoPlugin(std::string* error_msg) {
1826   constexpr const char* plugin_name = kIsDebugBuild ?
1827     "libperfetto_hprofd.so" : "libperfetto_hprof.so";
1828   return EnsurePluginLoaded(plugin_name, error_msg);
1829 }
1830 
EnsureJvmtiPlugin(Runtime * runtime,std::string * error_msg)1831 static bool EnsureJvmtiPlugin(Runtime* runtime,
1832                               std::string* error_msg) {
1833   // TODO Rename Dbg::IsJdwpAllowed is IsDebuggingAllowed.
1834   DCHECK(Dbg::IsJdwpAllowed() || !runtime->IsJavaDebuggable())
1835       << "Being debuggable requires that jdwp (i.e. debugging) is allowed.";
1836   // Is the process debuggable? Otherwise, do not attempt to load the plugin unless we are
1837   // specifically allowed.
1838   if (!Dbg::IsJdwpAllowed()) {
1839     *error_msg = "Process is not allowed to load openjdkjvmti plugin. Process must be debuggable";
1840     return false;
1841   }
1842 
1843   constexpr const char* plugin_name = kIsDebugBuild ? "libopenjdkjvmtid.so" : "libopenjdkjvmti.so";
1844   return runtime->EnsurePluginLoaded(plugin_name, error_msg);
1845 }
1846 
1847 // Attach a new agent and add it to the list of runtime agents
1848 //
1849 // TODO: once we decide on the threading model for agents,
1850 //   revisit this and make sure we're doing this on the right thread
1851 //   (and we synchronize access to any shared data structures like "agents_")
1852 //
AttachAgent(JNIEnv * env,const std::string & agent_arg,jobject class_loader)1853 void Runtime::AttachAgent(JNIEnv* env, const std::string& agent_arg, jobject class_loader) {
1854   std::string error_msg;
1855   if (!EnsureJvmtiPlugin(this, &error_msg)) {
1856     LOG(WARNING) << "Could not load plugin: " << error_msg;
1857     ScopedObjectAccess soa(Thread::Current());
1858     ThrowIOException("%s", error_msg.c_str());
1859     return;
1860   }
1861 
1862   ti::AgentSpec agent_spec(agent_arg);
1863 
1864   int res = 0;
1865   ti::LoadError error;
1866   std::unique_ptr<ti::Agent> agent = agent_spec.Attach(env, class_loader, &res, &error, &error_msg);
1867 
1868   if (agent != nullptr) {
1869     agents_.push_back(std::move(agent));
1870   } else {
1871     LOG(WARNING) << "Agent attach failed (result=" << error << ") : " << error_msg;
1872     ScopedObjectAccess soa(Thread::Current());
1873     ThrowIOException("%s", error_msg.c_str());
1874   }
1875 }
1876 
InitNativeMethods()1877 void Runtime::InitNativeMethods() {
1878   VLOG(startup) << "Runtime::InitNativeMethods entering";
1879   Thread* self = Thread::Current();
1880   JNIEnv* env = self->GetJniEnv();
1881 
1882   // Must be in the kNative state for calling native methods (JNI_OnLoad code).
1883   CHECK_EQ(self->GetState(), kNative);
1884 
1885   // Set up the native methods provided by the runtime itself.
1886   RegisterRuntimeNativeMethods(env);
1887 
1888   // Initialize classes used in JNI. The initialization requires runtime native
1889   // methods to be loaded first.
1890   WellKnownClasses::Init(env);
1891 
1892   // Then set up libjavacore / libopenjdk / libicu_jni ,which are just
1893   // a regular JNI libraries with a regular JNI_OnLoad. Most JNI libraries can
1894   // just use System.loadLibrary, but libcore can't because it's the library
1895   // that implements System.loadLibrary!
1896 
1897   // libicu_jni has to be initialized before libopenjdk{d} due to runtime dependency from
1898   // libopenjdk{d} to Icu4cMetadata native methods in libicu_jni. See http://b/143888405
1899   {
1900     std::string error_msg;
1901     if (!java_vm_->LoadNativeLibrary(
1902           env, "libicu_jni.so", nullptr, WellKnownClasses::java_lang_Object, &error_msg)) {
1903       LOG(FATAL) << "LoadNativeLibrary failed for \"libicu_jni.so\": " << error_msg;
1904     }
1905   }
1906   {
1907     std::string error_msg;
1908     if (!java_vm_->LoadNativeLibrary(
1909           env, "libjavacore.so", nullptr, WellKnownClasses::java_lang_Object, &error_msg)) {
1910       LOG(FATAL) << "LoadNativeLibrary failed for \"libjavacore.so\": " << error_msg;
1911     }
1912   }
1913   {
1914     constexpr const char* kOpenJdkLibrary = kIsDebugBuild
1915                                                 ? "libopenjdkd.so"
1916                                                 : "libopenjdk.so";
1917     std::string error_msg;
1918     if (!java_vm_->LoadNativeLibrary(
1919           env, kOpenJdkLibrary, nullptr, WellKnownClasses::java_lang_Object, &error_msg)) {
1920       LOG(FATAL) << "LoadNativeLibrary failed for \"" << kOpenJdkLibrary << "\": " << error_msg;
1921     }
1922   }
1923 
1924   // Initialize well known classes that may invoke runtime native methods.
1925   WellKnownClasses::LateInit(env);
1926 
1927   VLOG(startup) << "Runtime::InitNativeMethods exiting";
1928 }
1929 
ReclaimArenaPoolMemory()1930 void Runtime::ReclaimArenaPoolMemory() {
1931   arena_pool_->LockReclaimMemory();
1932 }
1933 
InitThreadGroups(Thread * self)1934 void Runtime::InitThreadGroups(Thread* self) {
1935   JNIEnvExt* env = self->GetJniEnv();
1936   ScopedJniEnvLocalRefState env_state(env);
1937   main_thread_group_ =
1938       env->NewGlobalRef(env->GetStaticObjectField(
1939           WellKnownClasses::java_lang_ThreadGroup,
1940           WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup));
1941   CHECK(main_thread_group_ != nullptr || IsAotCompiler());
1942   system_thread_group_ =
1943       env->NewGlobalRef(env->GetStaticObjectField(
1944           WellKnownClasses::java_lang_ThreadGroup,
1945           WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup));
1946   CHECK(system_thread_group_ != nullptr || IsAotCompiler());
1947 }
1948 
GetMainThreadGroup() const1949 jobject Runtime::GetMainThreadGroup() const {
1950   CHECK(main_thread_group_ != nullptr || IsAotCompiler());
1951   return main_thread_group_;
1952 }
1953 
GetSystemThreadGroup() const1954 jobject Runtime::GetSystemThreadGroup() const {
1955   CHECK(system_thread_group_ != nullptr || IsAotCompiler());
1956   return system_thread_group_;
1957 }
1958 
GetSystemClassLoader() const1959 jobject Runtime::GetSystemClassLoader() const {
1960   CHECK(system_class_loader_ != nullptr || IsAotCompiler());
1961   return system_class_loader_;
1962 }
1963 
RegisterRuntimeNativeMethods(JNIEnv * env)1964 void Runtime::RegisterRuntimeNativeMethods(JNIEnv* env) {
1965   register_dalvik_system_DexFile(env);
1966   register_dalvik_system_BaseDexClassLoader(env);
1967   register_dalvik_system_VMDebug(env);
1968   register_dalvik_system_VMRuntime(env);
1969   register_dalvik_system_VMStack(env);
1970   register_dalvik_system_ZygoteHooks(env);
1971   register_java_lang_Class(env);
1972   register_java_lang_Object(env);
1973   register_java_lang_invoke_MethodHandleImpl(env);
1974   register_java_lang_ref_FinalizerReference(env);
1975   register_java_lang_reflect_Array(env);
1976   register_java_lang_reflect_Constructor(env);
1977   register_java_lang_reflect_Executable(env);
1978   register_java_lang_reflect_Field(env);
1979   register_java_lang_reflect_Method(env);
1980   register_java_lang_reflect_Parameter(env);
1981   register_java_lang_reflect_Proxy(env);
1982   register_java_lang_ref_Reference(env);
1983   register_java_lang_String(env);
1984   register_java_lang_StringFactory(env);
1985   register_java_lang_System(env);
1986   register_java_lang_Thread(env);
1987   register_java_lang_Throwable(env);
1988   register_java_lang_VMClassLoader(env);
1989   register_java_util_concurrent_atomic_AtomicLong(env);
1990   register_libcore_util_CharsetUtils(env);
1991   register_org_apache_harmony_dalvik_ddmc_DdmServer(env);
1992   register_org_apache_harmony_dalvik_ddmc_DdmVmInternal(env);
1993   register_sun_misc_Unsafe(env);
1994 }
1995 
operator <<(std::ostream & os,const DeoptimizationKind & kind)1996 std::ostream& operator<<(std::ostream& os, const DeoptimizationKind& kind) {
1997   os << GetDeoptimizationKindName(kind);
1998   return os;
1999 }
2000 
DumpDeoptimizations(std::ostream & os)2001 void Runtime::DumpDeoptimizations(std::ostream& os) {
2002   for (size_t i = 0; i <= static_cast<size_t>(DeoptimizationKind::kLast); ++i) {
2003     if (deoptimization_counts_[i] != 0) {
2004       os << "Number of "
2005          << GetDeoptimizationKindName(static_cast<DeoptimizationKind>(i))
2006          << " deoptimizations: "
2007          << deoptimization_counts_[i]
2008          << "\n";
2009     }
2010   }
2011 }
2012 
DumpForSigQuit(std::ostream & os)2013 void Runtime::DumpForSigQuit(std::ostream& os) {
2014   GetClassLinker()->DumpForSigQuit(os);
2015   GetInternTable()->DumpForSigQuit(os);
2016   GetJavaVM()->DumpForSigQuit(os);
2017   GetHeap()->DumpForSigQuit(os);
2018   oat_file_manager_->DumpForSigQuit(os);
2019   if (GetJit() != nullptr) {
2020     GetJit()->DumpForSigQuit(os);
2021   } else {
2022     os << "Running non JIT\n";
2023   }
2024   DumpDeoptimizations(os);
2025   TrackedAllocators::Dump(os);
2026   os << "\n";
2027 
2028   thread_list_->DumpForSigQuit(os);
2029   BaseMutex::DumpAll(os);
2030 
2031   // Inform anyone else who is interested in SigQuit.
2032   {
2033     ScopedObjectAccess soa(Thread::Current());
2034     callbacks_->SigQuit();
2035   }
2036 }
2037 
DumpLockHolders(std::ostream & os)2038 void Runtime::DumpLockHolders(std::ostream& os) {
2039   uint64_t mutator_lock_owner = Locks::mutator_lock_->GetExclusiveOwnerTid();
2040   pid_t thread_list_lock_owner = GetThreadList()->GetLockOwner();
2041   pid_t classes_lock_owner = GetClassLinker()->GetClassesLockOwner();
2042   pid_t dex_lock_owner = GetClassLinker()->GetDexLockOwner();
2043   if ((thread_list_lock_owner | classes_lock_owner | dex_lock_owner) != 0) {
2044     os << "Mutator lock exclusive owner tid: " << mutator_lock_owner << "\n"
2045        << "ThreadList lock owner tid: " << thread_list_lock_owner << "\n"
2046        << "ClassLinker classes lock owner tid: " << classes_lock_owner << "\n"
2047        << "ClassLinker dex lock owner tid: " << dex_lock_owner << "\n";
2048   }
2049 }
2050 
SetStatsEnabled(bool new_state)2051 void Runtime::SetStatsEnabled(bool new_state) {
2052   Thread* self = Thread::Current();
2053   MutexLock mu(self, *Locks::instrument_entrypoints_lock_);
2054   if (new_state == true) {
2055     GetStats()->Clear(~0);
2056     // TODO: wouldn't it make more sense to clear _all_ threads' stats?
2057     self->GetStats()->Clear(~0);
2058     if (stats_enabled_ != new_state) {
2059       GetInstrumentation()->InstrumentQuickAllocEntryPointsLocked();
2060     }
2061   } else if (stats_enabled_ != new_state) {
2062     GetInstrumentation()->UninstrumentQuickAllocEntryPointsLocked();
2063   }
2064   stats_enabled_ = new_state;
2065 }
2066 
ResetStats(int kinds)2067 void Runtime::ResetStats(int kinds) {
2068   GetStats()->Clear(kinds & 0xffff);
2069   // TODO: wouldn't it make more sense to clear _all_ threads' stats?
2070   Thread::Current()->GetStats()->Clear(kinds >> 16);
2071 }
2072 
GetStat(int kind)2073 uint64_t Runtime::GetStat(int kind) {
2074   RuntimeStats* stats;
2075   if (kind < (1<<16)) {
2076     stats = GetStats();
2077   } else {
2078     stats = Thread::Current()->GetStats();
2079     kind >>= 16;
2080   }
2081   switch (kind) {
2082   case KIND_ALLOCATED_OBJECTS:
2083     return stats->allocated_objects;
2084   case KIND_ALLOCATED_BYTES:
2085     return stats->allocated_bytes;
2086   case KIND_FREED_OBJECTS:
2087     return stats->freed_objects;
2088   case KIND_FREED_BYTES:
2089     return stats->freed_bytes;
2090   case KIND_GC_INVOCATIONS:
2091     return stats->gc_for_alloc_count;
2092   case KIND_CLASS_INIT_COUNT:
2093     return stats->class_init_count;
2094   case KIND_CLASS_INIT_TIME:
2095     return stats->class_init_time_ns;
2096   case KIND_EXT_ALLOCATED_OBJECTS:
2097   case KIND_EXT_ALLOCATED_BYTES:
2098   case KIND_EXT_FREED_OBJECTS:
2099   case KIND_EXT_FREED_BYTES:
2100     return 0;  // backward compatibility
2101   default:
2102     LOG(FATAL) << "Unknown statistic " << kind;
2103     UNREACHABLE();
2104   }
2105 }
2106 
BlockSignals()2107 void Runtime::BlockSignals() {
2108   SignalSet signals;
2109   signals.Add(SIGPIPE);
2110   // SIGQUIT is used to dump the runtime's state (including stack traces).
2111   signals.Add(SIGQUIT);
2112   // SIGUSR1 is used to initiate a GC.
2113   signals.Add(SIGUSR1);
2114   signals.Block();
2115 }
2116 
AttachCurrentThread(const char * thread_name,bool as_daemon,jobject thread_group,bool create_peer)2117 bool Runtime::AttachCurrentThread(const char* thread_name, bool as_daemon, jobject thread_group,
2118                                   bool create_peer) {
2119   ScopedTrace trace(__FUNCTION__);
2120   Thread* self = Thread::Attach(thread_name, as_daemon, thread_group, create_peer);
2121   // Run ThreadGroup.add to notify the group that this thread is now started.
2122   if (self != nullptr && create_peer && !IsAotCompiler()) {
2123     ScopedObjectAccess soa(self);
2124     self->NotifyThreadGroup(soa, thread_group);
2125   }
2126   return self != nullptr;
2127 }
2128 
DetachCurrentThread()2129 void Runtime::DetachCurrentThread() {
2130   ScopedTrace trace(__FUNCTION__);
2131   Thread* self = Thread::Current();
2132   if (self == nullptr) {
2133     LOG(FATAL) << "attempting to detach thread that is not attached";
2134   }
2135   if (self->HasManagedStack()) {
2136     LOG(FATAL) << *Thread::Current() << " attempting to detach while still running code";
2137   }
2138   thread_list_->Unregister(self);
2139 }
2140 
GetPreAllocatedOutOfMemoryErrorWhenThrowingException()2141 mirror::Throwable* Runtime::GetPreAllocatedOutOfMemoryErrorWhenThrowingException() {
2142   mirror::Throwable* oome = pre_allocated_OutOfMemoryError_when_throwing_exception_.Read();
2143   if (oome == nullptr) {
2144     LOG(ERROR) << "Failed to return pre-allocated OOME-when-throwing-exception";
2145   }
2146   return oome;
2147 }
2148 
GetPreAllocatedOutOfMemoryErrorWhenThrowingOOME()2149 mirror::Throwable* Runtime::GetPreAllocatedOutOfMemoryErrorWhenThrowingOOME() {
2150   mirror::Throwable* oome = pre_allocated_OutOfMemoryError_when_throwing_oome_.Read();
2151   if (oome == nullptr) {
2152     LOG(ERROR) << "Failed to return pre-allocated OOME-when-throwing-OOME";
2153   }
2154   return oome;
2155 }
2156 
GetPreAllocatedOutOfMemoryErrorWhenHandlingStackOverflow()2157 mirror::Throwable* Runtime::GetPreAllocatedOutOfMemoryErrorWhenHandlingStackOverflow() {
2158   mirror::Throwable* oome = pre_allocated_OutOfMemoryError_when_handling_stack_overflow_.Read();
2159   if (oome == nullptr) {
2160     LOG(ERROR) << "Failed to return pre-allocated OOME-when-handling-stack-overflow";
2161   }
2162   return oome;
2163 }
2164 
GetPreAllocatedNoClassDefFoundError()2165 mirror::Throwable* Runtime::GetPreAllocatedNoClassDefFoundError() {
2166   mirror::Throwable* ncdfe = pre_allocated_NoClassDefFoundError_.Read();
2167   if (ncdfe == nullptr) {
2168     LOG(ERROR) << "Failed to return pre-allocated NoClassDefFoundError";
2169   }
2170   return ncdfe;
2171 }
2172 
VisitConstantRoots(RootVisitor * visitor)2173 void Runtime::VisitConstantRoots(RootVisitor* visitor) {
2174   // Visiting the roots of these ArtMethods is not currently required since all the GcRoots are
2175   // null.
2176   BufferedRootVisitor<16> buffered_visitor(visitor, RootInfo(kRootVMInternal));
2177   const PointerSize pointer_size = GetClassLinker()->GetImagePointerSize();
2178   if (HasResolutionMethod()) {
2179     resolution_method_->VisitRoots(buffered_visitor, pointer_size);
2180   }
2181   if (HasImtConflictMethod()) {
2182     imt_conflict_method_->VisitRoots(buffered_visitor, pointer_size);
2183   }
2184   if (imt_unimplemented_method_ != nullptr) {
2185     imt_unimplemented_method_->VisitRoots(buffered_visitor, pointer_size);
2186   }
2187   for (uint32_t i = 0; i < kCalleeSaveSize; ++i) {
2188     auto* m = reinterpret_cast<ArtMethod*>(callee_save_methods_[i]);
2189     if (m != nullptr) {
2190       m->VisitRoots(buffered_visitor, pointer_size);
2191     }
2192   }
2193 }
2194 
VisitConcurrentRoots(RootVisitor * visitor,VisitRootFlags flags)2195 void Runtime::VisitConcurrentRoots(RootVisitor* visitor, VisitRootFlags flags) {
2196   intern_table_->VisitRoots(visitor, flags);
2197   class_linker_->VisitRoots(visitor, flags);
2198   jni_id_manager_->VisitRoots(visitor);
2199   heap_->VisitAllocationRecords(visitor);
2200   if ((flags & kVisitRootFlagNewRoots) == 0) {
2201     // Guaranteed to have no new roots in the constant roots.
2202     VisitConstantRoots(visitor);
2203   }
2204 }
2205 
VisitTransactionRoots(RootVisitor * visitor)2206 void Runtime::VisitTransactionRoots(RootVisitor* visitor) {
2207   for (auto& transaction : preinitialization_transactions_) {
2208     transaction->VisitRoots(visitor);
2209   }
2210 }
2211 
VisitNonThreadRoots(RootVisitor * visitor)2212 void Runtime::VisitNonThreadRoots(RootVisitor* visitor) {
2213   java_vm_->VisitRoots(visitor);
2214   sentinel_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
2215   pre_allocated_OutOfMemoryError_when_throwing_exception_
2216       .VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
2217   pre_allocated_OutOfMemoryError_when_throwing_oome_
2218       .VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
2219   pre_allocated_OutOfMemoryError_when_handling_stack_overflow_
2220       .VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
2221   pre_allocated_NoClassDefFoundError_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
2222   VisitImageRoots(visitor);
2223   verifier::ClassVerifier::VisitStaticRoots(visitor);
2224   VisitTransactionRoots(visitor);
2225 }
2226 
VisitNonConcurrentRoots(RootVisitor * visitor,VisitRootFlags flags)2227 void Runtime::VisitNonConcurrentRoots(RootVisitor* visitor, VisitRootFlags flags) {
2228   VisitThreadRoots(visitor, flags);
2229   VisitNonThreadRoots(visitor);
2230 }
2231 
VisitThreadRoots(RootVisitor * visitor,VisitRootFlags flags)2232 void Runtime::VisitThreadRoots(RootVisitor* visitor, VisitRootFlags flags) {
2233   thread_list_->VisitRoots(visitor, flags);
2234 }
2235 
VisitRoots(RootVisitor * visitor,VisitRootFlags flags)2236 void Runtime::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
2237   VisitNonConcurrentRoots(visitor, flags);
2238   VisitConcurrentRoots(visitor, flags);
2239 }
2240 
VisitReflectiveTargets(ReflectiveValueVisitor * visitor)2241 void Runtime::VisitReflectiveTargets(ReflectiveValueVisitor *visitor) {
2242   thread_list_->VisitReflectiveTargets(visitor);
2243   heap_->VisitReflectiveTargets(visitor);
2244   jni_id_manager_->VisitReflectiveTargets(visitor);
2245   callbacks_->VisitReflectiveTargets(visitor);
2246 }
2247 
VisitImageRoots(RootVisitor * visitor)2248 void Runtime::VisitImageRoots(RootVisitor* visitor) {
2249   for (auto* space : GetHeap()->GetContinuousSpaces()) {
2250     if (space->IsImageSpace()) {
2251       auto* image_space = space->AsImageSpace();
2252       const auto& image_header = image_space->GetImageHeader();
2253       for (int32_t i = 0, size = image_header.GetImageRoots()->GetLength(); i != size; ++i) {
2254         mirror::Object* obj =
2255             image_header.GetImageRoot(static_cast<ImageHeader::ImageRoot>(i)).Ptr();
2256         if (obj != nullptr) {
2257           mirror::Object* after_obj = obj;
2258           visitor->VisitRoot(&after_obj, RootInfo(kRootStickyClass));
2259           CHECK_EQ(after_obj, obj);
2260         }
2261       }
2262     }
2263   }
2264 }
2265 
CreateRuntimeMethod(ClassLinker * class_linker,LinearAlloc * linear_alloc)2266 static ArtMethod* CreateRuntimeMethod(ClassLinker* class_linker, LinearAlloc* linear_alloc)
2267     REQUIRES_SHARED(Locks::mutator_lock_) {
2268   const PointerSize image_pointer_size = class_linker->GetImagePointerSize();
2269   const size_t method_alignment = ArtMethod::Alignment(image_pointer_size);
2270   const size_t method_size = ArtMethod::Size(image_pointer_size);
2271   LengthPrefixedArray<ArtMethod>* method_array = class_linker->AllocArtMethodArray(
2272       Thread::Current(),
2273       linear_alloc,
2274       1);
2275   ArtMethod* method = &method_array->At(0, method_size, method_alignment);
2276   CHECK(method != nullptr);
2277   method->SetDexMethodIndex(dex::kDexNoIndex);
2278   CHECK(method->IsRuntimeMethod());
2279   return method;
2280 }
2281 
CreateImtConflictMethod(LinearAlloc * linear_alloc)2282 ArtMethod* Runtime::CreateImtConflictMethod(LinearAlloc* linear_alloc) {
2283   ClassLinker* const class_linker = GetClassLinker();
2284   ArtMethod* method = CreateRuntimeMethod(class_linker, linear_alloc);
2285   // When compiling, the code pointer will get set later when the image is loaded.
2286   const PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set_);
2287   if (IsAotCompiler()) {
2288     method->SetEntryPointFromQuickCompiledCodePtrSize(nullptr, pointer_size);
2289   } else {
2290     method->SetEntryPointFromQuickCompiledCode(GetQuickImtConflictStub());
2291   }
2292   // Create empty conflict table.
2293   method->SetImtConflictTable(class_linker->CreateImtConflictTable(/*count=*/0u, linear_alloc),
2294                               pointer_size);
2295   return method;
2296 }
2297 
SetImtConflictMethod(ArtMethod * method)2298 void Runtime::SetImtConflictMethod(ArtMethod* method) {
2299   CHECK(method != nullptr);
2300   CHECK(method->IsRuntimeMethod());
2301   imt_conflict_method_ = method;
2302 }
2303 
CreateResolutionMethod()2304 ArtMethod* Runtime::CreateResolutionMethod() {
2305   auto* method = CreateRuntimeMethod(GetClassLinker(), GetLinearAlloc());
2306   // When compiling, the code pointer will get set later when the image is loaded.
2307   if (IsAotCompiler()) {
2308     PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set_);
2309     method->SetEntryPointFromQuickCompiledCodePtrSize(nullptr, pointer_size);
2310   } else {
2311     method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
2312   }
2313   return method;
2314 }
2315 
CreateCalleeSaveMethod()2316 ArtMethod* Runtime::CreateCalleeSaveMethod() {
2317   auto* method = CreateRuntimeMethod(GetClassLinker(), GetLinearAlloc());
2318   PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set_);
2319   method->SetEntryPointFromQuickCompiledCodePtrSize(nullptr, pointer_size);
2320   DCHECK_NE(instruction_set_, InstructionSet::kNone);
2321   DCHECK(method->IsRuntimeMethod());
2322   return method;
2323 }
2324 
DisallowNewSystemWeaks()2325 void Runtime::DisallowNewSystemWeaks() {
2326   CHECK(!kUseReadBarrier);
2327   monitor_list_->DisallowNewMonitors();
2328   intern_table_->ChangeWeakRootState(gc::kWeakRootStateNoReadsOrWrites);
2329   java_vm_->DisallowNewWeakGlobals();
2330   heap_->DisallowNewAllocationRecords();
2331   if (GetJit() != nullptr) {
2332     GetJit()->GetCodeCache()->DisallowInlineCacheAccess();
2333   }
2334 
2335   // All other generic system-weak holders.
2336   for (gc::AbstractSystemWeakHolder* holder : system_weak_holders_) {
2337     holder->Disallow();
2338   }
2339 }
2340 
AllowNewSystemWeaks()2341 void Runtime::AllowNewSystemWeaks() {
2342   CHECK(!kUseReadBarrier);
2343   monitor_list_->AllowNewMonitors();
2344   intern_table_->ChangeWeakRootState(gc::kWeakRootStateNormal);  // TODO: Do this in the sweeping.
2345   java_vm_->AllowNewWeakGlobals();
2346   heap_->AllowNewAllocationRecords();
2347   if (GetJit() != nullptr) {
2348     GetJit()->GetCodeCache()->AllowInlineCacheAccess();
2349   }
2350 
2351   // All other generic system-weak holders.
2352   for (gc::AbstractSystemWeakHolder* holder : system_weak_holders_) {
2353     holder->Allow();
2354   }
2355 }
2356 
BroadcastForNewSystemWeaks(bool broadcast_for_checkpoint)2357 void Runtime::BroadcastForNewSystemWeaks(bool broadcast_for_checkpoint) {
2358   // This is used for the read barrier case that uses the thread-local
2359   // Thread::GetWeakRefAccessEnabled() flag and the checkpoint while weak ref access is disabled
2360   // (see ThreadList::RunCheckpoint).
2361   monitor_list_->BroadcastForNewMonitors();
2362   intern_table_->BroadcastForNewInterns();
2363   java_vm_->BroadcastForNewWeakGlobals();
2364   heap_->BroadcastForNewAllocationRecords();
2365   if (GetJit() != nullptr) {
2366     GetJit()->GetCodeCache()->BroadcastForInlineCacheAccess();
2367   }
2368 
2369   // All other generic system-weak holders.
2370   for (gc::AbstractSystemWeakHolder* holder : system_weak_holders_) {
2371     holder->Broadcast(broadcast_for_checkpoint);
2372   }
2373 }
2374 
SetInstructionSet(InstructionSet instruction_set)2375 void Runtime::SetInstructionSet(InstructionSet instruction_set) {
2376   instruction_set_ = instruction_set;
2377   switch (instruction_set) {
2378     case InstructionSet::kThumb2:
2379       // kThumb2 is the same as kArm, use the canonical value.
2380       instruction_set_ = InstructionSet::kArm;
2381       break;
2382     case InstructionSet::kArm:
2383     case InstructionSet::kArm64:
2384     case InstructionSet::kX86:
2385     case InstructionSet::kX86_64:
2386       break;
2387     default:
2388       UNIMPLEMENTED(FATAL) << instruction_set_;
2389       UNREACHABLE();
2390   }
2391 }
2392 
ClearInstructionSet()2393 void Runtime::ClearInstructionSet() {
2394   instruction_set_ = InstructionSet::kNone;
2395 }
2396 
SetCalleeSaveMethod(ArtMethod * method,CalleeSaveType type)2397 void Runtime::SetCalleeSaveMethod(ArtMethod* method, CalleeSaveType type) {
2398   DCHECK_LT(static_cast<uint32_t>(type), kCalleeSaveSize);
2399   CHECK(method != nullptr);
2400   callee_save_methods_[static_cast<size_t>(type)] = reinterpret_cast<uintptr_t>(method);
2401 }
2402 
ClearCalleeSaveMethods()2403 void Runtime::ClearCalleeSaveMethods() {
2404   for (size_t i = 0; i < kCalleeSaveSize; ++i) {
2405     callee_save_methods_[i] = reinterpret_cast<uintptr_t>(nullptr);
2406   }
2407 }
2408 
RegisterAppInfo(const std::vector<std::string> & code_paths,const std::string & profile_output_filename)2409 void Runtime::RegisterAppInfo(const std::vector<std::string>& code_paths,
2410                               const std::string& profile_output_filename) {
2411   if (jit_.get() == nullptr) {
2412     // We are not JITing. Nothing to do.
2413     return;
2414   }
2415 
2416   VLOG(profiler) << "Register app with " << profile_output_filename
2417       << " " << android::base::Join(code_paths, ':');
2418 
2419   if (profile_output_filename.empty()) {
2420     LOG(WARNING) << "JIT profile information will not be recorded: profile filename is empty.";
2421     return;
2422   }
2423   if (!OS::FileExists(profile_output_filename.c_str(), /*check_file_type=*/ false)) {
2424     LOG(WARNING) << "JIT profile information will not be recorded: profile file does not exist.";
2425     return;
2426   }
2427   if (code_paths.empty()) {
2428     LOG(WARNING) << "JIT profile information will not be recorded: code paths is empty.";
2429     return;
2430   }
2431 
2432   jit_->StartProfileSaver(profile_output_filename, code_paths);
2433 }
2434 
2435 // Transaction support.
IsActiveTransaction() const2436 bool Runtime::IsActiveTransaction() const {
2437   return !preinitialization_transactions_.empty() && !GetTransaction()->IsRollingBack();
2438 }
2439 
EnterTransactionMode(bool strict,mirror::Class * root)2440 void Runtime::EnterTransactionMode(bool strict, mirror::Class* root) {
2441   DCHECK(IsAotCompiler());
2442   if (preinitialization_transactions_.empty()) {  // Top-level transaction?
2443     // Make initialized classes visibly initialized now. If that happened during the transaction
2444     // and then the transaction was aborted, we would roll back the status update but not the
2445     // ClassLinker's bookkeeping structures, so these classes would never be visibly initialized.
2446     GetClassLinker()->MakeInitializedClassesVisiblyInitialized(Thread::Current(), /*wait=*/ true);
2447   }
2448   preinitialization_transactions_.push_back(std::make_unique<Transaction>(strict, root));
2449 }
2450 
ExitTransactionMode()2451 void Runtime::ExitTransactionMode() {
2452   DCHECK(IsAotCompiler());
2453   DCHECK(IsActiveTransaction());
2454   preinitialization_transactions_.pop_back();
2455 }
2456 
RollbackAndExitTransactionMode()2457 void Runtime::RollbackAndExitTransactionMode() {
2458   DCHECK(IsAotCompiler());
2459   DCHECK(IsActiveTransaction());
2460   preinitialization_transactions_.back()->Rollback();
2461   preinitialization_transactions_.pop_back();
2462 }
2463 
IsTransactionAborted() const2464 bool Runtime::IsTransactionAborted() const {
2465   if (!IsActiveTransaction()) {
2466     return false;
2467   } else {
2468     DCHECK(IsAotCompiler());
2469     return GetTransaction()->IsAborted();
2470   }
2471 }
2472 
RollbackAllTransactions()2473 void Runtime::RollbackAllTransactions() {
2474   // If transaction is aborted, all transactions will be kept in the list.
2475   // Rollback and exit all of them.
2476   while (IsActiveTransaction()) {
2477     RollbackAndExitTransactionMode();
2478   }
2479 }
2480 
IsActiveStrictTransactionMode() const2481 bool Runtime::IsActiveStrictTransactionMode() const {
2482   return IsActiveTransaction() && GetTransaction()->IsStrict();
2483 }
2484 
GetTransaction() const2485 const std::unique_ptr<Transaction>& Runtime::GetTransaction() const {
2486   DCHECK(!preinitialization_transactions_.empty());
2487   return preinitialization_transactions_.back();
2488 }
2489 
AbortTransactionAndThrowAbortError(Thread * self,const std::string & abort_message)2490 void Runtime::AbortTransactionAndThrowAbortError(Thread* self, const std::string& abort_message) {
2491   DCHECK(IsAotCompiler());
2492   DCHECK(IsActiveTransaction());
2493   // Throwing an exception may cause its class initialization. If we mark the transaction
2494   // aborted before that, we may warn with a false alarm. Throwing the exception before
2495   // marking the transaction aborted avoids that.
2496   // But now the transaction can be nested, and abort the transaction will relax the constraints
2497   // for constructing stack trace.
2498   GetTransaction()->Abort(abort_message);
2499   GetTransaction()->ThrowAbortError(self, &abort_message);
2500 }
2501 
ThrowTransactionAbortError(Thread * self)2502 void Runtime::ThrowTransactionAbortError(Thread* self) {
2503   DCHECK(IsAotCompiler());
2504   DCHECK(IsActiveTransaction());
2505   // Passing nullptr means we rethrow an exception with the earlier transaction abort message.
2506   GetTransaction()->ThrowAbortError(self, nullptr);
2507 }
2508 
RecordWriteFieldBoolean(mirror::Object * obj,MemberOffset field_offset,uint8_t value,bool is_volatile) const2509 void Runtime::RecordWriteFieldBoolean(mirror::Object* obj, MemberOffset field_offset,
2510                                       uint8_t value, bool is_volatile) const {
2511   DCHECK(IsAotCompiler());
2512   DCHECK(IsActiveTransaction());
2513   GetTransaction()->RecordWriteFieldBoolean(obj, field_offset, value, is_volatile);
2514 }
2515 
RecordWriteFieldByte(mirror::Object * obj,MemberOffset field_offset,int8_t value,bool is_volatile) const2516 void Runtime::RecordWriteFieldByte(mirror::Object* obj, MemberOffset field_offset,
2517                                    int8_t value, bool is_volatile) const {
2518   DCHECK(IsAotCompiler());
2519   DCHECK(IsActiveTransaction());
2520   GetTransaction()->RecordWriteFieldByte(obj, field_offset, value, is_volatile);
2521 }
2522 
RecordWriteFieldChar(mirror::Object * obj,MemberOffset field_offset,uint16_t value,bool is_volatile) const2523 void Runtime::RecordWriteFieldChar(mirror::Object* obj, MemberOffset field_offset,
2524                                    uint16_t value, bool is_volatile) const {
2525   DCHECK(IsAotCompiler());
2526   DCHECK(IsActiveTransaction());
2527   GetTransaction()->RecordWriteFieldChar(obj, field_offset, value, is_volatile);
2528 }
2529 
RecordWriteFieldShort(mirror::Object * obj,MemberOffset field_offset,int16_t value,bool is_volatile) const2530 void Runtime::RecordWriteFieldShort(mirror::Object* obj, MemberOffset field_offset,
2531                                     int16_t value, bool is_volatile) const {
2532   DCHECK(IsAotCompiler());
2533   DCHECK(IsActiveTransaction());
2534   GetTransaction()->RecordWriteFieldShort(obj, field_offset, value, is_volatile);
2535 }
2536 
RecordWriteField32(mirror::Object * obj,MemberOffset field_offset,uint32_t value,bool is_volatile) const2537 void Runtime::RecordWriteField32(mirror::Object* obj, MemberOffset field_offset,
2538                                  uint32_t value, bool is_volatile) const {
2539   DCHECK(IsAotCompiler());
2540   DCHECK(IsActiveTransaction());
2541   GetTransaction()->RecordWriteField32(obj, field_offset, value, is_volatile);
2542 }
2543 
RecordWriteField64(mirror::Object * obj,MemberOffset field_offset,uint64_t value,bool is_volatile) const2544 void Runtime::RecordWriteField64(mirror::Object* obj, MemberOffset field_offset,
2545                                  uint64_t value, bool is_volatile) const {
2546   DCHECK(IsAotCompiler());
2547   DCHECK(IsActiveTransaction());
2548   GetTransaction()->RecordWriteField64(obj, field_offset, value, is_volatile);
2549 }
2550 
RecordWriteFieldReference(mirror::Object * obj,MemberOffset field_offset,ObjPtr<mirror::Object> value,bool is_volatile) const2551 void Runtime::RecordWriteFieldReference(mirror::Object* obj,
2552                                         MemberOffset field_offset,
2553                                         ObjPtr<mirror::Object> value,
2554                                         bool is_volatile) const {
2555   DCHECK(IsAotCompiler());
2556   DCHECK(IsActiveTransaction());
2557   GetTransaction()->RecordWriteFieldReference(obj,
2558                                                             field_offset,
2559                                                             value.Ptr(),
2560                                                             is_volatile);
2561 }
2562 
RecordWriteArray(mirror::Array * array,size_t index,uint64_t value) const2563 void Runtime::RecordWriteArray(mirror::Array* array, size_t index, uint64_t value) const {
2564   DCHECK(IsAotCompiler());
2565   DCHECK(IsActiveTransaction());
2566   GetTransaction()->RecordWriteArray(array, index, value);
2567 }
2568 
RecordStrongStringInsertion(ObjPtr<mirror::String> s) const2569 void Runtime::RecordStrongStringInsertion(ObjPtr<mirror::String> s) const {
2570   DCHECK(IsAotCompiler());
2571   DCHECK(IsActiveTransaction());
2572   GetTransaction()->RecordStrongStringInsertion(s);
2573 }
2574 
RecordWeakStringInsertion(ObjPtr<mirror::String> s) const2575 void Runtime::RecordWeakStringInsertion(ObjPtr<mirror::String> s) const {
2576   DCHECK(IsAotCompiler());
2577   DCHECK(IsActiveTransaction());
2578   GetTransaction()->RecordWeakStringInsertion(s);
2579 }
2580 
RecordStrongStringRemoval(ObjPtr<mirror::String> s) const2581 void Runtime::RecordStrongStringRemoval(ObjPtr<mirror::String> s) const {
2582   DCHECK(IsAotCompiler());
2583   DCHECK(IsActiveTransaction());
2584   GetTransaction()->RecordStrongStringRemoval(s);
2585 }
2586 
RecordWeakStringRemoval(ObjPtr<mirror::String> s) const2587 void Runtime::RecordWeakStringRemoval(ObjPtr<mirror::String> s) const {
2588   DCHECK(IsAotCompiler());
2589   DCHECK(IsActiveTransaction());
2590   GetTransaction()->RecordWeakStringRemoval(s);
2591 }
2592 
RecordResolveString(ObjPtr<mirror::DexCache> dex_cache,dex::StringIndex string_idx) const2593 void Runtime::RecordResolveString(ObjPtr<mirror::DexCache> dex_cache,
2594                                   dex::StringIndex string_idx) const {
2595   DCHECK(IsAotCompiler());
2596   DCHECK(IsActiveTransaction());
2597   GetTransaction()->RecordResolveString(dex_cache, string_idx);
2598 }
2599 
SetFaultMessage(const std::string & message)2600 void Runtime::SetFaultMessage(const std::string& message) {
2601   std::string* new_msg = new std::string(message);
2602   std::string* cur_msg = fault_message_.exchange(new_msg);
2603   delete cur_msg;
2604 }
2605 
GetFaultMessage()2606 std::string Runtime::GetFaultMessage() {
2607   // Retrieve the message. Temporarily replace with null so that SetFaultMessage will not delete
2608   // the string in parallel.
2609   std::string* cur_msg = fault_message_.exchange(nullptr);
2610 
2611   // Make a copy of the string.
2612   std::string ret = cur_msg == nullptr ? "" : *cur_msg;
2613 
2614   // Put the message back if it hasn't been updated.
2615   std::string* null_str = nullptr;
2616   if (!fault_message_.compare_exchange_strong(null_str, cur_msg)) {
2617     // Already replaced.
2618     delete cur_msg;
2619   }
2620 
2621   return ret;
2622 }
2623 
AddCurrentRuntimeFeaturesAsDex2OatArguments(std::vector<std::string> * argv) const2624 void Runtime::AddCurrentRuntimeFeaturesAsDex2OatArguments(std::vector<std::string>* argv)
2625     const {
2626   if (GetInstrumentation()->InterpretOnly()) {
2627     argv->push_back("--compiler-filter=quicken");
2628   }
2629 
2630   // Make the dex2oat instruction set match that of the launching runtime. If we have multiple
2631   // architecture support, dex2oat may be compiled as a different instruction-set than that
2632   // currently being executed.
2633   std::string instruction_set("--instruction-set=");
2634   instruction_set += GetInstructionSetString(kRuntimeISA);
2635   argv->push_back(instruction_set);
2636 
2637   if (InstructionSetFeatures::IsRuntimeDetectionSupported()) {
2638     argv->push_back("--instruction-set-features=runtime");
2639   } else {
2640     std::unique_ptr<const InstructionSetFeatures> features(
2641         InstructionSetFeatures::FromCppDefines());
2642     std::string feature_string("--instruction-set-features=");
2643     feature_string += features->GetFeatureString();
2644     argv->push_back(feature_string);
2645   }
2646 }
2647 
CreateJitCodeCache(bool rwx_memory_allowed)2648 void Runtime::CreateJitCodeCache(bool rwx_memory_allowed) {
2649   if (kIsDebugBuild && GetInstrumentation()->IsForcedInterpretOnly()) {
2650     DCHECK(!jit_options_->UseJitCompilation());
2651   }
2652 
2653   if (!jit_options_->UseJitCompilation() && !jit_options_->GetSaveProfilingInfo()) {
2654     return;
2655   }
2656 
2657   std::string error_msg;
2658   bool profiling_only = !jit_options_->UseJitCompilation();
2659   jit_code_cache_.reset(jit::JitCodeCache::Create(profiling_only,
2660                                                   rwx_memory_allowed,
2661                                                   IsZygote(),
2662                                                   &error_msg));
2663   if (jit_code_cache_.get() == nullptr) {
2664     LOG(WARNING) << "Failed to create JIT Code Cache: " << error_msg;
2665   }
2666 }
2667 
CreateJit()2668 void Runtime::CreateJit() {
2669   DCHECK(jit_ == nullptr);
2670   if (jit_code_cache_.get() == nullptr) {
2671     if (!IsSafeMode()) {
2672       LOG(WARNING) << "Missing code cache, cannot create JIT.";
2673     }
2674     return;
2675   }
2676   if (IsSafeMode()) {
2677     LOG(INFO) << "Not creating JIT because of SafeMode.";
2678     jit_code_cache_.reset();
2679     return;
2680   }
2681 
2682   jit::Jit* jit = jit::Jit::Create(jit_code_cache_.get(), jit_options_.get());
2683   DoAndMaybeSwitchInterpreter([=](){ jit_.reset(jit); });
2684   if (jit == nullptr) {
2685     LOG(WARNING) << "Failed to allocate JIT";
2686     // Release JIT code cache resources (several MB of memory).
2687     jit_code_cache_.reset();
2688   } else {
2689     jit->CreateThreadPool();
2690   }
2691 }
2692 
CanRelocate() const2693 bool Runtime::CanRelocate() const {
2694   return !IsAotCompiler();
2695 }
2696 
IsCompilingBootImage() const2697 bool Runtime::IsCompilingBootImage() const {
2698   return IsCompiler() && compiler_callbacks_->IsBootImage();
2699 }
2700 
SetResolutionMethod(ArtMethod * method)2701 void Runtime::SetResolutionMethod(ArtMethod* method) {
2702   CHECK(method != nullptr);
2703   CHECK(method->IsRuntimeMethod()) << method;
2704   resolution_method_ = method;
2705 }
2706 
SetImtUnimplementedMethod(ArtMethod * method)2707 void Runtime::SetImtUnimplementedMethod(ArtMethod* method) {
2708   CHECK(method != nullptr);
2709   CHECK(method->IsRuntimeMethod());
2710   imt_unimplemented_method_ = method;
2711 }
2712 
FixupConflictTables()2713 void Runtime::FixupConflictTables() {
2714   // We can only do this after the class linker is created.
2715   const PointerSize pointer_size = GetClassLinker()->GetImagePointerSize();
2716   if (imt_unimplemented_method_->GetImtConflictTable(pointer_size) == nullptr) {
2717     imt_unimplemented_method_->SetImtConflictTable(
2718         ClassLinker::CreateImtConflictTable(/*count=*/0u, GetLinearAlloc(), pointer_size),
2719         pointer_size);
2720   }
2721   if (imt_conflict_method_->GetImtConflictTable(pointer_size) == nullptr) {
2722     imt_conflict_method_->SetImtConflictTable(
2723           ClassLinker::CreateImtConflictTable(/*count=*/0u, GetLinearAlloc(), pointer_size),
2724           pointer_size);
2725   }
2726 }
2727 
DisableVerifier()2728 void Runtime::DisableVerifier() {
2729   verify_ = verifier::VerifyMode::kNone;
2730 }
2731 
IsVerificationEnabled() const2732 bool Runtime::IsVerificationEnabled() const {
2733   return verify_ == verifier::VerifyMode::kEnable ||
2734       verify_ == verifier::VerifyMode::kSoftFail;
2735 }
2736 
IsVerificationSoftFail() const2737 bool Runtime::IsVerificationSoftFail() const {
2738   return verify_ == verifier::VerifyMode::kSoftFail;
2739 }
2740 
IsAsyncDeoptimizeable(uintptr_t code) const2741 bool Runtime::IsAsyncDeoptimizeable(uintptr_t code) const {
2742   if (OatQuickMethodHeader::NterpMethodHeader != nullptr) {
2743     if (OatQuickMethodHeader::NterpMethodHeader->Contains(code)) {
2744       return true;
2745     }
2746   }
2747   // We only support async deopt (ie the compiled code is not explicitly asking for
2748   // deopt, but something else like the debugger) in debuggable JIT code.
2749   // We could look at the oat file where `code` is being defined,
2750   // and check whether it's been compiled debuggable, but we decided to
2751   // only rely on the JIT for debuggable apps.
2752   // The JIT-zygote is not debuggable so we need to be sure to exclude code from the non-private
2753   // region as well.
2754   return IsJavaDebuggable() && GetJit() != nullptr &&
2755          GetJit()->GetCodeCache()->PrivateRegionContainsPc(reinterpret_cast<const void*>(code));
2756 }
2757 
CreateLinearAlloc()2758 LinearAlloc* Runtime::CreateLinearAlloc() {
2759   // For 64 bit compilers, it needs to be in low 4GB in the case where we are cross compiling for a
2760   // 32 bit target. In this case, we have 32 bit pointers in the dex cache arrays which can't hold
2761   // when we have 64 bit ArtMethod pointers.
2762   return (IsAotCompiler() && Is64BitInstructionSet(kRuntimeISA))
2763       ? new LinearAlloc(low_4gb_arena_pool_.get())
2764       : new LinearAlloc(arena_pool_.get());
2765 }
2766 
GetHashTableMinLoadFactor() const2767 double Runtime::GetHashTableMinLoadFactor() const {
2768   return is_low_memory_mode_ ? kLowMemoryMinLoadFactor : kNormalMinLoadFactor;
2769 }
2770 
GetHashTableMaxLoadFactor() const2771 double Runtime::GetHashTableMaxLoadFactor() const {
2772   return is_low_memory_mode_ ? kLowMemoryMaxLoadFactor : kNormalMaxLoadFactor;
2773 }
2774 
UpdateProcessState(ProcessState process_state)2775 void Runtime::UpdateProcessState(ProcessState process_state) {
2776   ProcessState old_process_state = process_state_;
2777   process_state_ = process_state;
2778   GetHeap()->UpdateProcessState(old_process_state, process_state);
2779 }
2780 
RegisterSensitiveThread() const2781 void Runtime::RegisterSensitiveThread() const {
2782   Thread::SetJitSensitiveThread();
2783 }
2784 
2785 // Returns true if JIT compilations are enabled. GetJit() will be not null in this case.
UseJitCompilation() const2786 bool Runtime::UseJitCompilation() const {
2787   return (jit_ != nullptr) && jit_->UseJitCompilation();
2788 }
2789 
TakeSnapshot()2790 void Runtime::EnvSnapshot::TakeSnapshot() {
2791   char** env = GetEnviron();
2792   for (size_t i = 0; env[i] != nullptr; ++i) {
2793     name_value_pairs_.emplace_back(new std::string(env[i]));
2794   }
2795   // The strings in name_value_pairs_ retain ownership of the c_str, but we assign pointers
2796   // for quick use by GetSnapshot.  This avoids allocation and copying cost at Exec.
2797   c_env_vector_.reset(new char*[name_value_pairs_.size() + 1]);
2798   for (size_t i = 0; env[i] != nullptr; ++i) {
2799     c_env_vector_[i] = const_cast<char*>(name_value_pairs_[i]->c_str());
2800   }
2801   c_env_vector_[name_value_pairs_.size()] = nullptr;
2802 }
2803 
GetSnapshot() const2804 char** Runtime::EnvSnapshot::GetSnapshot() const {
2805   return c_env_vector_.get();
2806 }
2807 
AddSystemWeakHolder(gc::AbstractSystemWeakHolder * holder)2808 void Runtime::AddSystemWeakHolder(gc::AbstractSystemWeakHolder* holder) {
2809   gc::ScopedGCCriticalSection gcs(Thread::Current(),
2810                                   gc::kGcCauseAddRemoveSystemWeakHolder,
2811                                   gc::kCollectorTypeAddRemoveSystemWeakHolder);
2812   // Note: The ScopedGCCriticalSection also ensures that the rest of the function is in
2813   //       a critical section.
2814   system_weak_holders_.push_back(holder);
2815 }
2816 
RemoveSystemWeakHolder(gc::AbstractSystemWeakHolder * holder)2817 void Runtime::RemoveSystemWeakHolder(gc::AbstractSystemWeakHolder* holder) {
2818   gc::ScopedGCCriticalSection gcs(Thread::Current(),
2819                                   gc::kGcCauseAddRemoveSystemWeakHolder,
2820                                   gc::kCollectorTypeAddRemoveSystemWeakHolder);
2821   auto it = std::find(system_weak_holders_.begin(), system_weak_holders_.end(), holder);
2822   if (it != system_weak_holders_.end()) {
2823     system_weak_holders_.erase(it);
2824   }
2825 }
2826 
GetRuntimeCallbacks()2827 RuntimeCallbacks* Runtime::GetRuntimeCallbacks() {
2828   return callbacks_.get();
2829 }
2830 
2831 // Used to patch boot image method entry point to interpreter bridge.
2832 class UpdateEntryPointsClassVisitor : public ClassVisitor {
2833  public:
UpdateEntryPointsClassVisitor(instrumentation::Instrumentation * instrumentation)2834   explicit UpdateEntryPointsClassVisitor(instrumentation::Instrumentation* instrumentation)
2835       : instrumentation_(instrumentation) {}
2836 
operator ()(ObjPtr<mirror::Class> klass)2837   bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES(Locks::mutator_lock_) {
2838     DCHECK(Locks::mutator_lock_->IsExclusiveHeld(Thread::Current()));
2839     auto pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
2840     for (auto& m : klass->GetMethods(pointer_size)) {
2841       const void* code = m.GetEntryPointFromQuickCompiledCode();
2842       if (Runtime::Current()->GetHeap()->IsInBootImageOatFile(code) &&
2843           !m.IsNative() &&
2844           !m.IsProxyMethod()) {
2845         instrumentation_->UpdateMethodsCodeForJavaDebuggable(&m, GetQuickToInterpreterBridge());
2846       }
2847 
2848       if (Runtime::Current()->GetJit() != nullptr &&
2849           Runtime::Current()->GetJit()->GetCodeCache()->IsInZygoteExecSpace(code) &&
2850           !m.IsNative()) {
2851         DCHECK(!m.IsProxyMethod());
2852         instrumentation_->UpdateMethodsCodeForJavaDebuggable(&m, GetQuickToInterpreterBridge());
2853       }
2854 
2855       if (m.IsPreCompiled()) {
2856         // Precompilation is incompatible with debuggable, so clear the flag
2857         // and update the entrypoint in case it has been compiled.
2858         m.ClearPreCompiled();
2859         instrumentation_->UpdateMethodsCodeForJavaDebuggable(&m, GetQuickToInterpreterBridge());
2860       }
2861     }
2862     return true;
2863   }
2864 
2865  private:
2866   instrumentation::Instrumentation* const instrumentation_;
2867 };
2868 
SetJavaDebuggable(bool value)2869 void Runtime::SetJavaDebuggable(bool value) {
2870   is_java_debuggable_ = value;
2871   // Do not call DeoptimizeBootImage just yet, the runtime may still be starting up.
2872 }
2873 
DeoptimizeBootImage()2874 void Runtime::DeoptimizeBootImage() {
2875   // If we've already started and we are setting this runtime to debuggable,
2876   // we patch entry points of methods in boot image to interpreter bridge, as
2877   // boot image code may be AOT compiled as not debuggable.
2878   if (!GetInstrumentation()->IsForcedInterpretOnly()) {
2879     UpdateEntryPointsClassVisitor visitor(GetInstrumentation());
2880     GetClassLinker()->VisitClasses(&visitor);
2881     jit::Jit* jit = GetJit();
2882     if (jit != nullptr) {
2883       // Code previously compiled may not be compiled debuggable.
2884       jit->GetCodeCache()->TransitionToDebuggable();
2885     }
2886   }
2887   // Also de-quicken all -quick opcodes. We do this for both BCP and non-bcp so if we are swapping
2888   // debuggable during startup by a plugin (eg JVMTI) even non-BCP code has its vdex files deopted.
2889   std::unordered_set<const VdexFile*> vdexs;
2890   GetClassLinker()->VisitKnownDexFiles(Thread::Current(), [&](const art::DexFile* df) {
2891     const OatDexFile* odf = df->GetOatDexFile();
2892     if (odf == nullptr) {
2893       return;
2894     }
2895     const OatFile* of = odf->GetOatFile();
2896     if (of == nullptr || of->IsDebuggable()) {
2897       // no Oat or already debuggable so no -quick.
2898       return;
2899     }
2900     vdexs.insert(of->GetVdexFile());
2901   });
2902   LOG(INFO) << "Unquickening " << vdexs.size() << " vdex files!";
2903   for (const VdexFile* vf : vdexs) {
2904     vf->AllowWriting(true);
2905     vf->UnquickenInPlace(/*decompile_return_instruction=*/true);
2906     vf->AllowWriting(false);
2907   }
2908 }
2909 
ScopedThreadPoolUsage()2910 Runtime::ScopedThreadPoolUsage::ScopedThreadPoolUsage()
2911     : thread_pool_(Runtime::Current()->AcquireThreadPool()) {}
2912 
~ScopedThreadPoolUsage()2913 Runtime::ScopedThreadPoolUsage::~ScopedThreadPoolUsage() {
2914   Runtime::Current()->ReleaseThreadPool();
2915 }
2916 
DeleteThreadPool()2917 bool Runtime::DeleteThreadPool() {
2918   // Make sure workers are started to prevent thread shutdown errors.
2919   WaitForThreadPoolWorkersToStart();
2920   std::unique_ptr<ThreadPool> thread_pool;
2921   {
2922     MutexLock mu(Thread::Current(), *Locks::runtime_thread_pool_lock_);
2923     if (thread_pool_ref_count_ == 0) {
2924       thread_pool = std::move(thread_pool_);
2925     }
2926   }
2927   return thread_pool != nullptr;
2928 }
2929 
AcquireThreadPool()2930 ThreadPool* Runtime::AcquireThreadPool() {
2931   MutexLock mu(Thread::Current(), *Locks::runtime_thread_pool_lock_);
2932   ++thread_pool_ref_count_;
2933   return thread_pool_.get();
2934 }
2935 
ReleaseThreadPool()2936 void Runtime::ReleaseThreadPool() {
2937   MutexLock mu(Thread::Current(), *Locks::runtime_thread_pool_lock_);
2938   CHECK_GT(thread_pool_ref_count_, 0u);
2939   --thread_pool_ref_count_;
2940 }
2941 
WaitForThreadPoolWorkersToStart()2942 void Runtime::WaitForThreadPoolWorkersToStart() {
2943   // Need to make sure workers are created before deleting the pool.
2944   ScopedThreadPoolUsage stpu;
2945   if (stpu.GetThreadPool() != nullptr) {
2946     stpu.GetThreadPool()->WaitForWorkersToBeCreated();
2947   }
2948 }
2949 
ResetStartupCompleted()2950 void Runtime::ResetStartupCompleted() {
2951   startup_completed_.store(false, std::memory_order_seq_cst);
2952 }
2953 
2954 class Runtime::NotifyStartupCompletedTask : public gc::HeapTask {
2955  public:
NotifyStartupCompletedTask()2956   NotifyStartupCompletedTask() : gc::HeapTask(/*target_run_time=*/ NanoTime()) {}
2957 
Run(Thread * self)2958   void Run(Thread* self) override {
2959     VLOG(startup) << "NotifyStartupCompletedTask running";
2960     Runtime* const runtime = Runtime::Current();
2961     {
2962       ScopedTrace trace("Releasing app image spaces metadata");
2963       ScopedObjectAccess soa(Thread::Current());
2964       for (gc::space::ContinuousSpace* space : runtime->GetHeap()->GetContinuousSpaces()) {
2965         if (space->IsImageSpace()) {
2966           gc::space::ImageSpace* image_space = space->AsImageSpace();
2967           if (image_space->GetImageHeader().IsAppImage()) {
2968             image_space->DisablePreResolvedStrings();
2969           }
2970         }
2971       }
2972       // Request empty checkpoints to make sure no threads are accessing the image space metadata
2973       // section when we madvise it. Use GC exclusion to prevent deadlocks that may happen if
2974       // multiple threads are attempting to run empty checkpoints at the same time.
2975       {
2976         // Avoid using ScopedGCCriticalSection since that does not allow thread suspension. This is
2977         // not allowed to prevent allocations, but it's still safe to suspend temporarily for the
2978         // checkpoint.
2979         gc::ScopedInterruptibleGCCriticalSection sigcs(self,
2980                                                        gc::kGcCauseRunEmptyCheckpoint,
2981                                                        gc::kCollectorTypeCriticalSection);
2982         runtime->GetThreadList()->RunEmptyCheckpoint();
2983       }
2984       for (gc::space::ContinuousSpace* space : runtime->GetHeap()->GetContinuousSpaces()) {
2985         if (space->IsImageSpace()) {
2986           gc::space::ImageSpace* image_space = space->AsImageSpace();
2987           if (image_space->GetImageHeader().IsAppImage()) {
2988             image_space->ReleaseMetadata();
2989           }
2990         }
2991       }
2992     }
2993 
2994     {
2995       // Delete the thread pool used for app image loading since startup is assumed to be completed.
2996       ScopedTrace trace2("Delete thread pool");
2997       runtime->DeleteThreadPool();
2998     }
2999   }
3000 };
3001 
NotifyStartupCompleted()3002 void Runtime::NotifyStartupCompleted() {
3003   bool expected = false;
3004   if (!startup_completed_.compare_exchange_strong(expected, true, std::memory_order_seq_cst)) {
3005     // Right now NotifyStartupCompleted will be called up to twice, once from profiler and up to
3006     // once externally. For this reason there are no asserts.
3007     return;
3008   }
3009 
3010   VLOG(startup) << "Adding NotifyStartupCompleted task";
3011   // Use the heap task processor since we want to be exclusive with the GC and we don't want to
3012   // block the caller if the GC is running.
3013   if (!GetHeap()->AddHeapTask(new NotifyStartupCompletedTask)) {
3014     VLOG(startup) << "Failed to add NotifyStartupCompletedTask";
3015   }
3016 
3017   // Notify the profiler saver that startup is now completed.
3018   ProfileSaver::NotifyStartupCompleted();
3019 }
3020 
GetStartupCompleted() const3021 bool Runtime::GetStartupCompleted() const {
3022   return startup_completed_.load(std::memory_order_seq_cst);
3023 }
3024 
SetSignalHookDebuggable(bool value)3025 void Runtime::SetSignalHookDebuggable(bool value) {
3026   SkipAddSignalHandler(value);
3027 }
3028 
SetJniIdType(JniIdType t)3029 void Runtime::SetJniIdType(JniIdType t) {
3030   CHECK(CanSetJniIdType()) << "Not allowed to change id type!";
3031   if (t == GetJniIdType()) {
3032     return;
3033   }
3034   jni_ids_indirection_ = t;
3035   JNIEnvExt::ResetFunctionTable();
3036   WellKnownClasses::HandleJniIdTypeChange(Thread::Current()->GetJniEnv());
3037 }
3038 
GetOatFilesExecutable() const3039 bool Runtime::GetOatFilesExecutable() const {
3040   return !IsAotCompiler() && !(IsSystemServer() && jit_options_->GetSaveProfilingInfo());
3041 }
3042 
ProcessWeakClass(GcRoot<mirror::Class> * root_ptr,IsMarkedVisitor * visitor,mirror::Class * update)3043 void Runtime::ProcessWeakClass(GcRoot<mirror::Class>* root_ptr,
3044                                IsMarkedVisitor* visitor,
3045                                mirror::Class* update) {
3046     // This does not need a read barrier because this is called by GC.
3047   mirror::Class* cls = root_ptr->Read<kWithoutReadBarrier>();
3048   if (cls != nullptr && cls != GetWeakClassSentinel()) {
3049     DCHECK((cls->IsClass<kDefaultVerifyFlags>()));
3050     // Look at the classloader of the class to know if it has been unloaded.
3051     // This does not need a read barrier because this is called by GC.
3052     ObjPtr<mirror::Object> class_loader =
3053         cls->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>();
3054     if (class_loader == nullptr || visitor->IsMarked(class_loader.Ptr()) != nullptr) {
3055       // The class loader is live, update the entry if the class has moved.
3056       mirror::Class* new_cls = down_cast<mirror::Class*>(visitor->IsMarked(cls));
3057       // Note that new_object can be null for CMS and newly allocated objects.
3058       if (new_cls != nullptr && new_cls != cls) {
3059         *root_ptr = GcRoot<mirror::Class>(new_cls);
3060       }
3061     } else {
3062       // The class loader is not live, clear the entry.
3063       *root_ptr = GcRoot<mirror::Class>(update);
3064     }
3065   }
3066 }
3067 
3068 }  // namespace art
3069