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