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