runtime.cc revision 82558acbca3eae5b7e47748bcfb8070855266676
1/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "runtime.h"
18
19// sys/mount.h has to come before linux/fs.h due to redefinition of MS_RDONLY, MS_BIND, etc
20#include <sys/mount.h>
21#ifdef __linux__
22#include <linux/fs.h>
23#endif
24
25#include <signal.h>
26#include <sys/syscall.h>
27#include <valgrind.h>
28
29#include <cstdio>
30#include <cstdlib>
31#include <limits>
32#include <memory>
33#include <vector>
34#include <fcntl.h>
35
36#include "arch/arm/quick_method_frame_info_arm.h"
37#include "arch/arm/registers_arm.h"
38#include "arch/arm64/quick_method_frame_info_arm64.h"
39#include "arch/arm64/registers_arm64.h"
40#include "arch/mips/quick_method_frame_info_mips.h"
41#include "arch/mips/registers_mips.h"
42#include "arch/x86/quick_method_frame_info_x86.h"
43#include "arch/x86/registers_x86.h"
44#include "arch/x86_64/quick_method_frame_info_x86_64.h"
45#include "arch/x86_64/registers_x86_64.h"
46#include "atomic.h"
47#include "class_linker.h"
48#include "debugger.h"
49#include "fault_handler.h"
50#include "gc/accounting/card_table-inl.h"
51#include "gc/heap.h"
52#include "gc/space/space.h"
53#include "image.h"
54#include "instrumentation.h"
55#include "intern_table.h"
56#include "jni_internal.h"
57#include "mirror/art_field-inl.h"
58#include "mirror/art_method-inl.h"
59#include "mirror/array.h"
60#include "mirror/class-inl.h"
61#include "mirror/class_loader.h"
62#include "mirror/stack_trace_element.h"
63#include "mirror/throwable.h"
64#include "monitor.h"
65#include "parsed_options.h"
66#include "oat_file.h"
67#include "quick/quick_method_frame_info.h"
68#include "reflection.h"
69#include "ScopedLocalRef.h"
70#include "scoped_thread_state_change.h"
71#include "signal_catcher.h"
72#include "signal_set.h"
73#include "handle_scope-inl.h"
74#include "thread.h"
75#include "thread_list.h"
76#include "trace.h"
77#include "transaction.h"
78#include "profiler.h"
79#include "verifier/method_verifier.h"
80#include "well_known_classes.h"
81
82#include "JniConstants.h"  // Last to avoid LOG redefinition in ics-mr1-plus-art.
83
84#ifdef HAVE_ANDROID_OS
85#include "cutils/properties.h"
86#endif
87
88namespace art {
89
90static constexpr bool kEnableJavaStackTraceHandler = true;
91const char* Runtime::kDefaultInstructionSetFeatures =
92    STRINGIFY(ART_DEFAULT_INSTRUCTION_SET_FEATURES);
93Runtime* Runtime::instance_ = NULL;
94
95Runtime::Runtime()
96    : pre_allocated_OutOfMemoryError_(nullptr),
97      resolution_method_(nullptr),
98      imt_conflict_method_(nullptr),
99      default_imt_(nullptr),
100      instruction_set_(kNone),
101      compiler_callbacks_(nullptr),
102      is_zygote_(false),
103      is_concurrent_gc_enabled_(true),
104      is_explicit_gc_disabled_(false),
105      default_stack_size_(0),
106      heap_(nullptr),
107      max_spins_before_thin_lock_inflation_(Monitor::kDefaultMaxSpinsBeforeThinLockInflation),
108      monitor_list_(nullptr),
109      monitor_pool_(nullptr),
110      thread_list_(nullptr),
111      intern_table_(nullptr),
112      class_linker_(nullptr),
113      signal_catcher_(nullptr),
114      java_vm_(nullptr),
115      fault_message_lock_("Fault message lock"),
116      fault_message_(""),
117      method_verifier_lock_("Method verifiers lock"),
118      threads_being_born_(0),
119      shutdown_cond_(new ConditionVariable("Runtime shutdown", *Locks::runtime_shutdown_lock_)),
120      shutting_down_(false),
121      shutting_down_started_(false),
122      started_(false),
123      finished_starting_(false),
124      vfprintf_(nullptr),
125      exit_(nullptr),
126      abort_(nullptr),
127      stats_enabled_(false),
128      running_on_valgrind_(RUNNING_ON_VALGRIND > 0),
129      profiler_started_(false),
130      method_trace_(false),
131      method_trace_file_size_(0),
132      instrumentation_(),
133      use_compile_time_class_path_(false),
134      main_thread_group_(nullptr),
135      system_thread_group_(nullptr),
136      system_class_loader_(nullptr),
137      dump_gc_performance_on_shutdown_(false),
138      preinitialization_transaction_(nullptr),
139      null_pointer_handler_(nullptr),
140      suspend_handler_(nullptr),
141      stack_overflow_handler_(nullptr),
142      verify_(false),
143      target_sdk_version_(0),
144      implicit_null_checks_(false),
145      implicit_so_checks_(false),
146      implicit_suspend_checks_(false) {
147  for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
148    callee_save_methods_[i] = nullptr;
149  }
150}
151
152Runtime::~Runtime() {
153  if (method_trace_ && Thread::Current() == nullptr) {
154    // We need a current thread to shutdown method tracing: re-attach it now.
155    JNIEnv* unused_env;
156    if (GetJavaVM()->AttachCurrentThread(&unused_env, nullptr) != JNI_OK) {
157      LOG(ERROR) << "Could not attach current thread before runtime shutdown.";
158    }
159  }
160  if (dump_gc_performance_on_shutdown_) {
161    // This can't be called from the Heap destructor below because it
162    // could call RosAlloc::InspectAll() which needs the thread_list
163    // to be still alive.
164    heap_->DumpGcPerformanceInfo(LOG(INFO));
165  }
166
167  Thread* self = Thread::Current();
168  {
169    MutexLock mu(self, *Locks::runtime_shutdown_lock_);
170    shutting_down_started_ = true;
171    while (threads_being_born_ > 0) {
172      shutdown_cond_->Wait(self);
173    }
174    shutting_down_ = true;
175  }
176  // Shut down background profiler before the runtime exits.
177  if (profiler_started_) {
178    BackgroundMethodSamplingProfiler::Shutdown();
179  }
180
181  Trace::Shutdown();
182
183  // Make sure to let the GC complete if it is running.
184  heap_->WaitForGcToComplete(gc::kGcCauseBackground, self);
185  heap_->DeleteThreadPool();
186
187  // Make sure our internal threads are dead before we start tearing down things they're using.
188  Dbg::StopJdwp();
189  delete signal_catcher_;
190
191  // Make sure all other non-daemon threads have terminated, and all daemon threads are suspended.
192  delete thread_list_;
193  delete monitor_list_;
194  delete monitor_pool_;
195  delete class_linker_;
196  delete heap_;
197  delete intern_table_;
198  delete java_vm_;
199  Thread::Shutdown();
200  QuasiAtomic::Shutdown();
201  verifier::MethodVerifier::Shutdown();
202  // TODO: acquire a static mutex on Runtime to avoid racing.
203  CHECK(instance_ == nullptr || instance_ == this);
204  instance_ = nullptr;
205
206  delete null_pointer_handler_;
207  delete suspend_handler_;
208  delete stack_overflow_handler_;
209}
210
211struct AbortState {
212  void Dump(std::ostream& os) NO_THREAD_SAFETY_ANALYSIS {
213    if (gAborting > 1) {
214      os << "Runtime aborting --- recursively, so no thread-specific detail!\n";
215      return;
216    }
217    gAborting++;
218    os << "Runtime aborting...\n";
219    if (Runtime::Current() == NULL) {
220      os << "(Runtime does not yet exist!)\n";
221      return;
222    }
223    Thread* self = Thread::Current();
224    if (self == nullptr) {
225      os << "(Aborting thread was not attached to runtime!)\n";
226      DumpKernelStack(os, GetTid(), "  kernel: ", false);
227      DumpNativeStack(os, GetTid(), "  native: ", nullptr);
228    } else {
229      os << "Aborting thread:\n";
230      if (Locks::mutator_lock_->IsExclusiveHeld(self) || Locks::mutator_lock_->IsSharedHeld(self)) {
231        DumpThread(os, self);
232      } else {
233        if (Locks::mutator_lock_->SharedTryLock(self)) {
234          DumpThread(os, self);
235          Locks::mutator_lock_->SharedUnlock(self);
236        }
237      }
238    }
239    DumpAllThreads(os, self);
240  }
241
242  void DumpThread(std::ostream& os, Thread* self) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
243    self->Dump(os);
244    if (self->IsExceptionPending()) {
245      ThrowLocation throw_location;
246      mirror::Throwable* exception = self->GetException(&throw_location);
247      os << "Pending exception " << PrettyTypeOf(exception)
248          << " thrown by '" << throw_location.Dump() << "'\n"
249          << exception->Dump();
250    }
251  }
252
253  void DumpAllThreads(std::ostream& os, Thread* self) NO_THREAD_SAFETY_ANALYSIS {
254    Runtime* runtime = Runtime::Current();
255    if (runtime != nullptr) {
256      ThreadList* thread_list = runtime->GetThreadList();
257      if (thread_list != nullptr) {
258        bool tll_already_held = Locks::thread_list_lock_->IsExclusiveHeld(self);
259        bool ml_already_held = Locks::mutator_lock_->IsSharedHeld(self);
260        if (!tll_already_held || !ml_already_held) {
261          os << "Dumping all threads without appropriate locks held:"
262              << (!tll_already_held ? " thread list lock" : "")
263              << (!ml_already_held ? " mutator lock" : "")
264              << "\n";
265        }
266        os << "All threads:\n";
267        thread_list->DumpLocked(os);
268      }
269    }
270  }
271};
272
273void Runtime::Abort() {
274  gAborting++;  // set before taking any locks
275
276  // Ensure that we don't have multiple threads trying to abort at once,
277  // which would result in significantly worse diagnostics.
278  MutexLock mu(Thread::Current(), *Locks::abort_lock_);
279
280  // Get any pending output out of the way.
281  fflush(NULL);
282
283  // Many people have difficulty distinguish aborts from crashes,
284  // so be explicit.
285  AbortState state;
286  LOG(INTERNAL_FATAL) << Dumpable<AbortState>(state);
287
288  // Call the abort hook if we have one.
289  if (Runtime::Current() != NULL && Runtime::Current()->abort_ != NULL) {
290    LOG(INTERNAL_FATAL) << "Calling abort hook...";
291    Runtime::Current()->abort_();
292    // notreached
293    LOG(INTERNAL_FATAL) << "Unexpectedly returned from abort hook!";
294  }
295
296#if defined(__GLIBC__)
297  // TODO: we ought to be able to use pthread_kill(3) here (or abort(3),
298  // which POSIX defines in terms of raise(3), which POSIX defines in terms
299  // of pthread_kill(3)). On Linux, though, libcorkscrew can't unwind through
300  // libpthread, which means the stacks we dump would be useless. Calling
301  // tgkill(2) directly avoids that.
302  syscall(__NR_tgkill, getpid(), GetTid(), SIGABRT);
303  // TODO: LLVM installs it's own SIGABRT handler so exit to be safe... Can we disable that in LLVM?
304  // If not, we could use sigaction(3) before calling tgkill(2) and lose this call to exit(3).
305  exit(1);
306#else
307  abort();
308#endif
309  // notreached
310}
311
312void Runtime::PreZygoteFork() {
313  heap_->PreZygoteFork();
314}
315
316void Runtime::CallExitHook(jint status) {
317  if (exit_ != NULL) {
318    ScopedThreadStateChange tsc(Thread::Current(), kNative);
319    exit_(status);
320    LOG(WARNING) << "Exit hook returned instead of exiting!";
321  }
322}
323
324void Runtime::SweepSystemWeaks(IsMarkedCallback* visitor, void* arg) {
325  GetInternTable()->SweepInternTableWeaks(visitor, arg);
326  GetMonitorList()->SweepMonitorList(visitor, arg);
327  GetJavaVM()->SweepJniWeakGlobals(visitor, arg);
328}
329
330bool Runtime::Create(const Options& options, bool ignore_unrecognized) {
331  // TODO: acquire a static mutex on Runtime to avoid racing.
332  if (Runtime::instance_ != NULL) {
333    return false;
334  }
335  InitLogging(NULL);  // Calls Locks::Init() as a side effect.
336  instance_ = new Runtime;
337  if (!instance_->Init(options, ignore_unrecognized)) {
338    delete instance_;
339    instance_ = NULL;
340    return false;
341  }
342  return true;
343}
344
345jobject CreateSystemClassLoader() {
346  if (Runtime::Current()->UseCompileTimeClassPath()) {
347    return NULL;
348  }
349
350  ScopedObjectAccess soa(Thread::Current());
351  ClassLinker* cl = Runtime::Current()->GetClassLinker();
352
353  StackHandleScope<3> hs(soa.Self());
354  Handle<mirror::Class> class_loader_class(
355      hs.NewHandle(soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ClassLoader)));
356  CHECK(cl->EnsureInitialized(class_loader_class, true, true));
357
358  mirror::ArtMethod* getSystemClassLoader =
359      class_loader_class->FindDirectMethod("getSystemClassLoader", "()Ljava/lang/ClassLoader;");
360  CHECK(getSystemClassLoader != NULL);
361
362  JValue result = InvokeWithJValues(soa, nullptr, soa.EncodeMethod(getSystemClassLoader), nullptr);
363  Handle<mirror::ClassLoader> class_loader(
364      hs.NewHandle(down_cast<mirror::ClassLoader*>(result.GetL())));
365  CHECK(class_loader.Get() != nullptr);
366  JNIEnv* env = soa.Self()->GetJniEnv();
367  ScopedLocalRef<jobject> system_class_loader(env,
368                                              soa.AddLocalReference<jobject>(class_loader.Get()));
369  CHECK(system_class_loader.get() != nullptr);
370
371  soa.Self()->SetClassLoaderOverride(class_loader.Get());
372
373  Handle<mirror::Class> thread_class(
374      hs.NewHandle(soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread)));
375  CHECK(cl->EnsureInitialized(thread_class, true, true));
376
377  mirror::ArtField* contextClassLoader =
378      thread_class->FindDeclaredInstanceField("contextClassLoader", "Ljava/lang/ClassLoader;");
379  CHECK(contextClassLoader != NULL);
380
381  // We can't run in a transaction yet.
382  contextClassLoader->SetObject<false>(soa.Self()->GetPeer(), class_loader.Get());
383
384  return env->NewGlobalRef(system_class_loader.get());
385}
386
387std::string Runtime::GetCompilerExecutable() const {
388  if (!compiler_executable_.empty()) {
389    return compiler_executable_;
390  }
391  std::string compiler_executable(GetAndroidRoot());
392  compiler_executable += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat");
393  return compiler_executable;
394}
395
396bool Runtime::Start() {
397  VLOG(startup) << "Runtime::Start entering";
398
399  // Restore main thread state to kNative as expected by native code.
400  Thread* self = Thread::Current();
401  self->TransitionFromRunnableToSuspended(kNative);
402
403  started_ = true;
404
405  // InitNativeMethods needs to be after started_ so that the classes
406  // it touches will have methods linked to the oat file if necessary.
407  InitNativeMethods();
408
409  // Initialize well known thread group values that may be accessed threads while attaching.
410  InitThreadGroups(self);
411
412  Thread::FinishStartup();
413
414  if (is_zygote_) {
415    if (!InitZygote()) {
416      return false;
417    }
418  } else {
419    DidForkFromZygote();
420  }
421
422  StartDaemonThreads();
423
424  system_class_loader_ = CreateSystemClassLoader();
425
426  {
427    ScopedObjectAccess soa(self);
428    self->GetJniEnv()->locals.AssertEmpty();
429  }
430
431  VLOG(startup) << "Runtime::Start exiting";
432  finished_starting_ = true;
433
434  if (profiler_options_.IsEnabled() && !profile_output_filename_.empty()) {
435    // User has asked for a profile using -Xenable-profiler.
436    // Create the profile file if it doesn't exist.
437    int fd = open(profile_output_filename_.c_str(), O_RDWR|O_CREAT|O_EXCL, 0660);
438    if (fd >= 0) {
439      close(fd);
440    } else if (errno != EEXIST) {
441      LOG(INFO) << "Failed to access the profile file. Profiler disabled.";
442      return true;
443    }
444    StartProfiler(profile_output_filename_.c_str());
445  }
446
447  return true;
448}
449
450void Runtime::EndThreadBirth() EXCLUSIVE_LOCKS_REQUIRED(Locks::runtime_shutdown_lock_) {
451  DCHECK_GT(threads_being_born_, 0U);
452  threads_being_born_--;
453  if (shutting_down_started_ && threads_being_born_ == 0) {
454    shutdown_cond_->Broadcast(Thread::Current());
455  }
456}
457
458// Do zygote-mode-only initialization.
459bool Runtime::InitZygote() {
460#ifdef __linux__
461  // zygote goes into its own process group
462  setpgid(0, 0);
463
464  // See storage config details at http://source.android.com/tech/storage/
465  // Create private mount namespace shared by all children
466  if (unshare(CLONE_NEWNS) == -1) {
467    PLOG(WARNING) << "Failed to unshare()";
468    return false;
469  }
470
471  // Mark rootfs as being a slave so that changes from default
472  // namespace only flow into our children.
473  if (mount("rootfs", "/", NULL, (MS_SLAVE | MS_REC), NULL) == -1) {
474    PLOG(WARNING) << "Failed to mount() rootfs as MS_SLAVE";
475    return false;
476  }
477
478  // Create a staging tmpfs that is shared by our children; they will
479  // bind mount storage into their respective private namespaces, which
480  // are isolated from each other.
481  const char* target_base = getenv("EMULATED_STORAGE_TARGET");
482  if (target_base != NULL) {
483    if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
484              "uid=0,gid=1028,mode=0751") == -1) {
485      LOG(WARNING) << "Failed to mount tmpfs to " << target_base;
486      return false;
487    }
488  }
489
490  return true;
491#else
492  UNIMPLEMENTED(FATAL);
493  return false;
494#endif
495}
496
497void Runtime::DidForkFromZygote() {
498  is_zygote_ = false;
499
500  // Create the thread pool.
501  heap_->CreateThreadPool();
502
503  StartSignalCatcher();
504
505  // Start the JDWP thread. If the command-line debugger flags specified "suspend=y",
506  // this will pause the runtime, so we probably want this to come last.
507  Dbg::StartJdwp();
508}
509
510void Runtime::StartSignalCatcher() {
511  if (!is_zygote_) {
512    signal_catcher_ = new SignalCatcher(stack_trace_file_);
513  }
514}
515
516bool Runtime::IsShuttingDown(Thread* self) {
517  MutexLock mu(self, *Locks::runtime_shutdown_lock_);
518  return IsShuttingDownLocked();
519}
520
521void Runtime::StartDaemonThreads() {
522  VLOG(startup) << "Runtime::StartDaemonThreads entering";
523
524  Thread* self = Thread::Current();
525
526  // Must be in the kNative state for calling native methods.
527  CHECK_EQ(self->GetState(), kNative);
528
529  JNIEnv* env = self->GetJniEnv();
530  env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
531                            WellKnownClasses::java_lang_Daemons_start);
532  if (env->ExceptionCheck()) {
533    env->ExceptionDescribe();
534    LOG(FATAL) << "Error starting java.lang.Daemons";
535  }
536
537  VLOG(startup) << "Runtime::StartDaemonThreads exiting";
538}
539
540bool Runtime::Init(const Options& raw_options, bool ignore_unrecognized) {
541  CHECK_EQ(sysconf(_SC_PAGE_SIZE), kPageSize);
542
543  std::unique_ptr<ParsedOptions> options(ParsedOptions::Create(raw_options, ignore_unrecognized));
544  if (options.get() == NULL) {
545    LOG(ERROR) << "Failed to parse options";
546    return false;
547  }
548  VLOG(startup) << "Runtime::Init -verbose:startup enabled";
549
550  QuasiAtomic::Startup();
551
552  Monitor::Init(options->lock_profiling_threshold_, options->hook_is_sensitive_thread_);
553
554  boot_class_path_string_ = options->boot_class_path_string_;
555  class_path_string_ = options->class_path_string_;
556  properties_ = options->properties_;
557
558  compiler_callbacks_ = options->compiler_callbacks_;
559  is_zygote_ = options->is_zygote_;
560  is_explicit_gc_disabled_ = options->is_explicit_gc_disabled_;
561
562  vfprintf_ = options->hook_vfprintf_;
563  exit_ = options->hook_exit_;
564  abort_ = options->hook_abort_;
565
566  default_stack_size_ = options->stack_size_;
567  stack_trace_file_ = options->stack_trace_file_;
568
569  compiler_executable_ = options->compiler_executable_;
570  compiler_options_ = options->compiler_options_;
571  image_compiler_options_ = options->image_compiler_options_;
572
573  max_spins_before_thin_lock_inflation_ = options->max_spins_before_thin_lock_inflation_;
574
575  monitor_list_ = new MonitorList;
576  monitor_pool_ = MonitorPool::Create();
577  thread_list_ = new ThreadList;
578  intern_table_ = new InternTable;
579
580  verify_ = options->verify_;
581
582  if (options->interpreter_only_) {
583    GetInstrumentation()->ForceInterpretOnly();
584  }
585
586  heap_ = new gc::Heap(options->heap_initial_size_,
587                       options->heap_growth_limit_,
588                       options->heap_min_free_,
589                       options->heap_max_free_,
590                       options->heap_target_utilization_,
591                       options->foreground_heap_growth_multiplier_,
592                       options->heap_maximum_size_,
593                       options->image_,
594                       options->image_isa_,
595                       options->collector_type_,
596                       options->background_collector_type_,
597                       options->parallel_gc_threads_,
598                       options->conc_gc_threads_,
599                       options->low_memory_mode_,
600                       options->long_pause_log_threshold_,
601                       options->long_gc_log_threshold_,
602                       options->ignore_max_footprint_,
603                       options->use_tlab_,
604                       options->verify_pre_gc_heap_,
605                       options->verify_pre_sweeping_heap_,
606                       options->verify_post_gc_heap_,
607                       options->verify_pre_gc_rosalloc_,
608                       options->verify_pre_sweeping_rosalloc_,
609                       options->verify_post_gc_rosalloc_,
610                       options->use_homogeneous_space_compaction_for_oom_,
611                       options->min_interval_homogeneous_space_compaction_by_oom_);
612
613  dump_gc_performance_on_shutdown_ = options->dump_gc_performance_on_shutdown_;
614
615  BlockSignals();
616  InitPlatformSignalHandlers();
617
618  // Change the implicit checks flags based on runtime architecture.
619  switch (kRuntimeISA) {
620    case kArm:
621    case kThumb2:
622    case kX86:
623      implicit_null_checks_ = true;
624      implicit_so_checks_ = true;
625      break;
626    default:
627      // Keep the defaults.
628      break;
629  }
630
631  if (!options->interpreter_only_ &&
632    (implicit_null_checks_ || implicit_so_checks_ || implicit_suspend_checks_)) {
633    fault_manager.Init();
634
635    // These need to be in a specific order.  The null point check handler must be
636    // after the suspend check and stack overflow check handlers.
637    if (implicit_suspend_checks_) {
638      suspend_handler_ = new SuspensionHandler(&fault_manager);
639    }
640
641    if (implicit_so_checks_) {
642      stack_overflow_handler_ = new StackOverflowHandler(&fault_manager);
643    }
644
645    if (implicit_null_checks_) {
646      null_pointer_handler_ = new NullPointerHandler(&fault_manager);
647    }
648
649    if (kEnableJavaStackTraceHandler) {
650      new JavaStackTraceHandler(&fault_manager);
651    }
652  }
653
654  java_vm_ = new JavaVMExt(this, options.get());
655
656  Thread::Startup();
657
658  // ClassLinker needs an attached thread, but we can't fully attach a thread without creating
659  // objects. We can't supply a thread group yet; it will be fixed later. Since we are the main
660  // thread, we do not get a java peer.
661  Thread* self = Thread::Attach("main", false, NULL, false);
662  CHECK_EQ(self->GetThreadId(), ThreadList::kMainThreadId);
663  CHECK(self != NULL);
664
665  // Set us to runnable so tools using a runtime can allocate and GC by default
666  self->TransitionFromSuspendedToRunnable();
667
668  // Now we're attached, we can take the heap locks and validate the heap.
669  GetHeap()->EnableObjectValidation();
670
671  CHECK_GE(GetHeap()->GetContinuousSpaces().size(), 1U);
672  class_linker_ = new ClassLinker(intern_table_);
673  if (GetHeap()->HasImageSpace()) {
674    class_linker_->InitFromImage();
675    if (kIsDebugBuild) {
676      GetHeap()->GetImageSpace()->VerifyImageAllocations();
677    }
678  } else {
679    CHECK(options->boot_class_path_ != NULL);
680    CHECK_NE(options->boot_class_path_->size(), 0U);
681    class_linker_->InitFromCompiler(*options->boot_class_path_);
682  }
683  CHECK(class_linker_ != NULL);
684  verifier::MethodVerifier::Init();
685
686  method_trace_ = options->method_trace_;
687  method_trace_file_ = options->method_trace_file_;
688  method_trace_file_size_ = options->method_trace_file_size_;
689
690  profile_output_filename_ = options->profile_output_filename_;
691  profiler_options_ = options->profiler_options_;
692
693  // TODO: move this to just be an Trace::Start argument
694  Trace::SetDefaultClockSource(options->profile_clock_source_);
695
696  if (options->method_trace_) {
697    ScopedThreadStateChange tsc(self, kWaitingForMethodTracingStart);
698    Trace::Start(options->method_trace_file_.c_str(), -1, options->method_trace_file_size_, 0,
699                 false, false, 0);
700  }
701
702  // Pre-allocate an OutOfMemoryError for the double-OOME case.
703  self->ThrowNewException(ThrowLocation(), "Ljava/lang/OutOfMemoryError;",
704                          "OutOfMemoryError thrown while trying to throw OutOfMemoryError; "
705                          "no stack available");
706  pre_allocated_OutOfMemoryError_ = self->GetException(NULL);
707  self->ClearException();
708
709  VLOG(startup) << "Runtime::Init exiting";
710  return true;
711}
712
713void Runtime::InitNativeMethods() {
714  VLOG(startup) << "Runtime::InitNativeMethods entering";
715  Thread* self = Thread::Current();
716  JNIEnv* env = self->GetJniEnv();
717
718  // Must be in the kNative state for calling native methods (JNI_OnLoad code).
719  CHECK_EQ(self->GetState(), kNative);
720
721  // First set up JniConstants, which is used by both the runtime's built-in native
722  // methods and libcore.
723  JniConstants::init(env);
724  WellKnownClasses::Init(env);
725
726  // Then set up the native methods provided by the runtime itself.
727  RegisterRuntimeNativeMethods(env);
728
729  // Then set up libcore, which is just a regular JNI library with a regular JNI_OnLoad.
730  // Most JNI libraries can just use System.loadLibrary, but libcore can't because it's
731  // the library that implements System.loadLibrary!
732  {
733    std::string mapped_name(StringPrintf(OS_SHARED_LIB_FORMAT_STR, "javacore"));
734    std::string reason;
735    self->TransitionFromSuspendedToRunnable();
736    StackHandleScope<1> hs(self);
737    auto class_loader(hs.NewHandle<mirror::ClassLoader>(nullptr));
738    if (!instance_->java_vm_->LoadNativeLibrary(mapped_name, class_loader, &reason)) {
739      LOG(FATAL) << "LoadNativeLibrary failed for \"" << mapped_name << "\": " << reason;
740    }
741    self->TransitionFromRunnableToSuspended(kNative);
742  }
743
744  // Initialize well known classes that may invoke runtime native methods.
745  WellKnownClasses::LateInit(env);
746
747  VLOG(startup) << "Runtime::InitNativeMethods exiting";
748}
749
750void Runtime::InitThreadGroups(Thread* self) {
751  JNIEnvExt* env = self->GetJniEnv();
752  ScopedJniEnvLocalRefState env_state(env);
753  main_thread_group_ =
754      env->NewGlobalRef(env->GetStaticObjectField(
755          WellKnownClasses::java_lang_ThreadGroup,
756          WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup));
757  CHECK(main_thread_group_ != NULL || IsCompiler());
758  system_thread_group_ =
759      env->NewGlobalRef(env->GetStaticObjectField(
760          WellKnownClasses::java_lang_ThreadGroup,
761          WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup));
762  CHECK(system_thread_group_ != NULL || IsCompiler());
763}
764
765jobject Runtime::GetMainThreadGroup() const {
766  CHECK(main_thread_group_ != NULL || IsCompiler());
767  return main_thread_group_;
768}
769
770jobject Runtime::GetSystemThreadGroup() const {
771  CHECK(system_thread_group_ != NULL || IsCompiler());
772  return system_thread_group_;
773}
774
775jobject Runtime::GetSystemClassLoader() const {
776  CHECK(system_class_loader_ != NULL || IsCompiler());
777  return system_class_loader_;
778}
779
780void Runtime::RegisterRuntimeNativeMethods(JNIEnv* env) {
781#define REGISTER(FN) extern void FN(JNIEnv*); FN(env)
782  // Register Throwable first so that registration of other native methods can throw exceptions
783  REGISTER(register_java_lang_Throwable);
784  REGISTER(register_dalvik_system_DexFile);
785  REGISTER(register_dalvik_system_VMDebug);
786  REGISTER(register_dalvik_system_VMRuntime);
787  REGISTER(register_dalvik_system_VMStack);
788  REGISTER(register_dalvik_system_ZygoteHooks);
789  REGISTER(register_java_lang_Class);
790  REGISTER(register_java_lang_DexCache);
791  REGISTER(register_java_lang_Object);
792  REGISTER(register_java_lang_Runtime);
793  REGISTER(register_java_lang_String);
794  REGISTER(register_java_lang_System);
795  REGISTER(register_java_lang_Thread);
796  REGISTER(register_java_lang_VMClassLoader);
797  REGISTER(register_java_lang_ref_Reference);
798  REGISTER(register_java_lang_reflect_Array);
799  REGISTER(register_java_lang_reflect_Constructor);
800  REGISTER(register_java_lang_reflect_Field);
801  REGISTER(register_java_lang_reflect_Method);
802  REGISTER(register_java_lang_reflect_Proxy);
803  REGISTER(register_java_util_concurrent_atomic_AtomicLong);
804  REGISTER(register_org_apache_harmony_dalvik_ddmc_DdmServer);
805  REGISTER(register_org_apache_harmony_dalvik_ddmc_DdmVmInternal);
806  REGISTER(register_sun_misc_Unsafe);
807#undef REGISTER
808}
809
810void Runtime::DumpForSigQuit(std::ostream& os) {
811  GetClassLinker()->DumpForSigQuit(os);
812  GetInternTable()->DumpForSigQuit(os);
813  GetJavaVM()->DumpForSigQuit(os);
814  GetHeap()->DumpForSigQuit(os);
815  os << "\n";
816
817  thread_list_->DumpForSigQuit(os);
818  BaseMutex::DumpAll(os);
819}
820
821void Runtime::DumpLockHolders(std::ostream& os) {
822  uint64_t mutator_lock_owner = Locks::mutator_lock_->GetExclusiveOwnerTid();
823  pid_t thread_list_lock_owner = GetThreadList()->GetLockOwner();
824  pid_t classes_lock_owner = GetClassLinker()->GetClassesLockOwner();
825  pid_t dex_lock_owner = GetClassLinker()->GetDexLockOwner();
826  if ((thread_list_lock_owner | classes_lock_owner | dex_lock_owner) != 0) {
827    os << "Mutator lock exclusive owner tid: " << mutator_lock_owner << "\n"
828       << "ThreadList lock owner tid: " << thread_list_lock_owner << "\n"
829       << "ClassLinker classes lock owner tid: " << classes_lock_owner << "\n"
830       << "ClassLinker dex lock owner tid: " << dex_lock_owner << "\n";
831  }
832}
833
834void Runtime::SetStatsEnabled(bool new_state) {
835  if (new_state == true) {
836    GetStats()->Clear(~0);
837    // TODO: wouldn't it make more sense to clear _all_ threads' stats?
838    Thread::Current()->GetStats()->Clear(~0);
839    GetInstrumentation()->InstrumentQuickAllocEntryPoints();
840  } else {
841    GetInstrumentation()->UninstrumentQuickAllocEntryPoints();
842  }
843  stats_enabled_ = new_state;
844}
845
846void Runtime::ResetStats(int kinds) {
847  GetStats()->Clear(kinds & 0xffff);
848  // TODO: wouldn't it make more sense to clear _all_ threads' stats?
849  Thread::Current()->GetStats()->Clear(kinds >> 16);
850}
851
852int32_t Runtime::GetStat(int kind) {
853  RuntimeStats* stats;
854  if (kind < (1<<16)) {
855    stats = GetStats();
856  } else {
857    stats = Thread::Current()->GetStats();
858    kind >>= 16;
859  }
860  switch (kind) {
861  case KIND_ALLOCATED_OBJECTS:
862    return stats->allocated_objects;
863  case KIND_ALLOCATED_BYTES:
864    return stats->allocated_bytes;
865  case KIND_FREED_OBJECTS:
866    return stats->freed_objects;
867  case KIND_FREED_BYTES:
868    return stats->freed_bytes;
869  case KIND_GC_INVOCATIONS:
870    return stats->gc_for_alloc_count;
871  case KIND_CLASS_INIT_COUNT:
872    return stats->class_init_count;
873  case KIND_CLASS_INIT_TIME:
874    // Convert ns to us, reduce to 32 bits.
875    return static_cast<int>(stats->class_init_time_ns / 1000);
876  case KIND_EXT_ALLOCATED_OBJECTS:
877  case KIND_EXT_ALLOCATED_BYTES:
878  case KIND_EXT_FREED_OBJECTS:
879  case KIND_EXT_FREED_BYTES:
880    return 0;  // backward compatibility
881  default:
882    LOG(FATAL) << "Unknown statistic " << kind;
883    return -1;  // unreachable
884  }
885}
886
887void Runtime::BlockSignals() {
888  SignalSet signals;
889  signals.Add(SIGPIPE);
890  // SIGQUIT is used to dump the runtime's state (including stack traces).
891  signals.Add(SIGQUIT);
892  // SIGUSR1 is used to initiate a GC.
893  signals.Add(SIGUSR1);
894  signals.Block();
895}
896
897bool Runtime::AttachCurrentThread(const char* thread_name, bool as_daemon, jobject thread_group,
898                                  bool create_peer) {
899  bool success = Thread::Attach(thread_name, as_daemon, thread_group, create_peer) != NULL;
900  if (thread_name == NULL) {
901    LOG(WARNING) << *Thread::Current() << " attached without supplying a name";
902  }
903  return success;
904}
905
906void Runtime::DetachCurrentThread() {
907  Thread* self = Thread::Current();
908  if (self == NULL) {
909    LOG(FATAL) << "attempting to detach thread that is not attached";
910  }
911  if (self->HasManagedStack()) {
912    LOG(FATAL) << *Thread::Current() << " attempting to detach while still running code";
913  }
914  thread_list_->Unregister(self);
915}
916
917  mirror::Throwable* Runtime::GetPreAllocatedOutOfMemoryError() const {
918  if (pre_allocated_OutOfMemoryError_ == NULL) {
919    LOG(ERROR) << "Failed to return pre-allocated OOME";
920  }
921  return pre_allocated_OutOfMemoryError_;
922}
923
924void Runtime::VisitConstantRoots(RootCallback* callback, void* arg) {
925  // Visit the classes held as static in mirror classes, these can be visited concurrently and only
926  // need to be visited once per GC since they never change.
927  mirror::ArtField::VisitRoots(callback, arg);
928  mirror::ArtMethod::VisitRoots(callback, arg);
929  mirror::Class::VisitRoots(callback, arg);
930  mirror::Reference::VisitRoots(callback, arg);
931  mirror::StackTraceElement::VisitRoots(callback, arg);
932  mirror::String::VisitRoots(callback, arg);
933  mirror::Throwable::VisitRoots(callback, arg);
934  // Visit all the primitive array types classes.
935  mirror::PrimitiveArray<uint8_t>::VisitRoots(callback, arg);   // BooleanArray
936  mirror::PrimitiveArray<int8_t>::VisitRoots(callback, arg);    // ByteArray
937  mirror::PrimitiveArray<uint16_t>::VisitRoots(callback, arg);  // CharArray
938  mirror::PrimitiveArray<double>::VisitRoots(callback, arg);    // DoubleArray
939  mirror::PrimitiveArray<float>::VisitRoots(callback, arg);     // FloatArray
940  mirror::PrimitiveArray<int32_t>::VisitRoots(callback, arg);   // IntArray
941  mirror::PrimitiveArray<int64_t>::VisitRoots(callback, arg);   // LongArray
942  mirror::PrimitiveArray<int16_t>::VisitRoots(callback, arg);   // ShortArray
943}
944
945void Runtime::VisitConcurrentRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
946  intern_table_->VisitRoots(callback, arg, flags);
947  class_linker_->VisitRoots(callback, arg, flags);
948  if ((flags & kVisitRootFlagNewRoots) == 0) {
949    // Guaranteed to have no new roots in the constant roots.
950    VisitConstantRoots(callback, arg);
951  }
952}
953
954void Runtime::VisitNonThreadRoots(RootCallback* callback, void* arg) {
955  java_vm_->VisitRoots(callback, arg);
956  if (pre_allocated_OutOfMemoryError_ != nullptr) {
957    callback(reinterpret_cast<mirror::Object**>(&pre_allocated_OutOfMemoryError_), arg, 0,
958             kRootVMInternal);
959    DCHECK(pre_allocated_OutOfMemoryError_ != nullptr);
960  }
961  callback(reinterpret_cast<mirror::Object**>(&resolution_method_), arg, 0, kRootVMInternal);
962  DCHECK(resolution_method_ != nullptr);
963  if (HasImtConflictMethod()) {
964    callback(reinterpret_cast<mirror::Object**>(&imt_conflict_method_), arg, 0, kRootVMInternal);
965  }
966  if (HasDefaultImt()) {
967    callback(reinterpret_cast<mirror::Object**>(&default_imt_), arg, 0, kRootVMInternal);
968  }
969  for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
970    if (callee_save_methods_[i] != nullptr) {
971      callback(reinterpret_cast<mirror::Object**>(&callee_save_methods_[i]), arg, 0,
972               kRootVMInternal);
973    }
974  }
975  {
976    MutexLock mu(Thread::Current(), method_verifier_lock_);
977    for (verifier::MethodVerifier* verifier : method_verifiers_) {
978      verifier->VisitRoots(callback, arg);
979    }
980  }
981  if (preinitialization_transaction_ != nullptr) {
982    preinitialization_transaction_->VisitRoots(callback, arg);
983  }
984  instrumentation_.VisitRoots(callback, arg);
985}
986
987void Runtime::VisitNonConcurrentRoots(RootCallback* callback, void* arg) {
988  thread_list_->VisitRoots(callback, arg);
989  VisitNonThreadRoots(callback, arg);
990}
991
992void Runtime::VisitRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
993  VisitNonConcurrentRoots(callback, arg);
994  VisitConcurrentRoots(callback, arg, flags);
995}
996
997mirror::ObjectArray<mirror::ArtMethod>* Runtime::CreateDefaultImt(ClassLinker* cl) {
998  Thread* self = Thread::Current();
999  StackHandleScope<1> hs(self);
1000  Handle<mirror::ObjectArray<mirror::ArtMethod>> imtable(
1001      hs.NewHandle(cl->AllocArtMethodArray(self, 64)));
1002  mirror::ArtMethod* imt_conflict_method = Runtime::Current()->GetImtConflictMethod();
1003  for (size_t i = 0; i < static_cast<size_t>(imtable->GetLength()); i++) {
1004    imtable->Set<false>(i, imt_conflict_method);
1005  }
1006  return imtable.Get();
1007}
1008
1009mirror::ArtMethod* Runtime::CreateImtConflictMethod() {
1010  Thread* self = Thread::Current();
1011  Runtime* runtime = Runtime::Current();
1012  ClassLinker* class_linker = runtime->GetClassLinker();
1013  StackHandleScope<1> hs(self);
1014  Handle<mirror::ArtMethod> method(hs.NewHandle(class_linker->AllocArtMethod(self)));
1015  method->SetDeclaringClass(mirror::ArtMethod::GetJavaLangReflectArtMethod());
1016  // TODO: use a special method for imt conflict method saves.
1017  method->SetDexMethodIndex(DexFile::kDexNoIndex);
1018  // When compiling, the code pointer will get set later when the image is loaded.
1019  if (runtime->IsCompiler()) {
1020    method->SetEntryPointFromPortableCompiledCode(nullptr);
1021    method->SetEntryPointFromQuickCompiledCode(nullptr);
1022  } else {
1023    method->SetEntryPointFromPortableCompiledCode(class_linker->GetPortableImtConflictTrampoline());
1024    method->SetEntryPointFromQuickCompiledCode(class_linker->GetQuickImtConflictTrampoline());
1025  }
1026  return method.Get();
1027}
1028
1029mirror::ArtMethod* Runtime::CreateResolutionMethod() {
1030  Thread* self = Thread::Current();
1031  Runtime* runtime = Runtime::Current();
1032  ClassLinker* class_linker = runtime->GetClassLinker();
1033  StackHandleScope<1> hs(self);
1034  Handle<mirror::ArtMethod> method(hs.NewHandle(class_linker->AllocArtMethod(self)));
1035  method->SetDeclaringClass(mirror::ArtMethod::GetJavaLangReflectArtMethod());
1036  // TODO: use a special method for resolution method saves
1037  method->SetDexMethodIndex(DexFile::kDexNoIndex);
1038  // When compiling, the code pointer will get set later when the image is loaded.
1039  if (runtime->IsCompiler()) {
1040    method->SetEntryPointFromPortableCompiledCode(nullptr);
1041    method->SetEntryPointFromQuickCompiledCode(nullptr);
1042  } else {
1043    method->SetEntryPointFromPortableCompiledCode(class_linker->GetPortableResolutionTrampoline());
1044    method->SetEntryPointFromQuickCompiledCode(class_linker->GetQuickResolutionTrampoline());
1045  }
1046  return method.Get();
1047}
1048
1049mirror::ArtMethod* Runtime::CreateCalleeSaveMethod(CalleeSaveType type) {
1050  Thread* self = Thread::Current();
1051  Runtime* runtime = Runtime::Current();
1052  ClassLinker* class_linker = runtime->GetClassLinker();
1053  StackHandleScope<1> hs(self);
1054  Handle<mirror::ArtMethod> method(hs.NewHandle(class_linker->AllocArtMethod(self)));
1055  method->SetDeclaringClass(mirror::ArtMethod::GetJavaLangReflectArtMethod());
1056  // TODO: use a special method for callee saves
1057  method->SetDexMethodIndex(DexFile::kDexNoIndex);
1058  method->SetEntryPointFromPortableCompiledCode(nullptr);
1059  method->SetEntryPointFromQuickCompiledCode(nullptr);
1060  DCHECK_NE(instruction_set_, kNone);
1061  return method.Get();
1062}
1063
1064void Runtime::DisallowNewSystemWeaks() {
1065  monitor_list_->DisallowNewMonitors();
1066  intern_table_->DisallowNewInterns();
1067  java_vm_->DisallowNewWeakGlobals();
1068}
1069
1070void Runtime::AllowNewSystemWeaks() {
1071  monitor_list_->AllowNewMonitors();
1072  intern_table_->AllowNewInterns();
1073  java_vm_->AllowNewWeakGlobals();
1074}
1075
1076void Runtime::SetInstructionSet(InstructionSet instruction_set) {
1077  instruction_set_ = instruction_set;
1078  if ((instruction_set_ == kThumb2) || (instruction_set_ == kArm)) {
1079    for (int i = 0; i != kLastCalleeSaveType; ++i) {
1080      CalleeSaveType type = static_cast<CalleeSaveType>(i);
1081      callee_save_method_frame_infos_[i] = arm::ArmCalleeSaveMethodFrameInfo(type);
1082    }
1083  } else if (instruction_set_ == kMips) {
1084    for (int i = 0; i != kLastCalleeSaveType; ++i) {
1085      CalleeSaveType type = static_cast<CalleeSaveType>(i);
1086      callee_save_method_frame_infos_[i] = mips::MipsCalleeSaveMethodFrameInfo(type);
1087    }
1088  } else if (instruction_set_ == kX86) {
1089    for (int i = 0; i != kLastCalleeSaveType; ++i) {
1090      CalleeSaveType type = static_cast<CalleeSaveType>(i);
1091      callee_save_method_frame_infos_[i] = x86::X86CalleeSaveMethodFrameInfo(type);
1092    }
1093  } else if (instruction_set_ == kX86_64) {
1094    for (int i = 0; i != kLastCalleeSaveType; ++i) {
1095      CalleeSaveType type = static_cast<CalleeSaveType>(i);
1096      callee_save_method_frame_infos_[i] = x86_64::X86_64CalleeSaveMethodFrameInfo(type);
1097    }
1098  } else if (instruction_set_ == kArm64) {
1099    for (int i = 0; i != kLastCalleeSaveType; ++i) {
1100      CalleeSaveType type = static_cast<CalleeSaveType>(i);
1101      callee_save_method_frame_infos_[i] = arm64::Arm64CalleeSaveMethodFrameInfo(type);
1102    }
1103  } else {
1104    UNIMPLEMENTED(FATAL) << instruction_set_;
1105  }
1106}
1107
1108void Runtime::SetCalleeSaveMethod(mirror::ArtMethod* method, CalleeSaveType type) {
1109  DCHECK_LT(static_cast<int>(type), static_cast<int>(kLastCalleeSaveType));
1110  callee_save_methods_[type] = method;
1111}
1112
1113const std::vector<const DexFile*>& Runtime::GetCompileTimeClassPath(jobject class_loader) {
1114  if (class_loader == NULL) {
1115    return GetClassLinker()->GetBootClassPath();
1116  }
1117  CHECK(UseCompileTimeClassPath());
1118  CompileTimeClassPaths::const_iterator it = compile_time_class_paths_.find(class_loader);
1119  CHECK(it != compile_time_class_paths_.end());
1120  return it->second;
1121}
1122
1123void Runtime::SetCompileTimeClassPath(jobject class_loader,
1124                                      std::vector<const DexFile*>& class_path) {
1125  CHECK(!IsStarted());
1126  use_compile_time_class_path_ = true;
1127  compile_time_class_paths_.Put(class_loader, class_path);
1128}
1129
1130void Runtime::AddMethodVerifier(verifier::MethodVerifier* verifier) {
1131  DCHECK(verifier != nullptr);
1132  MutexLock mu(Thread::Current(), method_verifier_lock_);
1133  method_verifiers_.insert(verifier);
1134}
1135
1136void Runtime::RemoveMethodVerifier(verifier::MethodVerifier* verifier) {
1137  DCHECK(verifier != nullptr);
1138  MutexLock mu(Thread::Current(), method_verifier_lock_);
1139  auto it = method_verifiers_.find(verifier);
1140  CHECK(it != method_verifiers_.end());
1141  method_verifiers_.erase(it);
1142}
1143
1144void Runtime::StartProfiler(const char* profile_output_filename) {
1145  profile_output_filename_ = profile_output_filename;
1146  profiler_started_ =
1147    BackgroundMethodSamplingProfiler::Start(profile_output_filename_, profiler_options_);
1148}
1149
1150// Transaction support.
1151void Runtime::EnterTransactionMode(Transaction* transaction) {
1152  DCHECK(IsCompiler());
1153  DCHECK(transaction != nullptr);
1154  DCHECK(!IsActiveTransaction());
1155  preinitialization_transaction_ = transaction;
1156}
1157
1158void Runtime::ExitTransactionMode() {
1159  DCHECK(IsCompiler());
1160  DCHECK(IsActiveTransaction());
1161  preinitialization_transaction_ = nullptr;
1162}
1163
1164void Runtime::RecordWriteField32(mirror::Object* obj, MemberOffset field_offset,
1165                                 uint32_t value, bool is_volatile) const {
1166  DCHECK(IsCompiler());
1167  DCHECK(IsActiveTransaction());
1168  preinitialization_transaction_->RecordWriteField32(obj, field_offset, value, is_volatile);
1169}
1170
1171void Runtime::RecordWriteField64(mirror::Object* obj, MemberOffset field_offset,
1172                                 uint64_t value, bool is_volatile) const {
1173  DCHECK(IsCompiler());
1174  DCHECK(IsActiveTransaction());
1175  preinitialization_transaction_->RecordWriteField64(obj, field_offset, value, is_volatile);
1176}
1177
1178void Runtime::RecordWriteFieldReference(mirror::Object* obj, MemberOffset field_offset,
1179                                        mirror::Object* value, bool is_volatile) const {
1180  DCHECK(IsCompiler());
1181  DCHECK(IsActiveTransaction());
1182  preinitialization_transaction_->RecordWriteFieldReference(obj, field_offset, value, is_volatile);
1183}
1184
1185void Runtime::RecordWriteArray(mirror::Array* array, size_t index, uint64_t value) const {
1186  DCHECK(IsCompiler());
1187  DCHECK(IsActiveTransaction());
1188  preinitialization_transaction_->RecordWriteArray(array, index, value);
1189}
1190
1191void Runtime::RecordStrongStringInsertion(mirror::String* s, uint32_t hash_code) const {
1192  DCHECK(IsCompiler());
1193  DCHECK(IsActiveTransaction());
1194  preinitialization_transaction_->RecordStrongStringInsertion(s, hash_code);
1195}
1196
1197void Runtime::RecordWeakStringInsertion(mirror::String* s, uint32_t hash_code) const {
1198  DCHECK(IsCompiler());
1199  DCHECK(IsActiveTransaction());
1200  preinitialization_transaction_->RecordWeakStringInsertion(s, hash_code);
1201}
1202
1203void Runtime::RecordStrongStringRemoval(mirror::String* s, uint32_t hash_code) const {
1204  DCHECK(IsCompiler());
1205  DCHECK(IsActiveTransaction());
1206  preinitialization_transaction_->RecordStrongStringRemoval(s, hash_code);
1207}
1208
1209void Runtime::RecordWeakStringRemoval(mirror::String* s, uint32_t hash_code) const {
1210  DCHECK(IsCompiler());
1211  DCHECK(IsActiveTransaction());
1212  preinitialization_transaction_->RecordWeakStringRemoval(s, hash_code);
1213}
1214
1215void Runtime::SetFaultMessage(const std::string& message) {
1216  MutexLock mu(Thread::Current(), fault_message_lock_);
1217  fault_message_ = message;
1218}
1219
1220void Runtime::AddCurrentRuntimeFeaturesAsDex2OatArguments(std::vector<std::string>* argv)
1221    const {
1222  if (GetInstrumentation()->InterpretOnly()) {
1223    argv->push_back("--compiler-filter=interpret-only");
1224  }
1225
1226  // Make the dex2oat instruction set match that of the launching runtime. If we have multiple
1227  // architecture support, dex2oat may be compiled as a different instruction-set than that
1228  // currently being executed.
1229  std::string instruction_set("--instruction-set=");
1230  instruction_set += GetInstructionSetString(kRuntimeISA);
1231  argv->push_back(instruction_set);
1232
1233  std::string features("--instruction-set-features=");
1234  features += GetDefaultInstructionSetFeatures();
1235  argv->push_back(features);
1236}
1237
1238void Runtime::UpdateProfilerState(int state) {
1239  VLOG(profiler) << "Profiler state updated to " << state;
1240}
1241}  // namespace art
1242