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