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