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