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