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 #endif
24 
25 #define ATRACE_TAG ATRACE_TAG_DALVIK
26 #include <cutils/trace.h>
27 #include <signal.h>
28 #include <sys/syscall.h>
29 #include <valgrind.h>
30 
31 #include <cstdio>
32 #include <cstdlib>
33 #include <limits>
34 #include <memory_representation.h>
35 #include <vector>
36 #include <fcntl.h>
37 
38 #include "JniConstants.h"
39 #include "ScopedLocalRef.h"
40 #include "arch/arm/quick_method_frame_info_arm.h"
41 #include "arch/arm/registers_arm.h"
42 #include "arch/arm64/quick_method_frame_info_arm64.h"
43 #include "arch/arm64/registers_arm64.h"
44 #include "arch/instruction_set_features.h"
45 #include "arch/mips/quick_method_frame_info_mips.h"
46 #include "arch/mips/registers_mips.h"
47 #include "arch/mips64/quick_method_frame_info_mips64.h"
48 #include "arch/mips64/registers_mips64.h"
49 #include "arch/x86/quick_method_frame_info_x86.h"
50 #include "arch/x86/registers_x86.h"
51 #include "arch/x86_64/quick_method_frame_info_x86_64.h"
52 #include "arch/x86_64/registers_x86_64.h"
53 #include "art_field-inl.h"
54 #include "art_method-inl.h"
55 #include "asm_support.h"
56 #include "atomic.h"
57 #include "base/arena_allocator.h"
58 #include "base/dumpable.h"
59 #include "base/unix_file/fd_file.h"
60 #include "class_linker-inl.h"
61 #include "compiler_callbacks.h"
62 #include "debugger.h"
63 #include "elf_file.h"
64 #include "entrypoints/runtime_asm_entrypoints.h"
65 #include "fault_handler.h"
66 #include "gc/accounting/card_table-inl.h"
67 #include "gc/heap.h"
68 #include "gc/space/image_space.h"
69 #include "gc/space/space-inl.h"
70 #include "handle_scope-inl.h"
71 #include "image.h"
72 #include "instrumentation.h"
73 #include "intern_table.h"
74 #include "interpreter/interpreter.h"
75 #include "jit/jit.h"
76 #include "jni_internal.h"
77 #include "linear_alloc.h"
78 #include "mirror/array.h"
79 #include "mirror/class-inl.h"
80 #include "mirror/class_loader.h"
81 #include "mirror/field.h"
82 #include "mirror/method.h"
83 #include "mirror/stack_trace_element.h"
84 #include "mirror/throwable.h"
85 #include "monitor.h"
86 #include "native/dalvik_system_DexFile.h"
87 #include "native/dalvik_system_VMDebug.h"
88 #include "native/dalvik_system_VMRuntime.h"
89 #include "native/dalvik_system_VMStack.h"
90 #include "native/dalvik_system_ZygoteHooks.h"
91 #include "native/java_lang_Class.h"
92 #include "native/java_lang_DexCache.h"
93 #include "native/java_lang_Object.h"
94 #include "native/java_lang_Runtime.h"
95 #include "native/java_lang_String.h"
96 #include "native/java_lang_StringFactory.h"
97 #include "native/java_lang_System.h"
98 #include "native/java_lang_Thread.h"
99 #include "native/java_lang_Throwable.h"
100 #include "native/java_lang_VMClassLoader.h"
101 #include "native/java_lang_ref_FinalizerReference.h"
102 #include "native/java_lang_ref_Reference.h"
103 #include "native/java_lang_reflect_Array.h"
104 #include "native/java_lang_reflect_Constructor.h"
105 #include "native/java_lang_reflect_Field.h"
106 #include "native/java_lang_reflect_Method.h"
107 #include "native/java_lang_reflect_Proxy.h"
108 #include "native/java_util_concurrent_atomic_AtomicLong.h"
109 #include "native/libcore_util_CharsetUtils.h"
110 #include "native/org_apache_harmony_dalvik_ddmc_DdmServer.h"
111 #include "native/org_apache_harmony_dalvik_ddmc_DdmVmInternal.h"
112 #include "native/sun_misc_Unsafe.h"
113 #include "native_bridge_art_interface.h"
114 #include "oat_file.h"
115 #include "os.h"
116 #include "parsed_options.h"
117 #include "profiler.h"
118 #include "quick/quick_method_frame_info.h"
119 #include "reflection.h"
120 #include "runtime_options.h"
121 #include "ScopedLocalRef.h"
122 #include "scoped_thread_state_change.h"
123 #include "sigchain.h"
124 #include "signal_catcher.h"
125 #include "signal_set.h"
126 #include "thread.h"
127 #include "thread_list.h"
128 #include "trace.h"
129 #include "transaction.h"
130 #include "verifier/method_verifier.h"
131 #include "well_known_classes.h"
132 
133 namespace art {
134 
135 // If a signal isn't handled properly, enable a handler that attempts to dump the Java stack.
136 static constexpr bool kEnableJavaStackTraceHandler = false;
137 Runtime* Runtime::instance_ = nullptr;
138 
139 struct TraceConfig {
140   Trace::TraceMode trace_mode;
141   Trace::TraceOutputMode trace_output_mode;
142   std::string trace_file;
143   size_t trace_file_size;
144 };
145 
Runtime()146 Runtime::Runtime()
147     : resolution_method_(nullptr),
148       imt_conflict_method_(nullptr),
149       imt_unimplemented_method_(nullptr),
150       instruction_set_(kNone),
151       compiler_callbacks_(nullptr),
152       is_zygote_(false),
153       must_relocate_(false),
154       is_concurrent_gc_enabled_(true),
155       is_explicit_gc_disabled_(false),
156       dex2oat_enabled_(true),
157       image_dex2oat_enabled_(true),
158       default_stack_size_(0),
159       heap_(nullptr),
160       max_spins_before_thin_lock_inflation_(Monitor::kDefaultMaxSpinsBeforeThinLockInflation),
161       monitor_list_(nullptr),
162       monitor_pool_(nullptr),
163       thread_list_(nullptr),
164       intern_table_(nullptr),
165       class_linker_(nullptr),
166       signal_catcher_(nullptr),
167       java_vm_(nullptr),
168       fault_message_lock_("Fault message lock"),
169       fault_message_(""),
170       threads_being_born_(0),
171       shutdown_cond_(new ConditionVariable("Runtime shutdown", *Locks::runtime_shutdown_lock_)),
172       shutting_down_(false),
173       shutting_down_started_(false),
174       started_(false),
175       finished_starting_(false),
176       vfprintf_(nullptr),
177       exit_(nullptr),
178       abort_(nullptr),
179       stats_enabled_(false),
180       running_on_valgrind_(RUNNING_ON_VALGRIND > 0),
181       profiler_started_(false),
182       instrumentation_(),
183       main_thread_group_(nullptr),
184       system_thread_group_(nullptr),
185       system_class_loader_(nullptr),
186       dump_gc_performance_on_shutdown_(false),
187       preinitialization_transaction_(nullptr),
188       verify_(false),
189       allow_dex_file_fallback_(true),
190       target_sdk_version_(0),
191       implicit_null_checks_(false),
192       implicit_so_checks_(false),
193       implicit_suspend_checks_(false),
194       is_native_bridge_loaded_(false),
195       zygote_max_failed_boots_(0) {
196   CheckAsmSupportOffsetsAndSizes();
197   std::fill(callee_save_methods_, callee_save_methods_ + arraysize(callee_save_methods_), 0u);
198 }
199 
~Runtime()200 Runtime::~Runtime() {
201   if (is_native_bridge_loaded_) {
202     UnloadNativeBridge();
203   }
204   if (dump_gc_performance_on_shutdown_) {
205     // This can't be called from the Heap destructor below because it
206     // could call RosAlloc::InspectAll() which needs the thread_list
207     // to be still alive.
208     heap_->DumpGcPerformanceInfo(LOG(INFO));
209   }
210 
211   Thread* self = Thread::Current();
212   const bool attach_shutdown_thread = self == nullptr;
213   if (attach_shutdown_thread) {
214     CHECK(AttachCurrentThread("Shutdown thread", false, nullptr, false));
215     self = Thread::Current();
216   } else {
217     LOG(WARNING) << "Current thread not detached in Runtime shutdown";
218   }
219 
220   {
221     MutexLock mu(self, *Locks::runtime_shutdown_lock_);
222     shutting_down_started_ = true;
223     while (threads_being_born_ > 0) {
224       shutdown_cond_->Wait(self);
225     }
226     shutting_down_ = true;
227   }
228   // Shutdown and wait for the daemons.
229   CHECK(self != nullptr);
230   if (IsFinishedStarting()) {
231     self->ClearException();
232     self->GetJniEnv()->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
233                                             WellKnownClasses::java_lang_Daemons_stop);
234   }
235   if (attach_shutdown_thread) {
236     DetachCurrentThread();
237     self = nullptr;
238   }
239 
240   // Shut down background profiler before the runtime exits.
241   if (profiler_started_) {
242     BackgroundMethodSamplingProfiler::Shutdown();
243   }
244 
245   Trace::Shutdown();
246 
247   // Make sure to let the GC complete if it is running.
248   heap_->WaitForGcToComplete(gc::kGcCauseBackground, self);
249   heap_->DeleteThreadPool();
250   if (jit_.get() != nullptr) {
251     VLOG(jit) << "Deleting jit thread pool";
252     // Delete thread pool before the thread list since we don't want to wait forever on the
253     // JIT compiler threads.
254     jit_->DeleteThreadPool();
255   }
256 
257   // Make sure our internal threads are dead before we start tearing down things they're using.
258   Dbg::StopJdwp();
259   delete signal_catcher_;
260 
261   // Make sure all other non-daemon threads have terminated, and all daemon threads are suspended.
262   delete thread_list_;
263 
264   // Delete the JIT after thread list to ensure that there is no remaining threads which could be
265   // accessing the instrumentation when we delete it.
266   if (jit_.get() != nullptr) {
267     VLOG(jit) << "Deleting jit";
268     jit_.reset(nullptr);
269   }
270   linear_alloc_.reset();
271   arena_pool_.reset();
272   low_4gb_arena_pool_.reset();
273 
274   // Shutdown the fault manager if it was initialized.
275   fault_manager.Shutdown();
276 
277   delete monitor_list_;
278   delete monitor_pool_;
279   delete class_linker_;
280   delete heap_;
281   delete intern_table_;
282   delete java_vm_;
283   Thread::Shutdown();
284   QuasiAtomic::Shutdown();
285   verifier::MethodVerifier::Shutdown();
286   MemMap::Shutdown();
287   // TODO: acquire a static mutex on Runtime to avoid racing.
288   CHECK(instance_ == nullptr || instance_ == this);
289   instance_ = nullptr;
290 }
291 
292 struct AbortState {
Dumpart::AbortState293   void Dump(std::ostream& os) const {
294     if (gAborting > 1) {
295       os << "Runtime aborting --- recursively, so no thread-specific detail!\n";
296       return;
297     }
298     gAborting++;
299     os << "Runtime aborting...\n";
300     if (Runtime::Current() == nullptr) {
301       os << "(Runtime does not yet exist!)\n";
302       return;
303     }
304     Thread* self = Thread::Current();
305     if (self == nullptr) {
306       os << "(Aborting thread was not attached to runtime!)\n";
307       DumpKernelStack(os, GetTid(), "  kernel: ", false);
308       DumpNativeStack(os, GetTid(), "  native: ", nullptr);
309     } else {
310       os << "Aborting thread:\n";
311       if (Locks::mutator_lock_->IsExclusiveHeld(self) || Locks::mutator_lock_->IsSharedHeld(self)) {
312         DumpThread(os, self);
313       } else {
314         if (Locks::mutator_lock_->SharedTryLock(self)) {
315           DumpThread(os, self);
316           Locks::mutator_lock_->SharedUnlock(self);
317         }
318       }
319     }
320     DumpAllThreads(os, self);
321   }
322 
323   // No thread-safety analysis as we do explicitly test for holding the mutator lock.
DumpThreadart::AbortState324   void DumpThread(std::ostream& os, Thread* self) const NO_THREAD_SAFETY_ANALYSIS {
325     DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self) || Locks::mutator_lock_->IsSharedHeld(self));
326     self->Dump(os);
327     if (self->IsExceptionPending()) {
328       mirror::Throwable* exception = self->GetException();
329       os << "Pending exception " << exception->Dump();
330     }
331   }
332 
DumpAllThreadsart::AbortState333   void DumpAllThreads(std::ostream& os, Thread* self) const {
334     Runtime* runtime = Runtime::Current();
335     if (runtime != nullptr) {
336       ThreadList* thread_list = runtime->GetThreadList();
337       if (thread_list != nullptr) {
338         bool tll_already_held = Locks::thread_list_lock_->IsExclusiveHeld(self);
339         bool ml_already_held = Locks::mutator_lock_->IsSharedHeld(self);
340         if (!tll_already_held || !ml_already_held) {
341           os << "Dumping all threads without appropriate locks held:"
342               << (!tll_already_held ? " thread list lock" : "")
343               << (!ml_already_held ? " mutator lock" : "")
344               << "\n";
345         }
346         os << "All threads:\n";
347         thread_list->Dump(os);
348       }
349     }
350   }
351 };
352 
Abort()353 void Runtime::Abort() {
354   gAborting++;  // set before taking any locks
355 
356   // Ensure that we don't have multiple threads trying to abort at once,
357   // which would result in significantly worse diagnostics.
358   MutexLock mu(Thread::Current(), *Locks::abort_lock_);
359 
360   // Get any pending output out of the way.
361   fflush(nullptr);
362 
363   // Many people have difficulty distinguish aborts from crashes,
364   // so be explicit.
365   AbortState state;
366   LOG(INTERNAL_FATAL) << Dumpable<AbortState>(state);
367 
368   // Call the abort hook if we have one.
369   if (Runtime::Current() != nullptr && Runtime::Current()->abort_ != nullptr) {
370     LOG(INTERNAL_FATAL) << "Calling abort hook...";
371     Runtime::Current()->abort_();
372     // notreached
373     LOG(INTERNAL_FATAL) << "Unexpectedly returned from abort hook!";
374   }
375 
376 #if defined(__GLIBC__)
377   // TODO: we ought to be able to use pthread_kill(3) here (or abort(3),
378   // which POSIX defines in terms of raise(3), which POSIX defines in terms
379   // of pthread_kill(3)). On Linux, though, libcorkscrew can't unwind through
380   // libpthread, which means the stacks we dump would be useless. Calling
381   // tgkill(2) directly avoids that.
382   syscall(__NR_tgkill, getpid(), GetTid(), SIGABRT);
383   // TODO: LLVM installs it's own SIGABRT handler so exit to be safe... Can we disable that in LLVM?
384   // If not, we could use sigaction(3) before calling tgkill(2) and lose this call to exit(3).
385   exit(1);
386 #else
387   abort();
388 #endif
389   // notreached
390 }
391 
PreZygoteFork()392 void Runtime::PreZygoteFork() {
393   heap_->PreZygoteFork();
394 }
395 
CallExitHook(jint status)396 void Runtime::CallExitHook(jint status) {
397   if (exit_ != nullptr) {
398     ScopedThreadStateChange tsc(Thread::Current(), kNative);
399     exit_(status);
400     LOG(WARNING) << "Exit hook returned instead of exiting!";
401   }
402 }
403 
SweepSystemWeaks(IsMarkedCallback * visitor,void * arg)404 void Runtime::SweepSystemWeaks(IsMarkedCallback* visitor, void* arg) {
405   GetInternTable()->SweepInternTableWeaks(visitor, arg);
406   GetMonitorList()->SweepMonitorList(visitor, arg);
407   GetJavaVM()->SweepJniWeakGlobals(visitor, arg);
408 }
409 
Create(const RuntimeOptions & options,bool ignore_unrecognized)410 bool Runtime::Create(const RuntimeOptions& options, bool ignore_unrecognized) {
411   // TODO: acquire a static mutex on Runtime to avoid racing.
412   if (Runtime::instance_ != nullptr) {
413     return false;
414   }
415   InitLogging(nullptr);  // Calls Locks::Init() as a side effect.
416   instance_ = new Runtime;
417   if (!instance_->Init(options, ignore_unrecognized)) {
418     // TODO: Currently deleting the instance will abort the runtime on destruction. Now This will
419     // leak memory, instead. Fix the destructor. b/19100793.
420     // delete instance_;
421     instance_ = nullptr;
422     return false;
423   }
424   return true;
425 }
426 
CreateSystemClassLoader(Runtime * runtime)427 static jobject CreateSystemClassLoader(Runtime* runtime) {
428   if (runtime->IsAotCompiler() && !runtime->GetCompilerCallbacks()->IsBootImage()) {
429     return nullptr;
430   }
431 
432   ScopedObjectAccess soa(Thread::Current());
433   ClassLinker* cl = Runtime::Current()->GetClassLinker();
434   auto pointer_size = cl->GetImagePointerSize();
435 
436   StackHandleScope<2> hs(soa.Self());
437   Handle<mirror::Class> class_loader_class(
438       hs.NewHandle(soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ClassLoader)));
439   CHECK(cl->EnsureInitialized(soa.Self(), class_loader_class, true, true));
440 
441   ArtMethod* getSystemClassLoader = class_loader_class->FindDirectMethod(
442       "getSystemClassLoader", "()Ljava/lang/ClassLoader;", pointer_size);
443   CHECK(getSystemClassLoader != nullptr);
444 
445   JValue result = InvokeWithJValues(soa, nullptr, soa.EncodeMethod(getSystemClassLoader), nullptr);
446   JNIEnv* env = soa.Self()->GetJniEnv();
447   ScopedLocalRef<jobject> system_class_loader(env, soa.AddLocalReference<jobject>(result.GetL()));
448   CHECK(system_class_loader.get() != nullptr);
449 
450   soa.Self()->SetClassLoaderOverride(system_class_loader.get());
451 
452   Handle<mirror::Class> thread_class(
453       hs.NewHandle(soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread)));
454   CHECK(cl->EnsureInitialized(soa.Self(), thread_class, true, true));
455 
456   ArtField* contextClassLoader =
457       thread_class->FindDeclaredInstanceField("contextClassLoader", "Ljava/lang/ClassLoader;");
458   CHECK(contextClassLoader != nullptr);
459 
460   // We can't run in a transaction yet.
461   contextClassLoader->SetObject<false>(soa.Self()->GetPeer(),
462                                        soa.Decode<mirror::ClassLoader*>(system_class_loader.get()));
463 
464   return env->NewGlobalRef(system_class_loader.get());
465 }
466 
GetPatchoatExecutable() const467 std::string Runtime::GetPatchoatExecutable() const {
468   if (!patchoat_executable_.empty()) {
469     return patchoat_executable_;
470   }
471   std::string patchoat_executable(GetAndroidRoot());
472   patchoat_executable += (kIsDebugBuild ? "/bin/patchoatd" : "/bin/patchoat");
473   return patchoat_executable;
474 }
475 
GetCompilerExecutable() const476 std::string Runtime::GetCompilerExecutable() const {
477   if (!compiler_executable_.empty()) {
478     return compiler_executable_;
479   }
480   std::string compiler_executable(GetAndroidRoot());
481   compiler_executable += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat");
482   return compiler_executable;
483 }
484 
Start()485 bool Runtime::Start() {
486   VLOG(startup) << "Runtime::Start entering";
487 
488   // Restore main thread state to kNative as expected by native code.
489   Thread* self = Thread::Current();
490 
491   self->TransitionFromRunnableToSuspended(kNative);
492 
493   started_ = true;
494 
495   // Use !IsAotCompiler so that we get test coverage, tests are never the zygote.
496   if (!IsAotCompiler()) {
497     ScopedObjectAccess soa(self);
498     gc::space::ImageSpace* image_space = heap_->GetImageSpace();
499     if (image_space != nullptr) {
500       ATRACE_BEGIN("AddImageStringsToTable");
501       GetInternTable()->AddImageStringsToTable(image_space);
502       ATRACE_END();
503       ATRACE_BEGIN("MoveImageClassesToClassTable");
504       GetClassLinker()->MoveImageClassesToClassTable();
505       ATRACE_END();
506     }
507   }
508 
509   // If we are the zygote then we need to wait until after forking to create the code cache
510   // due to SELinux restrictions on r/w/x memory regions.
511   if (!IsZygote() && jit_options_->UseJIT()) {
512     CreateJit();
513   }
514 
515   if (!IsImageDex2OatEnabled() || !GetHeap()->HasImageSpace()) {
516     ScopedObjectAccess soa(self);
517     StackHandleScope<1> hs(soa.Self());
518     auto klass(hs.NewHandle<mirror::Class>(mirror::Class::GetJavaLangClass()));
519     class_linker_->EnsureInitialized(soa.Self(), klass, true, true);
520   }
521 
522   // InitNativeMethods needs to be after started_ so that the classes
523   // it touches will have methods linked to the oat file if necessary.
524   ATRACE_BEGIN("InitNativeMethods");
525   InitNativeMethods();
526   ATRACE_END();
527 
528   // Initialize well known thread group values that may be accessed threads while attaching.
529   InitThreadGroups(self);
530 
531   Thread::FinishStartup();
532 
533   system_class_loader_ = CreateSystemClassLoader(this);
534 
535   if (is_zygote_) {
536     if (!InitZygote()) {
537       return false;
538     }
539   } else {
540     if (is_native_bridge_loaded_) {
541       PreInitializeNativeBridge(".");
542     }
543     DidForkFromZygote(self->GetJniEnv(), NativeBridgeAction::kInitialize,
544                       GetInstructionSetString(kRuntimeISA));
545   }
546 
547   ATRACE_BEGIN("StartDaemonThreads");
548   StartDaemonThreads();
549   ATRACE_END();
550 
551   {
552     ScopedObjectAccess soa(self);
553     self->GetJniEnv()->locals.AssertEmpty();
554   }
555 
556   VLOG(startup) << "Runtime::Start exiting";
557   finished_starting_ = true;
558 
559   if (profiler_options_.IsEnabled() && !profile_output_filename_.empty()) {
560     // User has asked for a profile using -Xenable-profiler.
561     // Create the profile file if it doesn't exist.
562     int fd = open(profile_output_filename_.c_str(), O_RDWR|O_CREAT|O_EXCL, 0660);
563     if (fd >= 0) {
564       close(fd);
565     } else if (errno != EEXIST) {
566       LOG(INFO) << "Failed to access the profile file. Profiler disabled.";
567       return true;
568     }
569     StartProfiler(profile_output_filename_.c_str());
570   }
571 
572   if (trace_config_.get() != nullptr && trace_config_->trace_file != "") {
573     ScopedThreadStateChange tsc(self, kWaitingForMethodTracingStart);
574     Trace::Start(trace_config_->trace_file.c_str(),
575                  -1,
576                  static_cast<int>(trace_config_->trace_file_size),
577                  0,
578                  trace_config_->trace_output_mode,
579                  trace_config_->trace_mode,
580                  0);
581   }
582 
583   return true;
584 }
585 
EndThreadBirth()586 void Runtime::EndThreadBirth() EXCLUSIVE_LOCKS_REQUIRED(Locks::runtime_shutdown_lock_) {
587   DCHECK_GT(threads_being_born_, 0U);
588   threads_being_born_--;
589   if (shutting_down_started_ && threads_being_born_ == 0) {
590     shutdown_cond_->Broadcast(Thread::Current());
591   }
592 }
593 
594 // Do zygote-mode-only initialization.
InitZygote()595 bool Runtime::InitZygote() {
596 #ifdef __linux__
597   // zygote goes into its own process group
598   setpgid(0, 0);
599 
600   // See storage config details at http://source.android.com/tech/storage/
601   // Create private mount namespace shared by all children
602   if (unshare(CLONE_NEWNS) == -1) {
603     PLOG(WARNING) << "Failed to unshare()";
604     return false;
605   }
606 
607   // Mark rootfs as being a slave so that changes from default
608   // namespace only flow into our children.
609   if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
610     PLOG(WARNING) << "Failed to mount() rootfs as MS_SLAVE";
611     return false;
612   }
613 
614   // Create a staging tmpfs that is shared by our children; they will
615   // bind mount storage into their respective private namespaces, which
616   // are isolated from each other.
617   const char* target_base = getenv("EMULATED_STORAGE_TARGET");
618   if (target_base != nullptr) {
619     if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
620               "uid=0,gid=1028,mode=0751") == -1) {
621       LOG(WARNING) << "Failed to mount tmpfs to " << target_base;
622       return false;
623     }
624   }
625 
626   return true;
627 #else
628   UNIMPLEMENTED(FATAL);
629   return false;
630 #endif
631 }
632 
DidForkFromZygote(JNIEnv * env,NativeBridgeAction action,const char * isa)633 void Runtime::DidForkFromZygote(JNIEnv* env, NativeBridgeAction action, const char* isa) {
634   is_zygote_ = false;
635 
636   if (is_native_bridge_loaded_) {
637     switch (action) {
638       case NativeBridgeAction::kUnload:
639         UnloadNativeBridge();
640         is_native_bridge_loaded_ = false;
641         break;
642 
643       case NativeBridgeAction::kInitialize:
644         InitializeNativeBridge(env, isa);
645         break;
646     }
647   }
648 
649   // Create the thread pools.
650   heap_->CreateThreadPool();
651   // Reset the gc performance data at zygote fork so that the GCs
652   // before fork aren't attributed to an app.
653   heap_->ResetGcPerformanceInfo();
654 
655   if (jit_.get() == nullptr && jit_options_->UseJIT()) {
656     // Create the JIT if the flag is set and we haven't already create it (happens for run-tests).
657     CreateJit();
658   }
659 
660   StartSignalCatcher();
661 
662   // Start the JDWP thread. If the command-line debugger flags specified "suspend=y",
663   // this will pause the runtime, so we probably want this to come last.
664   Dbg::StartJdwp();
665 }
666 
StartSignalCatcher()667 void Runtime::StartSignalCatcher() {
668   if (!is_zygote_) {
669     signal_catcher_ = new SignalCatcher(stack_trace_file_);
670   }
671 }
672 
IsShuttingDown(Thread * self)673 bool Runtime::IsShuttingDown(Thread* self) {
674   MutexLock mu(self, *Locks::runtime_shutdown_lock_);
675   return IsShuttingDownLocked();
676 }
677 
StartDaemonThreads()678 void Runtime::StartDaemonThreads() {
679   VLOG(startup) << "Runtime::StartDaemonThreads entering";
680 
681   Thread* self = Thread::Current();
682 
683   // Must be in the kNative state for calling native methods.
684   CHECK_EQ(self->GetState(), kNative);
685 
686   JNIEnv* env = self->GetJniEnv();
687   env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
688                             WellKnownClasses::java_lang_Daemons_start);
689   if (env->ExceptionCheck()) {
690     env->ExceptionDescribe();
691     LOG(FATAL) << "Error starting java.lang.Daemons";
692   }
693 
694   VLOG(startup) << "Runtime::StartDaemonThreads exiting";
695 }
696 
OpenDexFilesFromImage(const std::string & image_location,std::vector<std::unique_ptr<const DexFile>> * dex_files,size_t * failures)697 static bool OpenDexFilesFromImage(const std::string& image_location,
698                                   std::vector<std::unique_ptr<const DexFile>>* dex_files,
699                                   size_t* failures) {
700   DCHECK(dex_files != nullptr) << "OpenDexFilesFromImage: out-param is nullptr";
701   std::string system_filename;
702   bool has_system = false;
703   std::string cache_filename_unused;
704   bool dalvik_cache_exists_unused;
705   bool has_cache_unused;
706   bool is_global_cache_unused;
707   bool found_image = gc::space::ImageSpace::FindImageFilename(image_location.c_str(),
708                                                               kRuntimeISA,
709                                                               &system_filename,
710                                                               &has_system,
711                                                               &cache_filename_unused,
712                                                               &dalvik_cache_exists_unused,
713                                                               &has_cache_unused,
714                                                               &is_global_cache_unused);
715   *failures = 0;
716   if (!found_image || !has_system) {
717     return false;
718   }
719   std::string error_msg;
720   // We are falling back to non-executable use of the oat file because patching failed, presumably
721   // due to lack of space.
722   std::string oat_filename = ImageHeader::GetOatLocationFromImageLocation(system_filename.c_str());
723   std::string oat_location = ImageHeader::GetOatLocationFromImageLocation(image_location.c_str());
724   std::unique_ptr<File> file(OS::OpenFileForReading(oat_filename.c_str()));
725   if (file.get() == nullptr) {
726     return false;
727   }
728   std::unique_ptr<ElfFile> elf_file(ElfFile::Open(file.release(), false, false, &error_msg));
729   if (elf_file.get() == nullptr) {
730     return false;
731   }
732   std::unique_ptr<OatFile> oat_file(OatFile::OpenWithElfFile(elf_file.release(), oat_location,
733                                                              nullptr, &error_msg));
734   if (oat_file.get() == nullptr) {
735     LOG(INFO) << "Unable to use '" << oat_filename << "' because " << error_msg;
736     return false;
737   }
738 
739   for (const OatFile::OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) {
740     if (oat_dex_file == nullptr) {
741       *failures += 1;
742       continue;
743     }
744     std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
745     if (dex_file.get() == nullptr) {
746       *failures += 1;
747     } else {
748       dex_files->push_back(std::move(dex_file));
749     }
750   }
751   Runtime::Current()->GetClassLinker()->RegisterOatFile(oat_file.release());
752   return true;
753 }
754 
755 
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)756 static size_t OpenDexFiles(const std::vector<std::string>& dex_filenames,
757                            const std::vector<std::string>& dex_locations,
758                            const std::string& image_location,
759                            std::vector<std::unique_ptr<const DexFile>>* dex_files) {
760   DCHECK(dex_files != nullptr) << "OpenDexFiles: out-param is nullptr";
761   size_t failure_count = 0;
762   if (!image_location.empty() && OpenDexFilesFromImage(image_location, dex_files, &failure_count)) {
763     return failure_count;
764   }
765   failure_count = 0;
766   for (size_t i = 0; i < dex_filenames.size(); i++) {
767     const char* dex_filename = dex_filenames[i].c_str();
768     const char* dex_location = dex_locations[i].c_str();
769     std::string error_msg;
770     if (!OS::FileExists(dex_filename)) {
771       LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
772       continue;
773     }
774     if (!DexFile::Open(dex_filename, dex_location, &error_msg, dex_files)) {
775       LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
776       ++failure_count;
777     }
778   }
779   return failure_count;
780 }
781 
Init(const RuntimeOptions & raw_options,bool ignore_unrecognized)782 bool Runtime::Init(const RuntimeOptions& raw_options, bool ignore_unrecognized) {
783   ATRACE_BEGIN("Runtime::Init");
784   CHECK_EQ(sysconf(_SC_PAGE_SIZE), kPageSize);
785 
786   MemMap::Init();
787 
788   using Opt = RuntimeArgumentMap;
789   RuntimeArgumentMap runtime_options;
790   std::unique_ptr<ParsedOptions> parsed_options(
791       ParsedOptions::Create(raw_options, ignore_unrecognized, &runtime_options));
792   if (parsed_options.get() == nullptr) {
793     LOG(ERROR) << "Failed to parse options";
794     ATRACE_END();
795     return false;
796   }
797   VLOG(startup) << "Runtime::Init -verbose:startup enabled";
798 
799   QuasiAtomic::Startup();
800 
801   Monitor::Init(runtime_options.GetOrDefault(Opt::LockProfThreshold),
802                 runtime_options.GetOrDefault(Opt::HookIsSensitiveThread));
803 
804   boot_class_path_string_ = runtime_options.ReleaseOrDefault(Opt::BootClassPath);
805   class_path_string_ = runtime_options.ReleaseOrDefault(Opt::ClassPath);
806   properties_ = runtime_options.ReleaseOrDefault(Opt::PropertiesList);
807 
808   compiler_callbacks_ = runtime_options.GetOrDefault(Opt::CompilerCallbacksPtr);
809   patchoat_executable_ = runtime_options.ReleaseOrDefault(Opt::PatchOat);
810   must_relocate_ = runtime_options.GetOrDefault(Opt::Relocate);
811   is_zygote_ = runtime_options.Exists(Opt::Zygote);
812   is_explicit_gc_disabled_ = runtime_options.Exists(Opt::DisableExplicitGC);
813   dex2oat_enabled_ = runtime_options.GetOrDefault(Opt::Dex2Oat);
814   image_dex2oat_enabled_ = runtime_options.GetOrDefault(Opt::ImageDex2Oat);
815 
816   vfprintf_ = runtime_options.GetOrDefault(Opt::HookVfprintf);
817   exit_ = runtime_options.GetOrDefault(Opt::HookExit);
818   abort_ = runtime_options.GetOrDefault(Opt::HookAbort);
819 
820   default_stack_size_ = runtime_options.GetOrDefault(Opt::StackSize);
821   stack_trace_file_ = runtime_options.ReleaseOrDefault(Opt::StackTraceFile);
822 
823   compiler_executable_ = runtime_options.ReleaseOrDefault(Opt::Compiler);
824   compiler_options_ = runtime_options.ReleaseOrDefault(Opt::CompilerOptions);
825   image_compiler_options_ = runtime_options.ReleaseOrDefault(Opt::ImageCompilerOptions);
826   image_location_ = runtime_options.GetOrDefault(Opt::Image);
827 
828   max_spins_before_thin_lock_inflation_ =
829       runtime_options.GetOrDefault(Opt::MaxSpinsBeforeThinLockInflation);
830 
831   monitor_list_ = new MonitorList;
832   monitor_pool_ = MonitorPool::Create();
833   thread_list_ = new ThreadList;
834   intern_table_ = new InternTable;
835 
836   verify_ = runtime_options.GetOrDefault(Opt::Verify);
837   allow_dex_file_fallback_ = !runtime_options.Exists(Opt::NoDexFileFallback);
838 
839   Split(runtime_options.GetOrDefault(Opt::CpuAbiList), ',', &cpu_abilist_);
840 
841   fingerprint_ = runtime_options.ReleaseOrDefault(Opt::Fingerprint);
842 
843   if (runtime_options.GetOrDefault(Opt::Interpret)) {
844     GetInstrumentation()->ForceInterpretOnly();
845   }
846 
847   zygote_max_failed_boots_ = runtime_options.GetOrDefault(Opt::ZygoteMaxFailedBoots);
848 
849   XGcOption xgc_option = runtime_options.GetOrDefault(Opt::GcOption);
850   ATRACE_BEGIN("CreateHeap");
851   heap_ = new gc::Heap(runtime_options.GetOrDefault(Opt::MemoryInitialSize),
852                        runtime_options.GetOrDefault(Opt::HeapGrowthLimit),
853                        runtime_options.GetOrDefault(Opt::HeapMinFree),
854                        runtime_options.GetOrDefault(Opt::HeapMaxFree),
855                        runtime_options.GetOrDefault(Opt::HeapTargetUtilization),
856                        runtime_options.GetOrDefault(Opt::ForegroundHeapGrowthMultiplier),
857                        runtime_options.GetOrDefault(Opt::MemoryMaximumSize),
858                        runtime_options.GetOrDefault(Opt::NonMovingSpaceCapacity),
859                        runtime_options.GetOrDefault(Opt::Image),
860                        runtime_options.GetOrDefault(Opt::ImageInstructionSet),
861                        xgc_option.collector_type_,
862                        runtime_options.GetOrDefault(Opt::BackgroundGc),
863                        runtime_options.GetOrDefault(Opt::LargeObjectSpace),
864                        runtime_options.GetOrDefault(Opt::LargeObjectThreshold),
865                        runtime_options.GetOrDefault(Opt::ParallelGCThreads),
866                        runtime_options.GetOrDefault(Opt::ConcGCThreads),
867                        runtime_options.Exists(Opt::LowMemoryMode),
868                        runtime_options.GetOrDefault(Opt::LongPauseLogThreshold),
869                        runtime_options.GetOrDefault(Opt::LongGCLogThreshold),
870                        runtime_options.Exists(Opt::IgnoreMaxFootprint),
871                        runtime_options.GetOrDefault(Opt::UseTLAB),
872                        xgc_option.verify_pre_gc_heap_,
873                        xgc_option.verify_pre_sweeping_heap_,
874                        xgc_option.verify_post_gc_heap_,
875                        xgc_option.verify_pre_gc_rosalloc_,
876                        xgc_option.verify_pre_sweeping_rosalloc_,
877                        xgc_option.verify_post_gc_rosalloc_,
878                        xgc_option.gcstress_,
879                        runtime_options.GetOrDefault(Opt::EnableHSpaceCompactForOOM),
880                        runtime_options.GetOrDefault(Opt::HSpaceCompactForOOMMinIntervalsMs));
881   ATRACE_END();
882 
883   if (heap_->GetImageSpace() == nullptr && !allow_dex_file_fallback_) {
884     LOG(ERROR) << "Dex file fallback disabled, cannot continue without image.";
885     ATRACE_END();
886     return false;
887   }
888 
889   dump_gc_performance_on_shutdown_ = runtime_options.Exists(Opt::DumpGCPerformanceOnShutdown);
890 
891   if (runtime_options.Exists(Opt::JdwpOptions)) {
892     Dbg::ConfigureJdwp(runtime_options.GetOrDefault(Opt::JdwpOptions));
893   }
894 
895   jit_options_.reset(jit::JitOptions::CreateFromRuntimeArguments(runtime_options));
896   if (IsAotCompiler()) {
897     // If we are already the compiler at this point, we must be dex2oat. Don't create the jit in
898     // this case.
899     // If runtime_options doesn't have UseJIT set to true then CreateFromRuntimeArguments returns
900     // null and we don't create the jit.
901     jit_options_->SetUseJIT(false);
902   }
903 
904   // Use MemMap arena pool for jit, malloc otherwise. Malloc arenas are faster to allocate but
905   // can't be trimmed as easily.
906   const bool use_malloc = IsAotCompiler();
907   arena_pool_.reset(new ArenaPool(use_malloc, false));
908   if (IsCompiler() && Is64BitInstructionSet(kRuntimeISA)) {
909     // 4gb, no malloc. Explanation in header.
910     low_4gb_arena_pool_.reset(new ArenaPool(false, true));
911     linear_alloc_.reset(new LinearAlloc(low_4gb_arena_pool_.get()));
912   } else {
913     linear_alloc_.reset(new LinearAlloc(arena_pool_.get()));
914   }
915 
916   BlockSignals();
917   InitPlatformSignalHandlers();
918 
919   // Change the implicit checks flags based on runtime architecture.
920   switch (kRuntimeISA) {
921     case kArm:
922     case kThumb2:
923     case kX86:
924     case kArm64:
925     case kX86_64:
926     case kMips:
927     case kMips64:
928       implicit_null_checks_ = true;
929       // Installing stack protection does not play well with valgrind.
930       implicit_so_checks_ = (RUNNING_ON_VALGRIND == 0);
931       break;
932     default:
933       // Keep the defaults.
934       break;
935   }
936 
937   // Always initialize the signal chain so that any calls to sigaction get
938   // correctly routed to the next in the chain regardless of whether we
939   // have claimed the signal or not.
940   InitializeSignalChain();
941 
942   if (implicit_null_checks_ || implicit_so_checks_ || implicit_suspend_checks_) {
943     fault_manager.Init();
944 
945     // These need to be in a specific order.  The null point check handler must be
946     // after the suspend check and stack overflow check handlers.
947     //
948     // Note: the instances attach themselves to the fault manager and are handled by it. The manager
949     //       will delete the instance on Shutdown().
950     if (implicit_suspend_checks_) {
951       new SuspensionHandler(&fault_manager);
952     }
953 
954     if (implicit_so_checks_) {
955       new StackOverflowHandler(&fault_manager);
956     }
957 
958     if (implicit_null_checks_) {
959       new NullPointerHandler(&fault_manager);
960     }
961 
962     if (kEnableJavaStackTraceHandler) {
963       new JavaStackTraceHandler(&fault_manager);
964     }
965   }
966 
967   java_vm_ = new JavaVMExt(this, runtime_options);
968 
969   Thread::Startup();
970 
971   // ClassLinker needs an attached thread, but we can't fully attach a thread without creating
972   // objects. We can't supply a thread group yet; it will be fixed later. Since we are the main
973   // thread, we do not get a java peer.
974   Thread* self = Thread::Attach("main", false, nullptr, false);
975   CHECK_EQ(self->GetThreadId(), ThreadList::kMainThreadId);
976   CHECK(self != nullptr);
977 
978   // Set us to runnable so tools using a runtime can allocate and GC by default
979   self->TransitionFromSuspendedToRunnable();
980 
981   // Now we're attached, we can take the heap locks and validate the heap.
982   GetHeap()->EnableObjectValidation();
983 
984   CHECK_GE(GetHeap()->GetContinuousSpaces().size(), 1U);
985   class_linker_ = new ClassLinker(intern_table_);
986   if (GetHeap()->HasImageSpace()) {
987     ATRACE_BEGIN("InitFromImage");
988     class_linker_->InitFromImage();
989     ATRACE_END();
990     if (kIsDebugBuild) {
991       GetHeap()->GetImageSpace()->VerifyImageAllocations();
992     }
993     if (boot_class_path_string_.empty()) {
994       // The bootclasspath is not explicitly specified: construct it from the loaded dex files.
995       const std::vector<const DexFile*>& boot_class_path = GetClassLinker()->GetBootClassPath();
996       std::vector<std::string> dex_locations;
997       dex_locations.reserve(boot_class_path.size());
998       for (const DexFile* dex_file : boot_class_path) {
999         dex_locations.push_back(dex_file->GetLocation());
1000       }
1001       boot_class_path_string_ = Join(dex_locations, ':');
1002     }
1003   } else {
1004     std::vector<std::string> dex_filenames;
1005     Split(boot_class_path_string_, ':', &dex_filenames);
1006 
1007     std::vector<std::string> dex_locations;
1008     if (!runtime_options.Exists(Opt::BootClassPathLocations)) {
1009       dex_locations = dex_filenames;
1010     } else {
1011       dex_locations = runtime_options.GetOrDefault(Opt::BootClassPathLocations);
1012       CHECK_EQ(dex_filenames.size(), dex_locations.size());
1013     }
1014 
1015     std::vector<std::unique_ptr<const DexFile>> boot_class_path;
1016     OpenDexFiles(dex_filenames,
1017                  dex_locations,
1018                  runtime_options.GetOrDefault(Opt::Image),
1019                  &boot_class_path);
1020     instruction_set_ = runtime_options.GetOrDefault(Opt::ImageInstructionSet);
1021     class_linker_->InitWithoutImage(std::move(boot_class_path));
1022 
1023     // TODO: Should we move the following to InitWithoutImage?
1024     SetInstructionSet(instruction_set_);
1025     for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
1026       Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
1027       if (!HasCalleeSaveMethod(type)) {
1028         SetCalleeSaveMethod(CreateCalleeSaveMethod(), type);
1029       }
1030     }
1031   }
1032 
1033   CHECK(class_linker_ != nullptr);
1034 
1035   // Initialize the special sentinel_ value early.
1036   sentinel_ = GcRoot<mirror::Object>(class_linker_->AllocObject(self));
1037   CHECK(sentinel_.Read() != nullptr);
1038 
1039   verifier::MethodVerifier::Init();
1040 
1041   if (runtime_options.Exists(Opt::MethodTrace)) {
1042     trace_config_.reset(new TraceConfig());
1043     trace_config_->trace_file = runtime_options.ReleaseOrDefault(Opt::MethodTraceFile);
1044     trace_config_->trace_file_size = runtime_options.ReleaseOrDefault(Opt::MethodTraceFileSize);
1045     trace_config_->trace_mode = Trace::TraceMode::kMethodTracing;
1046     trace_config_->trace_output_mode = runtime_options.Exists(Opt::MethodTraceStreaming) ?
1047         Trace::TraceOutputMode::kStreaming :
1048         Trace::TraceOutputMode::kFile;
1049   }
1050 
1051   {
1052     auto&& profiler_options = runtime_options.ReleaseOrDefault(Opt::ProfilerOpts);
1053     profile_output_filename_ = profiler_options.output_file_name_;
1054 
1055     // TODO: Don't do this, just change ProfilerOptions to include the output file name?
1056     ProfilerOptions other_options(
1057         profiler_options.enabled_,
1058         profiler_options.period_s_,
1059         profiler_options.duration_s_,
1060         profiler_options.interval_us_,
1061         profiler_options.backoff_coefficient_,
1062         profiler_options.start_immediately_,
1063         profiler_options.top_k_threshold_,
1064         profiler_options.top_k_change_threshold_,
1065         profiler_options.profile_type_,
1066         profiler_options.max_stack_depth_);
1067 
1068     profiler_options_ = other_options;
1069   }
1070 
1071   // TODO: move this to just be an Trace::Start argument
1072   Trace::SetDefaultClockSource(runtime_options.GetOrDefault(Opt::ProfileClock));
1073 
1074   // Pre-allocate an OutOfMemoryError for the double-OOME case.
1075   self->ThrowNewException("Ljava/lang/OutOfMemoryError;",
1076                           "OutOfMemoryError thrown while trying to throw OutOfMemoryError; "
1077                           "no stack trace available");
1078   pre_allocated_OutOfMemoryError_ = GcRoot<mirror::Throwable>(self->GetException());
1079   self->ClearException();
1080 
1081   // Pre-allocate a NoClassDefFoundError for the common case of failing to find a system class
1082   // ahead of checking the application's class loader.
1083   self->ThrowNewException("Ljava/lang/NoClassDefFoundError;",
1084                           "Class not found using the boot class loader; no stack trace available");
1085   pre_allocated_NoClassDefFoundError_ = GcRoot<mirror::Throwable>(self->GetException());
1086   self->ClearException();
1087 
1088   // Look for a native bridge.
1089   //
1090   // The intended flow here is, in the case of a running system:
1091   //
1092   // Runtime::Init() (zygote):
1093   //   LoadNativeBridge -> dlopen from cmd line parameter.
1094   //  |
1095   //  V
1096   // Runtime::Start() (zygote):
1097   //   No-op wrt native bridge.
1098   //  |
1099   //  | start app
1100   //  V
1101   // DidForkFromZygote(action)
1102   //   action = kUnload -> dlclose native bridge.
1103   //   action = kInitialize -> initialize library
1104   //
1105   //
1106   // The intended flow here is, in the case of a simple dalvikvm call:
1107   //
1108   // Runtime::Init():
1109   //   LoadNativeBridge -> dlopen from cmd line parameter.
1110   //  |
1111   //  V
1112   // Runtime::Start():
1113   //   DidForkFromZygote(kInitialize) -> try to initialize any native bridge given.
1114   //   No-op wrt native bridge.
1115   {
1116     std::string native_bridge_file_name = runtime_options.ReleaseOrDefault(Opt::NativeBridge);
1117     is_native_bridge_loaded_ = LoadNativeBridge(native_bridge_file_name);
1118   }
1119 
1120   VLOG(startup) << "Runtime::Init exiting";
1121 
1122   ATRACE_END();
1123 
1124   return true;
1125 }
1126 
InitNativeMethods()1127 void Runtime::InitNativeMethods() {
1128   VLOG(startup) << "Runtime::InitNativeMethods entering";
1129   Thread* self = Thread::Current();
1130   JNIEnv* env = self->GetJniEnv();
1131 
1132   // Must be in the kNative state for calling native methods (JNI_OnLoad code).
1133   CHECK_EQ(self->GetState(), kNative);
1134 
1135   // First set up JniConstants, which is used by both the runtime's built-in native
1136   // methods and libcore.
1137   JniConstants::init(env);
1138   WellKnownClasses::Init(env);
1139 
1140   // Then set up the native methods provided by the runtime itself.
1141   RegisterRuntimeNativeMethods(env);
1142 
1143   // Then set up libcore, which is just a regular JNI library with a regular JNI_OnLoad.
1144   // Most JNI libraries can just use System.loadLibrary, but libcore can't because it's
1145   // the library that implements System.loadLibrary!
1146   {
1147     std::string reason;
1148     if (!java_vm_->LoadNativeLibrary(env, "libjavacore.so", nullptr, &reason)) {
1149       LOG(FATAL) << "LoadNativeLibrary failed for \"libjavacore.so\": " << reason;
1150     }
1151   }
1152 
1153   // Initialize well known classes that may invoke runtime native methods.
1154   WellKnownClasses::LateInit(env);
1155 
1156   VLOG(startup) << "Runtime::InitNativeMethods exiting";
1157 }
1158 
InitThreadGroups(Thread * self)1159 void Runtime::InitThreadGroups(Thread* self) {
1160   JNIEnvExt* env = self->GetJniEnv();
1161   ScopedJniEnvLocalRefState env_state(env);
1162   main_thread_group_ =
1163       env->NewGlobalRef(env->GetStaticObjectField(
1164           WellKnownClasses::java_lang_ThreadGroup,
1165           WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup));
1166   CHECK(main_thread_group_ != nullptr || IsAotCompiler());
1167   system_thread_group_ =
1168       env->NewGlobalRef(env->GetStaticObjectField(
1169           WellKnownClasses::java_lang_ThreadGroup,
1170           WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup));
1171   CHECK(system_thread_group_ != nullptr || IsAotCompiler());
1172 }
1173 
GetMainThreadGroup() const1174 jobject Runtime::GetMainThreadGroup() const {
1175   CHECK(main_thread_group_ != nullptr || IsAotCompiler());
1176   return main_thread_group_;
1177 }
1178 
GetSystemThreadGroup() const1179 jobject Runtime::GetSystemThreadGroup() const {
1180   CHECK(system_thread_group_ != nullptr || IsAotCompiler());
1181   return system_thread_group_;
1182 }
1183 
GetSystemClassLoader() const1184 jobject Runtime::GetSystemClassLoader() const {
1185   CHECK(system_class_loader_ != nullptr || IsAotCompiler());
1186   return system_class_loader_;
1187 }
1188 
RegisterRuntimeNativeMethods(JNIEnv * env)1189 void Runtime::RegisterRuntimeNativeMethods(JNIEnv* env) {
1190   register_dalvik_system_DexFile(env);
1191   register_dalvik_system_VMDebug(env);
1192   register_dalvik_system_VMRuntime(env);
1193   register_dalvik_system_VMStack(env);
1194   register_dalvik_system_ZygoteHooks(env);
1195   register_java_lang_Class(env);
1196   register_java_lang_DexCache(env);
1197   register_java_lang_Object(env);
1198   register_java_lang_ref_FinalizerReference(env);
1199   register_java_lang_reflect_Array(env);
1200   register_java_lang_reflect_Constructor(env);
1201   register_java_lang_reflect_Field(env);
1202   register_java_lang_reflect_Method(env);
1203   register_java_lang_reflect_Proxy(env);
1204   register_java_lang_ref_Reference(env);
1205   register_java_lang_Runtime(env);
1206   register_java_lang_String(env);
1207   register_java_lang_StringFactory(env);
1208   register_java_lang_System(env);
1209   register_java_lang_Thread(env);
1210   register_java_lang_Throwable(env);
1211   register_java_lang_VMClassLoader(env);
1212   register_java_util_concurrent_atomic_AtomicLong(env);
1213   register_libcore_util_CharsetUtils(env);
1214   register_org_apache_harmony_dalvik_ddmc_DdmServer(env);
1215   register_org_apache_harmony_dalvik_ddmc_DdmVmInternal(env);
1216   register_sun_misc_Unsafe(env);
1217 }
1218 
DumpForSigQuit(std::ostream & os)1219 void Runtime::DumpForSigQuit(std::ostream& os) {
1220   GetClassLinker()->DumpForSigQuit(os);
1221   GetInternTable()->DumpForSigQuit(os);
1222   GetJavaVM()->DumpForSigQuit(os);
1223   GetHeap()->DumpForSigQuit(os);
1224   TrackedAllocators::Dump(os);
1225   os << "\n";
1226 
1227   thread_list_->DumpForSigQuit(os);
1228   BaseMutex::DumpAll(os);
1229 }
1230 
DumpLockHolders(std::ostream & os)1231 void Runtime::DumpLockHolders(std::ostream& os) {
1232   uint64_t mutator_lock_owner = Locks::mutator_lock_->GetExclusiveOwnerTid();
1233   pid_t thread_list_lock_owner = GetThreadList()->GetLockOwner();
1234   pid_t classes_lock_owner = GetClassLinker()->GetClassesLockOwner();
1235   pid_t dex_lock_owner = GetClassLinker()->GetDexLockOwner();
1236   if ((thread_list_lock_owner | classes_lock_owner | dex_lock_owner) != 0) {
1237     os << "Mutator lock exclusive owner tid: " << mutator_lock_owner << "\n"
1238        << "ThreadList lock owner tid: " << thread_list_lock_owner << "\n"
1239        << "ClassLinker classes lock owner tid: " << classes_lock_owner << "\n"
1240        << "ClassLinker dex lock owner tid: " << dex_lock_owner << "\n";
1241   }
1242 }
1243 
SetStatsEnabled(bool new_state)1244 void Runtime::SetStatsEnabled(bool new_state) {
1245   Thread* self = Thread::Current();
1246   MutexLock mu(self, *Locks::instrument_entrypoints_lock_);
1247   if (new_state == true) {
1248     GetStats()->Clear(~0);
1249     // TODO: wouldn't it make more sense to clear _all_ threads' stats?
1250     self->GetStats()->Clear(~0);
1251     if (stats_enabled_ != new_state) {
1252       GetInstrumentation()->InstrumentQuickAllocEntryPointsLocked();
1253     }
1254   } else if (stats_enabled_ != new_state) {
1255     GetInstrumentation()->UninstrumentQuickAllocEntryPointsLocked();
1256   }
1257   stats_enabled_ = new_state;
1258 }
1259 
ResetStats(int kinds)1260 void Runtime::ResetStats(int kinds) {
1261   GetStats()->Clear(kinds & 0xffff);
1262   // TODO: wouldn't it make more sense to clear _all_ threads' stats?
1263   Thread::Current()->GetStats()->Clear(kinds >> 16);
1264 }
1265 
GetStat(int kind)1266 int32_t Runtime::GetStat(int kind) {
1267   RuntimeStats* stats;
1268   if (kind < (1<<16)) {
1269     stats = GetStats();
1270   } else {
1271     stats = Thread::Current()->GetStats();
1272     kind >>= 16;
1273   }
1274   switch (kind) {
1275   case KIND_ALLOCATED_OBJECTS:
1276     return stats->allocated_objects;
1277   case KIND_ALLOCATED_BYTES:
1278     return stats->allocated_bytes;
1279   case KIND_FREED_OBJECTS:
1280     return stats->freed_objects;
1281   case KIND_FREED_BYTES:
1282     return stats->freed_bytes;
1283   case KIND_GC_INVOCATIONS:
1284     return stats->gc_for_alloc_count;
1285   case KIND_CLASS_INIT_COUNT:
1286     return stats->class_init_count;
1287   case KIND_CLASS_INIT_TIME:
1288     // Convert ns to us, reduce to 32 bits.
1289     return static_cast<int>(stats->class_init_time_ns / 1000);
1290   case KIND_EXT_ALLOCATED_OBJECTS:
1291   case KIND_EXT_ALLOCATED_BYTES:
1292   case KIND_EXT_FREED_OBJECTS:
1293   case KIND_EXT_FREED_BYTES:
1294     return 0;  // backward compatibility
1295   default:
1296     LOG(FATAL) << "Unknown statistic " << kind;
1297     return -1;  // unreachable
1298   }
1299 }
1300 
BlockSignals()1301 void Runtime::BlockSignals() {
1302   SignalSet signals;
1303   signals.Add(SIGPIPE);
1304   // SIGQUIT is used to dump the runtime's state (including stack traces).
1305   signals.Add(SIGQUIT);
1306   // SIGUSR1 is used to initiate a GC.
1307   signals.Add(SIGUSR1);
1308   signals.Block();
1309 }
1310 
AttachCurrentThread(const char * thread_name,bool as_daemon,jobject thread_group,bool create_peer)1311 bool Runtime::AttachCurrentThread(const char* thread_name, bool as_daemon, jobject thread_group,
1312                                   bool create_peer) {
1313   return Thread::Attach(thread_name, as_daemon, thread_group, create_peer) != nullptr;
1314 }
1315 
DetachCurrentThread()1316 void Runtime::DetachCurrentThread() {
1317   Thread* self = Thread::Current();
1318   if (self == nullptr) {
1319     LOG(FATAL) << "attempting to detach thread that is not attached";
1320   }
1321   if (self->HasManagedStack()) {
1322     LOG(FATAL) << *Thread::Current() << " attempting to detach while still running code";
1323   }
1324   thread_list_->Unregister(self);
1325 }
1326 
GetPreAllocatedOutOfMemoryError()1327 mirror::Throwable* Runtime::GetPreAllocatedOutOfMemoryError() {
1328   mirror::Throwable* oome = pre_allocated_OutOfMemoryError_.Read();
1329   if (oome == nullptr) {
1330     LOG(ERROR) << "Failed to return pre-allocated OOME";
1331   }
1332   return oome;
1333 }
1334 
GetPreAllocatedNoClassDefFoundError()1335 mirror::Throwable* Runtime::GetPreAllocatedNoClassDefFoundError() {
1336   mirror::Throwable* ncdfe = pre_allocated_NoClassDefFoundError_.Read();
1337   if (ncdfe == nullptr) {
1338     LOG(ERROR) << "Failed to return pre-allocated NoClassDefFoundError";
1339   }
1340   return ncdfe;
1341 }
1342 
VisitConstantRoots(RootVisitor * visitor)1343 void Runtime::VisitConstantRoots(RootVisitor* visitor) {
1344   // Visit the classes held as static in mirror classes, these can be visited concurrently and only
1345   // need to be visited once per GC since they never change.
1346   mirror::Class::VisitRoots(visitor);
1347   mirror::Constructor::VisitRoots(visitor);
1348   mirror::Reference::VisitRoots(visitor);
1349   mirror::Method::VisitRoots(visitor);
1350   mirror::StackTraceElement::VisitRoots(visitor);
1351   mirror::String::VisitRoots(visitor);
1352   mirror::Throwable::VisitRoots(visitor);
1353   mirror::Field::VisitRoots(visitor);
1354   // Visit all the primitive array types classes.
1355   mirror::PrimitiveArray<uint8_t>::VisitRoots(visitor);   // BooleanArray
1356   mirror::PrimitiveArray<int8_t>::VisitRoots(visitor);    // ByteArray
1357   mirror::PrimitiveArray<uint16_t>::VisitRoots(visitor);  // CharArray
1358   mirror::PrimitiveArray<double>::VisitRoots(visitor);    // DoubleArray
1359   mirror::PrimitiveArray<float>::VisitRoots(visitor);     // FloatArray
1360   mirror::PrimitiveArray<int32_t>::VisitRoots(visitor);   // IntArray
1361   mirror::PrimitiveArray<int64_t>::VisitRoots(visitor);   // LongArray
1362   mirror::PrimitiveArray<int16_t>::VisitRoots(visitor);   // ShortArray
1363   // Visiting the roots of these ArtMethods is not currently required since all the GcRoots are
1364   // null.
1365   BufferedRootVisitor<16> buffered_visitor(visitor, RootInfo(kRootVMInternal));
1366   if (HasResolutionMethod()) {
1367     resolution_method_->VisitRoots(buffered_visitor);
1368   }
1369   if (HasImtConflictMethod()) {
1370     imt_conflict_method_->VisitRoots(buffered_visitor);
1371   }
1372   if (imt_unimplemented_method_ != nullptr) {
1373     imt_unimplemented_method_->VisitRoots(buffered_visitor);
1374   }
1375   for (size_t i = 0; i < kLastCalleeSaveType; ++i) {
1376     auto* m = reinterpret_cast<ArtMethod*>(callee_save_methods_[i]);
1377     if (m != nullptr) {
1378       m->VisitRoots(buffered_visitor);
1379     }
1380   }
1381 }
1382 
VisitConcurrentRoots(RootVisitor * visitor,VisitRootFlags flags)1383 void Runtime::VisitConcurrentRoots(RootVisitor* visitor, VisitRootFlags flags) {
1384   intern_table_->VisitRoots(visitor, flags);
1385   class_linker_->VisitRoots(visitor, flags);
1386   if ((flags & kVisitRootFlagNewRoots) == 0) {
1387     // Guaranteed to have no new roots in the constant roots.
1388     VisitConstantRoots(visitor);
1389   }
1390 }
1391 
VisitTransactionRoots(RootVisitor * visitor)1392 void Runtime::VisitTransactionRoots(RootVisitor* visitor) {
1393   if (preinitialization_transaction_ != nullptr) {
1394     preinitialization_transaction_->VisitRoots(visitor);
1395   }
1396 }
1397 
VisitNonThreadRoots(RootVisitor * visitor)1398 void Runtime::VisitNonThreadRoots(RootVisitor* visitor) {
1399   java_vm_->VisitRoots(visitor);
1400   sentinel_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
1401   pre_allocated_OutOfMemoryError_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
1402   pre_allocated_NoClassDefFoundError_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
1403   verifier::MethodVerifier::VisitStaticRoots(visitor);
1404   VisitTransactionRoots(visitor);
1405 }
1406 
VisitNonConcurrentRoots(RootVisitor * visitor)1407 void Runtime::VisitNonConcurrentRoots(RootVisitor* visitor) {
1408   thread_list_->VisitRoots(visitor);
1409   VisitNonThreadRoots(visitor);
1410 }
1411 
VisitThreadRoots(RootVisitor * visitor)1412 void Runtime::VisitThreadRoots(RootVisitor* visitor) {
1413   thread_list_->VisitRoots(visitor);
1414 }
1415 
FlipThreadRoots(Closure * thread_flip_visitor,Closure * flip_callback,gc::collector::GarbageCollector * collector)1416 size_t Runtime::FlipThreadRoots(Closure* thread_flip_visitor, Closure* flip_callback,
1417                                 gc::collector::GarbageCollector* collector) {
1418   return thread_list_->FlipThreadRoots(thread_flip_visitor, flip_callback, collector);
1419 }
1420 
VisitRoots(RootVisitor * visitor,VisitRootFlags flags)1421 void Runtime::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
1422   VisitNonConcurrentRoots(visitor);
1423   VisitConcurrentRoots(visitor, flags);
1424 }
1425 
VisitImageRoots(RootVisitor * visitor)1426 void Runtime::VisitImageRoots(RootVisitor* visitor) {
1427   for (auto* space : GetHeap()->GetContinuousSpaces()) {
1428     if (space->IsImageSpace()) {
1429       auto* image_space = space->AsImageSpace();
1430       const auto& image_header = image_space->GetImageHeader();
1431       for (size_t i = 0; i < ImageHeader::kImageRootsMax; ++i) {
1432         auto* obj = image_header.GetImageRoot(static_cast<ImageHeader::ImageRoot>(i));
1433         if (obj != nullptr) {
1434           auto* after_obj = obj;
1435           visitor->VisitRoot(&after_obj, RootInfo(kRootStickyClass));
1436           CHECK_EQ(after_obj, obj);
1437         }
1438       }
1439     }
1440   }
1441 }
1442 
CreateImtConflictMethod()1443 ArtMethod* Runtime::CreateImtConflictMethod() {
1444   auto* method = Runtime::Current()->GetClassLinker()->CreateRuntimeMethod();
1445   // When compiling, the code pointer will get set later when the image is loaded.
1446   if (IsAotCompiler()) {
1447     size_t pointer_size = GetInstructionSetPointerSize(instruction_set_);
1448     method->SetEntryPointFromQuickCompiledCodePtrSize(nullptr, pointer_size);
1449   } else {
1450     method->SetEntryPointFromQuickCompiledCode(GetQuickImtConflictStub());
1451   }
1452   return method;
1453 }
1454 
SetImtConflictMethod(ArtMethod * method)1455 void Runtime::SetImtConflictMethod(ArtMethod* method) {
1456   CHECK(method != nullptr);
1457   CHECK(method->IsRuntimeMethod());
1458   imt_conflict_method_ = method;
1459 }
1460 
CreateResolutionMethod()1461 ArtMethod* Runtime::CreateResolutionMethod() {
1462   auto* method = Runtime::Current()->GetClassLinker()->CreateRuntimeMethod();
1463   // When compiling, the code pointer will get set later when the image is loaded.
1464   if (IsAotCompiler()) {
1465     size_t pointer_size = GetInstructionSetPointerSize(instruction_set_);
1466     method->SetEntryPointFromQuickCompiledCodePtrSize(nullptr, pointer_size);
1467   } else {
1468     method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
1469   }
1470   return method;
1471 }
1472 
CreateCalleeSaveMethod()1473 ArtMethod* Runtime::CreateCalleeSaveMethod() {
1474   auto* method = Runtime::Current()->GetClassLinker()->CreateRuntimeMethod();
1475   size_t pointer_size = GetInstructionSetPointerSize(instruction_set_);
1476   method->SetEntryPointFromQuickCompiledCodePtrSize(nullptr, pointer_size);
1477   DCHECK_NE(instruction_set_, kNone);
1478   DCHECK(method->IsRuntimeMethod());
1479   return method;
1480 }
1481 
DisallowNewSystemWeaks()1482 void Runtime::DisallowNewSystemWeaks() {
1483   monitor_list_->DisallowNewMonitors();
1484   intern_table_->DisallowNewInterns();
1485   java_vm_->DisallowNewWeakGlobals();
1486 }
1487 
AllowNewSystemWeaks()1488 void Runtime::AllowNewSystemWeaks() {
1489   monitor_list_->AllowNewMonitors();
1490   intern_table_->AllowNewInterns();
1491   java_vm_->AllowNewWeakGlobals();
1492 }
1493 
EnsureNewSystemWeaksDisallowed()1494 void Runtime::EnsureNewSystemWeaksDisallowed() {
1495   // Lock and unlock the system weak locks once to ensure that no
1496   // threads are still in the middle of adding new system weaks.
1497   monitor_list_->EnsureNewMonitorsDisallowed();
1498   intern_table_->EnsureNewInternsDisallowed();
1499   java_vm_->EnsureNewWeakGlobalsDisallowed();
1500 }
1501 
SetInstructionSet(InstructionSet instruction_set)1502 void Runtime::SetInstructionSet(InstructionSet instruction_set) {
1503   instruction_set_ = instruction_set;
1504   if ((instruction_set_ == kThumb2) || (instruction_set_ == kArm)) {
1505     for (int i = 0; i != kLastCalleeSaveType; ++i) {
1506       CalleeSaveType type = static_cast<CalleeSaveType>(i);
1507       callee_save_method_frame_infos_[i] = arm::ArmCalleeSaveMethodFrameInfo(type);
1508     }
1509   } else if (instruction_set_ == kMips) {
1510     for (int i = 0; i != kLastCalleeSaveType; ++i) {
1511       CalleeSaveType type = static_cast<CalleeSaveType>(i);
1512       callee_save_method_frame_infos_[i] = mips::MipsCalleeSaveMethodFrameInfo(type);
1513     }
1514   } else if (instruction_set_ == kMips64) {
1515     for (int i = 0; i != kLastCalleeSaveType; ++i) {
1516       CalleeSaveType type = static_cast<CalleeSaveType>(i);
1517       callee_save_method_frame_infos_[i] = mips64::Mips64CalleeSaveMethodFrameInfo(type);
1518     }
1519   } else if (instruction_set_ == kX86) {
1520     for (int i = 0; i != kLastCalleeSaveType; ++i) {
1521       CalleeSaveType type = static_cast<CalleeSaveType>(i);
1522       callee_save_method_frame_infos_[i] = x86::X86CalleeSaveMethodFrameInfo(type);
1523     }
1524   } else if (instruction_set_ == kX86_64) {
1525     for (int i = 0; i != kLastCalleeSaveType; ++i) {
1526       CalleeSaveType type = static_cast<CalleeSaveType>(i);
1527       callee_save_method_frame_infos_[i] = x86_64::X86_64CalleeSaveMethodFrameInfo(type);
1528     }
1529   } else if (instruction_set_ == kArm64) {
1530     for (int i = 0; i != kLastCalleeSaveType; ++i) {
1531       CalleeSaveType type = static_cast<CalleeSaveType>(i);
1532       callee_save_method_frame_infos_[i] = arm64::Arm64CalleeSaveMethodFrameInfo(type);
1533     }
1534   } else {
1535     UNIMPLEMENTED(FATAL) << instruction_set_;
1536   }
1537 }
1538 
SetCalleeSaveMethod(ArtMethod * method,CalleeSaveType type)1539 void Runtime::SetCalleeSaveMethod(ArtMethod* method, CalleeSaveType type) {
1540   DCHECK_LT(static_cast<int>(type), static_cast<int>(kLastCalleeSaveType));
1541   CHECK(method != nullptr);
1542   callee_save_methods_[type] = reinterpret_cast<uintptr_t>(method);
1543 }
1544 
StartProfiler(const char * profile_output_filename)1545 void Runtime::StartProfiler(const char* profile_output_filename) {
1546   profile_output_filename_ = profile_output_filename;
1547   profiler_started_ =
1548       BackgroundMethodSamplingProfiler::Start(profile_output_filename_, profiler_options_);
1549 }
1550 
1551 // Transaction support.
EnterTransactionMode(Transaction * transaction)1552 void Runtime::EnterTransactionMode(Transaction* transaction) {
1553   DCHECK(IsAotCompiler());
1554   DCHECK(transaction != nullptr);
1555   DCHECK(!IsActiveTransaction());
1556   preinitialization_transaction_ = transaction;
1557 }
1558 
ExitTransactionMode()1559 void Runtime::ExitTransactionMode() {
1560   DCHECK(IsAotCompiler());
1561   DCHECK(IsActiveTransaction());
1562   preinitialization_transaction_ = nullptr;
1563 }
1564 
IsTransactionAborted() const1565 bool Runtime::IsTransactionAborted() const {
1566   if (!IsActiveTransaction()) {
1567     return false;
1568   } else {
1569     DCHECK(IsAotCompiler());
1570     return preinitialization_transaction_->IsAborted();
1571   }
1572 }
1573 
AbortTransactionAndThrowAbortError(Thread * self,const std::string & abort_message)1574 void Runtime::AbortTransactionAndThrowAbortError(Thread* self, const std::string& abort_message) {
1575   DCHECK(IsAotCompiler());
1576   DCHECK(IsActiveTransaction());
1577   // Throwing an exception may cause its class initialization. If we mark the transaction
1578   // aborted before that, we may warn with a false alarm. Throwing the exception before
1579   // marking the transaction aborted avoids that.
1580   preinitialization_transaction_->ThrowAbortError(self, &abort_message);
1581   preinitialization_transaction_->Abort(abort_message);
1582 }
1583 
ThrowTransactionAbortError(Thread * self)1584 void Runtime::ThrowTransactionAbortError(Thread* self) {
1585   DCHECK(IsAotCompiler());
1586   DCHECK(IsActiveTransaction());
1587   // Passing nullptr means we rethrow an exception with the earlier transaction abort message.
1588   preinitialization_transaction_->ThrowAbortError(self, nullptr);
1589 }
1590 
RecordWriteFieldBoolean(mirror::Object * obj,MemberOffset field_offset,uint8_t value,bool is_volatile) const1591 void Runtime::RecordWriteFieldBoolean(mirror::Object* obj, MemberOffset field_offset,
1592                                       uint8_t value, bool is_volatile) const {
1593   DCHECK(IsAotCompiler());
1594   DCHECK(IsActiveTransaction());
1595   preinitialization_transaction_->RecordWriteFieldBoolean(obj, field_offset, value, is_volatile);
1596 }
1597 
RecordWriteFieldByte(mirror::Object * obj,MemberOffset field_offset,int8_t value,bool is_volatile) const1598 void Runtime::RecordWriteFieldByte(mirror::Object* obj, MemberOffset field_offset,
1599                                    int8_t value, bool is_volatile) const {
1600   DCHECK(IsAotCompiler());
1601   DCHECK(IsActiveTransaction());
1602   preinitialization_transaction_->RecordWriteFieldByte(obj, field_offset, value, is_volatile);
1603 }
1604 
RecordWriteFieldChar(mirror::Object * obj,MemberOffset field_offset,uint16_t value,bool is_volatile) const1605 void Runtime::RecordWriteFieldChar(mirror::Object* obj, MemberOffset field_offset,
1606                                    uint16_t value, bool is_volatile) const {
1607   DCHECK(IsAotCompiler());
1608   DCHECK(IsActiveTransaction());
1609   preinitialization_transaction_->RecordWriteFieldChar(obj, field_offset, value, is_volatile);
1610 }
1611 
RecordWriteFieldShort(mirror::Object * obj,MemberOffset field_offset,int16_t value,bool is_volatile) const1612 void Runtime::RecordWriteFieldShort(mirror::Object* obj, MemberOffset field_offset,
1613                                     int16_t value, bool is_volatile) const {
1614   DCHECK(IsAotCompiler());
1615   DCHECK(IsActiveTransaction());
1616   preinitialization_transaction_->RecordWriteFieldShort(obj, field_offset, value, is_volatile);
1617 }
1618 
RecordWriteField32(mirror::Object * obj,MemberOffset field_offset,uint32_t value,bool is_volatile) const1619 void Runtime::RecordWriteField32(mirror::Object* obj, MemberOffset field_offset,
1620                                  uint32_t value, bool is_volatile) const {
1621   DCHECK(IsAotCompiler());
1622   DCHECK(IsActiveTransaction());
1623   preinitialization_transaction_->RecordWriteField32(obj, field_offset, value, is_volatile);
1624 }
1625 
RecordWriteField64(mirror::Object * obj,MemberOffset field_offset,uint64_t value,bool is_volatile) const1626 void Runtime::RecordWriteField64(mirror::Object* obj, MemberOffset field_offset,
1627                                  uint64_t value, bool is_volatile) const {
1628   DCHECK(IsAotCompiler());
1629   DCHECK(IsActiveTransaction());
1630   preinitialization_transaction_->RecordWriteField64(obj, field_offset, value, is_volatile);
1631 }
1632 
RecordWriteFieldReference(mirror::Object * obj,MemberOffset field_offset,mirror::Object * value,bool is_volatile) const1633 void Runtime::RecordWriteFieldReference(mirror::Object* obj, MemberOffset field_offset,
1634                                         mirror::Object* value, bool is_volatile) const {
1635   DCHECK(IsAotCompiler());
1636   DCHECK(IsActiveTransaction());
1637   preinitialization_transaction_->RecordWriteFieldReference(obj, field_offset, value, is_volatile);
1638 }
1639 
RecordWriteArray(mirror::Array * array,size_t index,uint64_t value) const1640 void Runtime::RecordWriteArray(mirror::Array* array, size_t index, uint64_t value) const {
1641   DCHECK(IsAotCompiler());
1642   DCHECK(IsActiveTransaction());
1643   preinitialization_transaction_->RecordWriteArray(array, index, value);
1644 }
1645 
RecordStrongStringInsertion(mirror::String * s) const1646 void Runtime::RecordStrongStringInsertion(mirror::String* s) const {
1647   DCHECK(IsAotCompiler());
1648   DCHECK(IsActiveTransaction());
1649   preinitialization_transaction_->RecordStrongStringInsertion(s);
1650 }
1651 
RecordWeakStringInsertion(mirror::String * s) const1652 void Runtime::RecordWeakStringInsertion(mirror::String* s) const {
1653   DCHECK(IsAotCompiler());
1654   DCHECK(IsActiveTransaction());
1655   preinitialization_transaction_->RecordWeakStringInsertion(s);
1656 }
1657 
RecordStrongStringRemoval(mirror::String * s) const1658 void Runtime::RecordStrongStringRemoval(mirror::String* s) const {
1659   DCHECK(IsAotCompiler());
1660   DCHECK(IsActiveTransaction());
1661   preinitialization_transaction_->RecordStrongStringRemoval(s);
1662 }
1663 
RecordWeakStringRemoval(mirror::String * s) const1664 void Runtime::RecordWeakStringRemoval(mirror::String* s) const {
1665   DCHECK(IsAotCompiler());
1666   DCHECK(IsActiveTransaction());
1667   preinitialization_transaction_->RecordWeakStringRemoval(s);
1668 }
1669 
SetFaultMessage(const std::string & message)1670 void Runtime::SetFaultMessage(const std::string& message) {
1671   MutexLock mu(Thread::Current(), fault_message_lock_);
1672   fault_message_ = message;
1673 }
1674 
AddCurrentRuntimeFeaturesAsDex2OatArguments(std::vector<std::string> * argv) const1675 void Runtime::AddCurrentRuntimeFeaturesAsDex2OatArguments(std::vector<std::string>* argv)
1676     const {
1677   if (GetInstrumentation()->InterpretOnly() || UseJit()) {
1678     argv->push_back("--compiler-filter=interpret-only");
1679   }
1680 
1681   // Make the dex2oat instruction set match that of the launching runtime. If we have multiple
1682   // architecture support, dex2oat may be compiled as a different instruction-set than that
1683   // currently being executed.
1684   std::string instruction_set("--instruction-set=");
1685   instruction_set += GetInstructionSetString(kRuntimeISA);
1686   argv->push_back(instruction_set);
1687 
1688   std::unique_ptr<const InstructionSetFeatures> features(InstructionSetFeatures::FromCppDefines());
1689   std::string feature_string("--instruction-set-features=");
1690   feature_string += features->GetFeatureString();
1691   argv->push_back(feature_string);
1692 }
1693 
UpdateProfilerState(int state)1694 void Runtime::UpdateProfilerState(int state) {
1695   VLOG(profiler) << "Profiler state updated to " << state;
1696 }
1697 
CreateJit()1698 void Runtime::CreateJit() {
1699   CHECK(!IsAotCompiler());
1700   if (GetInstrumentation()->IsForcedInterpretOnly()) {
1701     // Don't create JIT if forced interpret only.
1702     return;
1703   }
1704   std::string error_msg;
1705   jit_.reset(jit::Jit::Create(jit_options_.get(), &error_msg));
1706   if (jit_.get() != nullptr) {
1707     compiler_callbacks_ = jit_->GetCompilerCallbacks();
1708     jit_->CreateInstrumentationCache(jit_options_->GetCompileThreshold());
1709     jit_->CreateThreadPool();
1710   } else {
1711     LOG(WARNING) << "Failed to create JIT " << error_msg;
1712   }
1713 }
1714 
CanRelocate() const1715 bool Runtime::CanRelocate() const {
1716   return !IsAotCompiler() || compiler_callbacks_->IsRelocationPossible();
1717 }
1718 
IsCompilingBootImage() const1719 bool Runtime::IsCompilingBootImage() const {
1720   return IsCompiler() && compiler_callbacks_->IsBootImage();
1721 }
1722 
SetResolutionMethod(ArtMethod * method)1723 void Runtime::SetResolutionMethod(ArtMethod* method) {
1724   CHECK(method != nullptr);
1725   CHECK(method->IsRuntimeMethod()) << method;
1726   resolution_method_ = method;
1727 }
1728 
SetImtUnimplementedMethod(ArtMethod * method)1729 void Runtime::SetImtUnimplementedMethod(ArtMethod* method) {
1730   CHECK(method != nullptr);
1731   CHECK(method->IsRuntimeMethod());
1732   imt_unimplemented_method_ = method;
1733 }
1734 
1735 }  // namespace art
1736