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