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