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