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