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