runtime.cc revision 9e82bd3f0ce9e5f5777bea2f752ff3e251d32f9f
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
643  dump_gc_performance_on_shutdown_ = options->dump_gc_performance_on_shutdown_;
644
645  BlockSignals();
646  InitPlatformSignalHandlers();
647
648  java_vm_ = new JavaVMExt(this, options.get());
649
650  Thread::Startup();
651
652  // ClassLinker needs an attached thread, but we can't fully attach a thread without creating
653  // objects. We can't supply a thread group yet; it will be fixed later. Since we are the main
654  // thread, we do not get a java peer.
655  Thread* self = Thread::Attach("main", false, NULL, false);
656  CHECK_EQ(self->GetThreadId(), ThreadList::kMainThreadId);
657  CHECK(self != NULL);
658
659  // Set us to runnable so tools using a runtime can allocate and GC by default
660  self->TransitionFromSuspendedToRunnable();
661
662  // Now we're attached, we can take the heap locks and validate the heap.
663  GetHeap()->EnableObjectValidation();
664
665  CHECK_GE(GetHeap()->GetContinuousSpaces().size(), 1U);
666  class_linker_ = new ClassLinker(intern_table_);
667  if (GetHeap()->HasImageSpace()) {
668    class_linker_->InitFromImage();
669    if (kIsDebugBuild) {
670      GetHeap()->GetImageSpace()->VerifyImageAllocations();
671    }
672  } else {
673    CHECK(options->boot_class_path_ != NULL);
674    CHECK_NE(options->boot_class_path_->size(), 0U);
675    class_linker_->InitFromCompiler(*options->boot_class_path_);
676  }
677  CHECK(class_linker_ != NULL);
678  verifier::MethodVerifier::Init();
679
680  method_trace_ = options->method_trace_;
681  method_trace_file_ = options->method_trace_file_;
682  method_trace_file_size_ = options->method_trace_file_size_;
683
684  profile_output_filename_ = options->profile_output_filename_;
685  profiler_options_ = options->profiler_options_;
686
687  // TODO: move this to just be an Trace::Start argument
688  Trace::SetDefaultClockSource(options->profile_clock_source_);
689
690  if (options->method_trace_) {
691    ScopedThreadStateChange tsc(self, kWaitingForMethodTracingStart);
692    Trace::Start(options->method_trace_file_.c_str(), -1, options->method_trace_file_size_, 0,
693                 false, false, 0);
694  }
695
696  // Pre-allocate an OutOfMemoryError for the double-OOME case.
697  self->ThrowNewException(ThrowLocation(), "Ljava/lang/OutOfMemoryError;",
698                          "OutOfMemoryError thrown while trying to throw OutOfMemoryError; "
699                          "no stack available");
700  pre_allocated_OutOfMemoryError_ = self->GetException(NULL);
701  self->ClearException();
702
703  VLOG(startup) << "Runtime::Init exiting";
704  return true;
705}
706
707void Runtime::InitNativeMethods() {
708  VLOG(startup) << "Runtime::InitNativeMethods entering";
709  Thread* self = Thread::Current();
710  JNIEnv* env = self->GetJniEnv();
711
712  // Must be in the kNative state for calling native methods (JNI_OnLoad code).
713  CHECK_EQ(self->GetState(), kNative);
714
715  // First set up JniConstants, which is used by both the runtime's built-in native
716  // methods and libcore.
717  JniConstants::init(env);
718  WellKnownClasses::Init(env);
719
720  // Then set up the native methods provided by the runtime itself.
721  RegisterRuntimeNativeMethods(env);
722
723  // Then set up libcore, which is just a regular JNI library with a regular JNI_OnLoad.
724  // Most JNI libraries can just use System.loadLibrary, but libcore can't because it's
725  // the library that implements System.loadLibrary!
726  {
727    std::string mapped_name(StringPrintf(OS_SHARED_LIB_FORMAT_STR, "javacore"));
728    std::string reason;
729    self->TransitionFromSuspendedToRunnable();
730    StackHandleScope<1> hs(self);
731    auto class_loader(hs.NewHandle<mirror::ClassLoader>(nullptr));
732    if (!instance_->java_vm_->LoadNativeLibrary(mapped_name, class_loader, &reason)) {
733      LOG(FATAL) << "LoadNativeLibrary failed for \"" << mapped_name << "\": " << reason;
734    }
735    self->TransitionFromRunnableToSuspended(kNative);
736  }
737
738  // Initialize well known classes that may invoke runtime native methods.
739  WellKnownClasses::LateInit(env);
740
741  VLOG(startup) << "Runtime::InitNativeMethods exiting";
742}
743
744void Runtime::InitThreadGroups(Thread* self) {
745  JNIEnvExt* env = self->GetJniEnv();
746  ScopedJniEnvLocalRefState env_state(env);
747  main_thread_group_ =
748      env->NewGlobalRef(env->GetStaticObjectField(
749          WellKnownClasses::java_lang_ThreadGroup,
750          WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup));
751  CHECK(main_thread_group_ != NULL || IsCompiler());
752  system_thread_group_ =
753      env->NewGlobalRef(env->GetStaticObjectField(
754          WellKnownClasses::java_lang_ThreadGroup,
755          WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup));
756  CHECK(system_thread_group_ != NULL || IsCompiler());
757}
758
759jobject Runtime::GetMainThreadGroup() const {
760  CHECK(main_thread_group_ != NULL || IsCompiler());
761  return main_thread_group_;
762}
763
764jobject Runtime::GetSystemThreadGroup() const {
765  CHECK(system_thread_group_ != NULL || IsCompiler());
766  return system_thread_group_;
767}
768
769jobject Runtime::GetSystemClassLoader() const {
770  CHECK(system_class_loader_ != NULL || IsCompiler());
771  return system_class_loader_;
772}
773
774void Runtime::RegisterRuntimeNativeMethods(JNIEnv* env) {
775#define REGISTER(FN) extern void FN(JNIEnv*); FN(env)
776  // Register Throwable first so that registration of other native methods can throw exceptions
777  REGISTER(register_java_lang_Throwable);
778  REGISTER(register_dalvik_system_DexFile);
779  REGISTER(register_dalvik_system_VMDebug);
780  REGISTER(register_dalvik_system_VMRuntime);
781  REGISTER(register_dalvik_system_VMStack);
782  REGISTER(register_dalvik_system_ZygoteHooks);
783  REGISTER(register_java_lang_Class);
784  REGISTER(register_java_lang_DexCache);
785  REGISTER(register_java_lang_Object);
786  REGISTER(register_java_lang_Runtime);
787  REGISTER(register_java_lang_String);
788  REGISTER(register_java_lang_System);
789  REGISTER(register_java_lang_Thread);
790  REGISTER(register_java_lang_VMClassLoader);
791  REGISTER(register_java_lang_ref_Reference);
792  REGISTER(register_java_lang_reflect_Array);
793  REGISTER(register_java_lang_reflect_Constructor);
794  REGISTER(register_java_lang_reflect_Field);
795  REGISTER(register_java_lang_reflect_Method);
796  REGISTER(register_java_lang_reflect_Proxy);
797  REGISTER(register_java_util_concurrent_atomic_AtomicLong);
798  REGISTER(register_org_apache_harmony_dalvik_ddmc_DdmServer);
799  REGISTER(register_org_apache_harmony_dalvik_ddmc_DdmVmInternal);
800  REGISTER(register_sun_misc_Unsafe);
801#undef REGISTER
802}
803
804void Runtime::DumpForSigQuit(std::ostream& os) {
805  GetClassLinker()->DumpForSigQuit(os);
806  GetInternTable()->DumpForSigQuit(os);
807  GetJavaVM()->DumpForSigQuit(os);
808  GetHeap()->DumpForSigQuit(os);
809  os << "\n";
810
811  thread_list_->DumpForSigQuit(os);
812  BaseMutex::DumpAll(os);
813}
814
815void Runtime::DumpLockHolders(std::ostream& os) {
816  uint64_t mutator_lock_owner = Locks::mutator_lock_->GetExclusiveOwnerTid();
817  pid_t thread_list_lock_owner = GetThreadList()->GetLockOwner();
818  pid_t classes_lock_owner = GetClassLinker()->GetClassesLockOwner();
819  pid_t dex_lock_owner = GetClassLinker()->GetDexLockOwner();
820  if ((thread_list_lock_owner | classes_lock_owner | dex_lock_owner) != 0) {
821    os << "Mutator lock exclusive owner tid: " << mutator_lock_owner << "\n"
822       << "ThreadList lock owner tid: " << thread_list_lock_owner << "\n"
823       << "ClassLinker classes lock owner tid: " << classes_lock_owner << "\n"
824       << "ClassLinker dex lock owner tid: " << dex_lock_owner << "\n";
825  }
826}
827
828void Runtime::SetStatsEnabled(bool new_state) {
829  if (new_state == true) {
830    GetStats()->Clear(~0);
831    // TODO: wouldn't it make more sense to clear _all_ threads' stats?
832    Thread::Current()->GetStats()->Clear(~0);
833    GetInstrumentation()->InstrumentQuickAllocEntryPoints();
834  } else {
835    GetInstrumentation()->UninstrumentQuickAllocEntryPoints();
836  }
837  stats_enabled_ = new_state;
838}
839
840void Runtime::ResetStats(int kinds) {
841  GetStats()->Clear(kinds & 0xffff);
842  // TODO: wouldn't it make more sense to clear _all_ threads' stats?
843  Thread::Current()->GetStats()->Clear(kinds >> 16);
844}
845
846int32_t Runtime::GetStat(int kind) {
847  RuntimeStats* stats;
848  if (kind < (1<<16)) {
849    stats = GetStats();
850  } else {
851    stats = Thread::Current()->GetStats();
852    kind >>= 16;
853  }
854  switch (kind) {
855  case KIND_ALLOCATED_OBJECTS:
856    return stats->allocated_objects;
857  case KIND_ALLOCATED_BYTES:
858    return stats->allocated_bytes;
859  case KIND_FREED_OBJECTS:
860    return stats->freed_objects;
861  case KIND_FREED_BYTES:
862    return stats->freed_bytes;
863  case KIND_GC_INVOCATIONS:
864    return stats->gc_for_alloc_count;
865  case KIND_CLASS_INIT_COUNT:
866    return stats->class_init_count;
867  case KIND_CLASS_INIT_TIME:
868    // Convert ns to us, reduce to 32 bits.
869    return static_cast<int>(stats->class_init_time_ns / 1000);
870  case KIND_EXT_ALLOCATED_OBJECTS:
871  case KIND_EXT_ALLOCATED_BYTES:
872  case KIND_EXT_FREED_OBJECTS:
873  case KIND_EXT_FREED_BYTES:
874    return 0;  // backward compatibility
875  default:
876    LOG(FATAL) << "Unknown statistic " << kind;
877    return -1;  // unreachable
878  }
879}
880
881void Runtime::BlockSignals() {
882  SignalSet signals;
883  signals.Add(SIGPIPE);
884  // SIGQUIT is used to dump the runtime's state (including stack traces).
885  signals.Add(SIGQUIT);
886  // SIGUSR1 is used to initiate a GC.
887  signals.Add(SIGUSR1);
888  signals.Block();
889}
890
891bool Runtime::AttachCurrentThread(const char* thread_name, bool as_daemon, jobject thread_group,
892                                  bool create_peer) {
893  bool success = Thread::Attach(thread_name, as_daemon, thread_group, create_peer) != NULL;
894  if (thread_name == NULL) {
895    LOG(WARNING) << *Thread::Current() << " attached without supplying a name";
896  }
897  return success;
898}
899
900void Runtime::DetachCurrentThread() {
901  Thread* self = Thread::Current();
902  if (self == NULL) {
903    LOG(FATAL) << "attempting to detach thread that is not attached";
904  }
905  if (self->HasManagedStack()) {
906    LOG(FATAL) << *Thread::Current() << " attempting to detach while still running code";
907  }
908  thread_list_->Unregister(self);
909}
910
911  mirror::Throwable* Runtime::GetPreAllocatedOutOfMemoryError() const {
912  if (pre_allocated_OutOfMemoryError_ == NULL) {
913    LOG(ERROR) << "Failed to return pre-allocated OOME";
914  }
915  return pre_allocated_OutOfMemoryError_;
916}
917
918void Runtime::VisitConstantRoots(RootCallback* callback, void* arg) {
919  // Visit the classes held as static in mirror classes, these can be visited concurrently and only
920  // need to be visited once per GC since they never change.
921  mirror::ArtField::VisitRoots(callback, arg);
922  mirror::ArtMethod::VisitRoots(callback, arg);
923  mirror::Class::VisitRoots(callback, arg);
924  mirror::StackTraceElement::VisitRoots(callback, arg);
925  mirror::String::VisitRoots(callback, arg);
926  mirror::Throwable::VisitRoots(callback, arg);
927  // Visit all the primitive array types classes.
928  mirror::PrimitiveArray<uint8_t>::VisitRoots(callback, arg);   // BooleanArray
929  mirror::PrimitiveArray<int8_t>::VisitRoots(callback, arg);    // ByteArray
930  mirror::PrimitiveArray<uint16_t>::VisitRoots(callback, arg);  // CharArray
931  mirror::PrimitiveArray<double>::VisitRoots(callback, arg);    // DoubleArray
932  mirror::PrimitiveArray<float>::VisitRoots(callback, arg);     // FloatArray
933  mirror::PrimitiveArray<int32_t>::VisitRoots(callback, arg);   // IntArray
934  mirror::PrimitiveArray<int64_t>::VisitRoots(callback, arg);   // LongArray
935  mirror::PrimitiveArray<int16_t>::VisitRoots(callback, arg);   // ShortArray
936}
937
938void Runtime::VisitConcurrentRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
939  intern_table_->VisitRoots(callback, arg, flags);
940  class_linker_->VisitRoots(callback, arg, flags);
941  if ((flags & kVisitRootFlagNewRoots) == 0) {
942    // Guaranteed to have no new roots in the constant roots.
943    VisitConstantRoots(callback, arg);
944  }
945}
946
947void Runtime::VisitNonThreadRoots(RootCallback* callback, void* arg) {
948  java_vm_->VisitRoots(callback, arg);
949  if (pre_allocated_OutOfMemoryError_ != nullptr) {
950    callback(reinterpret_cast<mirror::Object**>(&pre_allocated_OutOfMemoryError_), arg, 0,
951             kRootVMInternal);
952    DCHECK(pre_allocated_OutOfMemoryError_ != nullptr);
953  }
954  callback(reinterpret_cast<mirror::Object**>(&resolution_method_), arg, 0, kRootVMInternal);
955  DCHECK(resolution_method_ != nullptr);
956  if (HasImtConflictMethod()) {
957    callback(reinterpret_cast<mirror::Object**>(&imt_conflict_method_), arg, 0, kRootVMInternal);
958  }
959  if (HasDefaultImt()) {
960    callback(reinterpret_cast<mirror::Object**>(&default_imt_), arg, 0, kRootVMInternal);
961  }
962  for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
963    if (callee_save_methods_[i] != nullptr) {
964      callback(reinterpret_cast<mirror::Object**>(&callee_save_methods_[i]), arg, 0,
965               kRootVMInternal);
966    }
967  }
968  {
969    MutexLock mu(Thread::Current(), method_verifier_lock_);
970    for (verifier::MethodVerifier* verifier : method_verifiers_) {
971      verifier->VisitRoots(callback, arg);
972    }
973  }
974  if (preinitialization_transaction_ != nullptr) {
975    preinitialization_transaction_->VisitRoots(callback, arg);
976  }
977  instrumentation_.VisitRoots(callback, arg);
978}
979
980void Runtime::VisitNonConcurrentRoots(RootCallback* callback, void* arg) {
981  thread_list_->VisitRoots(callback, arg);
982  VisitNonThreadRoots(callback, arg);
983}
984
985void Runtime::VisitRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
986  VisitNonConcurrentRoots(callback, arg);
987  VisitConcurrentRoots(callback, arg, flags);
988}
989
990mirror::ObjectArray<mirror::ArtMethod>* Runtime::CreateDefaultImt(ClassLinker* cl) {
991  Thread* self = Thread::Current();
992  StackHandleScope<1> hs(self);
993  Handle<mirror::ObjectArray<mirror::ArtMethod>> imtable(
994      hs.NewHandle(cl->AllocArtMethodArray(self, 64)));
995  mirror::ArtMethod* imt_conflict_method = Runtime::Current()->GetImtConflictMethod();
996  for (size_t i = 0; i < static_cast<size_t>(imtable->GetLength()); i++) {
997    imtable->Set<false>(i, imt_conflict_method);
998  }
999  return imtable.Get();
1000}
1001
1002mirror::ArtMethod* Runtime::CreateImtConflictMethod() {
1003  Thread* self = Thread::Current();
1004  Runtime* runtime = Runtime::Current();
1005  ClassLinker* class_linker = runtime->GetClassLinker();
1006  StackHandleScope<1> hs(self);
1007  Handle<mirror::ArtMethod> method(hs.NewHandle(class_linker->AllocArtMethod(self)));
1008  method->SetDeclaringClass(mirror::ArtMethod::GetJavaLangReflectArtMethod());
1009  // TODO: use a special method for imt conflict method saves.
1010  method->SetDexMethodIndex(DexFile::kDexNoIndex);
1011  // When compiling, the code pointer will get set later when the image is loaded.
1012  if (runtime->IsCompiler()) {
1013    method->SetEntryPointFromPortableCompiledCode(nullptr);
1014    method->SetEntryPointFromQuickCompiledCode(nullptr);
1015  } else {
1016    method->SetEntryPointFromPortableCompiledCode(GetPortableImtConflictTrampoline(class_linker));
1017    method->SetEntryPointFromQuickCompiledCode(GetQuickImtConflictTrampoline(class_linker));
1018  }
1019  return method.Get();
1020}
1021
1022mirror::ArtMethod* Runtime::CreateResolutionMethod() {
1023  Thread* self = Thread::Current();
1024  Runtime* runtime = Runtime::Current();
1025  ClassLinker* class_linker = runtime->GetClassLinker();
1026  StackHandleScope<1> hs(self);
1027  Handle<mirror::ArtMethod> method(hs.NewHandle(class_linker->AllocArtMethod(self)));
1028  method->SetDeclaringClass(mirror::ArtMethod::GetJavaLangReflectArtMethod());
1029  // TODO: use a special method for resolution method saves
1030  method->SetDexMethodIndex(DexFile::kDexNoIndex);
1031  // When compiling, the code pointer will get set later when the image is loaded.
1032  if (runtime->IsCompiler()) {
1033    method->SetEntryPointFromPortableCompiledCode(nullptr);
1034    method->SetEntryPointFromQuickCompiledCode(nullptr);
1035  } else {
1036    method->SetEntryPointFromPortableCompiledCode(GetPortableResolutionTrampoline(class_linker));
1037    method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionTrampoline(class_linker));
1038  }
1039  return method.Get();
1040}
1041
1042mirror::ArtMethod* Runtime::CreateCalleeSaveMethod(CalleeSaveType type) {
1043  Thread* self = Thread::Current();
1044  Runtime* runtime = Runtime::Current();
1045  ClassLinker* class_linker = runtime->GetClassLinker();
1046  StackHandleScope<1> hs(self);
1047  Handle<mirror::ArtMethod> method(hs.NewHandle(class_linker->AllocArtMethod(self)));
1048  method->SetDeclaringClass(mirror::ArtMethod::GetJavaLangReflectArtMethod());
1049  // TODO: use a special method for callee saves
1050  method->SetDexMethodIndex(DexFile::kDexNoIndex);
1051  method->SetEntryPointFromPortableCompiledCode(nullptr);
1052  method->SetEntryPointFromQuickCompiledCode(nullptr);
1053  DCHECK_NE(instruction_set_, kNone);
1054  return method.Get();
1055}
1056
1057void Runtime::DisallowNewSystemWeaks() {
1058  monitor_list_->DisallowNewMonitors();
1059  intern_table_->DisallowNewInterns();
1060  java_vm_->DisallowNewWeakGlobals();
1061}
1062
1063void Runtime::AllowNewSystemWeaks() {
1064  monitor_list_->AllowNewMonitors();
1065  intern_table_->AllowNewInterns();
1066  java_vm_->AllowNewWeakGlobals();
1067}
1068
1069void Runtime::SetInstructionSet(InstructionSet instruction_set) {
1070  instruction_set_ = instruction_set;
1071  if ((instruction_set_ == kThumb2) || (instruction_set_ == kArm)) {
1072    for (int i = 0; i != kLastCalleeSaveType; ++i) {
1073      CalleeSaveType type = static_cast<CalleeSaveType>(i);
1074      callee_save_method_frame_infos_[i] = arm::ArmCalleeSaveMethodFrameInfo(type);
1075    }
1076  } else if (instruction_set_ == kMips) {
1077    for (int i = 0; i != kLastCalleeSaveType; ++i) {
1078      CalleeSaveType type = static_cast<CalleeSaveType>(i);
1079      callee_save_method_frame_infos_[i] = mips::MipsCalleeSaveMethodFrameInfo(type);
1080    }
1081  } else if (instruction_set_ == kX86) {
1082    for (int i = 0; i != kLastCalleeSaveType; ++i) {
1083      CalleeSaveType type = static_cast<CalleeSaveType>(i);
1084      callee_save_method_frame_infos_[i] = x86::X86CalleeSaveMethodFrameInfo(type);
1085    }
1086  } else if (instruction_set_ == kX86_64) {
1087    for (int i = 0; i != kLastCalleeSaveType; ++i) {
1088      CalleeSaveType type = static_cast<CalleeSaveType>(i);
1089      callee_save_method_frame_infos_[i] = x86_64::X86_64CalleeSaveMethodFrameInfo(type);
1090    }
1091  } else if (instruction_set_ == kArm64) {
1092    for (int i = 0; i != kLastCalleeSaveType; ++i) {
1093      CalleeSaveType type = static_cast<CalleeSaveType>(i);
1094      callee_save_method_frame_infos_[i] = arm64::Arm64CalleeSaveMethodFrameInfo(type);
1095    }
1096  } else {
1097    UNIMPLEMENTED(FATAL) << instruction_set_;
1098  }
1099}
1100
1101void Runtime::SetCalleeSaveMethod(mirror::ArtMethod* method, CalleeSaveType type) {
1102  DCHECK_LT(static_cast<int>(type), static_cast<int>(kLastCalleeSaveType));
1103  callee_save_methods_[type] = method;
1104}
1105
1106const std::vector<const DexFile*>& Runtime::GetCompileTimeClassPath(jobject class_loader) {
1107  if (class_loader == NULL) {
1108    return GetClassLinker()->GetBootClassPath();
1109  }
1110  CHECK(UseCompileTimeClassPath());
1111  CompileTimeClassPaths::const_iterator it = compile_time_class_paths_.find(class_loader);
1112  CHECK(it != compile_time_class_paths_.end());
1113  return it->second;
1114}
1115
1116void Runtime::SetCompileTimeClassPath(jobject class_loader,
1117                                      std::vector<const DexFile*>& class_path) {
1118  CHECK(!IsStarted());
1119  use_compile_time_class_path_ = true;
1120  compile_time_class_paths_.Put(class_loader, class_path);
1121}
1122
1123void Runtime::AddMethodVerifier(verifier::MethodVerifier* verifier) {
1124  DCHECK(verifier != nullptr);
1125  MutexLock mu(Thread::Current(), method_verifier_lock_);
1126  method_verifiers_.insert(verifier);
1127}
1128
1129void Runtime::RemoveMethodVerifier(verifier::MethodVerifier* verifier) {
1130  DCHECK(verifier != nullptr);
1131  MutexLock mu(Thread::Current(), method_verifier_lock_);
1132  auto it = method_verifiers_.find(verifier);
1133  CHECK(it != method_verifiers_.end());
1134  method_verifiers_.erase(it);
1135}
1136
1137void Runtime::StartProfiler(const char* profile_output_filename) {
1138  profile_output_filename_ = profile_output_filename;
1139  profiler_started_ =
1140    BackgroundMethodSamplingProfiler::Start(profile_output_filename_, profiler_options_);
1141}
1142
1143// Transaction support.
1144void Runtime::EnterTransactionMode(Transaction* transaction) {
1145  DCHECK(IsCompiler());
1146  DCHECK(transaction != nullptr);
1147  DCHECK(!IsActiveTransaction());
1148  preinitialization_transaction_ = transaction;
1149}
1150
1151void Runtime::ExitTransactionMode() {
1152  DCHECK(IsCompiler());
1153  DCHECK(IsActiveTransaction());
1154  preinitialization_transaction_ = nullptr;
1155}
1156
1157void Runtime::RecordWriteField32(mirror::Object* obj, MemberOffset field_offset,
1158                                 uint32_t value, bool is_volatile) const {
1159  DCHECK(IsCompiler());
1160  DCHECK(IsActiveTransaction());
1161  preinitialization_transaction_->RecordWriteField32(obj, field_offset, value, is_volatile);
1162}
1163
1164void Runtime::RecordWriteField64(mirror::Object* obj, MemberOffset field_offset,
1165                                 uint64_t value, bool is_volatile) const {
1166  DCHECK(IsCompiler());
1167  DCHECK(IsActiveTransaction());
1168  preinitialization_transaction_->RecordWriteField64(obj, field_offset, value, is_volatile);
1169}
1170
1171void Runtime::RecordWriteFieldReference(mirror::Object* obj, MemberOffset field_offset,
1172                                        mirror::Object* value, bool is_volatile) const {
1173  DCHECK(IsCompiler());
1174  DCHECK(IsActiveTransaction());
1175  preinitialization_transaction_->RecordWriteFieldReference(obj, field_offset, value, is_volatile);
1176}
1177
1178void Runtime::RecordWriteArray(mirror::Array* array, size_t index, uint64_t value) const {
1179  DCHECK(IsCompiler());
1180  DCHECK(IsActiveTransaction());
1181  preinitialization_transaction_->RecordWriteArray(array, index, value);
1182}
1183
1184void Runtime::RecordStrongStringInsertion(mirror::String* s, uint32_t hash_code) const {
1185  DCHECK(IsCompiler());
1186  DCHECK(IsActiveTransaction());
1187  preinitialization_transaction_->RecordStrongStringInsertion(s, hash_code);
1188}
1189
1190void Runtime::RecordWeakStringInsertion(mirror::String* s, uint32_t hash_code) const {
1191  DCHECK(IsCompiler());
1192  DCHECK(IsActiveTransaction());
1193  preinitialization_transaction_->RecordWeakStringInsertion(s, hash_code);
1194}
1195
1196void Runtime::RecordStrongStringRemoval(mirror::String* s, uint32_t hash_code) const {
1197  DCHECK(IsCompiler());
1198  DCHECK(IsActiveTransaction());
1199  preinitialization_transaction_->RecordStrongStringRemoval(s, hash_code);
1200}
1201
1202void Runtime::RecordWeakStringRemoval(mirror::String* s, uint32_t hash_code) const {
1203  DCHECK(IsCompiler());
1204  DCHECK(IsActiveTransaction());
1205  preinitialization_transaction_->RecordWeakStringRemoval(s, hash_code);
1206}
1207
1208void Runtime::SetFaultMessage(const std::string& message) {
1209  MutexLock mu(Thread::Current(), fault_message_lock_);
1210  fault_message_ = message;
1211}
1212
1213void Runtime::AddCurrentRuntimeFeaturesAsDex2OatArguments(std::vector<std::string>* argv)
1214    const {
1215  if (GetInstrumentation()->InterpretOnly()) {
1216    argv->push_back("--compiler-filter=interpret-only");
1217  }
1218
1219  argv->push_back("--runtime-arg");
1220  std::string checkstr = "-implicit-checks";
1221
1222  int nchecks = 0;
1223  char checksep = ':';
1224
1225  if (!ExplicitNullChecks()) {
1226    checkstr += checksep;
1227    checksep = ',';
1228    checkstr += "null";
1229    ++nchecks;
1230  }
1231  if (!ExplicitSuspendChecks()) {
1232    checkstr += checksep;
1233    checksep = ',';
1234    checkstr += "suspend";
1235    ++nchecks;
1236  }
1237
1238  if (!ExplicitStackOverflowChecks()) {
1239    checkstr += checksep;
1240    checksep = ',';
1241    checkstr += "stack";
1242    ++nchecks;
1243  }
1244
1245  if (nchecks == 0) {
1246    checkstr += ":none";
1247  }
1248  argv->push_back(checkstr);
1249
1250  // Make the dex2oat instruction set match that of the launching runtime. If we have multiple
1251  // architecture support, dex2oat may be compiled as a different instruction-set than that
1252  // currently being executed.
1253  std::string instruction_set("--instruction-set=");
1254  instruction_set += GetInstructionSetString(kRuntimeISA);
1255  argv->push_back(instruction_set);
1256
1257  std::string features("--instruction-set-features=");
1258  features += GetDefaultInstructionSetFeatures();
1259  argv->push_back(features);
1260}
1261
1262void Runtime::UpdateProfilerState(int state) {
1263  VLOG(profiler) << "Profiler state updated to " << state;
1264}
1265}  // namespace art
1266