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