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