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