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