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