runtime.cc revision e5fed03772144595c0904faf3d6974cc55214c8c
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_representation.h>
33#include <vector>
34#include <fcntl.h>
35
36#include "JniConstants.h"
37#include "ScopedLocalRef.h"
38#include "arch/arm/quick_method_frame_info_arm.h"
39#include "arch/arm/registers_arm.h"
40#include "arch/arm64/quick_method_frame_info_arm64.h"
41#include "arch/arm64/registers_arm64.h"
42#include "arch/instruction_set_features.h"
43#include "arch/mips/quick_method_frame_info_mips.h"
44#include "arch/mips/registers_mips.h"
45#include "arch/mips64/quick_method_frame_info_mips64.h"
46#include "arch/mips64/registers_mips64.h"
47#include "arch/x86/quick_method_frame_info_x86.h"
48#include "arch/x86/registers_x86.h"
49#include "arch/x86_64/quick_method_frame_info_x86_64.h"
50#include "arch/x86_64/registers_x86_64.h"
51#include "asm_support.h"
52#include "atomic.h"
53#include "base/dumpable.h"
54#include "base/unix_file/fd_file.h"
55#include "class_linker.h"
56#include "debugger.h"
57#include "elf_file.h"
58#include "entrypoints/runtime_asm_entrypoints.h"
59#include "fault_handler.h"
60#include "gc/accounting/card_table-inl.h"
61#include "gc/heap.h"
62#include "gc/space/image_space.h"
63#include "gc/space/space.h"
64#include "handle_scope-inl.h"
65#include "image.h"
66#include "instrumentation.h"
67#include "intern_table.h"
68#include "interpreter/interpreter.h"
69#include "jit/jit.h"
70#include "jni_internal.h"
71#include "mirror/array.h"
72#include "mirror/art_field-inl.h"
73#include "mirror/art_method-inl.h"
74#include "mirror/class-inl.h"
75#include "mirror/class_loader.h"
76#include "mirror/stack_trace_element.h"
77#include "mirror/throwable.h"
78#include "monitor.h"
79#include "native/dalvik_system_DexFile.h"
80#include "native/dalvik_system_VMDebug.h"
81#include "native/dalvik_system_VMRuntime.h"
82#include "native/dalvik_system_VMStack.h"
83#include "native/dalvik_system_ZygoteHooks.h"
84#include "native/java_lang_Class.h"
85#include "native/java_lang_DexCache.h"
86#include "native/java_lang_Object.h"
87#include "native/java_lang_Runtime.h"
88#include "native/java_lang_String.h"
89#include "native/java_lang_System.h"
90#include "native/java_lang_Thread.h"
91#include "native/java_lang_Throwable.h"
92#include "native/java_lang_VMClassLoader.h"
93#include "native/java_lang_ref_FinalizerReference.h"
94#include "native/java_lang_ref_Reference.h"
95#include "native/java_lang_reflect_Array.h"
96#include "native/java_lang_reflect_Constructor.h"
97#include "native/java_lang_reflect_Field.h"
98#include "native/java_lang_reflect_Method.h"
99#include "native/java_lang_reflect_Proxy.h"
100#include "native/java_util_concurrent_atomic_AtomicLong.h"
101#include "native/org_apache_harmony_dalvik_ddmc_DdmServer.h"
102#include "native/org_apache_harmony_dalvik_ddmc_DdmVmInternal.h"
103#include "native/sun_misc_Unsafe.h"
104#include "native_bridge_art_interface.h"
105#include "oat_file.h"
106#include "os.h"
107#include "parsed_options.h"
108#include "profiler.h"
109#include "quick/quick_method_frame_info.h"
110#include "reflection.h"
111#include "runtime_options.h"
112#include "ScopedLocalRef.h"
113#include "scoped_thread_state_change.h"
114#include "sigchain.h"
115#include "signal_catcher.h"
116#include "signal_set.h"
117#include "thread.h"
118#include "thread_list.h"
119#include "trace.h"
120#include "transaction.h"
121#include "verifier/method_verifier.h"
122#include "well_known_classes.h"
123
124namespace art {
125
126// If a signal isn't handled properly, enable a handler that attempts to dump the Java stack.
127static constexpr bool kEnableJavaStackTraceHandler = false;
128Runtime* Runtime::instance_ = nullptr;
129
130Runtime::Runtime()
131    : instruction_set_(kNone),
132      compiler_callbacks_(nullptr),
133      is_zygote_(false),
134      must_relocate_(false),
135      is_concurrent_gc_enabled_(true),
136      is_explicit_gc_disabled_(false),
137      dex2oat_enabled_(true),
138      image_dex2oat_enabled_(true),
139      default_stack_size_(0),
140      heap_(nullptr),
141      max_spins_before_thin_lock_inflation_(Monitor::kDefaultMaxSpinsBeforeThinLockInflation),
142      monitor_list_(nullptr),
143      monitor_pool_(nullptr),
144      thread_list_(nullptr),
145      intern_table_(nullptr),
146      class_linker_(nullptr),
147      signal_catcher_(nullptr),
148      java_vm_(nullptr),
149      fault_message_lock_("Fault message lock"),
150      fault_message_(""),
151      method_verifier_lock_("Method verifiers lock"),
152      threads_being_born_(0),
153      shutdown_cond_(new ConditionVariable("Runtime shutdown", *Locks::runtime_shutdown_lock_)),
154      shutting_down_(false),
155      shutting_down_started_(false),
156      started_(false),
157      finished_starting_(false),
158      vfprintf_(nullptr),
159      exit_(nullptr),
160      abort_(nullptr),
161      stats_enabled_(false),
162      running_on_valgrind_(RUNNING_ON_VALGRIND > 0),
163      profiler_started_(false),
164      method_trace_(false),
165      method_trace_file_size_(0),
166      instrumentation_(),
167      use_compile_time_class_path_(false),
168      main_thread_group_(nullptr),
169      system_thread_group_(nullptr),
170      system_class_loader_(nullptr),
171      dump_gc_performance_on_shutdown_(false),
172      preinitialization_transaction_(nullptr),
173      verify_(false),
174      allow_dex_file_fallback_(true),
175      target_sdk_version_(0),
176      implicit_null_checks_(false),
177      implicit_so_checks_(false),
178      implicit_suspend_checks_(false),
179      is_native_bridge_loaded_(false),
180      zygote_max_failed_boots_(0) {
181  CheckAsmSupportOffsetsAndSizes();
182}
183
184Runtime::~Runtime() {
185  if (is_native_bridge_loaded_) {
186    UnloadNativeBridge();
187  }
188  if (dump_gc_performance_on_shutdown_) {
189    // This can't be called from the Heap destructor below because it
190    // could call RosAlloc::InspectAll() which needs the thread_list
191    // to be still alive.
192    heap_->DumpGcPerformanceInfo(LOG(INFO));
193  }
194
195  Thread* self = Thread::Current();
196  const bool attach_shutdown_thread = self == nullptr;
197  if (attach_shutdown_thread) {
198    CHECK(AttachCurrentThread("Shutdown thread", false, nullptr, false));
199    self = Thread::Current();
200  } else {
201    LOG(WARNING) << "Current thread not detached in Runtime shutdown";
202  }
203
204  {
205    MutexLock mu(self, *Locks::runtime_shutdown_lock_);
206    shutting_down_started_ = true;
207    while (threads_being_born_ > 0) {
208      shutdown_cond_->Wait(self);
209    }
210    shutting_down_ = true;
211  }
212  // Shutdown and wait for the daemons.
213  CHECK(self != nullptr);
214  if (IsFinishedStarting()) {
215    self->ClearException();
216    self->GetJniEnv()->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
217                                            WellKnownClasses::java_lang_Daemons_stop);
218  }
219  if (attach_shutdown_thread) {
220    DetachCurrentThread();
221    self = nullptr;
222  }
223
224  // Shut down background profiler before the runtime exits.
225  if (profiler_started_) {
226    BackgroundMethodSamplingProfiler::Shutdown();
227  }
228
229  Trace::Shutdown();
230
231  // Make sure to let the GC complete if it is running.
232  heap_->WaitForGcToComplete(gc::kGcCauseBackground, self);
233  heap_->DeleteThreadPool();
234  if (jit_.get() != nullptr) {
235    VLOG(jit) << "Deleting jit thread pool";
236    // Delete thread pool before the thread list since we don't want to wait forever on the
237    // JIT compiler threads.
238    jit_->DeleteThreadPool();
239  }
240
241  // Make sure our internal threads are dead before we start tearing down things they're using.
242  Dbg::StopJdwp();
243  delete signal_catcher_;
244
245  // Make sure all other non-daemon threads have terminated, and all daemon threads are suspended.
246  delete thread_list_;
247
248  // Delete the JIT after thread list to ensure that there is no remaining threads which could be
249  // accessing the instrumentation when we delete it.
250  if (jit_.get() != nullptr) {
251    VLOG(jit) << "Deleting jit";
252    jit_.reset(nullptr);
253  }
254  arena_pool_.reset();
255
256  // Shutdown the fault manager if it was initialized.
257  fault_manager.Shutdown();
258
259  delete monitor_list_;
260  delete monitor_pool_;
261  delete class_linker_;
262  delete heap_;
263  delete intern_table_;
264  delete java_vm_;
265  Thread::Shutdown();
266  QuasiAtomic::Shutdown();
267  verifier::MethodVerifier::Shutdown();
268  MemMap::Shutdown();
269  // TODO: acquire a static mutex on Runtime to avoid racing.
270  CHECK(instance_ == nullptr || instance_ == this);
271  instance_ = nullptr;
272}
273
274struct AbortState {
275  void Dump(std::ostream& os) const {
276    if (gAborting > 1) {
277      os << "Runtime aborting --- recursively, so no thread-specific detail!\n";
278      return;
279    }
280    gAborting++;
281    os << "Runtime aborting...\n";
282    if (Runtime::Current() == NULL) {
283      os << "(Runtime does not yet exist!)\n";
284      return;
285    }
286    Thread* self = Thread::Current();
287    if (self == nullptr) {
288      os << "(Aborting thread was not attached to runtime!)\n";
289      DumpKernelStack(os, GetTid(), "  kernel: ", false);
290      DumpNativeStack(os, GetTid(), "  native: ", nullptr);
291    } else {
292      os << "Aborting thread:\n";
293      if (Locks::mutator_lock_->IsExclusiveHeld(self) || Locks::mutator_lock_->IsSharedHeld(self)) {
294        DumpThread(os, self);
295      } else {
296        if (Locks::mutator_lock_->SharedTryLock(self)) {
297          DumpThread(os, self);
298          Locks::mutator_lock_->SharedUnlock(self);
299        }
300      }
301    }
302    DumpAllThreads(os, self);
303  }
304
305  // No thread-safety analysis as we do explicitly test for holding the mutator lock.
306  void DumpThread(std::ostream& os, Thread* self) const NO_THREAD_SAFETY_ANALYSIS {
307    DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self) || Locks::mutator_lock_->IsSharedHeld(self));
308    self->Dump(os);
309    if (self->IsExceptionPending()) {
310      mirror::Throwable* exception = self->GetException();
311      os << "Pending exception " << exception->Dump();
312    }
313  }
314
315  void DumpAllThreads(std::ostream& os, Thread* self) const {
316    Runtime* runtime = Runtime::Current();
317    if (runtime != nullptr) {
318      ThreadList* thread_list = runtime->GetThreadList();
319      if (thread_list != nullptr) {
320        bool tll_already_held = Locks::thread_list_lock_->IsExclusiveHeld(self);
321        bool ml_already_held = Locks::mutator_lock_->IsSharedHeld(self);
322        if (!tll_already_held || !ml_already_held) {
323          os << "Dumping all threads without appropriate locks held:"
324              << (!tll_already_held ? " thread list lock" : "")
325              << (!ml_already_held ? " mutator lock" : "")
326              << "\n";
327        }
328        os << "All threads:\n";
329        thread_list->Dump(os);
330      }
331    }
332  }
333};
334
335void Runtime::Abort() {
336  gAborting++;  // set before taking any locks
337
338  // Ensure that we don't have multiple threads trying to abort at once,
339  // which would result in significantly worse diagnostics.
340  MutexLock mu(Thread::Current(), *Locks::abort_lock_);
341
342  // Get any pending output out of the way.
343  fflush(NULL);
344
345  // Many people have difficulty distinguish aborts from crashes,
346  // so be explicit.
347  AbortState state;
348  LOG(INTERNAL_FATAL) << Dumpable<AbortState>(state);
349
350  // Call the abort hook if we have one.
351  if (Runtime::Current() != NULL && Runtime::Current()->abort_ != NULL) {
352    LOG(INTERNAL_FATAL) << "Calling abort hook...";
353    Runtime::Current()->abort_();
354    // notreached
355    LOG(INTERNAL_FATAL) << "Unexpectedly returned from abort hook!";
356  }
357
358#if defined(__GLIBC__)
359  // TODO: we ought to be able to use pthread_kill(3) here (or abort(3),
360  // which POSIX defines in terms of raise(3), which POSIX defines in terms
361  // of pthread_kill(3)). On Linux, though, libcorkscrew can't unwind through
362  // libpthread, which means the stacks we dump would be useless. Calling
363  // tgkill(2) directly avoids that.
364  syscall(__NR_tgkill, getpid(), GetTid(), SIGABRT);
365  // TODO: LLVM installs it's own SIGABRT handler so exit to be safe... Can we disable that in LLVM?
366  // If not, we could use sigaction(3) before calling tgkill(2) and lose this call to exit(3).
367  exit(1);
368#else
369  abort();
370#endif
371  // notreached
372}
373
374void Runtime::PreZygoteFork() {
375  heap_->PreZygoteFork();
376}
377
378void Runtime::CallExitHook(jint status) {
379  if (exit_ != NULL) {
380    ScopedThreadStateChange tsc(Thread::Current(), kNative);
381    exit_(status);
382    LOG(WARNING) << "Exit hook returned instead of exiting!";
383  }
384}
385
386void Runtime::SweepSystemWeaks(IsMarkedCallback* visitor, void* arg) {
387  GetInternTable()->SweepInternTableWeaks(visitor, arg);
388  GetMonitorList()->SweepMonitorList(visitor, arg);
389  GetJavaVM()->SweepJniWeakGlobals(visitor, arg);
390}
391
392bool Runtime::Create(const RuntimeOptions& options, bool ignore_unrecognized) {
393  // TODO: acquire a static mutex on Runtime to avoid racing.
394  if (Runtime::instance_ != NULL) {
395    return false;
396  }
397  InitLogging(NULL);  // Calls Locks::Init() as a side effect.
398  instance_ = new Runtime;
399  if (!instance_->Init(options, ignore_unrecognized)) {
400    // TODO: Currently deleting the instance will abort the runtime on destruction. Now This will
401    // leak memory, instead. Fix the destructor. b/19100793.
402    // delete instance_;
403    instance_ = NULL;
404    return false;
405  }
406  return true;
407}
408
409static jobject CreateSystemClassLoader() {
410  if (Runtime::Current()->UseCompileTimeClassPath()) {
411    return NULL;
412  }
413
414  ScopedObjectAccess soa(Thread::Current());
415  ClassLinker* cl = Runtime::Current()->GetClassLinker();
416
417  StackHandleScope<2> hs(soa.Self());
418  Handle<mirror::Class> class_loader_class(
419      hs.NewHandle(soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ClassLoader)));
420  CHECK(cl->EnsureInitialized(soa.Self(), class_loader_class, true, true));
421
422  mirror::ArtMethod* getSystemClassLoader =
423      class_loader_class->FindDirectMethod("getSystemClassLoader", "()Ljava/lang/ClassLoader;");
424  CHECK(getSystemClassLoader != NULL);
425
426  JValue result = InvokeWithJValues(soa, nullptr, soa.EncodeMethod(getSystemClassLoader), nullptr);
427  JNIEnv* env = soa.Self()->GetJniEnv();
428  ScopedLocalRef<jobject> system_class_loader(env,
429                                              soa.AddLocalReference<jobject>(result.GetL()));
430  CHECK(system_class_loader.get() != nullptr);
431
432  soa.Self()->SetClassLoaderOverride(system_class_loader.get());
433
434  Handle<mirror::Class> thread_class(
435      hs.NewHandle(soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread)));
436  CHECK(cl->EnsureInitialized(soa.Self(), thread_class, true, true));
437
438  mirror::ArtField* contextClassLoader =
439      thread_class->FindDeclaredInstanceField("contextClassLoader", "Ljava/lang/ClassLoader;");
440  CHECK(contextClassLoader != NULL);
441
442  // We can't run in a transaction yet.
443  contextClassLoader->SetObject<false>(soa.Self()->GetPeer(),
444                                       soa.Decode<mirror::ClassLoader*>(system_class_loader.get()));
445
446  return env->NewGlobalRef(system_class_loader.get());
447}
448
449std::string Runtime::GetPatchoatExecutable() const {
450  if (!patchoat_executable_.empty()) {
451    return patchoat_executable_;
452  }
453  std::string patchoat_executable(GetAndroidRoot());
454  patchoat_executable += (kIsDebugBuild ? "/bin/patchoatd" : "/bin/patchoat");
455  return patchoat_executable;
456}
457
458std::string Runtime::GetCompilerExecutable() const {
459  if (!compiler_executable_.empty()) {
460    return compiler_executable_;
461  }
462  std::string compiler_executable(GetAndroidRoot());
463  compiler_executable += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat");
464  return compiler_executable;
465}
466
467bool Runtime::Start() {
468  VLOG(startup) << "Runtime::Start entering";
469
470  // Restore main thread state to kNative as expected by native code.
471  Thread* self = Thread::Current();
472
473  self->TransitionFromRunnableToSuspended(kNative);
474
475  started_ = true;
476
477  // Use !IsAotCompiler so that we get test coverage, tests are never the zygote.
478  if (!IsAotCompiler()) {
479    ScopedObjectAccess soa(self);
480    gc::space::ImageSpace* image_space = heap_->GetImageSpace();
481    if (image_space != nullptr) {
482      GetInternTable()->AddImageStringsToTable(image_space);
483      GetClassLinker()->MoveImageClassesToClassTable();
484    }
485  }
486
487  // If we are the zygote then we need to wait until after forking to create the code cache due to
488  // SELinux restrictions on r/w/x memory regions.
489  if (!IsZygote() && jit_.get() != nullptr) {
490    jit_->CreateInstrumentationCache(jit_options_->GetCompileThreshold());
491    jit_->CreateThreadPool();
492  }
493
494  if (!IsImageDex2OatEnabled() || !GetHeap()->HasImageSpace()) {
495    ScopedObjectAccess soa(self);
496    StackHandleScope<1> hs(soa.Self());
497    auto klass(hs.NewHandle<mirror::Class>(mirror::Class::GetJavaLangClass()));
498    class_linker_->EnsureInitialized(soa.Self(), klass, true, true);
499  }
500
501  // InitNativeMethods needs to be after started_ so that the classes
502  // it touches will have methods linked to the oat file if necessary.
503  InitNativeMethods();
504
505  // Initialize well known thread group values that may be accessed threads while attaching.
506  InitThreadGroups(self);
507
508  Thread::FinishStartup();
509
510  system_class_loader_ = CreateSystemClassLoader();
511
512  if (is_zygote_) {
513    if (!InitZygote()) {
514      return false;
515    }
516  } else {
517    if (is_native_bridge_loaded_) {
518      PreInitializeNativeBridge(".");
519    }
520    DidForkFromZygote(self->GetJniEnv(), NativeBridgeAction::kInitialize,
521                      GetInstructionSetString(kRuntimeISA));
522  }
523
524  StartDaemonThreads();
525
526  {
527    ScopedObjectAccess soa(self);
528    self->GetJniEnv()->locals.AssertEmpty();
529  }
530
531  VLOG(startup) << "Runtime::Start exiting";
532  finished_starting_ = true;
533
534  if (profiler_options_.IsEnabled() && !profile_output_filename_.empty()) {
535    // User has asked for a profile using -Xenable-profiler.
536    // Create the profile file if it doesn't exist.
537    int fd = open(profile_output_filename_.c_str(), O_RDWR|O_CREAT|O_EXCL, 0660);
538    if (fd >= 0) {
539      close(fd);
540    } else if (errno != EEXIST) {
541      LOG(INFO) << "Failed to access the profile file. Profiler disabled.";
542      return true;
543    }
544    StartProfiler(profile_output_filename_.c_str());
545  }
546
547  return true;
548}
549
550void Runtime::EndThreadBirth() EXCLUSIVE_LOCKS_REQUIRED(Locks::runtime_shutdown_lock_) {
551  DCHECK_GT(threads_being_born_, 0U);
552  threads_being_born_--;
553  if (shutting_down_started_ && threads_being_born_ == 0) {
554    shutdown_cond_->Broadcast(Thread::Current());
555  }
556}
557
558// Do zygote-mode-only initialization.
559bool Runtime::InitZygote() {
560#ifdef __linux__
561  // zygote goes into its own process group
562  setpgid(0, 0);
563
564  // See storage config details at http://source.android.com/tech/storage/
565  // Create private mount namespace shared by all children
566  if (unshare(CLONE_NEWNS) == -1) {
567    PLOG(WARNING) << "Failed to unshare()";
568    return false;
569  }
570
571  // Mark rootfs as being a slave so that changes from default
572  // namespace only flow into our children.
573  if (mount("rootfs", "/", NULL, (MS_SLAVE | MS_REC), NULL) == -1) {
574    PLOG(WARNING) << "Failed to mount() rootfs as MS_SLAVE";
575    return false;
576  }
577
578  // Create a staging tmpfs that is shared by our children; they will
579  // bind mount storage into their respective private namespaces, which
580  // are isolated from each other.
581  const char* target_base = getenv("EMULATED_STORAGE_TARGET");
582  if (target_base != NULL) {
583    if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
584              "uid=0,gid=1028,mode=0751") == -1) {
585      LOG(WARNING) << "Failed to mount tmpfs to " << target_base;
586      return false;
587    }
588  }
589
590  return true;
591#else
592  UNIMPLEMENTED(FATAL);
593  return false;
594#endif
595}
596
597void Runtime::DidForkFromZygote(JNIEnv* env, NativeBridgeAction action, const char* isa) {
598  is_zygote_ = false;
599
600  if (is_native_bridge_loaded_) {
601    switch (action) {
602      case NativeBridgeAction::kUnload:
603        UnloadNativeBridge();
604        is_native_bridge_loaded_ = false;
605        break;
606
607      case NativeBridgeAction::kInitialize:
608        InitializeNativeBridge(env, isa);
609        break;
610    }
611  }
612
613  // Create the thread pools.
614  heap_->CreateThreadPool();
615  if (jit_options_.get() != nullptr && jit_.get() == nullptr) {
616    // Create the JIT if the flag is set and we haven't already create it (happens for run-tests).
617    CreateJit();
618    jit_->CreateInstrumentationCache(jit_options_->GetCompileThreshold());
619    jit_->CreateThreadPool();
620  }
621
622  StartSignalCatcher();
623
624  // Start the JDWP thread. If the command-line debugger flags specified "suspend=y",
625  // this will pause the runtime, so we probably want this to come last.
626  Dbg::StartJdwp();
627}
628
629void Runtime::StartSignalCatcher() {
630  if (!is_zygote_) {
631    signal_catcher_ = new SignalCatcher(stack_trace_file_);
632  }
633}
634
635bool Runtime::IsShuttingDown(Thread* self) {
636  MutexLock mu(self, *Locks::runtime_shutdown_lock_);
637  return IsShuttingDownLocked();
638}
639
640void Runtime::StartDaemonThreads() {
641  VLOG(startup) << "Runtime::StartDaemonThreads entering";
642
643  Thread* self = Thread::Current();
644
645  // Must be in the kNative state for calling native methods.
646  CHECK_EQ(self->GetState(), kNative);
647
648  JNIEnv* env = self->GetJniEnv();
649  env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
650                            WellKnownClasses::java_lang_Daemons_start);
651  if (env->ExceptionCheck()) {
652    env->ExceptionDescribe();
653    LOG(FATAL) << "Error starting java.lang.Daemons";
654  }
655
656  VLOG(startup) << "Runtime::StartDaemonThreads exiting";
657}
658
659static bool OpenDexFilesFromImage(const std::string& image_location,
660                                  std::vector<std::unique_ptr<const DexFile>>* dex_files,
661                                  size_t* failures) {
662  DCHECK(dex_files != nullptr) << "OpenDexFilesFromImage: out-param is NULL";
663  std::string system_filename;
664  bool has_system = false;
665  std::string cache_filename_unused;
666  bool dalvik_cache_exists_unused;
667  bool has_cache_unused;
668  bool is_global_cache_unused;
669  bool found_image = gc::space::ImageSpace::FindImageFilename(image_location.c_str(),
670                                                              kRuntimeISA,
671                                                              &system_filename,
672                                                              &has_system,
673                                                              &cache_filename_unused,
674                                                              &dalvik_cache_exists_unused,
675                                                              &has_cache_unused,
676                                                              &is_global_cache_unused);
677  *failures = 0;
678  if (!found_image || !has_system) {
679    return false;
680  }
681  std::string error_msg;
682  // We are falling back to non-executable use of the oat file because patching failed, presumably
683  // due to lack of space.
684  std::string oat_filename = ImageHeader::GetOatLocationFromImageLocation(system_filename.c_str());
685  std::string oat_location = ImageHeader::GetOatLocationFromImageLocation(image_location.c_str());
686  std::unique_ptr<File> file(OS::OpenFileForReading(oat_filename.c_str()));
687  if (file.get() == nullptr) {
688    return false;
689  }
690  std::unique_ptr<ElfFile> elf_file(ElfFile::Open(file.release(), false, false, &error_msg));
691  if (elf_file.get() == nullptr) {
692    return false;
693  }
694  std::unique_ptr<OatFile> oat_file(OatFile::OpenWithElfFile(elf_file.release(), oat_location,
695                                                             nullptr, &error_msg));
696  if (oat_file.get() == nullptr) {
697    LOG(INFO) << "Unable to use '" << oat_filename << "' because " << error_msg;
698    return false;
699  }
700
701  for (const OatFile::OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) {
702    if (oat_dex_file == nullptr) {
703      *failures += 1;
704      continue;
705    }
706    std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
707    if (dex_file.get() == nullptr) {
708      *failures += 1;
709    } else {
710      dex_files->push_back(std::move(dex_file));
711    }
712  }
713  Runtime::Current()->GetClassLinker()->RegisterOatFile(oat_file.release());
714  return true;
715}
716
717
718static size_t OpenDexFiles(const std::vector<std::string>& dex_filenames,
719                           const std::vector<std::string>& dex_locations,
720                           const std::string& image_location,
721                           std::vector<std::unique_ptr<const DexFile>>* dex_files) {
722  DCHECK(dex_files != nullptr) << "OpenDexFiles: out-param is NULL";
723  size_t failure_count = 0;
724  if (!image_location.empty() && OpenDexFilesFromImage(image_location, dex_files, &failure_count)) {
725    return failure_count;
726  }
727  failure_count = 0;
728  for (size_t i = 0; i < dex_filenames.size(); i++) {
729    const char* dex_filename = dex_filenames[i].c_str();
730    const char* dex_location = dex_locations[i].c_str();
731    std::string error_msg;
732    if (!OS::FileExists(dex_filename)) {
733      LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
734      continue;
735    }
736    if (!DexFile::Open(dex_filename, dex_location, &error_msg, dex_files)) {
737      LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
738      ++failure_count;
739    }
740  }
741  return failure_count;
742}
743
744bool Runtime::Init(const RuntimeOptions& raw_options, bool ignore_unrecognized) {
745  CHECK_EQ(sysconf(_SC_PAGE_SIZE), kPageSize);
746
747  MemMap::Init();
748
749  using Opt = RuntimeArgumentMap;
750  RuntimeArgumentMap runtime_options;
751  std::unique_ptr<ParsedOptions> parsed_options(
752      ParsedOptions::Create(raw_options, ignore_unrecognized, &runtime_options));
753  if (parsed_options.get() == nullptr) {
754    LOG(ERROR) << "Failed to parse options";
755    return false;
756  }
757  VLOG(startup) << "Runtime::Init -verbose:startup enabled";
758
759  QuasiAtomic::Startup();
760
761  Monitor::Init(runtime_options.GetOrDefault(Opt::LockProfThreshold),
762                runtime_options.GetOrDefault(Opt::HookIsSensitiveThread));
763
764  boot_class_path_string_ = runtime_options.ReleaseOrDefault(Opt::BootClassPath);
765  class_path_string_ = runtime_options.ReleaseOrDefault(Opt::ClassPath);
766  properties_ = runtime_options.ReleaseOrDefault(Opt::PropertiesList);
767
768  compiler_callbacks_ = runtime_options.GetOrDefault(Opt::CompilerCallbacksPtr);
769  patchoat_executable_ = runtime_options.ReleaseOrDefault(Opt::PatchOat);
770  must_relocate_ = runtime_options.GetOrDefault(Opt::Relocate);
771  is_zygote_ = runtime_options.Exists(Opt::Zygote);
772  is_explicit_gc_disabled_ = runtime_options.Exists(Opt::DisableExplicitGC);
773  dex2oat_enabled_ = runtime_options.GetOrDefault(Opt::Dex2Oat);
774  image_dex2oat_enabled_ = runtime_options.GetOrDefault(Opt::ImageDex2Oat);
775
776  vfprintf_ = runtime_options.GetOrDefault(Opt::HookVfprintf);
777  exit_ = runtime_options.GetOrDefault(Opt::HookExit);
778  abort_ = runtime_options.GetOrDefault(Opt::HookAbort);
779
780  default_stack_size_ = runtime_options.GetOrDefault(Opt::StackSize);
781  stack_trace_file_ = runtime_options.ReleaseOrDefault(Opt::StackTraceFile);
782
783  compiler_executable_ = runtime_options.ReleaseOrDefault(Opt::Compiler);
784  compiler_options_ = runtime_options.ReleaseOrDefault(Opt::CompilerOptions);
785  image_compiler_options_ = runtime_options.ReleaseOrDefault(Opt::ImageCompilerOptions);
786  image_location_ = runtime_options.GetOrDefault(Opt::Image);
787
788  max_spins_before_thin_lock_inflation_ =
789      runtime_options.GetOrDefault(Opt::MaxSpinsBeforeThinLockInflation);
790
791  monitor_list_ = new MonitorList;
792  monitor_pool_ = MonitorPool::Create();
793  thread_list_ = new ThreadList;
794  intern_table_ = new InternTable;
795
796  verify_ = runtime_options.GetOrDefault(Opt::Verify);
797  allow_dex_file_fallback_ = !runtime_options.Exists(Opt::NoDexFileFallback);
798
799  if (runtime_options.GetOrDefault(Opt::Interpret)) {
800    GetInstrumentation()->ForceInterpretOnly();
801  }
802
803  zygote_max_failed_boots_ = runtime_options.GetOrDefault(Opt::ZygoteMaxFailedBoots);
804
805  XGcOption xgc_option = runtime_options.GetOrDefault(Opt::GcOption);
806  heap_ = new gc::Heap(runtime_options.GetOrDefault(Opt::MemoryInitialSize),
807                       runtime_options.GetOrDefault(Opt::HeapGrowthLimit),
808                       runtime_options.GetOrDefault(Opt::HeapMinFree),
809                       runtime_options.GetOrDefault(Opt::HeapMaxFree),
810                       runtime_options.GetOrDefault(Opt::HeapTargetUtilization),
811                       runtime_options.GetOrDefault(Opt::ForegroundHeapGrowthMultiplier),
812                       runtime_options.GetOrDefault(Opt::MemoryMaximumSize),
813                       runtime_options.GetOrDefault(Opt::NonMovingSpaceCapacity),
814                       runtime_options.GetOrDefault(Opt::Image),
815                       runtime_options.GetOrDefault(Opt::ImageInstructionSet),
816                       xgc_option.collector_type_,
817                       runtime_options.GetOrDefault(Opt::BackgroundGc),
818                       runtime_options.GetOrDefault(Opt::LargeObjectSpace),
819                       runtime_options.GetOrDefault(Opt::LargeObjectThreshold),
820                       runtime_options.GetOrDefault(Opt::ParallelGCThreads),
821                       runtime_options.GetOrDefault(Opt::ConcGCThreads),
822                       runtime_options.Exists(Opt::LowMemoryMode),
823                       runtime_options.GetOrDefault(Opt::LongPauseLogThreshold),
824                       runtime_options.GetOrDefault(Opt::LongGCLogThreshold),
825                       runtime_options.Exists(Opt::IgnoreMaxFootprint),
826                       runtime_options.GetOrDefault(Opt::UseTLAB),
827                       xgc_option.verify_pre_gc_heap_,
828                       xgc_option.verify_pre_sweeping_heap_,
829                       xgc_option.verify_post_gc_heap_,
830                       xgc_option.verify_pre_gc_rosalloc_,
831                       xgc_option.verify_pre_sweeping_rosalloc_,
832                       xgc_option.verify_post_gc_rosalloc_,
833                       runtime_options.GetOrDefault(Opt::EnableHSpaceCompactForOOM),
834                       runtime_options.GetOrDefault(Opt::HSpaceCompactForOOMMinIntervalsMs));
835
836  if (heap_->GetImageSpace() == nullptr && !allow_dex_file_fallback_) {
837    LOG(ERROR) << "Dex file fallback disabled, cannot continue without image.";
838    return false;
839  }
840
841  dump_gc_performance_on_shutdown_ = runtime_options.Exists(Opt::DumpGCPerformanceOnShutdown);
842
843  if (runtime_options.Exists(Opt::JdwpOptions)) {
844    Dbg::ConfigureJdwp(runtime_options.GetOrDefault(Opt::JdwpOptions));
845  }
846
847  if (!IsAotCompiler()) {
848    // If we are already the compiler at this point, we must be dex2oat. Don't create the jit in
849    // this case.
850    // If runtime_options doesn't have UseJIT set to true then CreateFromRuntimeArguments returns
851    // nullptr and we don't create the jit.
852    jit_options_.reset(jit::JitOptions::CreateFromRuntimeArguments(runtime_options));
853  }
854  if (!IsZygote() && jit_options_.get() != nullptr) {
855    CreateJit();
856  }
857
858  // Use MemMap arena pool for jit, malloc otherwise. Malloc arenas are faster to allocate but
859  // can't be trimmed as easily.
860  const bool use_malloc = jit_options_.get() == nullptr;
861  arena_pool_.reset(new ArenaPool(use_malloc));
862
863  BlockSignals();
864  InitPlatformSignalHandlers();
865
866  // Change the implicit checks flags based on runtime architecture.
867  switch (kRuntimeISA) {
868    case kArm:
869    case kThumb2:
870    case kX86:
871    case kArm64:
872    case kX86_64:
873      implicit_null_checks_ = true;
874      // Installing stack protection does not play well with valgrind.
875      implicit_so_checks_ = (RUNNING_ON_VALGRIND == 0);
876      break;
877    default:
878      // Keep the defaults.
879      break;
880  }
881
882  // Always initialize the signal chain so that any calls to sigaction get
883  // correctly routed to the next in the chain regardless of whether we
884  // have claimed the signal or not.
885  InitializeSignalChain();
886
887  if (implicit_null_checks_ || implicit_so_checks_ || implicit_suspend_checks_) {
888    fault_manager.Init();
889
890    // These need to be in a specific order.  The null point check handler must be
891    // after the suspend check and stack overflow check handlers.
892    //
893    // Note: the instances attach themselves to the fault manager and are handled by it. The manager
894    //       will delete the instance on Shutdown().
895    if (implicit_suspend_checks_) {
896      new SuspensionHandler(&fault_manager);
897    }
898
899    if (implicit_so_checks_) {
900      new StackOverflowHandler(&fault_manager);
901    }
902
903    if (implicit_null_checks_) {
904      new NullPointerHandler(&fault_manager);
905    }
906
907    if (kEnableJavaStackTraceHandler) {
908      new JavaStackTraceHandler(&fault_manager);
909    }
910  }
911
912  java_vm_ = new JavaVMExt(this, runtime_options);
913
914  Thread::Startup();
915
916  // ClassLinker needs an attached thread, but we can't fully attach a thread without creating
917  // objects. We can't supply a thread group yet; it will be fixed later. Since we are the main
918  // thread, we do not get a java peer.
919  Thread* self = Thread::Attach("main", false, nullptr, false);
920  CHECK_EQ(self->GetThreadId(), ThreadList::kMainThreadId);
921  CHECK(self != nullptr);
922
923  // Set us to runnable so tools using a runtime can allocate and GC by default
924  self->TransitionFromSuspendedToRunnable();
925
926  // Now we're attached, we can take the heap locks and validate the heap.
927  GetHeap()->EnableObjectValidation();
928
929  CHECK_GE(GetHeap()->GetContinuousSpaces().size(), 1U);
930  class_linker_ = new ClassLinker(intern_table_);
931  if (GetHeap()->HasImageSpace()) {
932    class_linker_->InitFromImage();
933    if (kIsDebugBuild) {
934      GetHeap()->GetImageSpace()->VerifyImageAllocations();
935    }
936    if (boot_class_path_string_.empty()) {
937      // The bootclasspath is not explicitly specified: construct it from the loaded dex files.
938      const std::vector<const DexFile*>& boot_class_path = GetClassLinker()->GetBootClassPath();
939      std::vector<std::string> dex_locations;
940      dex_locations.reserve(boot_class_path.size());
941      for (const DexFile* dex_file : boot_class_path) {
942        dex_locations.push_back(dex_file->GetLocation());
943      }
944      boot_class_path_string_ = Join(dex_locations, ':');
945    }
946  } else {
947    std::vector<std::string> dex_filenames;
948    Split(boot_class_path_string_, ':', &dex_filenames);
949
950    std::vector<std::string> dex_locations;
951    if (!runtime_options.Exists(Opt::BootClassPathLocations)) {
952      dex_locations = dex_filenames;
953    } else {
954      dex_locations = runtime_options.GetOrDefault(Opt::BootClassPathLocations);
955      CHECK_EQ(dex_filenames.size(), dex_locations.size());
956    }
957
958    std::vector<std::unique_ptr<const DexFile>> boot_class_path;
959    OpenDexFiles(dex_filenames,
960                 dex_locations,
961                 runtime_options.GetOrDefault(Opt::Image),
962                 &boot_class_path);
963    instruction_set_ = runtime_options.GetOrDefault(Opt::ImageInstructionSet);
964    class_linker_->InitWithoutImage(std::move(boot_class_path));
965
966    // TODO: Should we move the following to InitWithoutImage?
967    SetInstructionSet(instruction_set_);
968    for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
969      Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
970      if (!HasCalleeSaveMethod(type)) {
971        SetCalleeSaveMethod(CreateCalleeSaveMethod(), type);
972      }
973    }
974  }
975
976  CHECK(class_linker_ != nullptr);
977
978  // Initialize the special sentinel_ value early.
979  sentinel_ = GcRoot<mirror::Object>(class_linker_->AllocObject(self));
980  CHECK(sentinel_.Read() != nullptr);
981
982  verifier::MethodVerifier::Init();
983
984  method_trace_ = runtime_options.Exists(Opt::MethodTrace);
985  method_trace_file_ = runtime_options.ReleaseOrDefault(Opt::MethodTraceFile);
986  method_trace_file_size_ = runtime_options.ReleaseOrDefault(Opt::MethodTraceFileSize);
987
988  {
989    auto&& profiler_options = runtime_options.ReleaseOrDefault(Opt::ProfilerOpts);
990    profile_output_filename_ = profiler_options.output_file_name_;
991
992    // TODO: Don't do this, just change ProfilerOptions to include the output file name?
993    ProfilerOptions other_options(
994        profiler_options.enabled_,
995        profiler_options.period_s_,
996        profiler_options.duration_s_,
997        profiler_options.interval_us_,
998        profiler_options.backoff_coefficient_,
999        profiler_options.start_immediately_,
1000        profiler_options.top_k_threshold_,
1001        profiler_options.top_k_change_threshold_,
1002        profiler_options.profile_type_,
1003        profiler_options.max_stack_depth_);
1004
1005    profiler_options_ = other_options;
1006  }
1007
1008  // TODO: move this to just be an Trace::Start argument
1009  Trace::SetDefaultClockSource(runtime_options.GetOrDefault(Opt::ProfileClock));
1010
1011  if (method_trace_) {
1012    ScopedThreadStateChange tsc(self, kWaitingForMethodTracingStart);
1013    Trace::Start(method_trace_file_.c_str(),
1014                 -1,
1015                 static_cast<int>(method_trace_file_size_),
1016                 0,
1017                 false,
1018                 false,
1019                 0);
1020  }
1021
1022  // Pre-allocate an OutOfMemoryError for the double-OOME case.
1023  self->ThrowNewException("Ljava/lang/OutOfMemoryError;",
1024                          "OutOfMemoryError thrown while trying to throw OutOfMemoryError; "
1025                          "no stack trace available");
1026  pre_allocated_OutOfMemoryError_ = GcRoot<mirror::Throwable>(self->GetException());
1027  self->ClearException();
1028
1029  // Pre-allocate a NoClassDefFoundError for the common case of failing to find a system class
1030  // ahead of checking the application's class loader.
1031  self->ThrowNewException("Ljava/lang/NoClassDefFoundError;",
1032                          "Class not found using the boot class loader; no stack trace available");
1033  pre_allocated_NoClassDefFoundError_ = GcRoot<mirror::Throwable>(self->GetException());
1034  self->ClearException();
1035
1036  // Look for a native bridge.
1037  //
1038  // The intended flow here is, in the case of a running system:
1039  //
1040  // Runtime::Init() (zygote):
1041  //   LoadNativeBridge -> dlopen from cmd line parameter.
1042  //  |
1043  //  V
1044  // Runtime::Start() (zygote):
1045  //   No-op wrt native bridge.
1046  //  |
1047  //  | start app
1048  //  V
1049  // DidForkFromZygote(action)
1050  //   action = kUnload -> dlclose native bridge.
1051  //   action = kInitialize -> initialize library
1052  //
1053  //
1054  // The intended flow here is, in the case of a simple dalvikvm call:
1055  //
1056  // Runtime::Init():
1057  //   LoadNativeBridge -> dlopen from cmd line parameter.
1058  //  |
1059  //  V
1060  // Runtime::Start():
1061  //   DidForkFromZygote(kInitialize) -> try to initialize any native bridge given.
1062  //   No-op wrt native bridge.
1063  {
1064    std::string native_bridge_file_name = runtime_options.ReleaseOrDefault(Opt::NativeBridge);
1065    is_native_bridge_loaded_ = LoadNativeBridge(native_bridge_file_name);
1066  }
1067
1068  VLOG(startup) << "Runtime::Init exiting";
1069  return true;
1070}
1071
1072void Runtime::InitNativeMethods() {
1073  VLOG(startup) << "Runtime::InitNativeMethods entering";
1074  Thread* self = Thread::Current();
1075  JNIEnv* env = self->GetJniEnv();
1076
1077  // Must be in the kNative state for calling native methods (JNI_OnLoad code).
1078  CHECK_EQ(self->GetState(), kNative);
1079
1080  // First set up JniConstants, which is used by both the runtime's built-in native
1081  // methods and libcore.
1082  JniConstants::init(env);
1083  WellKnownClasses::Init(env);
1084
1085  // Then set up the native methods provided by the runtime itself.
1086  RegisterRuntimeNativeMethods(env);
1087
1088  // Then set up libcore, which is just a regular JNI library with a regular JNI_OnLoad.
1089  // Most JNI libraries can just use System.loadLibrary, but libcore can't because it's
1090  // the library that implements System.loadLibrary!
1091  {
1092    std::string reason;
1093    if (!java_vm_->LoadNativeLibrary(env, "libjavacore.so", nullptr, &reason)) {
1094      LOG(FATAL) << "LoadNativeLibrary failed for \"libjavacore.so\": " << reason;
1095    }
1096  }
1097
1098  // Initialize well known classes that may invoke runtime native methods.
1099  WellKnownClasses::LateInit(env);
1100
1101  VLOG(startup) << "Runtime::InitNativeMethods exiting";
1102}
1103
1104void Runtime::InitThreadGroups(Thread* self) {
1105  JNIEnvExt* env = self->GetJniEnv();
1106  ScopedJniEnvLocalRefState env_state(env);
1107  main_thread_group_ =
1108      env->NewGlobalRef(env->GetStaticObjectField(
1109          WellKnownClasses::java_lang_ThreadGroup,
1110          WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup));
1111  CHECK(main_thread_group_ != NULL || IsAotCompiler());
1112  system_thread_group_ =
1113      env->NewGlobalRef(env->GetStaticObjectField(
1114          WellKnownClasses::java_lang_ThreadGroup,
1115          WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup));
1116  CHECK(system_thread_group_ != NULL || IsAotCompiler());
1117}
1118
1119jobject Runtime::GetMainThreadGroup() const {
1120  CHECK(main_thread_group_ != NULL || IsAotCompiler());
1121  return main_thread_group_;
1122}
1123
1124jobject Runtime::GetSystemThreadGroup() const {
1125  CHECK(system_thread_group_ != NULL || IsAotCompiler());
1126  return system_thread_group_;
1127}
1128
1129jobject Runtime::GetSystemClassLoader() const {
1130  CHECK(system_class_loader_ != NULL || IsAotCompiler());
1131  return system_class_loader_;
1132}
1133
1134void Runtime::RegisterRuntimeNativeMethods(JNIEnv* env) {
1135  register_dalvik_system_DexFile(env);
1136  register_dalvik_system_VMDebug(env);
1137  register_dalvik_system_VMRuntime(env);
1138  register_dalvik_system_VMStack(env);
1139  register_dalvik_system_ZygoteHooks(env);
1140  register_java_lang_Class(env);
1141  register_java_lang_DexCache(env);
1142  register_java_lang_Object(env);
1143  register_java_lang_ref_FinalizerReference(env);
1144  register_java_lang_reflect_Array(env);
1145  register_java_lang_reflect_Constructor(env);
1146  register_java_lang_reflect_Field(env);
1147  register_java_lang_reflect_Method(env);
1148  register_java_lang_reflect_Proxy(env);
1149  register_java_lang_ref_Reference(env);
1150  register_java_lang_Runtime(env);
1151  register_java_lang_String(env);
1152  register_java_lang_System(env);
1153  register_java_lang_Thread(env);
1154  register_java_lang_Throwable(env);
1155  register_java_lang_VMClassLoader(env);
1156  register_java_util_concurrent_atomic_AtomicLong(env);
1157  register_org_apache_harmony_dalvik_ddmc_DdmServer(env);
1158  register_org_apache_harmony_dalvik_ddmc_DdmVmInternal(env);
1159  register_sun_misc_Unsafe(env);
1160}
1161
1162void Runtime::DumpForSigQuit(std::ostream& os) {
1163  GetClassLinker()->DumpForSigQuit(os);
1164  GetInternTable()->DumpForSigQuit(os);
1165  GetJavaVM()->DumpForSigQuit(os);
1166  GetHeap()->DumpForSigQuit(os);
1167  TrackedAllocators::Dump(os);
1168  os << "\n";
1169
1170  thread_list_->DumpForSigQuit(os);
1171  BaseMutex::DumpAll(os);
1172}
1173
1174void Runtime::DumpLockHolders(std::ostream& os) {
1175  uint64_t mutator_lock_owner = Locks::mutator_lock_->GetExclusiveOwnerTid();
1176  pid_t thread_list_lock_owner = GetThreadList()->GetLockOwner();
1177  pid_t classes_lock_owner = GetClassLinker()->GetClassesLockOwner();
1178  pid_t dex_lock_owner = GetClassLinker()->GetDexLockOwner();
1179  if ((thread_list_lock_owner | classes_lock_owner | dex_lock_owner) != 0) {
1180    os << "Mutator lock exclusive owner tid: " << mutator_lock_owner << "\n"
1181       << "ThreadList lock owner tid: " << thread_list_lock_owner << "\n"
1182       << "ClassLinker classes lock owner tid: " << classes_lock_owner << "\n"
1183       << "ClassLinker dex lock owner tid: " << dex_lock_owner << "\n";
1184  }
1185}
1186
1187void Runtime::SetStatsEnabled(bool new_state) {
1188  Thread* self = Thread::Current();
1189  MutexLock mu(self, *Locks::instrument_entrypoints_lock_);
1190  if (new_state == true) {
1191    GetStats()->Clear(~0);
1192    // TODO: wouldn't it make more sense to clear _all_ threads' stats?
1193    self->GetStats()->Clear(~0);
1194    if (stats_enabled_ != new_state) {
1195      GetInstrumentation()->InstrumentQuickAllocEntryPointsLocked();
1196    }
1197  } else if (stats_enabled_ != new_state) {
1198    GetInstrumentation()->UninstrumentQuickAllocEntryPointsLocked();
1199  }
1200  stats_enabled_ = new_state;
1201}
1202
1203void Runtime::ResetStats(int kinds) {
1204  GetStats()->Clear(kinds & 0xffff);
1205  // TODO: wouldn't it make more sense to clear _all_ threads' stats?
1206  Thread::Current()->GetStats()->Clear(kinds >> 16);
1207}
1208
1209int32_t Runtime::GetStat(int kind) {
1210  RuntimeStats* stats;
1211  if (kind < (1<<16)) {
1212    stats = GetStats();
1213  } else {
1214    stats = Thread::Current()->GetStats();
1215    kind >>= 16;
1216  }
1217  switch (kind) {
1218  case KIND_ALLOCATED_OBJECTS:
1219    return stats->allocated_objects;
1220  case KIND_ALLOCATED_BYTES:
1221    return stats->allocated_bytes;
1222  case KIND_FREED_OBJECTS:
1223    return stats->freed_objects;
1224  case KIND_FREED_BYTES:
1225    return stats->freed_bytes;
1226  case KIND_GC_INVOCATIONS:
1227    return stats->gc_for_alloc_count;
1228  case KIND_CLASS_INIT_COUNT:
1229    return stats->class_init_count;
1230  case KIND_CLASS_INIT_TIME:
1231    // Convert ns to us, reduce to 32 bits.
1232    return static_cast<int>(stats->class_init_time_ns / 1000);
1233  case KIND_EXT_ALLOCATED_OBJECTS:
1234  case KIND_EXT_ALLOCATED_BYTES:
1235  case KIND_EXT_FREED_OBJECTS:
1236  case KIND_EXT_FREED_BYTES:
1237    return 0;  // backward compatibility
1238  default:
1239    LOG(FATAL) << "Unknown statistic " << kind;
1240    return -1;  // unreachable
1241  }
1242}
1243
1244void Runtime::BlockSignals() {
1245  SignalSet signals;
1246  signals.Add(SIGPIPE);
1247  // SIGQUIT is used to dump the runtime's state (including stack traces).
1248  signals.Add(SIGQUIT);
1249  // SIGUSR1 is used to initiate a GC.
1250  signals.Add(SIGUSR1);
1251  signals.Block();
1252}
1253
1254bool Runtime::AttachCurrentThread(const char* thread_name, bool as_daemon, jobject thread_group,
1255                                  bool create_peer) {
1256  return Thread::Attach(thread_name, as_daemon, thread_group, create_peer) != NULL;
1257}
1258
1259void Runtime::DetachCurrentThread() {
1260  Thread* self = Thread::Current();
1261  if (self == NULL) {
1262    LOG(FATAL) << "attempting to detach thread that is not attached";
1263  }
1264  if (self->HasManagedStack()) {
1265    LOG(FATAL) << *Thread::Current() << " attempting to detach while still running code";
1266  }
1267  thread_list_->Unregister(self);
1268}
1269
1270mirror::Throwable* Runtime::GetPreAllocatedOutOfMemoryError() {
1271  mirror::Throwable* oome = pre_allocated_OutOfMemoryError_.Read();
1272  if (oome == nullptr) {
1273    LOG(ERROR) << "Failed to return pre-allocated OOME";
1274  }
1275  return oome;
1276}
1277
1278mirror::Throwable* Runtime::GetPreAllocatedNoClassDefFoundError() {
1279  mirror::Throwable* ncdfe = pre_allocated_NoClassDefFoundError_.Read();
1280  if (ncdfe == nullptr) {
1281    LOG(ERROR) << "Failed to return pre-allocated NoClassDefFoundError";
1282  }
1283  return ncdfe;
1284}
1285
1286void Runtime::VisitConstantRoots(RootCallback* callback, void* arg) {
1287  // Visit the classes held as static in mirror classes, these can be visited concurrently and only
1288  // need to be visited once per GC since they never change.
1289  mirror::ArtField::VisitRoots(callback, arg);
1290  mirror::ArtMethod::VisitRoots(callback, arg);
1291  mirror::Class::VisitRoots(callback, arg);
1292  mirror::Reference::VisitRoots(callback, arg);
1293  mirror::StackTraceElement::VisitRoots(callback, arg);
1294  mirror::String::VisitRoots(callback, arg);
1295  mirror::Throwable::VisitRoots(callback, arg);
1296  // Visit all the primitive array types classes.
1297  mirror::PrimitiveArray<uint8_t>::VisitRoots(callback, arg);   // BooleanArray
1298  mirror::PrimitiveArray<int8_t>::VisitRoots(callback, arg);    // ByteArray
1299  mirror::PrimitiveArray<uint16_t>::VisitRoots(callback, arg);  // CharArray
1300  mirror::PrimitiveArray<double>::VisitRoots(callback, arg);    // DoubleArray
1301  mirror::PrimitiveArray<float>::VisitRoots(callback, arg);     // FloatArray
1302  mirror::PrimitiveArray<int32_t>::VisitRoots(callback, arg);   // IntArray
1303  mirror::PrimitiveArray<int64_t>::VisitRoots(callback, arg);   // LongArray
1304  mirror::PrimitiveArray<int16_t>::VisitRoots(callback, arg);   // ShortArray
1305}
1306
1307void Runtime::VisitConcurrentRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
1308  intern_table_->VisitRoots(callback, arg, flags);
1309  class_linker_->VisitRoots(callback, arg, flags);
1310  if ((flags & kVisitRootFlagNewRoots) == 0) {
1311    // Guaranteed to have no new roots in the constant roots.
1312    VisitConstantRoots(callback, arg);
1313  }
1314}
1315
1316void Runtime::VisitTransactionRoots(RootCallback* callback, void* arg) {
1317  if (preinitialization_transaction_ != nullptr) {
1318    preinitialization_transaction_->VisitRoots(callback, arg);
1319  }
1320}
1321
1322void Runtime::VisitNonThreadRoots(RootCallback* callback, void* arg) {
1323  java_vm_->VisitRoots(callback, arg);
1324  sentinel_.VisitRootIfNonNull(callback, arg, RootInfo(kRootVMInternal));
1325  pre_allocated_OutOfMemoryError_.VisitRootIfNonNull(callback, arg, RootInfo(kRootVMInternal));
1326  resolution_method_.VisitRoot(callback, arg, RootInfo(kRootVMInternal));
1327  pre_allocated_NoClassDefFoundError_.VisitRootIfNonNull(callback, arg, RootInfo(kRootVMInternal));
1328  imt_conflict_method_.VisitRootIfNonNull(callback, arg, RootInfo(kRootVMInternal));
1329  imt_unimplemented_method_.VisitRootIfNonNull(callback, arg, RootInfo(kRootVMInternal));
1330  default_imt_.VisitRootIfNonNull(callback, arg, RootInfo(kRootVMInternal));
1331  for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
1332    callee_save_methods_[i].VisitRootIfNonNull(callback, arg, RootInfo(kRootVMInternal));
1333  }
1334  verifier::MethodVerifier::VisitStaticRoots(callback, arg);
1335  {
1336    MutexLock mu(Thread::Current(), method_verifier_lock_);
1337    for (verifier::MethodVerifier* verifier : method_verifiers_) {
1338      verifier->VisitRoots(callback, arg);
1339    }
1340  }
1341  VisitTransactionRoots(callback, arg);
1342  instrumentation_.VisitRoots(callback, arg);
1343}
1344
1345void Runtime::VisitNonConcurrentRoots(RootCallback* callback, void* arg) {
1346  thread_list_->VisitRoots(callback, arg);
1347  VisitNonThreadRoots(callback, arg);
1348}
1349
1350void Runtime::VisitThreadRoots(RootCallback* callback, void* arg) {
1351  thread_list_->VisitRoots(callback, arg);
1352}
1353
1354size_t Runtime::FlipThreadRoots(Closure* thread_flip_visitor, Closure* flip_callback,
1355                                gc::collector::GarbageCollector* collector) {
1356  return thread_list_->FlipThreadRoots(thread_flip_visitor, flip_callback, collector);
1357}
1358
1359void Runtime::VisitRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
1360  VisitNonConcurrentRoots(callback, arg);
1361  VisitConcurrentRoots(callback, arg, flags);
1362}
1363
1364mirror::ObjectArray<mirror::ArtMethod>* Runtime::CreateDefaultImt(ClassLinker* cl) {
1365  Thread* self = Thread::Current();
1366  StackHandleScope<1> hs(self);
1367  Handle<mirror::ObjectArray<mirror::ArtMethod>> imtable(
1368      hs.NewHandle(cl->AllocArtMethodArray(self, 64)));
1369  mirror::ArtMethod* imt_conflict_method = Runtime::Current()->GetImtConflictMethod();
1370  for (size_t i = 0; i < static_cast<size_t>(imtable->GetLength()); i++) {
1371    imtable->Set<false>(i, imt_conflict_method);
1372  }
1373  return imtable.Get();
1374}
1375
1376mirror::ArtMethod* Runtime::CreateImtConflictMethod() {
1377  Thread* self = Thread::Current();
1378  Runtime* runtime = Runtime::Current();
1379  ClassLinker* class_linker = runtime->GetClassLinker();
1380  StackHandleScope<1> hs(self);
1381  Handle<mirror::ArtMethod> method(hs.NewHandle(class_linker->AllocArtMethod(self)));
1382  method->SetDeclaringClass(mirror::ArtMethod::GetJavaLangReflectArtMethod());
1383  // TODO: use a special method for imt conflict method saves.
1384  method->SetDexMethodIndex(DexFile::kDexNoIndex);
1385  // When compiling, the code pointer will get set later when the image is loaded.
1386  if (runtime->IsAotCompiler()) {
1387    size_t pointer_size = GetInstructionSetPointerSize(instruction_set_);
1388    method->SetEntryPointFromQuickCompiledCodePtrSize(nullptr, pointer_size);
1389  } else {
1390    method->SetEntryPointFromQuickCompiledCode(GetQuickImtConflictStub());
1391  }
1392  return method.Get();
1393}
1394
1395void Runtime::SetImtConflictMethod(mirror::ArtMethod* method) {
1396  imt_conflict_method_ = GcRoot<mirror::ArtMethod>(method);
1397}
1398
1399mirror::ArtMethod* Runtime::CreateResolutionMethod() {
1400  Thread* self = Thread::Current();
1401  Runtime* runtime = Runtime::Current();
1402  ClassLinker* class_linker = runtime->GetClassLinker();
1403  StackHandleScope<1> hs(self);
1404  Handle<mirror::ArtMethod> method(hs.NewHandle(class_linker->AllocArtMethod(self)));
1405  method->SetDeclaringClass(mirror::ArtMethod::GetJavaLangReflectArtMethod());
1406  // TODO: use a special method for resolution method saves
1407  method->SetDexMethodIndex(DexFile::kDexNoIndex);
1408  // When compiling, the code pointer will get set later when the image is loaded.
1409  if (runtime->IsAotCompiler()) {
1410    size_t pointer_size = GetInstructionSetPointerSize(instruction_set_);
1411    method->SetEntryPointFromQuickCompiledCodePtrSize(nullptr, pointer_size);
1412  } else {
1413    method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
1414  }
1415  return method.Get();
1416}
1417
1418mirror::ArtMethod* Runtime::CreateCalleeSaveMethod() {
1419  Thread* self = Thread::Current();
1420  Runtime* runtime = Runtime::Current();
1421  ClassLinker* class_linker = runtime->GetClassLinker();
1422  StackHandleScope<1> hs(self);
1423  Handle<mirror::ArtMethod> method(hs.NewHandle(class_linker->AllocArtMethod(self)));
1424  method->SetDeclaringClass(mirror::ArtMethod::GetJavaLangReflectArtMethod());
1425  // TODO: use a special method for callee saves
1426  method->SetDexMethodIndex(DexFile::kDexNoIndex);
1427  size_t pointer_size = GetInstructionSetPointerSize(instruction_set_);
1428  method->SetEntryPointFromQuickCompiledCodePtrSize(nullptr, pointer_size);
1429  DCHECK_NE(instruction_set_, kNone);
1430  return method.Get();
1431}
1432
1433void Runtime::DisallowNewSystemWeaks() {
1434  monitor_list_->DisallowNewMonitors();
1435  intern_table_->DisallowNewInterns();
1436  java_vm_->DisallowNewWeakGlobals();
1437}
1438
1439void Runtime::AllowNewSystemWeaks() {
1440  monitor_list_->AllowNewMonitors();
1441  intern_table_->AllowNewInterns();
1442  java_vm_->AllowNewWeakGlobals();
1443}
1444
1445void Runtime::EnsureNewSystemWeaksDisallowed() {
1446  // Lock and unlock the system weak locks once to ensure that no
1447  // threads are still in the middle of adding new system weaks.
1448  monitor_list_->EnsureNewMonitorsDisallowed();
1449  intern_table_->EnsureNewInternsDisallowed();
1450  java_vm_->EnsureNewWeakGlobalsDisallowed();
1451}
1452
1453void Runtime::SetInstructionSet(InstructionSet instruction_set) {
1454  instruction_set_ = instruction_set;
1455  if ((instruction_set_ == kThumb2) || (instruction_set_ == kArm)) {
1456    for (int i = 0; i != kLastCalleeSaveType; ++i) {
1457      CalleeSaveType type = static_cast<CalleeSaveType>(i);
1458      callee_save_method_frame_infos_[i] = arm::ArmCalleeSaveMethodFrameInfo(type);
1459    }
1460  } else if (instruction_set_ == kMips) {
1461    for (int i = 0; i != kLastCalleeSaveType; ++i) {
1462      CalleeSaveType type = static_cast<CalleeSaveType>(i);
1463      callee_save_method_frame_infos_[i] = mips::MipsCalleeSaveMethodFrameInfo(type);
1464    }
1465  } else if (instruction_set_ == kMips64) {
1466    for (int i = 0; i != kLastCalleeSaveType; ++i) {
1467      CalleeSaveType type = static_cast<CalleeSaveType>(i);
1468      callee_save_method_frame_infos_[i] = mips64::Mips64CalleeSaveMethodFrameInfo(type);
1469    }
1470  } else if (instruction_set_ == kX86) {
1471    for (int i = 0; i != kLastCalleeSaveType; ++i) {
1472      CalleeSaveType type = static_cast<CalleeSaveType>(i);
1473      callee_save_method_frame_infos_[i] = x86::X86CalleeSaveMethodFrameInfo(type);
1474    }
1475  } else if (instruction_set_ == kX86_64) {
1476    for (int i = 0; i != kLastCalleeSaveType; ++i) {
1477      CalleeSaveType type = static_cast<CalleeSaveType>(i);
1478      callee_save_method_frame_infos_[i] = x86_64::X86_64CalleeSaveMethodFrameInfo(type);
1479    }
1480  } else if (instruction_set_ == kArm64) {
1481    for (int i = 0; i != kLastCalleeSaveType; ++i) {
1482      CalleeSaveType type = static_cast<CalleeSaveType>(i);
1483      callee_save_method_frame_infos_[i] = arm64::Arm64CalleeSaveMethodFrameInfo(type);
1484    }
1485  } else {
1486    UNIMPLEMENTED(FATAL) << instruction_set_;
1487  }
1488}
1489
1490void Runtime::SetCalleeSaveMethod(mirror::ArtMethod* method, CalleeSaveType type) {
1491  DCHECK_LT(static_cast<int>(type), static_cast<int>(kLastCalleeSaveType));
1492  callee_save_methods_[type] = GcRoot<mirror::ArtMethod>(method);
1493}
1494
1495const std::vector<const DexFile*>& Runtime::GetCompileTimeClassPath(jobject class_loader) {
1496  if (class_loader == NULL) {
1497    return GetClassLinker()->GetBootClassPath();
1498  }
1499  CHECK(UseCompileTimeClassPath());
1500  CompileTimeClassPaths::const_iterator it = compile_time_class_paths_.find(class_loader);
1501  CHECK(it != compile_time_class_paths_.end());
1502  return it->second;
1503}
1504
1505void Runtime::SetCompileTimeClassPath(jobject class_loader,
1506                                      std::vector<const DexFile*>& class_path) {
1507  CHECK(!IsStarted());
1508  use_compile_time_class_path_ = true;
1509  compile_time_class_paths_.Put(class_loader, class_path);
1510}
1511
1512void Runtime::AddMethodVerifier(verifier::MethodVerifier* verifier) {
1513  DCHECK(verifier != nullptr);
1514  if (gAborting) {
1515    return;
1516  }
1517  MutexLock mu(Thread::Current(), method_verifier_lock_);
1518  method_verifiers_.insert(verifier);
1519}
1520
1521void Runtime::RemoveMethodVerifier(verifier::MethodVerifier* verifier) {
1522  DCHECK(verifier != nullptr);
1523  if (gAborting) {
1524    return;
1525  }
1526  MutexLock mu(Thread::Current(), method_verifier_lock_);
1527  auto it = method_verifiers_.find(verifier);
1528  CHECK(it != method_verifiers_.end());
1529  method_verifiers_.erase(it);
1530}
1531
1532void Runtime::StartProfiler(const char* profile_output_filename) {
1533  profile_output_filename_ = profile_output_filename;
1534  profiler_started_ =
1535    BackgroundMethodSamplingProfiler::Start(profile_output_filename_, profiler_options_);
1536}
1537
1538// Transaction support.
1539void Runtime::EnterTransactionMode(Transaction* transaction) {
1540  DCHECK(IsAotCompiler());
1541  DCHECK(transaction != nullptr);
1542  DCHECK(!IsActiveTransaction());
1543  preinitialization_transaction_ = transaction;
1544}
1545
1546void Runtime::ExitTransactionMode() {
1547  DCHECK(IsAotCompiler());
1548  DCHECK(IsActiveTransaction());
1549  preinitialization_transaction_ = nullptr;
1550}
1551
1552
1553bool Runtime::IsTransactionAborted() const {
1554  if (!IsActiveTransaction()) {
1555    return false;
1556  } else {
1557    DCHECK(IsAotCompiler());
1558    return preinitialization_transaction_->IsAborted();
1559  }
1560}
1561
1562void Runtime::AbortTransactionAndThrowInternalError(Thread* self,
1563                                                    const std::string& abort_message) {
1564  DCHECK(IsAotCompiler());
1565  DCHECK(IsActiveTransaction());
1566  // Throwing an exception may cause its class initialization. If we mark the transaction
1567  // aborted before that, we may warn with a false alarm. Throwing the exception before
1568  // marking the transaction aborted avoids that.
1569  preinitialization_transaction_->ThrowInternalError(self, false);
1570  preinitialization_transaction_->Abort(abort_message);
1571}
1572
1573void Runtime::ThrowInternalErrorForAbortedTransaction(Thread* self) {
1574  DCHECK(IsAotCompiler());
1575  DCHECK(IsActiveTransaction());
1576  preinitialization_transaction_->ThrowInternalError(self, true);
1577}
1578
1579void Runtime::RecordWriteFieldBoolean(mirror::Object* obj, MemberOffset field_offset,
1580                                      uint8_t value, bool is_volatile) const {
1581  DCHECK(IsAotCompiler());
1582  DCHECK(IsActiveTransaction());
1583  preinitialization_transaction_->RecordWriteFieldBoolean(obj, field_offset, value, is_volatile);
1584}
1585
1586void Runtime::RecordWriteFieldByte(mirror::Object* obj, MemberOffset field_offset,
1587                                   int8_t value, bool is_volatile) const {
1588  DCHECK(IsAotCompiler());
1589  DCHECK(IsActiveTransaction());
1590  preinitialization_transaction_->RecordWriteFieldByte(obj, field_offset, value, is_volatile);
1591}
1592
1593void Runtime::RecordWriteFieldChar(mirror::Object* obj, MemberOffset field_offset,
1594                                   uint16_t value, bool is_volatile) const {
1595  DCHECK(IsAotCompiler());
1596  DCHECK(IsActiveTransaction());
1597  preinitialization_transaction_->RecordWriteFieldChar(obj, field_offset, value, is_volatile);
1598}
1599
1600void Runtime::RecordWriteFieldShort(mirror::Object* obj, MemberOffset field_offset,
1601                                    int16_t value, bool is_volatile) const {
1602  DCHECK(IsAotCompiler());
1603  DCHECK(IsActiveTransaction());
1604  preinitialization_transaction_->RecordWriteFieldShort(obj, field_offset, value, is_volatile);
1605}
1606
1607void Runtime::RecordWriteField32(mirror::Object* obj, MemberOffset field_offset,
1608                                 uint32_t value, bool is_volatile) const {
1609  DCHECK(IsAotCompiler());
1610  DCHECK(IsActiveTransaction());
1611  preinitialization_transaction_->RecordWriteField32(obj, field_offset, value, is_volatile);
1612}
1613
1614void Runtime::RecordWriteField64(mirror::Object* obj, MemberOffset field_offset,
1615                                 uint64_t value, bool is_volatile) const {
1616  DCHECK(IsAotCompiler());
1617  DCHECK(IsActiveTransaction());
1618  preinitialization_transaction_->RecordWriteField64(obj, field_offset, value, is_volatile);
1619}
1620
1621void Runtime::RecordWriteFieldReference(mirror::Object* obj, MemberOffset field_offset,
1622                                        mirror::Object* value, bool is_volatile) const {
1623  DCHECK(IsAotCompiler());
1624  DCHECK(IsActiveTransaction());
1625  preinitialization_transaction_->RecordWriteFieldReference(obj, field_offset, value, is_volatile);
1626}
1627
1628void Runtime::RecordWriteArray(mirror::Array* array, size_t index, uint64_t value) const {
1629  DCHECK(IsAotCompiler());
1630  DCHECK(IsActiveTransaction());
1631  preinitialization_transaction_->RecordWriteArray(array, index, value);
1632}
1633
1634void Runtime::RecordStrongStringInsertion(mirror::String* s) const {
1635  DCHECK(IsAotCompiler());
1636  DCHECK(IsActiveTransaction());
1637  preinitialization_transaction_->RecordStrongStringInsertion(s);
1638}
1639
1640void Runtime::RecordWeakStringInsertion(mirror::String* s) const {
1641  DCHECK(IsAotCompiler());
1642  DCHECK(IsActiveTransaction());
1643  preinitialization_transaction_->RecordWeakStringInsertion(s);
1644}
1645
1646void Runtime::RecordStrongStringRemoval(mirror::String* s) const {
1647  DCHECK(IsAotCompiler());
1648  DCHECK(IsActiveTransaction());
1649  preinitialization_transaction_->RecordStrongStringRemoval(s);
1650}
1651
1652void Runtime::RecordWeakStringRemoval(mirror::String* s) const {
1653  DCHECK(IsAotCompiler());
1654  DCHECK(IsActiveTransaction());
1655  preinitialization_transaction_->RecordWeakStringRemoval(s);
1656}
1657
1658void Runtime::SetFaultMessage(const std::string& message) {
1659  MutexLock mu(Thread::Current(), fault_message_lock_);
1660  fault_message_ = message;
1661}
1662
1663void Runtime::AddCurrentRuntimeFeaturesAsDex2OatArguments(std::vector<std::string>* argv)
1664    const {
1665  if (GetInstrumentation()->InterpretOnly() || UseJit()) {
1666    argv->push_back("--compiler-filter=interpret-only");
1667  }
1668
1669  // Make the dex2oat instruction set match that of the launching runtime. If we have multiple
1670  // architecture support, dex2oat may be compiled as a different instruction-set than that
1671  // currently being executed.
1672  std::string instruction_set("--instruction-set=");
1673  instruction_set += GetInstructionSetString(kRuntimeISA);
1674  argv->push_back(instruction_set);
1675
1676  std::unique_ptr<const InstructionSetFeatures> features(InstructionSetFeatures::FromCppDefines());
1677  std::string feature_string("--instruction-set-features=");
1678  feature_string += features->GetFeatureString();
1679  argv->push_back(feature_string);
1680
1681  if (Dbg::IsJdwpConfigured()) {
1682    argv->push_back("--debuggable");
1683  }
1684}
1685
1686void Runtime::UpdateProfilerState(int state) {
1687  VLOG(profiler) << "Profiler state updated to " << state;
1688}
1689
1690void Runtime::CreateJit() {
1691  CHECK(jit_options_.get() != nullptr);
1692  std::string error_msg;
1693  jit_.reset(jit::Jit::Create(jit_options_.get(), &error_msg));
1694  if (jit_.get() != nullptr) {
1695    compiler_callbacks_ = jit_->GetCompilerCallbacks();
1696  } else {
1697    LOG(WARNING) << "Failed to create JIT " << error_msg;
1698  }
1699}
1700
1701}  // namespace art
1702