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