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