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