1 /*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "runtime.h"
18
19 // sys/mount.h has to come before linux/fs.h due to redefinition of MS_RDONLY, MS_BIND, etc
20 #include <sys/mount.h>
21 #ifdef __linux__
22 #include <linux/fs.h>
23 #include <sys/prctl.h>
24 #endif
25
26 #include <signal.h>
27 #include <sys/syscall.h>
28 #include "base/memory_tool.h"
29 #if defined(__APPLE__)
30 #include <crt_externs.h> // for _NSGetEnviron
31 #endif
32
33 #include <cstdio>
34 #include <cstdlib>
35 #include <limits>
36 #include <memory_representation.h>
37 #include <vector>
38 #include <fcntl.h>
39
40 #include "JniConstants.h"
41 #include "ScopedLocalRef.h"
42 #include "arch/arm/quick_method_frame_info_arm.h"
43 #include "arch/arm/registers_arm.h"
44 #include "arch/arm64/quick_method_frame_info_arm64.h"
45 #include "arch/arm64/registers_arm64.h"
46 #include "arch/instruction_set_features.h"
47 #include "arch/mips/quick_method_frame_info_mips.h"
48 #include "arch/mips/registers_mips.h"
49 #include "arch/mips64/quick_method_frame_info_mips64.h"
50 #include "arch/mips64/registers_mips64.h"
51 #include "arch/x86/quick_method_frame_info_x86.h"
52 #include "arch/x86/registers_x86.h"
53 #include "arch/x86_64/quick_method_frame_info_x86_64.h"
54 #include "arch/x86_64/registers_x86_64.h"
55 #include "art_field-inl.h"
56 #include "art_method-inl.h"
57 #include "asm_support.h"
58 #include "atomic.h"
59 #include "base/arena_allocator.h"
60 #include "base/dumpable.h"
61 #include "base/stl_util.h"
62 #include "base/systrace.h"
63 #include "base/unix_file/fd_file.h"
64 #include "class_linker-inl.h"
65 #include "compiler_callbacks.h"
66 #include "compiler_filter.h"
67 #include "debugger.h"
68 #include "elf_file.h"
69 #include "entrypoints/runtime_asm_entrypoints.h"
70 #include "experimental_flags.h"
71 #include "fault_handler.h"
72 #include "gc/accounting/card_table-inl.h"
73 #include "gc/heap.h"
74 #include "gc/space/image_space.h"
75 #include "gc/space/space-inl.h"
76 #include "handle_scope-inl.h"
77 #include "image-inl.h"
78 #include "instrumentation.h"
79 #include "intern_table.h"
80 #include "interpreter/interpreter.h"
81 #include "jit/jit.h"
82 #include "jni_internal.h"
83 #include "linear_alloc.h"
84 #include "lambda/box_table.h"
85 #include "mirror/array.h"
86 #include "mirror/class-inl.h"
87 #include "mirror/class_loader.h"
88 #include "mirror/field.h"
89 #include "mirror/method.h"
90 #include "mirror/stack_trace_element.h"
91 #include "mirror/throwable.h"
92 #include "monitor.h"
93 #include "native/dalvik_system_DexFile.h"
94 #include "native/dalvik_system_VMDebug.h"
95 #include "native/dalvik_system_VMRuntime.h"
96 #include "native/dalvik_system_VMStack.h"
97 #include "native/dalvik_system_ZygoteHooks.h"
98 #include "native/java_lang_Class.h"
99 #include "native/java_lang_DexCache.h"
100 #include "native/java_lang_Object.h"
101 #include "native/java_lang_String.h"
102 #include "native/java_lang_StringFactory.h"
103 #include "native/java_lang_System.h"
104 #include "native/java_lang_Thread.h"
105 #include "native/java_lang_Throwable.h"
106 #include "native/java_lang_VMClassLoader.h"
107 #include "native/java_lang_ref_FinalizerReference.h"
108 #include "native/java_lang_ref_Reference.h"
109 #include "native/java_lang_reflect_AbstractMethod.h"
110 #include "native/java_lang_reflect_Array.h"
111 #include "native/java_lang_reflect_Constructor.h"
112 #include "native/java_lang_reflect_Field.h"
113 #include "native/java_lang_reflect_Method.h"
114 #include "native/java_lang_reflect_Proxy.h"
115 #include "native/java_util_concurrent_atomic_AtomicLong.h"
116 #include "native/libcore_util_CharsetUtils.h"
117 #include "native/org_apache_harmony_dalvik_ddmc_DdmServer.h"
118 #include "native/org_apache_harmony_dalvik_ddmc_DdmVmInternal.h"
119 #include "native/sun_misc_Unsafe.h"
120 #include "native_bridge_art_interface.h"
121 #include "oat_file.h"
122 #include "oat_file_manager.h"
123 #include "os.h"
124 #include "parsed_options.h"
125 #include "profiler.h"
126 #include "jit/profile_saver.h"
127 #include "quick/quick_method_frame_info.h"
128 #include "reflection.h"
129 #include "runtime_options.h"
130 #include "ScopedLocalRef.h"
131 #include "scoped_thread_state_change.h"
132 #include "sigchain.h"
133 #include "signal_catcher.h"
134 #include "signal_set.h"
135 #include "thread.h"
136 #include "thread_list.h"
137 #include "trace.h"
138 #include "transaction.h"
139 #include "utils.h"
140 #include "verifier/method_verifier.h"
141 #include "well_known_classes.h"
142
143 namespace art {
144
145 // If a signal isn't handled properly, enable a handler that attempts to dump the Java stack.
146 static constexpr bool kEnableJavaStackTraceHandler = false;
147 // Tuned by compiling GmsCore under perf and measuring time spent in DescriptorEquals for class
148 // linking.
149 static constexpr double kLowMemoryMinLoadFactor = 0.5;
150 static constexpr double kLowMemoryMaxLoadFactor = 0.8;
151 static constexpr double kNormalMinLoadFactor = 0.4;
152 static constexpr double kNormalMaxLoadFactor = 0.7;
153 Runtime* Runtime::instance_ = nullptr;
154
155 struct TraceConfig {
156 Trace::TraceMode trace_mode;
157 Trace::TraceOutputMode trace_output_mode;
158 std::string trace_file;
159 size_t trace_file_size;
160 };
161
162 namespace {
163 #ifdef __APPLE__
GetEnviron()164 inline char** GetEnviron() {
165 // When Google Test is built as a framework on MacOS X, the environ variable
166 // is unavailable. Apple's documentation (man environ) recommends using
167 // _NSGetEnviron() instead.
168 return *_NSGetEnviron();
169 }
170 #else
171 // Some POSIX platforms expect you to declare environ. extern "C" makes
172 // it reside in the global namespace.
173 extern "C" char** environ;
174 inline char** GetEnviron() { return environ; }
175 #endif
176 } // namespace
177
Runtime()178 Runtime::Runtime()
179 : resolution_method_(nullptr),
180 imt_conflict_method_(nullptr),
181 imt_unimplemented_method_(nullptr),
182 instruction_set_(kNone),
183 compiler_callbacks_(nullptr),
184 is_zygote_(false),
185 must_relocate_(false),
186 is_concurrent_gc_enabled_(true),
187 is_explicit_gc_disabled_(false),
188 dex2oat_enabled_(true),
189 image_dex2oat_enabled_(true),
190 default_stack_size_(0),
191 heap_(nullptr),
192 max_spins_before_thin_lock_inflation_(Monitor::kDefaultMaxSpinsBeforeThinLockInflation),
193 monitor_list_(nullptr),
194 monitor_pool_(nullptr),
195 thread_list_(nullptr),
196 intern_table_(nullptr),
197 class_linker_(nullptr),
198 signal_catcher_(nullptr),
199 java_vm_(nullptr),
200 fault_message_lock_("Fault message lock"),
201 fault_message_(""),
202 threads_being_born_(0),
203 shutdown_cond_(new ConditionVariable("Runtime shutdown", *Locks::runtime_shutdown_lock_)),
204 shutting_down_(false),
205 shutting_down_started_(false),
206 started_(false),
207 finished_starting_(false),
208 vfprintf_(nullptr),
209 exit_(nullptr),
210 abort_(nullptr),
211 stats_enabled_(false),
212 is_running_on_memory_tool_(RUNNING_ON_MEMORY_TOOL),
213 instrumentation_(),
214 main_thread_group_(nullptr),
215 system_thread_group_(nullptr),
216 system_class_loader_(nullptr),
217 dump_gc_performance_on_shutdown_(false),
218 preinitialization_transaction_(nullptr),
219 verify_(verifier::VerifyMode::kNone),
220 allow_dex_file_fallback_(true),
221 target_sdk_version_(0),
222 implicit_null_checks_(false),
223 implicit_so_checks_(false),
224 implicit_suspend_checks_(false),
225 no_sig_chain_(false),
226 force_native_bridge_(false),
227 is_native_bridge_loaded_(false),
228 is_native_debuggable_(false),
229 zygote_max_failed_boots_(0),
230 experimental_flags_(ExperimentalFlags::kNone),
231 oat_file_manager_(nullptr),
232 is_low_memory_mode_(false),
233 safe_mode_(false),
234 dump_native_stack_on_sig_quit_(true),
235 pruned_dalvik_cache_(false),
236 // Initially assume we perceive jank in case the process state is never updated.
237 process_state_(kProcessStateJankPerceptible),
238 zygote_no_threads_(false) {
239 CheckAsmSupportOffsetsAndSizes();
240 std::fill(callee_save_methods_, callee_save_methods_ + arraysize(callee_save_methods_), 0u);
241 interpreter::CheckInterpreterAsmConstants();
242 }
243
~Runtime()244 Runtime::~Runtime() {
245 ScopedTrace trace("Runtime shutdown");
246 if (is_native_bridge_loaded_) {
247 UnloadNativeBridge();
248 }
249
250 if (dump_gc_performance_on_shutdown_) {
251 // This can't be called from the Heap destructor below because it
252 // could call RosAlloc::InspectAll() which needs the thread_list
253 // to be still alive.
254 heap_->DumpGcPerformanceInfo(LOG(INFO));
255 }
256
257 Thread* self = Thread::Current();
258 const bool attach_shutdown_thread = self == nullptr;
259 if (attach_shutdown_thread) {
260 CHECK(AttachCurrentThread("Shutdown thread", false, nullptr, false));
261 self = Thread::Current();
262 } else {
263 LOG(WARNING) << "Current thread not detached in Runtime shutdown";
264 }
265
266 {
267 ScopedTrace trace2("Wait for shutdown cond");
268 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
269 shutting_down_started_ = true;
270 while (threads_being_born_ > 0) {
271 shutdown_cond_->Wait(self);
272 }
273 shutting_down_ = true;
274 }
275 // Shutdown and wait for the daemons.
276 CHECK(self != nullptr);
277 if (IsFinishedStarting()) {
278 ScopedTrace trace2("Waiting for Daemons");
279 self->ClearException();
280 self->GetJniEnv()->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
281 WellKnownClasses::java_lang_Daemons_stop);
282 }
283
284 Trace::Shutdown();
285
286 if (attach_shutdown_thread) {
287 DetachCurrentThread();
288 self = nullptr;
289 }
290
291 // Make sure to let the GC complete if it is running.
292 heap_->WaitForGcToComplete(gc::kGcCauseBackground, self);
293 heap_->DeleteThreadPool();
294 if (jit_ != nullptr) {
295 ScopedTrace trace2("Delete jit");
296 VLOG(jit) << "Deleting jit thread pool";
297 // Delete thread pool before the thread list since we don't want to wait forever on the
298 // JIT compiler threads.
299 jit_->DeleteThreadPool();
300 // Similarly, stop the profile saver thread before deleting the thread list.
301 jit_->StopProfileSaver();
302 }
303
304 // Make sure our internal threads are dead before we start tearing down things they're using.
305 Dbg::StopJdwp();
306 delete signal_catcher_;
307
308 // Make sure all other non-daemon threads have terminated, and all daemon threads are suspended.
309 {
310 ScopedTrace trace2("Delete thread list");
311 delete thread_list_;
312 }
313 // Delete the JIT after thread list to ensure that there is no remaining threads which could be
314 // accessing the instrumentation when we delete it.
315 if (jit_ != nullptr) {
316 VLOG(jit) << "Deleting jit";
317 jit_.reset(nullptr);
318 }
319
320 // Shutdown the fault manager if it was initialized.
321 fault_manager.Shutdown();
322
323 ScopedTrace trace2("Delete state");
324 delete monitor_list_;
325 delete monitor_pool_;
326 delete class_linker_;
327 delete heap_;
328 delete intern_table_;
329 delete java_vm_;
330 delete oat_file_manager_;
331 Thread::Shutdown();
332 QuasiAtomic::Shutdown();
333 verifier::MethodVerifier::Shutdown();
334
335 // Destroy allocators before shutting down the MemMap because they may use it.
336 linear_alloc_.reset();
337 low_4gb_arena_pool_.reset();
338 arena_pool_.reset();
339 jit_arena_pool_.reset();
340 MemMap::Shutdown();
341
342 // TODO: acquire a static mutex on Runtime to avoid racing.
343 CHECK(instance_ == nullptr || instance_ == this);
344 instance_ = nullptr;
345 }
346
347 struct AbortState {
Dumpart::AbortState348 void Dump(std::ostream& os) const {
349 if (gAborting > 1) {
350 os << "Runtime aborting --- recursively, so no thread-specific detail!\n";
351 return;
352 }
353 gAborting++;
354 os << "Runtime aborting...\n";
355 if (Runtime::Current() == nullptr) {
356 os << "(Runtime does not yet exist!)\n";
357 DumpNativeStack(os, GetTid(), nullptr, " native: ", nullptr);
358 return;
359 }
360 Thread* self = Thread::Current();
361 if (self == nullptr) {
362 os << "(Aborting thread was not attached to runtime!)\n";
363 DumpKernelStack(os, GetTid(), " kernel: ", false);
364 DumpNativeStack(os, GetTid(), nullptr, " native: ", nullptr);
365 } else {
366 os << "Aborting thread:\n";
367 if (Locks::mutator_lock_->IsExclusiveHeld(self) || Locks::mutator_lock_->IsSharedHeld(self)) {
368 DumpThread(os, self);
369 } else {
370 if (Locks::mutator_lock_->SharedTryLock(self)) {
371 DumpThread(os, self);
372 Locks::mutator_lock_->SharedUnlock(self);
373 }
374 }
375 }
376 DumpAllThreads(os, self);
377 }
378
379 // No thread-safety analysis as we do explicitly test for holding the mutator lock.
DumpThreadart::AbortState380 void DumpThread(std::ostream& os, Thread* self) const NO_THREAD_SAFETY_ANALYSIS {
381 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self) || Locks::mutator_lock_->IsSharedHeld(self));
382 self->Dump(os);
383 if (self->IsExceptionPending()) {
384 mirror::Throwable* exception = self->GetException();
385 os << "Pending exception " << exception->Dump();
386 }
387 }
388
DumpAllThreadsart::AbortState389 void DumpAllThreads(std::ostream& os, Thread* self) const {
390 Runtime* runtime = Runtime::Current();
391 if (runtime != nullptr) {
392 ThreadList* thread_list = runtime->GetThreadList();
393 if (thread_list != nullptr) {
394 bool tll_already_held = Locks::thread_list_lock_->IsExclusiveHeld(self);
395 bool ml_already_held = Locks::mutator_lock_->IsSharedHeld(self);
396 if (!tll_already_held || !ml_already_held) {
397 os << "Dumping all threads without appropriate locks held:"
398 << (!tll_already_held ? " thread list lock" : "")
399 << (!ml_already_held ? " mutator lock" : "")
400 << "\n";
401 }
402 os << "All threads:\n";
403 thread_list->Dump(os);
404 }
405 }
406 }
407 };
408
Abort(const char * msg)409 void Runtime::Abort(const char* msg) {
410 gAborting++; // set before taking any locks
411
412 // Ensure that we don't have multiple threads trying to abort at once,
413 // which would result in significantly worse diagnostics.
414 MutexLock mu(Thread::Current(), *Locks::abort_lock_);
415
416 // Get any pending output out of the way.
417 fflush(nullptr);
418
419 // Many people have difficulty distinguish aborts from crashes,
420 // so be explicit.
421 AbortState state;
422 LOG(INTERNAL_FATAL) << Dumpable<AbortState>(state);
423
424 // Sometimes we dump long messages, and the Android abort message only retains the first line.
425 // In those cases, just log the message again, to avoid logcat limits.
426 if (msg != nullptr && strchr(msg, '\n') != nullptr) {
427 LOG(INTERNAL_FATAL) << msg;
428 }
429
430 // Call the abort hook if we have one.
431 if (Runtime::Current() != nullptr && Runtime::Current()->abort_ != nullptr) {
432 LOG(INTERNAL_FATAL) << "Calling abort hook...";
433 Runtime::Current()->abort_();
434 // notreached
435 LOG(INTERNAL_FATAL) << "Unexpectedly returned from abort hook!";
436 }
437
438 #if defined(__GLIBC__)
439 // TODO: we ought to be able to use pthread_kill(3) here (or abort(3),
440 // which POSIX defines in terms of raise(3), which POSIX defines in terms
441 // of pthread_kill(3)). On Linux, though, libcorkscrew can't unwind through
442 // libpthread, which means the stacks we dump would be useless. Calling
443 // tgkill(2) directly avoids that.
444 syscall(__NR_tgkill, getpid(), GetTid(), SIGABRT);
445 // TODO: LLVM installs it's own SIGABRT handler so exit to be safe... Can we disable that in LLVM?
446 // If not, we could use sigaction(3) before calling tgkill(2) and lose this call to exit(3).
447 exit(1);
448 #else
449 abort();
450 #endif
451 // notreached
452 }
453
PreZygoteFork()454 void Runtime::PreZygoteFork() {
455 heap_->PreZygoteFork();
456 }
457
CallExitHook(jint status)458 void Runtime::CallExitHook(jint status) {
459 if (exit_ != nullptr) {
460 ScopedThreadStateChange tsc(Thread::Current(), kNative);
461 exit_(status);
462 LOG(WARNING) << "Exit hook returned instead of exiting!";
463 }
464 }
465
SweepSystemWeaks(IsMarkedVisitor * visitor)466 void Runtime::SweepSystemWeaks(IsMarkedVisitor* visitor) {
467 GetInternTable()->SweepInternTableWeaks(visitor);
468 GetMonitorList()->SweepMonitorList(visitor);
469 GetJavaVM()->SweepJniWeakGlobals(visitor);
470 GetHeap()->SweepAllocationRecords(visitor);
471 GetLambdaBoxTable()->SweepWeakBoxedLambdas(visitor);
472 }
473
ParseOptions(const RuntimeOptions & raw_options,bool ignore_unrecognized,RuntimeArgumentMap * runtime_options)474 bool Runtime::ParseOptions(const RuntimeOptions& raw_options,
475 bool ignore_unrecognized,
476 RuntimeArgumentMap* runtime_options) {
477 InitLogging(/* argv */ nullptr); // Calls Locks::Init() as a side effect.
478 bool parsed = ParsedOptions::Parse(raw_options, ignore_unrecognized, runtime_options);
479 if (!parsed) {
480 LOG(ERROR) << "Failed to parse options";
481 return false;
482 }
483 return true;
484 }
485
Create(RuntimeArgumentMap && runtime_options)486 bool Runtime::Create(RuntimeArgumentMap&& runtime_options) {
487 // TODO: acquire a static mutex on Runtime to avoid racing.
488 if (Runtime::instance_ != nullptr) {
489 return false;
490 }
491 instance_ = new Runtime;
492 if (!instance_->Init(std::move(runtime_options))) {
493 // TODO: Currently deleting the instance will abort the runtime on destruction. Now This will
494 // leak memory, instead. Fix the destructor. b/19100793.
495 // delete instance_;
496 instance_ = nullptr;
497 return false;
498 }
499 return true;
500 }
501
Create(const RuntimeOptions & raw_options,bool ignore_unrecognized)502 bool Runtime::Create(const RuntimeOptions& raw_options, bool ignore_unrecognized) {
503 RuntimeArgumentMap runtime_options;
504 return ParseOptions(raw_options, ignore_unrecognized, &runtime_options) &&
505 Create(std::move(runtime_options));
506 }
507
CreateSystemClassLoader(Runtime * runtime)508 static jobject CreateSystemClassLoader(Runtime* runtime) {
509 if (runtime->IsAotCompiler() && !runtime->GetCompilerCallbacks()->IsBootImage()) {
510 return nullptr;
511 }
512
513 ScopedObjectAccess soa(Thread::Current());
514 ClassLinker* cl = Runtime::Current()->GetClassLinker();
515 auto pointer_size = cl->GetImagePointerSize();
516
517 StackHandleScope<2> hs(soa.Self());
518 Handle<mirror::Class> class_loader_class(
519 hs.NewHandle(soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ClassLoader)));
520 CHECK(cl->EnsureInitialized(soa.Self(), class_loader_class, true, true));
521
522 ArtMethod* getSystemClassLoader = class_loader_class->FindDirectMethod(
523 "getSystemClassLoader", "()Ljava/lang/ClassLoader;", pointer_size);
524 CHECK(getSystemClassLoader != nullptr);
525
526 JValue result = InvokeWithJValues(soa, nullptr, soa.EncodeMethod(getSystemClassLoader), nullptr);
527 JNIEnv* env = soa.Self()->GetJniEnv();
528 ScopedLocalRef<jobject> system_class_loader(env, soa.AddLocalReference<jobject>(result.GetL()));
529 CHECK(system_class_loader.get() != nullptr);
530
531 soa.Self()->SetClassLoaderOverride(system_class_loader.get());
532
533 Handle<mirror::Class> thread_class(
534 hs.NewHandle(soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread)));
535 CHECK(cl->EnsureInitialized(soa.Self(), thread_class, true, true));
536
537 ArtField* contextClassLoader =
538 thread_class->FindDeclaredInstanceField("contextClassLoader", "Ljava/lang/ClassLoader;");
539 CHECK(contextClassLoader != nullptr);
540
541 // We can't run in a transaction yet.
542 contextClassLoader->SetObject<false>(soa.Self()->GetPeer(),
543 soa.Decode<mirror::ClassLoader*>(system_class_loader.get()));
544
545 return env->NewGlobalRef(system_class_loader.get());
546 }
547
GetPatchoatExecutable() const548 std::string Runtime::GetPatchoatExecutable() const {
549 if (!patchoat_executable_.empty()) {
550 return patchoat_executable_;
551 }
552 std::string patchoat_executable(GetAndroidRoot());
553 patchoat_executable += (kIsDebugBuild ? "/bin/patchoatd" : "/bin/patchoat");
554 return patchoat_executable;
555 }
556
GetCompilerExecutable() const557 std::string Runtime::GetCompilerExecutable() const {
558 if (!compiler_executable_.empty()) {
559 return compiler_executable_;
560 }
561 std::string compiler_executable(GetAndroidRoot());
562 compiler_executable += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat");
563 return compiler_executable;
564 }
565
Start()566 bool Runtime::Start() {
567 VLOG(startup) << "Runtime::Start entering";
568
569 CHECK(!no_sig_chain_) << "A started runtime should have sig chain enabled";
570
571 // If a debug host build, disable ptrace restriction for debugging and test timeout thread dump.
572 // Only 64-bit as prctl() may fail in 32 bit userspace on a 64-bit kernel.
573 #if defined(__linux__) && !defined(__ANDROID__) && defined(__x86_64__)
574 if (kIsDebugBuild) {
575 CHECK_EQ(prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY), 0);
576 }
577 #endif
578
579 // Restore main thread state to kNative as expected by native code.
580 Thread* self = Thread::Current();
581
582 self->TransitionFromRunnableToSuspended(kNative);
583
584 started_ = true;
585
586 if (!IsImageDex2OatEnabled() || !GetHeap()->HasBootImageSpace()) {
587 ScopedObjectAccess soa(self);
588 StackHandleScope<2> hs(soa.Self());
589
590 auto class_class(hs.NewHandle<mirror::Class>(mirror::Class::GetJavaLangClass()));
591 auto field_class(hs.NewHandle<mirror::Class>(mirror::Field::StaticClass()));
592
593 class_linker_->EnsureInitialized(soa.Self(), class_class, true, true);
594 // Field class is needed for register_java_net_InetAddress in libcore, b/28153851.
595 class_linker_->EnsureInitialized(soa.Self(), field_class, true, true);
596 }
597
598 // InitNativeMethods needs to be after started_ so that the classes
599 // it touches will have methods linked to the oat file if necessary.
600 {
601 ScopedTrace trace2("InitNativeMethods");
602 InitNativeMethods();
603 }
604
605 // Initialize well known thread group values that may be accessed threads while attaching.
606 InitThreadGroups(self);
607
608 Thread::FinishStartup();
609
610 // Create the JIT either if we have to use JIT compilation or save profiling info. This is
611 // done after FinishStartup as the JIT pool needs Java thread peers, which require the main
612 // ThreadGroup to exist.
613 //
614 // TODO(calin): We use the JIT class as a proxy for JIT compilation and for
615 // recoding profiles. Maybe we should consider changing the name to be more clear it's
616 // not only about compiling. b/28295073.
617 if (jit_options_->UseJitCompilation() || jit_options_->GetSaveProfilingInfo()) {
618 std::string error_msg;
619 if (!IsZygote()) {
620 // If we are the zygote then we need to wait until after forking to create the code cache
621 // due to SELinux restrictions on r/w/x memory regions.
622 CreateJit();
623 } else if (jit_options_->UseJitCompilation()) {
624 if (!jit::Jit::LoadCompilerLibrary(&error_msg)) {
625 // Try to load compiler pre zygote to reduce PSS. b/27744947
626 LOG(WARNING) << "Failed to load JIT compiler with error " << error_msg;
627 }
628 }
629 }
630
631 system_class_loader_ = CreateSystemClassLoader(this);
632
633 if (is_zygote_) {
634 if (!InitZygote()) {
635 return false;
636 }
637 } else {
638 if (is_native_bridge_loaded_) {
639 PreInitializeNativeBridge(".");
640 }
641 NativeBridgeAction action = force_native_bridge_
642 ? NativeBridgeAction::kInitialize
643 : NativeBridgeAction::kUnload;
644 InitNonZygoteOrPostFork(self->GetJniEnv(),
645 /* is_system_server */ false,
646 action,
647 GetInstructionSetString(kRuntimeISA));
648 }
649
650 StartDaemonThreads();
651
652 {
653 ScopedObjectAccess soa(self);
654 self->GetJniEnv()->locals.AssertEmpty();
655 }
656
657 VLOG(startup) << "Runtime::Start exiting";
658 finished_starting_ = true;
659
660 if (profiler_options_.IsEnabled() && !profile_output_filename_.empty()) {
661 // User has asked for a profile using -Xenable-profiler.
662 // Create the profile file if it doesn't exist.
663 int fd = open(profile_output_filename_.c_str(), O_RDWR|O_CREAT|O_EXCL, 0660);
664 if (fd >= 0) {
665 close(fd);
666 } else if (errno != EEXIST) {
667 LOG(WARNING) << "Failed to access the profile file. Profiler disabled.";
668 }
669 }
670
671 if (trace_config_.get() != nullptr && trace_config_->trace_file != "") {
672 ScopedThreadStateChange tsc(self, kWaitingForMethodTracingStart);
673 Trace::Start(trace_config_->trace_file.c_str(),
674 -1,
675 static_cast<int>(trace_config_->trace_file_size),
676 0,
677 trace_config_->trace_output_mode,
678 trace_config_->trace_mode,
679 0);
680 }
681
682 return true;
683 }
684
EndThreadBirth()685 void Runtime::EndThreadBirth() REQUIRES(Locks::runtime_shutdown_lock_) {
686 DCHECK_GT(threads_being_born_, 0U);
687 threads_being_born_--;
688 if (shutting_down_started_ && threads_being_born_ == 0) {
689 shutdown_cond_->Broadcast(Thread::Current());
690 }
691 }
692
693 // Do zygote-mode-only initialization.
InitZygote()694 bool Runtime::InitZygote() {
695 #ifdef __linux__
696 // zygote goes into its own process group
697 setpgid(0, 0);
698
699 // See storage config details at http://source.android.com/tech/storage/
700 // Create private mount namespace shared by all children
701 if (unshare(CLONE_NEWNS) == -1) {
702 PLOG(ERROR) << "Failed to unshare()";
703 return false;
704 }
705
706 // Mark rootfs as being a slave so that changes from default
707 // namespace only flow into our children.
708 if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
709 PLOG(ERROR) << "Failed to mount() rootfs as MS_SLAVE";
710 return false;
711 }
712
713 // Create a staging tmpfs that is shared by our children; they will
714 // bind mount storage into their respective private namespaces, which
715 // are isolated from each other.
716 const char* target_base = getenv("EMULATED_STORAGE_TARGET");
717 if (target_base != nullptr) {
718 if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
719 "uid=0,gid=1028,mode=0751") == -1) {
720 PLOG(ERROR) << "Failed to mount tmpfs to " << target_base;
721 return false;
722 }
723 }
724
725 return true;
726 #else
727 UNIMPLEMENTED(FATAL);
728 return false;
729 #endif
730 }
731
InitNonZygoteOrPostFork(JNIEnv * env,bool is_system_server,NativeBridgeAction action,const char * isa)732 void Runtime::InitNonZygoteOrPostFork(
733 JNIEnv* env, bool is_system_server, NativeBridgeAction action, const char* isa) {
734 is_zygote_ = false;
735
736 if (is_native_bridge_loaded_) {
737 switch (action) {
738 case NativeBridgeAction::kUnload:
739 UnloadNativeBridge();
740 is_native_bridge_loaded_ = false;
741 break;
742
743 case NativeBridgeAction::kInitialize:
744 InitializeNativeBridge(env, isa);
745 break;
746 }
747 }
748
749 // Create the thread pools.
750 heap_->CreateThreadPool();
751 // Reset the gc performance data at zygote fork so that the GCs
752 // before fork aren't attributed to an app.
753 heap_->ResetGcPerformanceInfo();
754
755
756 if (!is_system_server &&
757 !safe_mode_ &&
758 (jit_options_->UseJitCompilation() || jit_options_->GetSaveProfilingInfo()) &&
759 jit_.get() == nullptr) {
760 // Note that when running ART standalone (not zygote, nor zygote fork),
761 // the jit may have already been created.
762 CreateJit();
763 }
764
765 StartSignalCatcher();
766
767 // Start the JDWP thread. If the command-line debugger flags specified "suspend=y",
768 // this will pause the runtime, so we probably want this to come last.
769 Dbg::StartJdwp();
770 }
771
StartSignalCatcher()772 void Runtime::StartSignalCatcher() {
773 if (!is_zygote_) {
774 signal_catcher_ = new SignalCatcher(stack_trace_file_);
775 }
776 }
777
IsShuttingDown(Thread * self)778 bool Runtime::IsShuttingDown(Thread* self) {
779 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
780 return IsShuttingDownLocked();
781 }
782
IsDebuggable() const783 bool Runtime::IsDebuggable() const {
784 const OatFile* oat_file = GetOatFileManager().GetPrimaryOatFile();
785 return oat_file != nullptr && oat_file->IsDebuggable();
786 }
787
StartDaemonThreads()788 void Runtime::StartDaemonThreads() {
789 ScopedTrace trace(__FUNCTION__);
790 VLOG(startup) << "Runtime::StartDaemonThreads entering";
791
792 Thread* self = Thread::Current();
793
794 // Must be in the kNative state for calling native methods.
795 CHECK_EQ(self->GetState(), kNative);
796
797 JNIEnv* env = self->GetJniEnv();
798 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
799 WellKnownClasses::java_lang_Daemons_start);
800 if (env->ExceptionCheck()) {
801 env->ExceptionDescribe();
802 LOG(FATAL) << "Error starting java.lang.Daemons";
803 }
804
805 VLOG(startup) << "Runtime::StartDaemonThreads exiting";
806 }
807
808 // Attempts to open dex files from image(s). Given the image location, try to find the oat file
809 // and open it to get the stored dex file. If the image is the first for a multi-image boot
810 // classpath, go on and also open the other images.
OpenDexFilesFromImage(const std::string & image_location,std::vector<std::unique_ptr<const DexFile>> * dex_files,size_t * failures)811 static bool OpenDexFilesFromImage(const std::string& image_location,
812 std::vector<std::unique_ptr<const DexFile>>* dex_files,
813 size_t* failures) {
814 DCHECK(dex_files != nullptr) << "OpenDexFilesFromImage: out-param is nullptr";
815
816 // Use a work-list approach, so that we can easily reuse the opening code.
817 std::vector<std::string> image_locations;
818 image_locations.push_back(image_location);
819
820 for (size_t index = 0; index < image_locations.size(); ++index) {
821 std::string system_filename;
822 bool has_system = false;
823 std::string cache_filename_unused;
824 bool dalvik_cache_exists_unused;
825 bool has_cache_unused;
826 bool is_global_cache_unused;
827 bool found_image = gc::space::ImageSpace::FindImageFilename(image_locations[index].c_str(),
828 kRuntimeISA,
829 &system_filename,
830 &has_system,
831 &cache_filename_unused,
832 &dalvik_cache_exists_unused,
833 &has_cache_unused,
834 &is_global_cache_unused);
835
836 if (!found_image || !has_system) {
837 return false;
838 }
839
840 // We are falling back to non-executable use of the oat file because patching failed, presumably
841 // due to lack of space.
842 std::string oat_filename =
843 ImageHeader::GetOatLocationFromImageLocation(system_filename.c_str());
844 std::string oat_location =
845 ImageHeader::GetOatLocationFromImageLocation(image_locations[index].c_str());
846 // Note: in the multi-image case, the image location may end in ".jar," and not ".art." Handle
847 // that here.
848 if (EndsWith(oat_location, ".jar")) {
849 oat_location.replace(oat_location.length() - 3, 3, "oat");
850 }
851
852 std::unique_ptr<File> file(OS::OpenFileForReading(oat_filename.c_str()));
853 if (file.get() == nullptr) {
854 return false;
855 }
856 std::string error_msg;
857 std::unique_ptr<ElfFile> elf_file(ElfFile::Open(file.get(),
858 false,
859 false,
860 /*low_4gb*/false,
861 &error_msg));
862 if (elf_file.get() == nullptr) {
863 return false;
864 }
865 std::unique_ptr<const OatFile> oat_file(
866 OatFile::OpenWithElfFile(elf_file.release(), oat_location, nullptr, &error_msg));
867 if (oat_file == nullptr) {
868 LOG(WARNING) << "Unable to use '" << oat_filename << "' because " << error_msg;
869 return false;
870 }
871
872 for (const OatFile::OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) {
873 if (oat_dex_file == nullptr) {
874 *failures += 1;
875 continue;
876 }
877 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
878 if (dex_file.get() == nullptr) {
879 *failures += 1;
880 } else {
881 dex_files->push_back(std::move(dex_file));
882 }
883 }
884
885 if (index == 0) {
886 // First file. See if this is a multi-image environment, and if so, enqueue the other images.
887 const OatHeader& boot_oat_header = oat_file->GetOatHeader();
888 const char* boot_cp = boot_oat_header.GetStoreValueByKey(OatHeader::kBootClassPathKey);
889 if (boot_cp != nullptr) {
890 gc::space::ImageSpace::ExtractMultiImageLocations(image_locations[0],
891 boot_cp,
892 &image_locations);
893 }
894 }
895
896 Runtime::Current()->GetOatFileManager().RegisterOatFile(std::move(oat_file));
897 }
898 return true;
899 }
900
901
OpenDexFiles(const std::vector<std::string> & dex_filenames,const std::vector<std::string> & dex_locations,const std::string & image_location,std::vector<std::unique_ptr<const DexFile>> * dex_files)902 static size_t OpenDexFiles(const std::vector<std::string>& dex_filenames,
903 const std::vector<std::string>& dex_locations,
904 const std::string& image_location,
905 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
906 DCHECK(dex_files != nullptr) << "OpenDexFiles: out-param is nullptr";
907 size_t failure_count = 0;
908 if (!image_location.empty() && OpenDexFilesFromImage(image_location, dex_files, &failure_count)) {
909 return failure_count;
910 }
911 failure_count = 0;
912 for (size_t i = 0; i < dex_filenames.size(); i++) {
913 const char* dex_filename = dex_filenames[i].c_str();
914 const char* dex_location = dex_locations[i].c_str();
915 std::string error_msg;
916 if (!OS::FileExists(dex_filename)) {
917 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
918 continue;
919 }
920 if (!DexFile::Open(dex_filename, dex_location, &error_msg, dex_files)) {
921 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
922 ++failure_count;
923 }
924 }
925 return failure_count;
926 }
927
SetSentinel(mirror::Object * sentinel)928 void Runtime::SetSentinel(mirror::Object* sentinel) {
929 CHECK(sentinel_.Read() == nullptr);
930 CHECK(sentinel != nullptr);
931 CHECK(!heap_->IsMovableObject(sentinel));
932 sentinel_ = GcRoot<mirror::Object>(sentinel);
933 }
934
Init(RuntimeArgumentMap && runtime_options_in)935 bool Runtime::Init(RuntimeArgumentMap&& runtime_options_in) {
936 // (b/30160149): protect subprocesses from modifications to LD_LIBRARY_PATH, etc.
937 // Take a snapshot of the environment at the time the runtime was created, for use by Exec, etc.
938 env_snapshot_.TakeSnapshot();
939
940 RuntimeArgumentMap runtime_options(std::move(runtime_options_in));
941 ScopedTrace trace(__FUNCTION__);
942 CHECK_EQ(sysconf(_SC_PAGE_SIZE), kPageSize);
943
944 MemMap::Init();
945
946 using Opt = RuntimeArgumentMap;
947 VLOG(startup) << "Runtime::Init -verbose:startup enabled";
948
949 QuasiAtomic::Startup();
950
951 oat_file_manager_ = new OatFileManager;
952
953 Thread::SetSensitiveThreadHook(runtime_options.GetOrDefault(Opt::HookIsSensitiveThread));
954 Monitor::Init(runtime_options.GetOrDefault(Opt::LockProfThreshold));
955
956 boot_class_path_string_ = runtime_options.ReleaseOrDefault(Opt::BootClassPath);
957 class_path_string_ = runtime_options.ReleaseOrDefault(Opt::ClassPath);
958 properties_ = runtime_options.ReleaseOrDefault(Opt::PropertiesList);
959
960 compiler_callbacks_ = runtime_options.GetOrDefault(Opt::CompilerCallbacksPtr);
961 patchoat_executable_ = runtime_options.ReleaseOrDefault(Opt::PatchOat);
962 must_relocate_ = runtime_options.GetOrDefault(Opt::Relocate);
963 is_zygote_ = runtime_options.Exists(Opt::Zygote);
964 is_explicit_gc_disabled_ = runtime_options.Exists(Opt::DisableExplicitGC);
965 dex2oat_enabled_ = runtime_options.GetOrDefault(Opt::Dex2Oat);
966 image_dex2oat_enabled_ = runtime_options.GetOrDefault(Opt::ImageDex2Oat);
967 dump_native_stack_on_sig_quit_ = runtime_options.GetOrDefault(Opt::DumpNativeStackOnSigQuit);
968
969 vfprintf_ = runtime_options.GetOrDefault(Opt::HookVfprintf);
970 exit_ = runtime_options.GetOrDefault(Opt::HookExit);
971 abort_ = runtime_options.GetOrDefault(Opt::HookAbort);
972
973 default_stack_size_ = runtime_options.GetOrDefault(Opt::StackSize);
974 stack_trace_file_ = runtime_options.ReleaseOrDefault(Opt::StackTraceFile);
975
976 compiler_executable_ = runtime_options.ReleaseOrDefault(Opt::Compiler);
977 compiler_options_ = runtime_options.ReleaseOrDefault(Opt::CompilerOptions);
978 image_compiler_options_ = runtime_options.ReleaseOrDefault(Opt::ImageCompilerOptions);
979 image_location_ = runtime_options.GetOrDefault(Opt::Image);
980
981 max_spins_before_thin_lock_inflation_ =
982 runtime_options.GetOrDefault(Opt::MaxSpinsBeforeThinLockInflation);
983
984 monitor_list_ = new MonitorList;
985 monitor_pool_ = MonitorPool::Create();
986 thread_list_ = new ThreadList;
987 intern_table_ = new InternTable;
988
989 verify_ = runtime_options.GetOrDefault(Opt::Verify);
990 allow_dex_file_fallback_ = !runtime_options.Exists(Opt::NoDexFileFallback);
991
992 no_sig_chain_ = runtime_options.Exists(Opt::NoSigChain);
993 force_native_bridge_ = runtime_options.Exists(Opt::ForceNativeBridge);
994
995 Split(runtime_options.GetOrDefault(Opt::CpuAbiList), ',', &cpu_abilist_);
996
997 fingerprint_ = runtime_options.ReleaseOrDefault(Opt::Fingerprint);
998
999 if (runtime_options.GetOrDefault(Opt::Interpret)) {
1000 GetInstrumentation()->ForceInterpretOnly();
1001 }
1002
1003 zygote_max_failed_boots_ = runtime_options.GetOrDefault(Opt::ZygoteMaxFailedBoots);
1004 experimental_flags_ = runtime_options.GetOrDefault(Opt::Experimental);
1005 is_low_memory_mode_ = runtime_options.Exists(Opt::LowMemoryMode);
1006
1007 {
1008 CompilerFilter::Filter filter;
1009 std::string filter_str = runtime_options.GetOrDefault(Opt::OatFileManagerCompilerFilter);
1010 if (!CompilerFilter::ParseCompilerFilter(filter_str.c_str(), &filter)) {
1011 LOG(ERROR) << "Cannot parse compiler filter " << filter_str;
1012 return false;
1013 }
1014 OatFileManager::SetCompilerFilter(filter);
1015 }
1016
1017 XGcOption xgc_option = runtime_options.GetOrDefault(Opt::GcOption);
1018 heap_ = new gc::Heap(runtime_options.GetOrDefault(Opt::MemoryInitialSize),
1019 runtime_options.GetOrDefault(Opt::HeapGrowthLimit),
1020 runtime_options.GetOrDefault(Opt::HeapMinFree),
1021 runtime_options.GetOrDefault(Opt::HeapMaxFree),
1022 runtime_options.GetOrDefault(Opt::HeapTargetUtilization),
1023 runtime_options.GetOrDefault(Opt::ForegroundHeapGrowthMultiplier),
1024 runtime_options.GetOrDefault(Opt::MemoryMaximumSize),
1025 runtime_options.GetOrDefault(Opt::NonMovingSpaceCapacity),
1026 runtime_options.GetOrDefault(Opt::Image),
1027 runtime_options.GetOrDefault(Opt::ImageInstructionSet),
1028 xgc_option.collector_type_,
1029 runtime_options.GetOrDefault(Opt::BackgroundGc),
1030 runtime_options.GetOrDefault(Opt::LargeObjectSpace),
1031 runtime_options.GetOrDefault(Opt::LargeObjectThreshold),
1032 runtime_options.GetOrDefault(Opt::ParallelGCThreads),
1033 runtime_options.GetOrDefault(Opt::ConcGCThreads),
1034 runtime_options.Exists(Opt::LowMemoryMode),
1035 runtime_options.GetOrDefault(Opt::LongPauseLogThreshold),
1036 runtime_options.GetOrDefault(Opt::LongGCLogThreshold),
1037 runtime_options.Exists(Opt::IgnoreMaxFootprint),
1038 runtime_options.GetOrDefault(Opt::UseTLAB),
1039 xgc_option.verify_pre_gc_heap_,
1040 xgc_option.verify_pre_sweeping_heap_,
1041 xgc_option.verify_post_gc_heap_,
1042 xgc_option.verify_pre_gc_rosalloc_,
1043 xgc_option.verify_pre_sweeping_rosalloc_,
1044 xgc_option.verify_post_gc_rosalloc_,
1045 xgc_option.gcstress_,
1046 runtime_options.GetOrDefault(Opt::EnableHSpaceCompactForOOM),
1047 runtime_options.GetOrDefault(Opt::HSpaceCompactForOOMMinIntervalsMs));
1048
1049 if (!heap_->HasBootImageSpace() && !allow_dex_file_fallback_) {
1050 LOG(ERROR) << "Dex file fallback disabled, cannot continue without image.";
1051 return false;
1052 }
1053
1054 dump_gc_performance_on_shutdown_ = runtime_options.Exists(Opt::DumpGCPerformanceOnShutdown);
1055
1056 if (runtime_options.Exists(Opt::JdwpOptions)) {
1057 Dbg::ConfigureJdwp(runtime_options.GetOrDefault(Opt::JdwpOptions));
1058 }
1059
1060 jit_options_.reset(jit::JitOptions::CreateFromRuntimeArguments(runtime_options));
1061 if (IsAotCompiler()) {
1062 // If we are already the compiler at this point, we must be dex2oat. Don't create the jit in
1063 // this case.
1064 // If runtime_options doesn't have UseJIT set to true then CreateFromRuntimeArguments returns
1065 // null and we don't create the jit.
1066 jit_options_->SetUseJitCompilation(false);
1067 jit_options_->SetSaveProfilingInfo(false);
1068 }
1069
1070 // Allocate a global table of boxed lambda objects <-> closures.
1071 lambda_box_table_ = MakeUnique<lambda::BoxTable>();
1072
1073 // Use MemMap arena pool for jit, malloc otherwise. Malloc arenas are faster to allocate but
1074 // can't be trimmed as easily.
1075 const bool use_malloc = IsAotCompiler();
1076 arena_pool_.reset(new ArenaPool(use_malloc, /* low_4gb */ false));
1077 jit_arena_pool_.reset(
1078 new ArenaPool(/* use_malloc */ false, /* low_4gb */ false, "CompilerMetadata"));
1079
1080 if (IsAotCompiler() && Is64BitInstructionSet(kRuntimeISA)) {
1081 // 4gb, no malloc. Explanation in header.
1082 low_4gb_arena_pool_.reset(new ArenaPool(/* use_malloc */ false, /* low_4gb */ true));
1083 }
1084 linear_alloc_.reset(CreateLinearAlloc());
1085
1086 BlockSignals();
1087 InitPlatformSignalHandlers();
1088
1089 // Change the implicit checks flags based on runtime architecture.
1090 switch (kRuntimeISA) {
1091 case kArm:
1092 case kThumb2:
1093 case kX86:
1094 case kArm64:
1095 case kX86_64:
1096 case kMips:
1097 case kMips64:
1098 implicit_null_checks_ = true;
1099 // Installing stack protection does not play well with valgrind.
1100 implicit_so_checks_ = !(RUNNING_ON_MEMORY_TOOL && kMemoryToolIsValgrind);
1101 break;
1102 default:
1103 // Keep the defaults.
1104 break;
1105 }
1106
1107 if (!no_sig_chain_) {
1108 // Dex2Oat's Runtime does not need the signal chain or the fault handler.
1109
1110 // Initialize the signal chain so that any calls to sigaction get
1111 // correctly routed to the next in the chain regardless of whether we
1112 // have claimed the signal or not.
1113 InitializeSignalChain();
1114
1115 if (implicit_null_checks_ || implicit_so_checks_ || implicit_suspend_checks_) {
1116 fault_manager.Init();
1117
1118 // These need to be in a specific order. The null point check handler must be
1119 // after the suspend check and stack overflow check handlers.
1120 //
1121 // Note: the instances attach themselves to the fault manager and are handled by it. The manager
1122 // will delete the instance on Shutdown().
1123 if (implicit_suspend_checks_) {
1124 new SuspensionHandler(&fault_manager);
1125 }
1126
1127 if (implicit_so_checks_) {
1128 new StackOverflowHandler(&fault_manager);
1129 }
1130
1131 if (implicit_null_checks_) {
1132 new NullPointerHandler(&fault_manager);
1133 }
1134
1135 if (kEnableJavaStackTraceHandler) {
1136 new JavaStackTraceHandler(&fault_manager);
1137 }
1138 }
1139 }
1140
1141 java_vm_ = new JavaVMExt(this, runtime_options);
1142
1143 Thread::Startup();
1144
1145 // ClassLinker needs an attached thread, but we can't fully attach a thread without creating
1146 // objects. We can't supply a thread group yet; it will be fixed later. Since we are the main
1147 // thread, we do not get a java peer.
1148 Thread* self = Thread::Attach("main", false, nullptr, false);
1149 CHECK_EQ(self->GetThreadId(), ThreadList::kMainThreadId);
1150 CHECK(self != nullptr);
1151
1152 self->SetCanCallIntoJava(!IsAotCompiler());
1153
1154 // Set us to runnable so tools using a runtime can allocate and GC by default
1155 self->TransitionFromSuspendedToRunnable();
1156
1157 // Now we're attached, we can take the heap locks and validate the heap.
1158 GetHeap()->EnableObjectValidation();
1159
1160 CHECK_GE(GetHeap()->GetContinuousSpaces().size(), 1U);
1161 class_linker_ = new ClassLinker(intern_table_);
1162 if (GetHeap()->HasBootImageSpace()) {
1163 std::string error_msg;
1164 bool result = class_linker_->InitFromBootImage(&error_msg);
1165 if (!result) {
1166 LOG(ERROR) << "Could not initialize from image: " << error_msg;
1167 return false;
1168 }
1169 if (kIsDebugBuild) {
1170 for (auto image_space : GetHeap()->GetBootImageSpaces()) {
1171 image_space->VerifyImageAllocations();
1172 }
1173 }
1174 if (boot_class_path_string_.empty()) {
1175 // The bootclasspath is not explicitly specified: construct it from the loaded dex files.
1176 const std::vector<const DexFile*>& boot_class_path = GetClassLinker()->GetBootClassPath();
1177 std::vector<std::string> dex_locations;
1178 dex_locations.reserve(boot_class_path.size());
1179 for (const DexFile* dex_file : boot_class_path) {
1180 dex_locations.push_back(dex_file->GetLocation());
1181 }
1182 boot_class_path_string_ = Join(dex_locations, ':');
1183 }
1184 {
1185 ScopedTrace trace2("AddImageStringsToTable");
1186 GetInternTable()->AddImagesStringsToTable(heap_->GetBootImageSpaces());
1187 }
1188 {
1189 ScopedTrace trace2("MoveImageClassesToClassTable");
1190 GetClassLinker()->AddBootImageClassesToClassTable();
1191 }
1192 } else {
1193 std::vector<std::string> dex_filenames;
1194 Split(boot_class_path_string_, ':', &dex_filenames);
1195
1196 std::vector<std::string> dex_locations;
1197 if (!runtime_options.Exists(Opt::BootClassPathLocations)) {
1198 dex_locations = dex_filenames;
1199 } else {
1200 dex_locations = runtime_options.GetOrDefault(Opt::BootClassPathLocations);
1201 CHECK_EQ(dex_filenames.size(), dex_locations.size());
1202 }
1203
1204 std::vector<std::unique_ptr<const DexFile>> boot_class_path;
1205 if (runtime_options.Exists(Opt::BootClassPathDexList)) {
1206 boot_class_path.swap(*runtime_options.GetOrDefault(Opt::BootClassPathDexList));
1207 } else {
1208 OpenDexFiles(dex_filenames,
1209 dex_locations,
1210 runtime_options.GetOrDefault(Opt::Image),
1211 &boot_class_path);
1212 }
1213 instruction_set_ = runtime_options.GetOrDefault(Opt::ImageInstructionSet);
1214 std::string error_msg;
1215 if (!class_linker_->InitWithoutImage(std::move(boot_class_path), &error_msg)) {
1216 LOG(ERROR) << "Could not initialize without image: " << error_msg;
1217 return false;
1218 }
1219
1220 // TODO: Should we move the following to InitWithoutImage?
1221 SetInstructionSet(instruction_set_);
1222 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
1223 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
1224 if (!HasCalleeSaveMethod(type)) {
1225 SetCalleeSaveMethod(CreateCalleeSaveMethod(), type);
1226 }
1227 }
1228 }
1229
1230 CHECK(class_linker_ != nullptr);
1231
1232 verifier::MethodVerifier::Init();
1233
1234 if (runtime_options.Exists(Opt::MethodTrace)) {
1235 trace_config_.reset(new TraceConfig());
1236 trace_config_->trace_file = runtime_options.ReleaseOrDefault(Opt::MethodTraceFile);
1237 trace_config_->trace_file_size = runtime_options.ReleaseOrDefault(Opt::MethodTraceFileSize);
1238 trace_config_->trace_mode = Trace::TraceMode::kMethodTracing;
1239 trace_config_->trace_output_mode = runtime_options.Exists(Opt::MethodTraceStreaming) ?
1240 Trace::TraceOutputMode::kStreaming :
1241 Trace::TraceOutputMode::kFile;
1242 }
1243
1244 {
1245 auto&& profiler_options = runtime_options.ReleaseOrDefault(Opt::ProfilerOpts);
1246 profile_output_filename_ = profiler_options.output_file_name_;
1247
1248 // TODO: Don't do this, just change ProfilerOptions to include the output file name?
1249 ProfilerOptions other_options(
1250 profiler_options.enabled_,
1251 profiler_options.period_s_,
1252 profiler_options.duration_s_,
1253 profiler_options.interval_us_,
1254 profiler_options.backoff_coefficient_,
1255 profiler_options.start_immediately_,
1256 profiler_options.top_k_threshold_,
1257 profiler_options.top_k_change_threshold_,
1258 profiler_options.profile_type_,
1259 profiler_options.max_stack_depth_);
1260
1261 profiler_options_ = other_options;
1262 }
1263
1264 // TODO: move this to just be an Trace::Start argument
1265 Trace::SetDefaultClockSource(runtime_options.GetOrDefault(Opt::ProfileClock));
1266
1267 // Pre-allocate an OutOfMemoryError for the double-OOME case.
1268 self->ThrowNewException("Ljava/lang/OutOfMemoryError;",
1269 "OutOfMemoryError thrown while trying to throw OutOfMemoryError; "
1270 "no stack trace available");
1271 pre_allocated_OutOfMemoryError_ = GcRoot<mirror::Throwable>(self->GetException());
1272 self->ClearException();
1273
1274 // Pre-allocate a NoClassDefFoundError for the common case of failing to find a system class
1275 // ahead of checking the application's class loader.
1276 self->ThrowNewException("Ljava/lang/NoClassDefFoundError;",
1277 "Class not found using the boot class loader; no stack trace available");
1278 pre_allocated_NoClassDefFoundError_ = GcRoot<mirror::Throwable>(self->GetException());
1279 self->ClearException();
1280
1281 // Look for a native bridge.
1282 //
1283 // The intended flow here is, in the case of a running system:
1284 //
1285 // Runtime::Init() (zygote):
1286 // LoadNativeBridge -> dlopen from cmd line parameter.
1287 // |
1288 // V
1289 // Runtime::Start() (zygote):
1290 // No-op wrt native bridge.
1291 // |
1292 // | start app
1293 // V
1294 // DidForkFromZygote(action)
1295 // action = kUnload -> dlclose native bridge.
1296 // action = kInitialize -> initialize library
1297 //
1298 //
1299 // The intended flow here is, in the case of a simple dalvikvm call:
1300 //
1301 // Runtime::Init():
1302 // LoadNativeBridge -> dlopen from cmd line parameter.
1303 // |
1304 // V
1305 // Runtime::Start():
1306 // DidForkFromZygote(kInitialize) -> try to initialize any native bridge given.
1307 // No-op wrt native bridge.
1308 {
1309 std::string native_bridge_file_name = runtime_options.ReleaseOrDefault(Opt::NativeBridge);
1310 is_native_bridge_loaded_ = LoadNativeBridge(native_bridge_file_name);
1311 }
1312
1313 VLOG(startup) << "Runtime::Init exiting";
1314
1315 return true;
1316 }
1317
InitNativeMethods()1318 void Runtime::InitNativeMethods() {
1319 VLOG(startup) << "Runtime::InitNativeMethods entering";
1320 Thread* self = Thread::Current();
1321 JNIEnv* env = self->GetJniEnv();
1322
1323 // Must be in the kNative state for calling native methods (JNI_OnLoad code).
1324 CHECK_EQ(self->GetState(), kNative);
1325
1326 // First set up JniConstants, which is used by both the runtime's built-in native
1327 // methods and libcore.
1328 JniConstants::init(env);
1329
1330 // Then set up the native methods provided by the runtime itself.
1331 RegisterRuntimeNativeMethods(env);
1332
1333 // Initialize classes used in JNI. The initialization requires runtime native
1334 // methods to be loaded first.
1335 WellKnownClasses::Init(env);
1336
1337 // Then set up libjavacore / libopenjdk, which are just a regular JNI libraries with
1338 // a regular JNI_OnLoad. Most JNI libraries can just use System.loadLibrary, but
1339 // libcore can't because it's the library that implements System.loadLibrary!
1340 {
1341 std::string error_msg;
1342 if (!java_vm_->LoadNativeLibrary(env, "libjavacore.so", nullptr, nullptr, &error_msg)) {
1343 LOG(FATAL) << "LoadNativeLibrary failed for \"libjavacore.so\": " << error_msg;
1344 }
1345 }
1346 {
1347 constexpr const char* kOpenJdkLibrary = kIsDebugBuild
1348 ? "libopenjdkd.so"
1349 : "libopenjdk.so";
1350 std::string error_msg;
1351 if (!java_vm_->LoadNativeLibrary(env, kOpenJdkLibrary, nullptr, nullptr, &error_msg)) {
1352 LOG(FATAL) << "LoadNativeLibrary failed for \"" << kOpenJdkLibrary << "\": " << error_msg;
1353 }
1354 }
1355
1356 // Initialize well known classes that may invoke runtime native methods.
1357 WellKnownClasses::LateInit(env);
1358
1359 VLOG(startup) << "Runtime::InitNativeMethods exiting";
1360 }
1361
ReclaimArenaPoolMemory()1362 void Runtime::ReclaimArenaPoolMemory() {
1363 arena_pool_->LockReclaimMemory();
1364 }
1365
InitThreadGroups(Thread * self)1366 void Runtime::InitThreadGroups(Thread* self) {
1367 JNIEnvExt* env = self->GetJniEnv();
1368 ScopedJniEnvLocalRefState env_state(env);
1369 main_thread_group_ =
1370 env->NewGlobalRef(env->GetStaticObjectField(
1371 WellKnownClasses::java_lang_ThreadGroup,
1372 WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup));
1373 CHECK(main_thread_group_ != nullptr || IsAotCompiler());
1374 system_thread_group_ =
1375 env->NewGlobalRef(env->GetStaticObjectField(
1376 WellKnownClasses::java_lang_ThreadGroup,
1377 WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup));
1378 CHECK(system_thread_group_ != nullptr || IsAotCompiler());
1379 }
1380
GetMainThreadGroup() const1381 jobject Runtime::GetMainThreadGroup() const {
1382 CHECK(main_thread_group_ != nullptr || IsAotCompiler());
1383 return main_thread_group_;
1384 }
1385
GetSystemThreadGroup() const1386 jobject Runtime::GetSystemThreadGroup() const {
1387 CHECK(system_thread_group_ != nullptr || IsAotCompiler());
1388 return system_thread_group_;
1389 }
1390
GetSystemClassLoader() const1391 jobject Runtime::GetSystemClassLoader() const {
1392 CHECK(system_class_loader_ != nullptr || IsAotCompiler());
1393 return system_class_loader_;
1394 }
1395
RegisterRuntimeNativeMethods(JNIEnv * env)1396 void Runtime::RegisterRuntimeNativeMethods(JNIEnv* env) {
1397 register_dalvik_system_DexFile(env);
1398 register_dalvik_system_VMDebug(env);
1399 register_dalvik_system_VMRuntime(env);
1400 register_dalvik_system_VMStack(env);
1401 register_dalvik_system_ZygoteHooks(env);
1402 register_java_lang_Class(env);
1403 register_java_lang_DexCache(env);
1404 register_java_lang_Object(env);
1405 register_java_lang_ref_FinalizerReference(env);
1406 register_java_lang_reflect_AbstractMethod(env);
1407 register_java_lang_reflect_Array(env);
1408 register_java_lang_reflect_Constructor(env);
1409 register_java_lang_reflect_Field(env);
1410 register_java_lang_reflect_Method(env);
1411 register_java_lang_reflect_Proxy(env);
1412 register_java_lang_ref_Reference(env);
1413 register_java_lang_String(env);
1414 register_java_lang_StringFactory(env);
1415 register_java_lang_System(env);
1416 register_java_lang_Thread(env);
1417 register_java_lang_Throwable(env);
1418 register_java_lang_VMClassLoader(env);
1419 register_java_util_concurrent_atomic_AtomicLong(env);
1420 register_libcore_util_CharsetUtils(env);
1421 register_org_apache_harmony_dalvik_ddmc_DdmServer(env);
1422 register_org_apache_harmony_dalvik_ddmc_DdmVmInternal(env);
1423 register_sun_misc_Unsafe(env);
1424 }
1425
DumpForSigQuit(std::ostream & os)1426 void Runtime::DumpForSigQuit(std::ostream& os) {
1427 GetClassLinker()->DumpForSigQuit(os);
1428 GetInternTable()->DumpForSigQuit(os);
1429 GetJavaVM()->DumpForSigQuit(os);
1430 GetHeap()->DumpForSigQuit(os);
1431 oat_file_manager_->DumpForSigQuit(os);
1432 if (GetJit() != nullptr) {
1433 GetJit()->DumpForSigQuit(os);
1434 } else {
1435 os << "Running non JIT\n";
1436 }
1437 TrackedAllocators::Dump(os);
1438 os << "\n";
1439
1440 thread_list_->DumpForSigQuit(os);
1441 BaseMutex::DumpAll(os);
1442 }
1443
DumpLockHolders(std::ostream & os)1444 void Runtime::DumpLockHolders(std::ostream& os) {
1445 uint64_t mutator_lock_owner = Locks::mutator_lock_->GetExclusiveOwnerTid();
1446 pid_t thread_list_lock_owner = GetThreadList()->GetLockOwner();
1447 pid_t classes_lock_owner = GetClassLinker()->GetClassesLockOwner();
1448 pid_t dex_lock_owner = GetClassLinker()->GetDexLockOwner();
1449 if ((thread_list_lock_owner | classes_lock_owner | dex_lock_owner) != 0) {
1450 os << "Mutator lock exclusive owner tid: " << mutator_lock_owner << "\n"
1451 << "ThreadList lock owner tid: " << thread_list_lock_owner << "\n"
1452 << "ClassLinker classes lock owner tid: " << classes_lock_owner << "\n"
1453 << "ClassLinker dex lock owner tid: " << dex_lock_owner << "\n";
1454 }
1455 }
1456
SetStatsEnabled(bool new_state)1457 void Runtime::SetStatsEnabled(bool new_state) {
1458 Thread* self = Thread::Current();
1459 MutexLock mu(self, *Locks::instrument_entrypoints_lock_);
1460 if (new_state == true) {
1461 GetStats()->Clear(~0);
1462 // TODO: wouldn't it make more sense to clear _all_ threads' stats?
1463 self->GetStats()->Clear(~0);
1464 if (stats_enabled_ != new_state) {
1465 GetInstrumentation()->InstrumentQuickAllocEntryPointsLocked();
1466 }
1467 } else if (stats_enabled_ != new_state) {
1468 GetInstrumentation()->UninstrumentQuickAllocEntryPointsLocked();
1469 }
1470 stats_enabled_ = new_state;
1471 }
1472
ResetStats(int kinds)1473 void Runtime::ResetStats(int kinds) {
1474 GetStats()->Clear(kinds & 0xffff);
1475 // TODO: wouldn't it make more sense to clear _all_ threads' stats?
1476 Thread::Current()->GetStats()->Clear(kinds >> 16);
1477 }
1478
GetStat(int kind)1479 int32_t Runtime::GetStat(int kind) {
1480 RuntimeStats* stats;
1481 if (kind < (1<<16)) {
1482 stats = GetStats();
1483 } else {
1484 stats = Thread::Current()->GetStats();
1485 kind >>= 16;
1486 }
1487 switch (kind) {
1488 case KIND_ALLOCATED_OBJECTS:
1489 return stats->allocated_objects;
1490 case KIND_ALLOCATED_BYTES:
1491 return stats->allocated_bytes;
1492 case KIND_FREED_OBJECTS:
1493 return stats->freed_objects;
1494 case KIND_FREED_BYTES:
1495 return stats->freed_bytes;
1496 case KIND_GC_INVOCATIONS:
1497 return stats->gc_for_alloc_count;
1498 case KIND_CLASS_INIT_COUNT:
1499 return stats->class_init_count;
1500 case KIND_CLASS_INIT_TIME:
1501 // Convert ns to us, reduce to 32 bits.
1502 return static_cast<int>(stats->class_init_time_ns / 1000);
1503 case KIND_EXT_ALLOCATED_OBJECTS:
1504 case KIND_EXT_ALLOCATED_BYTES:
1505 case KIND_EXT_FREED_OBJECTS:
1506 case KIND_EXT_FREED_BYTES:
1507 return 0; // backward compatibility
1508 default:
1509 LOG(FATAL) << "Unknown statistic " << kind;
1510 return -1; // unreachable
1511 }
1512 }
1513
BlockSignals()1514 void Runtime::BlockSignals() {
1515 SignalSet signals;
1516 signals.Add(SIGPIPE);
1517 // SIGQUIT is used to dump the runtime's state (including stack traces).
1518 signals.Add(SIGQUIT);
1519 // SIGUSR1 is used to initiate a GC.
1520 signals.Add(SIGUSR1);
1521 signals.Block();
1522 }
1523
AttachCurrentThread(const char * thread_name,bool as_daemon,jobject thread_group,bool create_peer)1524 bool Runtime::AttachCurrentThread(const char* thread_name, bool as_daemon, jobject thread_group,
1525 bool create_peer) {
1526 ScopedTrace trace(__FUNCTION__);
1527 return Thread::Attach(thread_name, as_daemon, thread_group, create_peer) != nullptr;
1528 }
1529
DetachCurrentThread()1530 void Runtime::DetachCurrentThread() {
1531 ScopedTrace trace(__FUNCTION__);
1532 Thread* self = Thread::Current();
1533 if (self == nullptr) {
1534 LOG(FATAL) << "attempting to detach thread that is not attached";
1535 }
1536 if (self->HasManagedStack()) {
1537 LOG(FATAL) << *Thread::Current() << " attempting to detach while still running code";
1538 }
1539 thread_list_->Unregister(self);
1540 }
1541
GetPreAllocatedOutOfMemoryError()1542 mirror::Throwable* Runtime::GetPreAllocatedOutOfMemoryError() {
1543 mirror::Throwable* oome = pre_allocated_OutOfMemoryError_.Read();
1544 if (oome == nullptr) {
1545 LOG(ERROR) << "Failed to return pre-allocated OOME";
1546 }
1547 return oome;
1548 }
1549
GetPreAllocatedNoClassDefFoundError()1550 mirror::Throwable* Runtime::GetPreAllocatedNoClassDefFoundError() {
1551 mirror::Throwable* ncdfe = pre_allocated_NoClassDefFoundError_.Read();
1552 if (ncdfe == nullptr) {
1553 LOG(ERROR) << "Failed to return pre-allocated NoClassDefFoundError";
1554 }
1555 return ncdfe;
1556 }
1557
VisitConstantRoots(RootVisitor * visitor)1558 void Runtime::VisitConstantRoots(RootVisitor* visitor) {
1559 // Visit the classes held as static in mirror classes, these can be visited concurrently and only
1560 // need to be visited once per GC since they never change.
1561 mirror::Class::VisitRoots(visitor);
1562 mirror::Constructor::VisitRoots(visitor);
1563 mirror::Reference::VisitRoots(visitor);
1564 mirror::Method::VisitRoots(visitor);
1565 mirror::StackTraceElement::VisitRoots(visitor);
1566 mirror::String::VisitRoots(visitor);
1567 mirror::Throwable::VisitRoots(visitor);
1568 mirror::Field::VisitRoots(visitor);
1569 // Visit all the primitive array types classes.
1570 mirror::PrimitiveArray<uint8_t>::VisitRoots(visitor); // BooleanArray
1571 mirror::PrimitiveArray<int8_t>::VisitRoots(visitor); // ByteArray
1572 mirror::PrimitiveArray<uint16_t>::VisitRoots(visitor); // CharArray
1573 mirror::PrimitiveArray<double>::VisitRoots(visitor); // DoubleArray
1574 mirror::PrimitiveArray<float>::VisitRoots(visitor); // FloatArray
1575 mirror::PrimitiveArray<int32_t>::VisitRoots(visitor); // IntArray
1576 mirror::PrimitiveArray<int64_t>::VisitRoots(visitor); // LongArray
1577 mirror::PrimitiveArray<int16_t>::VisitRoots(visitor); // ShortArray
1578 // Visiting the roots of these ArtMethods is not currently required since all the GcRoots are
1579 // null.
1580 BufferedRootVisitor<16> buffered_visitor(visitor, RootInfo(kRootVMInternal));
1581 const size_t pointer_size = GetClassLinker()->GetImagePointerSize();
1582 if (HasResolutionMethod()) {
1583 resolution_method_->VisitRoots(buffered_visitor, pointer_size);
1584 }
1585 if (HasImtConflictMethod()) {
1586 imt_conflict_method_->VisitRoots(buffered_visitor, pointer_size);
1587 }
1588 if (imt_unimplemented_method_ != nullptr) {
1589 imt_unimplemented_method_->VisitRoots(buffered_visitor, pointer_size);
1590 }
1591 for (size_t i = 0; i < kLastCalleeSaveType; ++i) {
1592 auto* m = reinterpret_cast<ArtMethod*>(callee_save_methods_[i]);
1593 if (m != nullptr) {
1594 m->VisitRoots(buffered_visitor, pointer_size);
1595 }
1596 }
1597 }
1598
VisitConcurrentRoots(RootVisitor * visitor,VisitRootFlags flags)1599 void Runtime::VisitConcurrentRoots(RootVisitor* visitor, VisitRootFlags flags) {
1600 intern_table_->VisitRoots(visitor, flags);
1601 class_linker_->VisitRoots(visitor, flags);
1602 heap_->VisitAllocationRecords(visitor);
1603 if ((flags & kVisitRootFlagNewRoots) == 0) {
1604 // Guaranteed to have no new roots in the constant roots.
1605 VisitConstantRoots(visitor);
1606 }
1607 Dbg::VisitRoots(visitor);
1608 }
1609
VisitTransactionRoots(RootVisitor * visitor)1610 void Runtime::VisitTransactionRoots(RootVisitor* visitor) {
1611 if (preinitialization_transaction_ != nullptr) {
1612 preinitialization_transaction_->VisitRoots(visitor);
1613 }
1614 }
1615
VisitNonThreadRoots(RootVisitor * visitor)1616 void Runtime::VisitNonThreadRoots(RootVisitor* visitor) {
1617 java_vm_->VisitRoots(visitor);
1618 sentinel_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
1619 pre_allocated_OutOfMemoryError_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
1620 pre_allocated_NoClassDefFoundError_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
1621 verifier::MethodVerifier::VisitStaticRoots(visitor);
1622 VisitTransactionRoots(visitor);
1623 }
1624
VisitNonConcurrentRoots(RootVisitor * visitor)1625 void Runtime::VisitNonConcurrentRoots(RootVisitor* visitor) {
1626 thread_list_->VisitRoots(visitor);
1627 VisitNonThreadRoots(visitor);
1628 }
1629
VisitThreadRoots(RootVisitor * visitor)1630 void Runtime::VisitThreadRoots(RootVisitor* visitor) {
1631 thread_list_->VisitRoots(visitor);
1632 }
1633
FlipThreadRoots(Closure * thread_flip_visitor,Closure * flip_callback,gc::collector::GarbageCollector * collector)1634 size_t Runtime::FlipThreadRoots(Closure* thread_flip_visitor, Closure* flip_callback,
1635 gc::collector::GarbageCollector* collector) {
1636 return thread_list_->FlipThreadRoots(thread_flip_visitor, flip_callback, collector);
1637 }
1638
VisitRoots(RootVisitor * visitor,VisitRootFlags flags)1639 void Runtime::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
1640 VisitNonConcurrentRoots(visitor);
1641 VisitConcurrentRoots(visitor, flags);
1642 }
1643
VisitImageRoots(RootVisitor * visitor)1644 void Runtime::VisitImageRoots(RootVisitor* visitor) {
1645 for (auto* space : GetHeap()->GetContinuousSpaces()) {
1646 if (space->IsImageSpace()) {
1647 auto* image_space = space->AsImageSpace();
1648 const auto& image_header = image_space->GetImageHeader();
1649 for (size_t i = 0; i < ImageHeader::kImageRootsMax; ++i) {
1650 auto* obj = image_header.GetImageRoot(static_cast<ImageHeader::ImageRoot>(i));
1651 if (obj != nullptr) {
1652 auto* after_obj = obj;
1653 visitor->VisitRoot(&after_obj, RootInfo(kRootStickyClass));
1654 CHECK_EQ(after_obj, obj);
1655 }
1656 }
1657 }
1658 }
1659 }
1660
CreateImtConflictMethod(LinearAlloc * linear_alloc)1661 ArtMethod* Runtime::CreateImtConflictMethod(LinearAlloc* linear_alloc) {
1662 ClassLinker* const class_linker = GetClassLinker();
1663 ArtMethod* method = class_linker->CreateRuntimeMethod(linear_alloc);
1664 // When compiling, the code pointer will get set later when the image is loaded.
1665 const size_t pointer_size = GetInstructionSetPointerSize(instruction_set_);
1666 if (IsAotCompiler()) {
1667 method->SetEntryPointFromQuickCompiledCodePtrSize(nullptr, pointer_size);
1668 } else {
1669 method->SetEntryPointFromQuickCompiledCode(GetQuickImtConflictStub());
1670 }
1671 // Create empty conflict table.
1672 method->SetImtConflictTable(class_linker->CreateImtConflictTable(/*count*/0u, linear_alloc),
1673 pointer_size);
1674 return method;
1675 }
1676
SetImtConflictMethod(ArtMethod * method)1677 void Runtime::SetImtConflictMethod(ArtMethod* method) {
1678 CHECK(method != nullptr);
1679 CHECK(method->IsRuntimeMethod());
1680 imt_conflict_method_ = method;
1681 }
1682
CreateResolutionMethod()1683 ArtMethod* Runtime::CreateResolutionMethod() {
1684 auto* method = GetClassLinker()->CreateRuntimeMethod(GetLinearAlloc());
1685 // When compiling, the code pointer will get set later when the image is loaded.
1686 if (IsAotCompiler()) {
1687 size_t pointer_size = GetInstructionSetPointerSize(instruction_set_);
1688 method->SetEntryPointFromQuickCompiledCodePtrSize(nullptr, pointer_size);
1689 } else {
1690 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
1691 }
1692 return method;
1693 }
1694
CreateCalleeSaveMethod()1695 ArtMethod* Runtime::CreateCalleeSaveMethod() {
1696 auto* method = GetClassLinker()->CreateRuntimeMethod(GetLinearAlloc());
1697 size_t pointer_size = GetInstructionSetPointerSize(instruction_set_);
1698 method->SetEntryPointFromQuickCompiledCodePtrSize(nullptr, pointer_size);
1699 DCHECK_NE(instruction_set_, kNone);
1700 DCHECK(method->IsRuntimeMethod());
1701 return method;
1702 }
1703
DisallowNewSystemWeaks()1704 void Runtime::DisallowNewSystemWeaks() {
1705 CHECK(!kUseReadBarrier);
1706 monitor_list_->DisallowNewMonitors();
1707 intern_table_->ChangeWeakRootState(gc::kWeakRootStateNoReadsOrWrites);
1708 java_vm_->DisallowNewWeakGlobals();
1709 heap_->DisallowNewAllocationRecords();
1710 lambda_box_table_->DisallowNewWeakBoxedLambdas();
1711 }
1712
AllowNewSystemWeaks()1713 void Runtime::AllowNewSystemWeaks() {
1714 CHECK(!kUseReadBarrier);
1715 monitor_list_->AllowNewMonitors();
1716 intern_table_->ChangeWeakRootState(gc::kWeakRootStateNormal); // TODO: Do this in the sweeping.
1717 java_vm_->AllowNewWeakGlobals();
1718 heap_->AllowNewAllocationRecords();
1719 lambda_box_table_->AllowNewWeakBoxedLambdas();
1720 }
1721
BroadcastForNewSystemWeaks()1722 void Runtime::BroadcastForNewSystemWeaks() {
1723 // This is used for the read barrier case that uses the thread-local
1724 // Thread::GetWeakRefAccessEnabled() flag.
1725 CHECK(kUseReadBarrier);
1726 monitor_list_->BroadcastForNewMonitors();
1727 intern_table_->BroadcastForNewInterns();
1728 java_vm_->BroadcastForNewWeakGlobals();
1729 heap_->BroadcastForNewAllocationRecords();
1730 lambda_box_table_->BroadcastForNewWeakBoxedLambdas();
1731 }
1732
SetInstructionSet(InstructionSet instruction_set)1733 void Runtime::SetInstructionSet(InstructionSet instruction_set) {
1734 instruction_set_ = instruction_set;
1735 if ((instruction_set_ == kThumb2) || (instruction_set_ == kArm)) {
1736 for (int i = 0; i != kLastCalleeSaveType; ++i) {
1737 CalleeSaveType type = static_cast<CalleeSaveType>(i);
1738 callee_save_method_frame_infos_[i] = arm::ArmCalleeSaveMethodFrameInfo(type);
1739 }
1740 } else if (instruction_set_ == kMips) {
1741 for (int i = 0; i != kLastCalleeSaveType; ++i) {
1742 CalleeSaveType type = static_cast<CalleeSaveType>(i);
1743 callee_save_method_frame_infos_[i] = mips::MipsCalleeSaveMethodFrameInfo(type);
1744 }
1745 } else if (instruction_set_ == kMips64) {
1746 for (int i = 0; i != kLastCalleeSaveType; ++i) {
1747 CalleeSaveType type = static_cast<CalleeSaveType>(i);
1748 callee_save_method_frame_infos_[i] = mips64::Mips64CalleeSaveMethodFrameInfo(type);
1749 }
1750 } else if (instruction_set_ == kX86) {
1751 for (int i = 0; i != kLastCalleeSaveType; ++i) {
1752 CalleeSaveType type = static_cast<CalleeSaveType>(i);
1753 callee_save_method_frame_infos_[i] = x86::X86CalleeSaveMethodFrameInfo(type);
1754 }
1755 } else if (instruction_set_ == kX86_64) {
1756 for (int i = 0; i != kLastCalleeSaveType; ++i) {
1757 CalleeSaveType type = static_cast<CalleeSaveType>(i);
1758 callee_save_method_frame_infos_[i] = x86_64::X86_64CalleeSaveMethodFrameInfo(type);
1759 }
1760 } else if (instruction_set_ == kArm64) {
1761 for (int i = 0; i != kLastCalleeSaveType; ++i) {
1762 CalleeSaveType type = static_cast<CalleeSaveType>(i);
1763 callee_save_method_frame_infos_[i] = arm64::Arm64CalleeSaveMethodFrameInfo(type);
1764 }
1765 } else {
1766 UNIMPLEMENTED(FATAL) << instruction_set_;
1767 }
1768 }
1769
SetCalleeSaveMethod(ArtMethod * method,CalleeSaveType type)1770 void Runtime::SetCalleeSaveMethod(ArtMethod* method, CalleeSaveType type) {
1771 DCHECK_LT(static_cast<int>(type), static_cast<int>(kLastCalleeSaveType));
1772 CHECK(method != nullptr);
1773 callee_save_methods_[type] = reinterpret_cast<uintptr_t>(method);
1774 }
1775
RegisterAppInfo(const std::vector<std::string> & code_paths,const std::string & profile_output_filename,const std::string & foreign_dex_profile_path,const std::string & app_dir)1776 void Runtime::RegisterAppInfo(const std::vector<std::string>& code_paths,
1777 const std::string& profile_output_filename,
1778 const std::string& foreign_dex_profile_path,
1779 const std::string& app_dir) {
1780 if (jit_.get() == nullptr) {
1781 // We are not JITing. Nothing to do.
1782 return;
1783 }
1784
1785 VLOG(profiler) << "Register app with " << profile_output_filename
1786 << " " << Join(code_paths, ':');
1787
1788 if (profile_output_filename.empty()) {
1789 LOG(WARNING) << "JIT profile information will not be recorded: profile filename is empty.";
1790 return;
1791 }
1792 if (!FileExists(profile_output_filename)) {
1793 LOG(WARNING) << "JIT profile information will not be recorded: profile file does not exits.";
1794 return;
1795 }
1796 if (code_paths.empty()) {
1797 LOG(WARNING) << "JIT profile information will not be recorded: code paths is empty.";
1798 return;
1799 }
1800
1801 profile_output_filename_ = profile_output_filename;
1802 jit_->StartProfileSaver(profile_output_filename,
1803 code_paths,
1804 foreign_dex_profile_path,
1805 app_dir);
1806 }
1807
NotifyDexLoaded(const std::string & dex_location)1808 void Runtime::NotifyDexLoaded(const std::string& dex_location) {
1809 VLOG(profiler) << "Notify dex loaded: " << dex_location;
1810 // We know that if the ProfileSaver is started then we can record profile information.
1811 if (ProfileSaver::IsStarted()) {
1812 ProfileSaver::NotifyDexUse(dex_location);
1813 }
1814 }
1815
1816 // Transaction support.
EnterTransactionMode(Transaction * transaction)1817 void Runtime::EnterTransactionMode(Transaction* transaction) {
1818 DCHECK(IsAotCompiler());
1819 DCHECK(transaction != nullptr);
1820 DCHECK(!IsActiveTransaction());
1821 preinitialization_transaction_ = transaction;
1822 }
1823
ExitTransactionMode()1824 void Runtime::ExitTransactionMode() {
1825 DCHECK(IsAotCompiler());
1826 DCHECK(IsActiveTransaction());
1827 preinitialization_transaction_ = nullptr;
1828 }
1829
IsTransactionAborted() const1830 bool Runtime::IsTransactionAborted() const {
1831 if (!IsActiveTransaction()) {
1832 return false;
1833 } else {
1834 DCHECK(IsAotCompiler());
1835 return preinitialization_transaction_->IsAborted();
1836 }
1837 }
1838
AbortTransactionAndThrowAbortError(Thread * self,const std::string & abort_message)1839 void Runtime::AbortTransactionAndThrowAbortError(Thread* self, const std::string& abort_message) {
1840 DCHECK(IsAotCompiler());
1841 DCHECK(IsActiveTransaction());
1842 // Throwing an exception may cause its class initialization. If we mark the transaction
1843 // aborted before that, we may warn with a false alarm. Throwing the exception before
1844 // marking the transaction aborted avoids that.
1845 preinitialization_transaction_->ThrowAbortError(self, &abort_message);
1846 preinitialization_transaction_->Abort(abort_message);
1847 }
1848
ThrowTransactionAbortError(Thread * self)1849 void Runtime::ThrowTransactionAbortError(Thread* self) {
1850 DCHECK(IsAotCompiler());
1851 DCHECK(IsActiveTransaction());
1852 // Passing nullptr means we rethrow an exception with the earlier transaction abort message.
1853 preinitialization_transaction_->ThrowAbortError(self, nullptr);
1854 }
1855
RecordWriteFieldBoolean(mirror::Object * obj,MemberOffset field_offset,uint8_t value,bool is_volatile) const1856 void Runtime::RecordWriteFieldBoolean(mirror::Object* obj, MemberOffset field_offset,
1857 uint8_t value, bool is_volatile) const {
1858 DCHECK(IsAotCompiler());
1859 DCHECK(IsActiveTransaction());
1860 preinitialization_transaction_->RecordWriteFieldBoolean(obj, field_offset, value, is_volatile);
1861 }
1862
RecordWriteFieldByte(mirror::Object * obj,MemberOffset field_offset,int8_t value,bool is_volatile) const1863 void Runtime::RecordWriteFieldByte(mirror::Object* obj, MemberOffset field_offset,
1864 int8_t value, bool is_volatile) const {
1865 DCHECK(IsAotCompiler());
1866 DCHECK(IsActiveTransaction());
1867 preinitialization_transaction_->RecordWriteFieldByte(obj, field_offset, value, is_volatile);
1868 }
1869
RecordWriteFieldChar(mirror::Object * obj,MemberOffset field_offset,uint16_t value,bool is_volatile) const1870 void Runtime::RecordWriteFieldChar(mirror::Object* obj, MemberOffset field_offset,
1871 uint16_t value, bool is_volatile) const {
1872 DCHECK(IsAotCompiler());
1873 DCHECK(IsActiveTransaction());
1874 preinitialization_transaction_->RecordWriteFieldChar(obj, field_offset, value, is_volatile);
1875 }
1876
RecordWriteFieldShort(mirror::Object * obj,MemberOffset field_offset,int16_t value,bool is_volatile) const1877 void Runtime::RecordWriteFieldShort(mirror::Object* obj, MemberOffset field_offset,
1878 int16_t value, bool is_volatile) const {
1879 DCHECK(IsAotCompiler());
1880 DCHECK(IsActiveTransaction());
1881 preinitialization_transaction_->RecordWriteFieldShort(obj, field_offset, value, is_volatile);
1882 }
1883
RecordWriteField32(mirror::Object * obj,MemberOffset field_offset,uint32_t value,bool is_volatile) const1884 void Runtime::RecordWriteField32(mirror::Object* obj, MemberOffset field_offset,
1885 uint32_t value, bool is_volatile) const {
1886 DCHECK(IsAotCompiler());
1887 DCHECK(IsActiveTransaction());
1888 preinitialization_transaction_->RecordWriteField32(obj, field_offset, value, is_volatile);
1889 }
1890
RecordWriteField64(mirror::Object * obj,MemberOffset field_offset,uint64_t value,bool is_volatile) const1891 void Runtime::RecordWriteField64(mirror::Object* obj, MemberOffset field_offset,
1892 uint64_t value, bool is_volatile) const {
1893 DCHECK(IsAotCompiler());
1894 DCHECK(IsActiveTransaction());
1895 preinitialization_transaction_->RecordWriteField64(obj, field_offset, value, is_volatile);
1896 }
1897
RecordWriteFieldReference(mirror::Object * obj,MemberOffset field_offset,mirror::Object * value,bool is_volatile) const1898 void Runtime::RecordWriteFieldReference(mirror::Object* obj, MemberOffset field_offset,
1899 mirror::Object* value, bool is_volatile) const {
1900 DCHECK(IsAotCompiler());
1901 DCHECK(IsActiveTransaction());
1902 preinitialization_transaction_->RecordWriteFieldReference(obj, field_offset, value, is_volatile);
1903 }
1904
RecordWriteArray(mirror::Array * array,size_t index,uint64_t value) const1905 void Runtime::RecordWriteArray(mirror::Array* array, size_t index, uint64_t value) const {
1906 DCHECK(IsAotCompiler());
1907 DCHECK(IsActiveTransaction());
1908 preinitialization_transaction_->RecordWriteArray(array, index, value);
1909 }
1910
RecordStrongStringInsertion(mirror::String * s) const1911 void Runtime::RecordStrongStringInsertion(mirror::String* s) const {
1912 DCHECK(IsAotCompiler());
1913 DCHECK(IsActiveTransaction());
1914 preinitialization_transaction_->RecordStrongStringInsertion(s);
1915 }
1916
RecordWeakStringInsertion(mirror::String * s) const1917 void Runtime::RecordWeakStringInsertion(mirror::String* s) const {
1918 DCHECK(IsAotCompiler());
1919 DCHECK(IsActiveTransaction());
1920 preinitialization_transaction_->RecordWeakStringInsertion(s);
1921 }
1922
RecordStrongStringRemoval(mirror::String * s) const1923 void Runtime::RecordStrongStringRemoval(mirror::String* s) const {
1924 DCHECK(IsAotCompiler());
1925 DCHECK(IsActiveTransaction());
1926 preinitialization_transaction_->RecordStrongStringRemoval(s);
1927 }
1928
RecordWeakStringRemoval(mirror::String * s) const1929 void Runtime::RecordWeakStringRemoval(mirror::String* s) const {
1930 DCHECK(IsAotCompiler());
1931 DCHECK(IsActiveTransaction());
1932 preinitialization_transaction_->RecordWeakStringRemoval(s);
1933 }
1934
SetFaultMessage(const std::string & message)1935 void Runtime::SetFaultMessage(const std::string& message) {
1936 MutexLock mu(Thread::Current(), fault_message_lock_);
1937 fault_message_ = message;
1938 }
1939
AddCurrentRuntimeFeaturesAsDex2OatArguments(std::vector<std::string> * argv) const1940 void Runtime::AddCurrentRuntimeFeaturesAsDex2OatArguments(std::vector<std::string>* argv)
1941 const {
1942 if (GetInstrumentation()->InterpretOnly()) {
1943 argv->push_back("--compiler-filter=interpret-only");
1944 }
1945
1946 // Make the dex2oat instruction set match that of the launching runtime. If we have multiple
1947 // architecture support, dex2oat may be compiled as a different instruction-set than that
1948 // currently being executed.
1949 std::string instruction_set("--instruction-set=");
1950 instruction_set += GetInstructionSetString(kRuntimeISA);
1951 argv->push_back(instruction_set);
1952
1953 std::unique_ptr<const InstructionSetFeatures> features(InstructionSetFeatures::FromCppDefines());
1954 std::string feature_string("--instruction-set-features=");
1955 feature_string += features->GetFeatureString();
1956 argv->push_back(feature_string);
1957 }
1958
CreateJit()1959 void Runtime::CreateJit() {
1960 CHECK(!IsAotCompiler());
1961 if (kIsDebugBuild && GetInstrumentation()->IsForcedInterpretOnly()) {
1962 DCHECK(!jit_options_->UseJitCompilation());
1963 }
1964 std::string error_msg;
1965 jit_.reset(jit::Jit::Create(jit_options_.get(), &error_msg));
1966 if (jit_.get() == nullptr) {
1967 LOG(WARNING) << "Failed to create JIT " << error_msg;
1968 }
1969 }
1970
CanRelocate() const1971 bool Runtime::CanRelocate() const {
1972 return !IsAotCompiler() || compiler_callbacks_->IsRelocationPossible();
1973 }
1974
IsCompilingBootImage() const1975 bool Runtime::IsCompilingBootImage() const {
1976 return IsCompiler() && compiler_callbacks_->IsBootImage();
1977 }
1978
SetResolutionMethod(ArtMethod * method)1979 void Runtime::SetResolutionMethod(ArtMethod* method) {
1980 CHECK(method != nullptr);
1981 CHECK(method->IsRuntimeMethod()) << method;
1982 resolution_method_ = method;
1983 }
1984
SetImtUnimplementedMethod(ArtMethod * method)1985 void Runtime::SetImtUnimplementedMethod(ArtMethod* method) {
1986 CHECK(method != nullptr);
1987 CHECK(method->IsRuntimeMethod());
1988 imt_unimplemented_method_ = method;
1989 }
1990
FixupConflictTables()1991 void Runtime::FixupConflictTables() {
1992 // We can only do this after the class linker is created.
1993 const size_t pointer_size = GetClassLinker()->GetImagePointerSize();
1994 if (imt_unimplemented_method_->GetImtConflictTable(pointer_size) == nullptr) {
1995 imt_unimplemented_method_->SetImtConflictTable(
1996 ClassLinker::CreateImtConflictTable(/*count*/0u, GetLinearAlloc(), pointer_size),
1997 pointer_size);
1998 }
1999 if (imt_conflict_method_->GetImtConflictTable(pointer_size) == nullptr) {
2000 imt_conflict_method_->SetImtConflictTable(
2001 ClassLinker::CreateImtConflictTable(/*count*/0u, GetLinearAlloc(), pointer_size),
2002 pointer_size);
2003 }
2004 }
2005
IsVerificationEnabled() const2006 bool Runtime::IsVerificationEnabled() const {
2007 return verify_ == verifier::VerifyMode::kEnable ||
2008 verify_ == verifier::VerifyMode::kSoftFail;
2009 }
2010
IsVerificationSoftFail() const2011 bool Runtime::IsVerificationSoftFail() const {
2012 return verify_ == verifier::VerifyMode::kSoftFail;
2013 }
2014
CreateLinearAlloc()2015 LinearAlloc* Runtime::CreateLinearAlloc() {
2016 // For 64 bit compilers, it needs to be in low 4GB in the case where we are cross compiling for a
2017 // 32 bit target. In this case, we have 32 bit pointers in the dex cache arrays which can't hold
2018 // when we have 64 bit ArtMethod pointers.
2019 return (IsAotCompiler() && Is64BitInstructionSet(kRuntimeISA))
2020 ? new LinearAlloc(low_4gb_arena_pool_.get())
2021 : new LinearAlloc(arena_pool_.get());
2022 }
2023
GetHashTableMinLoadFactor() const2024 double Runtime::GetHashTableMinLoadFactor() const {
2025 return is_low_memory_mode_ ? kLowMemoryMinLoadFactor : kNormalMinLoadFactor;
2026 }
2027
GetHashTableMaxLoadFactor() const2028 double Runtime::GetHashTableMaxLoadFactor() const {
2029 return is_low_memory_mode_ ? kLowMemoryMaxLoadFactor : kNormalMaxLoadFactor;
2030 }
2031
UpdateProcessState(ProcessState process_state)2032 void Runtime::UpdateProcessState(ProcessState process_state) {
2033 ProcessState old_process_state = process_state_;
2034 process_state_ = process_state;
2035 GetHeap()->UpdateProcessState(old_process_state, process_state);
2036 }
2037
RegisterSensitiveThread() const2038 void Runtime::RegisterSensitiveThread() const {
2039 Thread::SetJitSensitiveThread();
2040 }
2041
2042 // Returns true if JIT compilations are enabled. GetJit() will be not null in this case.
UseJitCompilation() const2043 bool Runtime::UseJitCompilation() const {
2044 return (jit_ != nullptr) && jit_->UseJitCompilation();
2045 }
2046
2047 // Returns true if profile saving is enabled. GetJit() will be not null in this case.
SaveProfileInfo() const2048 bool Runtime::SaveProfileInfo() const {
2049 return (jit_ != nullptr) && jit_->SaveProfilingInfo();
2050 }
2051
TakeSnapshot()2052 void Runtime::EnvSnapshot::TakeSnapshot() {
2053 char** env = GetEnviron();
2054 for (size_t i = 0; env[i] != nullptr; ++i) {
2055 name_value_pairs_.emplace_back(new std::string(env[i]));
2056 }
2057 // The strings in name_value_pairs_ retain ownership of the c_str, but we assign pointers
2058 // for quick use by GetSnapshot. This avoids allocation and copying cost at Exec.
2059 c_env_vector_.reset(new char*[name_value_pairs_.size() + 1]);
2060 for (size_t i = 0; env[i] != nullptr; ++i) {
2061 c_env_vector_[i] = const_cast<char*>(name_value_pairs_[i]->c_str());
2062 }
2063 c_env_vector_[name_value_pairs_.size()] = nullptr;
2064 }
2065
GetSnapshot() const2066 char** Runtime::EnvSnapshot::GetSnapshot() const {
2067 return c_env_vector_.get();
2068 }
2069
2070 } // namespace art
2071