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