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