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