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