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