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