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 #include <signal.h>
27 #include <sys/syscall.h>
28 #include "base/memory_tool.h"
29 #if defined(__APPLE__)
30 #include <crt_externs.h> // for _NSGetEnviron
31 #endif
32
33 #include <cstdio>
34 #include <cstdlib>
35 #include <limits>
36 #include <memory_representation.h>
37 #include <vector>
38 #include <fcntl.h>
39
40 #include "android-base/strings.h"
41
42 #include "JniConstants.h"
43 #include "ScopedLocalRef.h"
44 #include "arch/arm/quick_method_frame_info_arm.h"
45 #include "arch/arm/registers_arm.h"
46 #include "arch/arm64/quick_method_frame_info_arm64.h"
47 #include "arch/arm64/registers_arm64.h"
48 #include "arch/instruction_set_features.h"
49 #include "arch/mips/quick_method_frame_info_mips.h"
50 #include "arch/mips/registers_mips.h"
51 #include "arch/mips64/quick_method_frame_info_mips64.h"
52 #include "arch/mips64/registers_mips64.h"
53 #include "arch/x86/quick_method_frame_info_x86.h"
54 #include "arch/x86/registers_x86.h"
55 #include "arch/x86_64/quick_method_frame_info_x86_64.h"
56 #include "arch/x86_64/registers_x86_64.h"
57 #include "art_field-inl.h"
58 #include "art_method-inl.h"
59 #include "asm_support.h"
60 #include "atomic.h"
61 #include "base/arena_allocator.h"
62 #include "base/dumpable.h"
63 #include "base/enums.h"
64 #include "base/stl_util.h"
65 #include "base/systrace.h"
66 #include "base/unix_file/fd_file.h"
67 #include "cha.h"
68 #include "class_linker-inl.h"
69 #include "compiler_callbacks.h"
70 #include "debugger.h"
71 #include "elf_file.h"
72 #include "entrypoints/runtime_asm_entrypoints.h"
73 #include "experimental_flags.h"
74 #include "fault_handler.h"
75 #include "gc/accounting/card_table-inl.h"
76 #include "gc/heap.h"
77 #include "gc/scoped_gc_critical_section.h"
78 #include "gc/space/image_space.h"
79 #include "gc/space/space-inl.h"
80 #include "gc/system_weak.h"
81 #include "handle_scope-inl.h"
82 #include "image-inl.h"
83 #include "instrumentation.h"
84 #include "intern_table.h"
85 #include "interpreter/interpreter.h"
86 #include "java_vm_ext.h"
87 #include "jit/jit.h"
88 #include "jit/jit_code_cache.h"
89 #include "jni_internal.h"
90 #include "linear_alloc.h"
91 #include "mirror/array.h"
92 #include "mirror/class-inl.h"
93 #include "mirror/class_ext.h"
94 #include "mirror/class_loader.h"
95 #include "mirror/emulated_stack_frame.h"
96 #include "mirror/field.h"
97 #include "mirror/method.h"
98 #include "mirror/method_handle_impl.h"
99 #include "mirror/method_handles_lookup.h"
100 #include "mirror/method_type.h"
101 #include "mirror/stack_trace_element.h"
102 #include "mirror/throwable.h"
103 #include "monitor.h"
104 #include "native/dalvik_system_DexFile.h"
105 #include "native/dalvik_system_VMDebug.h"
106 #include "native/dalvik_system_VMRuntime.h"
107 #include "native/dalvik_system_VMStack.h"
108 #include "native/dalvik_system_ZygoteHooks.h"
109 #include "native/java_lang_Class.h"
110 #include "native/java_lang_Object.h"
111 #include "native/java_lang_String.h"
112 #include "native/java_lang_StringFactory.h"
113 #include "native/java_lang_System.h"
114 #include "native/java_lang_Thread.h"
115 #include "native/java_lang_Throwable.h"
116 #include "native/java_lang_VMClassLoader.h"
117 #include "native/java_lang_Void.h"
118 #include "native/java_lang_invoke_MethodHandleImpl.h"
119 #include "native/java_lang_ref_FinalizerReference.h"
120 #include "native/java_lang_ref_Reference.h"
121 #include "native/java_lang_reflect_Array.h"
122 #include "native/java_lang_reflect_Constructor.h"
123 #include "native/java_lang_reflect_Executable.h"
124 #include "native/java_lang_reflect_Field.h"
125 #include "native/java_lang_reflect_Method.h"
126 #include "native/java_lang_reflect_Parameter.h"
127 #include "native/java_lang_reflect_Proxy.h"
128 #include "native/java_util_concurrent_atomic_AtomicLong.h"
129 #include "native/libcore_util_CharsetUtils.h"
130 #include "native/org_apache_harmony_dalvik_ddmc_DdmServer.h"
131 #include "native/org_apache_harmony_dalvik_ddmc_DdmVmInternal.h"
132 #include "native/sun_misc_Unsafe.h"
133 #include "native_bridge_art_interface.h"
134 #include "native_stack_dump.h"
135 #include "oat_file.h"
136 #include "oat_file_manager.h"
137 #include "os.h"
138 #include "parsed_options.h"
139 #include "jit/profile_saver.h"
140 #include "quick/quick_method_frame_info.h"
141 #include "reflection.h"
142 #include "runtime_callbacks.h"
143 #include "runtime_options.h"
144 #include "ScopedLocalRef.h"
145 #include "scoped_thread_state_change-inl.h"
146 #include "sigchain.h"
147 #include "signal_catcher.h"
148 #include "signal_set.h"
149 #include "thread.h"
150 #include "thread_list.h"
151 #include "ti/agent.h"
152 #include "trace.h"
153 #include "transaction.h"
154 #include "utils.h"
155 #include "vdex_file.h"
156 #include "verifier/method_verifier.h"
157 #include "well_known_classes.h"
158
159 #ifdef ART_TARGET_ANDROID
160 #include <android/set_abort_message.h>
161 #endif
162
163 namespace art {
164
165 // If a signal isn't handled properly, enable a handler that attempts to dump the Java stack.
166 static constexpr bool kEnableJavaStackTraceHandler = false;
167 // Tuned by compiling GmsCore under perf and measuring time spent in DescriptorEquals for class
168 // linking.
169 static constexpr double kLowMemoryMinLoadFactor = 0.5;
170 static constexpr double kLowMemoryMaxLoadFactor = 0.8;
171 static constexpr double kNormalMinLoadFactor = 0.4;
172 static constexpr double kNormalMaxLoadFactor = 0.7;
173 Runtime* Runtime::instance_ = nullptr;
174
175 struct TraceConfig {
176 Trace::TraceMode trace_mode;
177 Trace::TraceOutputMode trace_output_mode;
178 std::string trace_file;
179 size_t trace_file_size;
180 };
181
182 namespace {
183 #ifdef __APPLE__
GetEnviron()184 inline char** GetEnviron() {
185 // When Google Test is built as a framework on MacOS X, the environ variable
186 // is unavailable. Apple's documentation (man environ) recommends using
187 // _NSGetEnviron() instead.
188 return *_NSGetEnviron();
189 }
190 #else
191 // Some POSIX platforms expect you to declare environ. extern "C" makes
192 // it reside in the global namespace.
193 extern "C" char** environ;
194 inline char** GetEnviron() { return environ; }
195 #endif
196 } // namespace
197
Runtime()198 Runtime::Runtime()
199 : resolution_method_(nullptr),
200 imt_conflict_method_(nullptr),
201 imt_unimplemented_method_(nullptr),
202 instruction_set_(kNone),
203 compiler_callbacks_(nullptr),
204 is_zygote_(false),
205 must_relocate_(false),
206 is_concurrent_gc_enabled_(true),
207 is_explicit_gc_disabled_(false),
208 dex2oat_enabled_(true),
209 image_dex2oat_enabled_(true),
210 default_stack_size_(0),
211 heap_(nullptr),
212 max_spins_before_thin_lock_inflation_(Monitor::kDefaultMaxSpinsBeforeThinLockInflation),
213 monitor_list_(nullptr),
214 monitor_pool_(nullptr),
215 thread_list_(nullptr),
216 intern_table_(nullptr),
217 class_linker_(nullptr),
218 signal_catcher_(nullptr),
219 java_vm_(nullptr),
220 fault_message_lock_("Fault message lock"),
221 fault_message_(""),
222 threads_being_born_(0),
223 shutdown_cond_(new ConditionVariable("Runtime shutdown", *Locks::runtime_shutdown_lock_)),
224 shutting_down_(false),
225 shutting_down_started_(false),
226 started_(false),
227 finished_starting_(false),
228 vfprintf_(nullptr),
229 exit_(nullptr),
230 abort_(nullptr),
231 stats_enabled_(false),
232 is_running_on_memory_tool_(RUNNING_ON_MEMORY_TOOL),
233 instrumentation_(),
234 main_thread_group_(nullptr),
235 system_thread_group_(nullptr),
236 system_class_loader_(nullptr),
237 dump_gc_performance_on_shutdown_(false),
238 preinitialization_transaction_(nullptr),
239 verify_(verifier::VerifyMode::kNone),
240 allow_dex_file_fallback_(true),
241 target_sdk_version_(0),
242 implicit_null_checks_(false),
243 implicit_so_checks_(false),
244 implicit_suspend_checks_(false),
245 no_sig_chain_(false),
246 force_native_bridge_(false),
247 is_native_bridge_loaded_(false),
248 is_native_debuggable_(false),
249 is_java_debuggable_(false),
250 zygote_max_failed_boots_(0),
251 experimental_flags_(ExperimentalFlags::kNone),
252 oat_file_manager_(nullptr),
253 is_low_memory_mode_(false),
254 safe_mode_(false),
255 dump_native_stack_on_sig_quit_(true),
256 pruned_dalvik_cache_(false),
257 // Initially assume we perceive jank in case the process state is never updated.
258 process_state_(kProcessStateJankPerceptible),
259 zygote_no_threads_(false),
260 cha_(nullptr) {
261 CheckAsmSupportOffsetsAndSizes();
262 std::fill(callee_save_methods_, callee_save_methods_ + arraysize(callee_save_methods_), 0u);
263 interpreter::CheckInterpreterAsmConstants();
264 callbacks_.reset(new RuntimeCallbacks());
265 for (size_t i = 0; i <= static_cast<size_t>(DeoptimizationKind::kLast); ++i) {
266 deoptimization_counts_[i] = 0u;
267 }
268 }
269
~Runtime()270 Runtime::~Runtime() {
271 ScopedTrace trace("Runtime shutdown");
272 if (is_native_bridge_loaded_) {
273 UnloadNativeBridge();
274 }
275
276 Thread* self = Thread::Current();
277 const bool attach_shutdown_thread = self == nullptr;
278 if (attach_shutdown_thread) {
279 CHECK(AttachCurrentThread("Shutdown thread", false, nullptr, false));
280 self = Thread::Current();
281 } else {
282 LOG(WARNING) << "Current thread not detached in Runtime shutdown";
283 }
284
285 if (dump_gc_performance_on_shutdown_) {
286 // This can't be called from the Heap destructor below because it
287 // could call RosAlloc::InspectAll() which needs the thread_list
288 // to be still alive.
289 heap_->DumpGcPerformanceInfo(LOG_STREAM(INFO));
290 }
291
292 if (jit_ != nullptr) {
293 // Stop the profile saver thread before marking the runtime as shutting down.
294 // The saver will try to dump the profiles before being sopped and that
295 // requires holding the mutator lock.
296 jit_->StopProfileSaver();
297 }
298
299 {
300 ScopedTrace trace2("Wait for shutdown cond");
301 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
302 shutting_down_started_ = true;
303 while (threads_being_born_ > 0) {
304 shutdown_cond_->Wait(self);
305 }
306 shutting_down_ = true;
307 }
308 // Shutdown and wait for the daemons.
309 CHECK(self != nullptr);
310 if (IsFinishedStarting()) {
311 ScopedTrace trace2("Waiting for Daemons");
312 self->ClearException();
313 self->GetJniEnv()->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
314 WellKnownClasses::java_lang_Daemons_stop);
315 }
316
317 Trace::Shutdown();
318
319 // Report death. Clients me require a working thread, still, so do it before GC completes and
320 // all non-daemon threads are done.
321 {
322 ScopedObjectAccess soa(self);
323 callbacks_->NextRuntimePhase(RuntimePhaseCallback::RuntimePhase::kDeath);
324 }
325
326 if (attach_shutdown_thread) {
327 DetachCurrentThread();
328 self = nullptr;
329 }
330
331 // Make sure to let the GC complete if it is running.
332 heap_->WaitForGcToComplete(gc::kGcCauseBackground, self);
333 heap_->DeleteThreadPool();
334 if (jit_ != nullptr) {
335 ScopedTrace trace2("Delete jit");
336 VLOG(jit) << "Deleting jit thread pool";
337 // Delete thread pool before the thread list since we don't want to wait forever on the
338 // JIT compiler threads.
339 jit_->DeleteThreadPool();
340 }
341
342 // TODO Maybe do some locking.
343 for (auto& agent : agents_) {
344 agent.Unload();
345 }
346
347 // TODO Maybe do some locking
348 for (auto& plugin : plugins_) {
349 plugin.Unload();
350 }
351
352 // Make sure our internal threads are dead before we start tearing down things they're using.
353 Dbg::StopJdwp();
354 delete signal_catcher_;
355
356 // Make sure all other non-daemon threads have terminated, and all daemon threads are suspended.
357 {
358 ScopedTrace trace2("Delete thread list");
359 delete thread_list_;
360 }
361 // Delete the JIT after thread list to ensure that there is no remaining threads which could be
362 // accessing the instrumentation when we delete it.
363 if (jit_ != nullptr) {
364 VLOG(jit) << "Deleting jit";
365 jit_.reset(nullptr);
366 }
367
368 // Shutdown the fault manager if it was initialized.
369 fault_manager.Shutdown();
370
371 ScopedTrace trace2("Delete state");
372 delete monitor_list_;
373 delete monitor_pool_;
374 delete class_linker_;
375 delete cha_;
376 delete heap_;
377 delete intern_table_;
378 delete oat_file_manager_;
379 Thread::Shutdown();
380 QuasiAtomic::Shutdown();
381 verifier::MethodVerifier::Shutdown();
382
383 // Destroy allocators before shutting down the MemMap because they may use it.
384 java_vm_.reset();
385 linear_alloc_.reset();
386 low_4gb_arena_pool_.reset();
387 arena_pool_.reset();
388 jit_arena_pool_.reset();
389 MemMap::Shutdown();
390
391 // TODO: acquire a static mutex on Runtime to avoid racing.
392 CHECK(instance_ == nullptr || instance_ == this);
393 instance_ = nullptr;
394 }
395
396 struct AbortState {
Dumpart::AbortState397 void Dump(std::ostream& os) const {
398 if (gAborting > 1) {
399 os << "Runtime aborting --- recursively, so no thread-specific detail!\n";
400 DumpRecursiveAbort(os);
401 return;
402 }
403 gAborting++;
404 os << "Runtime aborting...\n";
405 if (Runtime::Current() == nullptr) {
406 os << "(Runtime does not yet exist!)\n";
407 DumpNativeStack(os, GetTid(), nullptr, " native: ", nullptr);
408 return;
409 }
410 Thread* self = Thread::Current();
411 if (self == nullptr) {
412 os << "(Aborting thread was not attached to runtime!)\n";
413 DumpKernelStack(os, GetTid(), " kernel: ", false);
414 DumpNativeStack(os, GetTid(), nullptr, " native: ", nullptr);
415 } else {
416 os << "Aborting thread:\n";
417 if (Locks::mutator_lock_->IsExclusiveHeld(self) || Locks::mutator_lock_->IsSharedHeld(self)) {
418 DumpThread(os, self);
419 } else {
420 if (Locks::mutator_lock_->SharedTryLock(self)) {
421 DumpThread(os, self);
422 Locks::mutator_lock_->SharedUnlock(self);
423 }
424 }
425 }
426 DumpAllThreads(os, self);
427 }
428
429 // No thread-safety analysis as we do explicitly test for holding the mutator lock.
DumpThreadart::AbortState430 void DumpThread(std::ostream& os, Thread* self) const NO_THREAD_SAFETY_ANALYSIS {
431 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self) || Locks::mutator_lock_->IsSharedHeld(self));
432 self->Dump(os);
433 if (self->IsExceptionPending()) {
434 mirror::Throwable* exception = self->GetException();
435 os << "Pending exception " << exception->Dump();
436 }
437 }
438
DumpAllThreadsart::AbortState439 void DumpAllThreads(std::ostream& os, Thread* self) const {
440 Runtime* runtime = Runtime::Current();
441 if (runtime != nullptr) {
442 ThreadList* thread_list = runtime->GetThreadList();
443 if (thread_list != nullptr) {
444 bool tll_already_held = Locks::thread_list_lock_->IsExclusiveHeld(self);
445 bool ml_already_held = Locks::mutator_lock_->IsSharedHeld(self);
446 if (!tll_already_held || !ml_already_held) {
447 os << "Dumping all threads without appropriate locks held:"
448 << (!tll_already_held ? " thread list lock" : "")
449 << (!ml_already_held ? " mutator lock" : "")
450 << "\n";
451 }
452 os << "All threads:\n";
453 thread_list->Dump(os);
454 }
455 }
456 }
457
458 // For recursive aborts.
DumpRecursiveAbortart::AbortState459 void DumpRecursiveAbort(std::ostream& os) const NO_THREAD_SAFETY_ANALYSIS {
460 // The only thing we'll attempt is dumping the native stack of the current thread. We will only
461 // try this if we haven't exceeded an arbitrary amount of recursions, to recover and actually
462 // die.
463 // Note: as we're using a global counter for the recursive abort detection, there is a potential
464 // race here and it is not OK to just print when the counter is "2" (one from
465 // Runtime::Abort(), one from previous Dump() call). Use a number that seems large enough.
466 static constexpr size_t kOnlyPrintWhenRecursionLessThan = 100u;
467 if (gAborting < kOnlyPrintWhenRecursionLessThan) {
468 gAborting++;
469 DumpNativeStack(os, GetTid());
470 }
471 }
472 };
473
Abort(const char * msg)474 void Runtime::Abort(const char* msg) {
475 gAborting++; // set before taking any locks
476
477 // Ensure that we don't have multiple threads trying to abort at once,
478 // which would result in significantly worse diagnostics.
479 MutexLock mu(Thread::Current(), *Locks::abort_lock_);
480
481 // Get any pending output out of the way.
482 fflush(nullptr);
483
484 // Many people have difficulty distinguish aborts from crashes,
485 // so be explicit.
486 // Note: use cerr on the host to print log lines immediately, so we get at least some output
487 // in case of recursive aborts. We lose annotation with the source file and line number
488 // here, which is a minor issue. The same is significantly more complicated on device,
489 // which is why we ignore the issue there.
490 AbortState state;
491 if (kIsTargetBuild) {
492 LOG(FATAL_WITHOUT_ABORT) << Dumpable<AbortState>(state);
493 } else {
494 std::cerr << Dumpable<AbortState>(state);
495 }
496
497 // Sometimes we dump long messages, and the Android abort message only retains the first line.
498 // In those cases, just log the message again, to avoid logcat limits.
499 if (msg != nullptr && strchr(msg, '\n') != nullptr) {
500 LOG(FATAL_WITHOUT_ABORT) << msg;
501 }
502
503 // Call the abort hook if we have one.
504 if (Runtime::Current() != nullptr && Runtime::Current()->abort_ != nullptr) {
505 LOG(FATAL_WITHOUT_ABORT) << "Calling abort hook...";
506 Runtime::Current()->abort_();
507 // notreached
508 LOG(FATAL_WITHOUT_ABORT) << "Unexpectedly returned from abort hook!";
509 }
510
511 #if defined(__GLIBC__)
512 // TODO: we ought to be able to use pthread_kill(3) here (or abort(3),
513 // which POSIX defines in terms of raise(3), which POSIX defines in terms
514 // of pthread_kill(3)). On Linux, though, libcorkscrew can't unwind through
515 // libpthread, which means the stacks we dump would be useless. Calling
516 // tgkill(2) directly avoids that.
517 syscall(__NR_tgkill, getpid(), GetTid(), SIGABRT);
518 // TODO: LLVM installs it's own SIGABRT handler so exit to be safe... Can we disable that in LLVM?
519 // If not, we could use sigaction(3) before calling tgkill(2) and lose this call to exit(3).
520 exit(1);
521 #else
522 abort();
523 #endif
524 // notreached
525 }
526
PreZygoteFork()527 void Runtime::PreZygoteFork() {
528 heap_->PreZygoteFork();
529 }
530
CallExitHook(jint status)531 void Runtime::CallExitHook(jint status) {
532 if (exit_ != nullptr) {
533 ScopedThreadStateChange tsc(Thread::Current(), kNative);
534 exit_(status);
535 LOG(WARNING) << "Exit hook returned instead of exiting!";
536 }
537 }
538
SweepSystemWeaks(IsMarkedVisitor * visitor)539 void Runtime::SweepSystemWeaks(IsMarkedVisitor* visitor) {
540 GetInternTable()->SweepInternTableWeaks(visitor);
541 GetMonitorList()->SweepMonitorList(visitor);
542 GetJavaVM()->SweepJniWeakGlobals(visitor);
543 GetHeap()->SweepAllocationRecords(visitor);
544 if (GetJit() != nullptr) {
545 // Visit JIT literal tables. Objects in these tables are classes and strings
546 // and only classes can be affected by class unloading. The strings always
547 // stay alive as they are strongly interned.
548 // TODO: Move this closer to CleanupClassLoaders, to avoid blocking weak accesses
549 // from mutators. See b/32167580.
550 GetJit()->GetCodeCache()->SweepRootTables(visitor);
551 }
552
553 // All other generic system-weak holders.
554 for (gc::AbstractSystemWeakHolder* holder : system_weak_holders_) {
555 holder->Sweep(visitor);
556 }
557 }
558
ParseOptions(const RuntimeOptions & raw_options,bool ignore_unrecognized,RuntimeArgumentMap * runtime_options)559 bool Runtime::ParseOptions(const RuntimeOptions& raw_options,
560 bool ignore_unrecognized,
561 RuntimeArgumentMap* runtime_options) {
562 InitLogging(/* argv */ nullptr, Aborter); // Calls Locks::Init() as a side effect.
563 bool parsed = ParsedOptions::Parse(raw_options, ignore_unrecognized, runtime_options);
564 if (!parsed) {
565 LOG(ERROR) << "Failed to parse options";
566 return false;
567 }
568 return true;
569 }
570
571 // Callback to check whether it is safe to call Abort (e.g., to use a call to
572 // LOG(FATAL)). It is only safe to call Abort if the runtime has been created,
573 // properly initialized, and has not shut down.
IsSafeToCallAbort()574 static bool IsSafeToCallAbort() NO_THREAD_SAFETY_ANALYSIS {
575 Runtime* runtime = Runtime::Current();
576 return runtime != nullptr && runtime->IsStarted() && !runtime->IsShuttingDownLocked();
577 }
578
Create(RuntimeArgumentMap && runtime_options)579 bool Runtime::Create(RuntimeArgumentMap&& runtime_options) {
580 // TODO: acquire a static mutex on Runtime to avoid racing.
581 if (Runtime::instance_ != nullptr) {
582 return false;
583 }
584 instance_ = new Runtime;
585 Locks::SetClientCallback(IsSafeToCallAbort);
586 if (!instance_->Init(std::move(runtime_options))) {
587 // TODO: Currently deleting the instance will abort the runtime on destruction. Now This will
588 // leak memory, instead. Fix the destructor. b/19100793.
589 // delete instance_;
590 instance_ = nullptr;
591 return false;
592 }
593 return true;
594 }
595
Create(const RuntimeOptions & raw_options,bool ignore_unrecognized)596 bool Runtime::Create(const RuntimeOptions& raw_options, bool ignore_unrecognized) {
597 RuntimeArgumentMap runtime_options;
598 return ParseOptions(raw_options, ignore_unrecognized, &runtime_options) &&
599 Create(std::move(runtime_options));
600 }
601
CreateSystemClassLoader(Runtime * runtime)602 static jobject CreateSystemClassLoader(Runtime* runtime) {
603 if (runtime->IsAotCompiler() && !runtime->GetCompilerCallbacks()->IsBootImage()) {
604 return nullptr;
605 }
606
607 ScopedObjectAccess soa(Thread::Current());
608 ClassLinker* cl = Runtime::Current()->GetClassLinker();
609 auto pointer_size = cl->GetImagePointerSize();
610
611 StackHandleScope<2> hs(soa.Self());
612 Handle<mirror::Class> class_loader_class(
613 hs.NewHandle(soa.Decode<mirror::Class>(WellKnownClasses::java_lang_ClassLoader)));
614 CHECK(cl->EnsureInitialized(soa.Self(), class_loader_class, true, true));
615
616 ArtMethod* getSystemClassLoader = class_loader_class->FindDirectMethod(
617 "getSystemClassLoader", "()Ljava/lang/ClassLoader;", pointer_size);
618 CHECK(getSystemClassLoader != nullptr);
619
620 JValue result = InvokeWithJValues(soa,
621 nullptr,
622 jni::EncodeArtMethod(getSystemClassLoader),
623 nullptr);
624 JNIEnv* env = soa.Self()->GetJniEnv();
625 ScopedLocalRef<jobject> system_class_loader(env, soa.AddLocalReference<jobject>(result.GetL()));
626 CHECK(system_class_loader.get() != nullptr);
627
628 soa.Self()->SetClassLoaderOverride(system_class_loader.get());
629
630 Handle<mirror::Class> thread_class(
631 hs.NewHandle(soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread)));
632 CHECK(cl->EnsureInitialized(soa.Self(), thread_class, true, true));
633
634 ArtField* contextClassLoader =
635 thread_class->FindDeclaredInstanceField("contextClassLoader", "Ljava/lang/ClassLoader;");
636 CHECK(contextClassLoader != nullptr);
637
638 // We can't run in a transaction yet.
639 contextClassLoader->SetObject<false>(
640 soa.Self()->GetPeer(),
641 soa.Decode<mirror::ClassLoader>(system_class_loader.get()).Ptr());
642
643 return env->NewGlobalRef(system_class_loader.get());
644 }
645
GetPatchoatExecutable() const646 std::string Runtime::GetPatchoatExecutable() const {
647 if (!patchoat_executable_.empty()) {
648 return patchoat_executable_;
649 }
650 std::string patchoat_executable(GetAndroidRoot());
651 patchoat_executable += (kIsDebugBuild ? "/bin/patchoatd" : "/bin/patchoat");
652 return patchoat_executable;
653 }
654
GetCompilerExecutable() const655 std::string Runtime::GetCompilerExecutable() const {
656 if (!compiler_executable_.empty()) {
657 return compiler_executable_;
658 }
659 std::string compiler_executable(GetAndroidRoot());
660 compiler_executable += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat");
661 return compiler_executable;
662 }
663
Start()664 bool Runtime::Start() {
665 VLOG(startup) << "Runtime::Start entering";
666
667 CHECK(!no_sig_chain_) << "A started runtime should have sig chain enabled";
668
669 // If a debug host build, disable ptrace restriction for debugging and test timeout thread dump.
670 // Only 64-bit as prctl() may fail in 32 bit userspace on a 64-bit kernel.
671 #if defined(__linux__) && !defined(ART_TARGET_ANDROID) && defined(__x86_64__)
672 if (kIsDebugBuild) {
673 CHECK_EQ(prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY), 0);
674 }
675 #endif
676
677 // Restore main thread state to kNative as expected by native code.
678 Thread* self = Thread::Current();
679
680 self->TransitionFromRunnableToSuspended(kNative);
681
682 started_ = true;
683
684 if (!IsImageDex2OatEnabled() || !GetHeap()->HasBootImageSpace()) {
685 ScopedObjectAccess soa(self);
686 StackHandleScope<2> hs(soa.Self());
687
688 auto class_class(hs.NewHandle<mirror::Class>(mirror::Class::GetJavaLangClass()));
689 auto field_class(hs.NewHandle<mirror::Class>(mirror::Field::StaticClass()));
690
691 class_linker_->EnsureInitialized(soa.Self(), class_class, true, true);
692 // Field class is needed for register_java_net_InetAddress in libcore, b/28153851.
693 class_linker_->EnsureInitialized(soa.Self(), field_class, true, true);
694 }
695
696 // InitNativeMethods needs to be after started_ so that the classes
697 // it touches will have methods linked to the oat file if necessary.
698 {
699 ScopedTrace trace2("InitNativeMethods");
700 InitNativeMethods();
701 }
702
703 // Initialize well known thread group values that may be accessed threads while attaching.
704 InitThreadGroups(self);
705
706 Thread::FinishStartup();
707
708 // Create the JIT either if we have to use JIT compilation or save profiling info. This is
709 // done after FinishStartup as the JIT pool needs Java thread peers, which require the main
710 // ThreadGroup to exist.
711 //
712 // TODO(calin): We use the JIT class as a proxy for JIT compilation and for
713 // recoding profiles. Maybe we should consider changing the name to be more clear it's
714 // not only about compiling. b/28295073.
715 if (jit_options_->UseJitCompilation() || jit_options_->GetSaveProfilingInfo()) {
716 std::string error_msg;
717 if (!IsZygote()) {
718 // If we are the zygote then we need to wait until after forking to create the code cache
719 // due to SELinux restrictions on r/w/x memory regions.
720 CreateJit();
721 } else if (jit_options_->UseJitCompilation()) {
722 if (!jit::Jit::LoadCompilerLibrary(&error_msg)) {
723 // Try to load compiler pre zygote to reduce PSS. b/27744947
724 LOG(WARNING) << "Failed to load JIT compiler with error " << error_msg;
725 }
726 }
727 }
728
729 // Send the start phase event. We have to wait till here as this is when the main thread peer
730 // has just been generated, important root clinits have been run and JNI is completely functional.
731 {
732 ScopedObjectAccess soa(self);
733 callbacks_->NextRuntimePhase(RuntimePhaseCallback::RuntimePhase::kStart);
734 }
735
736 system_class_loader_ = CreateSystemClassLoader(this);
737
738 if (!is_zygote_) {
739 if (is_native_bridge_loaded_) {
740 PreInitializeNativeBridge(".");
741 }
742 NativeBridgeAction action = force_native_bridge_
743 ? NativeBridgeAction::kInitialize
744 : NativeBridgeAction::kUnload;
745 InitNonZygoteOrPostFork(self->GetJniEnv(),
746 /* is_system_server */ false,
747 action,
748 GetInstructionSetString(kRuntimeISA));
749 }
750
751 // Send the initialized phase event. Send it before starting daemons, as otherwise
752 // sending thread events becomes complicated.
753 {
754 ScopedObjectAccess soa(self);
755 callbacks_->NextRuntimePhase(RuntimePhaseCallback::RuntimePhase::kInit);
756 }
757
758 StartDaemonThreads();
759
760 {
761 ScopedObjectAccess soa(self);
762 self->GetJniEnv()->locals.AssertEmpty();
763 }
764
765 VLOG(startup) << "Runtime::Start exiting";
766 finished_starting_ = true;
767
768 if (trace_config_.get() != nullptr && trace_config_->trace_file != "") {
769 ScopedThreadStateChange tsc(self, kWaitingForMethodTracingStart);
770 Trace::Start(trace_config_->trace_file.c_str(),
771 -1,
772 static_cast<int>(trace_config_->trace_file_size),
773 0,
774 trace_config_->trace_output_mode,
775 trace_config_->trace_mode,
776 0);
777 }
778
779 return true;
780 }
781
EndThreadBirth()782 void Runtime::EndThreadBirth() REQUIRES(Locks::runtime_shutdown_lock_) {
783 DCHECK_GT(threads_being_born_, 0U);
784 threads_being_born_--;
785 if (shutting_down_started_ && threads_being_born_ == 0) {
786 shutdown_cond_->Broadcast(Thread::Current());
787 }
788 }
789
InitNonZygoteOrPostFork(JNIEnv * env,bool is_system_server,NativeBridgeAction action,const char * isa)790 void Runtime::InitNonZygoteOrPostFork(
791 JNIEnv* env, bool is_system_server, NativeBridgeAction action, const char* isa) {
792 is_zygote_ = false;
793
794 if (is_native_bridge_loaded_) {
795 switch (action) {
796 case NativeBridgeAction::kUnload:
797 UnloadNativeBridge();
798 is_native_bridge_loaded_ = false;
799 break;
800
801 case NativeBridgeAction::kInitialize:
802 InitializeNativeBridge(env, isa);
803 break;
804 }
805 }
806
807 // Create the thread pools.
808 heap_->CreateThreadPool();
809 // Reset the gc performance data at zygote fork so that the GCs
810 // before fork aren't attributed to an app.
811 heap_->ResetGcPerformanceInfo();
812
813 // We may want to collect profiling samples for system server, but we never want to JIT there.
814 if ((!is_system_server || !jit_options_->UseJitCompilation()) &&
815 !safe_mode_ &&
816 (jit_options_->UseJitCompilation() || jit_options_->GetSaveProfilingInfo()) &&
817 jit_ == nullptr) {
818 // Note that when running ART standalone (not zygote, nor zygote fork),
819 // the jit may have already been created.
820 CreateJit();
821 }
822
823 StartSignalCatcher();
824
825 // Start the JDWP thread. If the command-line debugger flags specified "suspend=y",
826 // this will pause the runtime, so we probably want this to come last.
827 Dbg::StartJdwp();
828 }
829
StartSignalCatcher()830 void Runtime::StartSignalCatcher() {
831 if (!is_zygote_) {
832 signal_catcher_ = new SignalCatcher(stack_trace_file_);
833 }
834 }
835
IsShuttingDown(Thread * self)836 bool Runtime::IsShuttingDown(Thread* self) {
837 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
838 return IsShuttingDownLocked();
839 }
840
StartDaemonThreads()841 void Runtime::StartDaemonThreads() {
842 ScopedTrace trace(__FUNCTION__);
843 VLOG(startup) << "Runtime::StartDaemonThreads entering";
844
845 Thread* self = Thread::Current();
846
847 // Must be in the kNative state for calling native methods.
848 CHECK_EQ(self->GetState(), kNative);
849
850 JNIEnv* env = self->GetJniEnv();
851 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
852 WellKnownClasses::java_lang_Daemons_start);
853 if (env->ExceptionCheck()) {
854 env->ExceptionDescribe();
855 LOG(FATAL) << "Error starting java.lang.Daemons";
856 }
857
858 VLOG(startup) << "Runtime::StartDaemonThreads exiting";
859 }
860
861 // Attempts to open dex files from image(s). Given the image location, try to find the oat file
862 // and open it to get the stored dex file. If the image is the first for a multi-image boot
863 // classpath, go on and also open the other images.
OpenDexFilesFromImage(const std::string & image_location,std::vector<std::unique_ptr<const DexFile>> * dex_files,size_t * failures)864 static bool OpenDexFilesFromImage(const std::string& image_location,
865 std::vector<std::unique_ptr<const DexFile>>* dex_files,
866 size_t* failures) {
867 DCHECK(dex_files != nullptr) << "OpenDexFilesFromImage: out-param is nullptr";
868
869 // Use a work-list approach, so that we can easily reuse the opening code.
870 std::vector<std::string> image_locations;
871 image_locations.push_back(image_location);
872
873 for (size_t index = 0; index < image_locations.size(); ++index) {
874 std::string system_filename;
875 bool has_system = false;
876 std::string cache_filename_unused;
877 bool dalvik_cache_exists_unused;
878 bool has_cache_unused;
879 bool is_global_cache_unused;
880 bool found_image = gc::space::ImageSpace::FindImageFilename(image_locations[index].c_str(),
881 kRuntimeISA,
882 &system_filename,
883 &has_system,
884 &cache_filename_unused,
885 &dalvik_cache_exists_unused,
886 &has_cache_unused,
887 &is_global_cache_unused);
888
889 if (!found_image || !has_system) {
890 return false;
891 }
892
893 // We are falling back to non-executable use of the oat file because patching failed, presumably
894 // due to lack of space.
895 std::string vdex_filename =
896 ImageHeader::GetVdexLocationFromImageLocation(system_filename.c_str());
897 std::string oat_filename =
898 ImageHeader::GetOatLocationFromImageLocation(system_filename.c_str());
899 std::string oat_location =
900 ImageHeader::GetOatLocationFromImageLocation(image_locations[index].c_str());
901 // Note: in the multi-image case, the image location may end in ".jar," and not ".art." Handle
902 // that here.
903 if (android::base::EndsWith(oat_location, ".jar")) {
904 oat_location.replace(oat_location.length() - 3, 3, "oat");
905 }
906 std::string error_msg;
907
908 std::unique_ptr<VdexFile> vdex_file(VdexFile::Open(vdex_filename,
909 false /* writable */,
910 false /* low_4gb */,
911 false, /* unquicken */
912 &error_msg));
913 if (vdex_file.get() == nullptr) {
914 return false;
915 }
916
917 std::unique_ptr<File> file(OS::OpenFileForReading(oat_filename.c_str()));
918 if (file.get() == nullptr) {
919 return false;
920 }
921 std::unique_ptr<ElfFile> elf_file(ElfFile::Open(file.get(),
922 false /* writable */,
923 false /* program_header_only */,
924 false /* low_4gb */,
925 &error_msg));
926 if (elf_file.get() == nullptr) {
927 return false;
928 }
929 std::unique_ptr<const OatFile> oat_file(
930 OatFile::OpenWithElfFile(elf_file.release(),
931 vdex_file.release(),
932 oat_location,
933 nullptr,
934 &error_msg));
935 if (oat_file == nullptr) {
936 LOG(WARNING) << "Unable to use '" << oat_filename << "' because " << error_msg;
937 return false;
938 }
939
940 for (const OatFile::OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) {
941 if (oat_dex_file == nullptr) {
942 *failures += 1;
943 continue;
944 }
945 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
946 if (dex_file.get() == nullptr) {
947 *failures += 1;
948 } else {
949 dex_files->push_back(std::move(dex_file));
950 }
951 }
952
953 if (index == 0) {
954 // First file. See if this is a multi-image environment, and if so, enqueue the other images.
955 const OatHeader& boot_oat_header = oat_file->GetOatHeader();
956 const char* boot_cp = boot_oat_header.GetStoreValueByKey(OatHeader::kBootClassPathKey);
957 if (boot_cp != nullptr) {
958 gc::space::ImageSpace::ExtractMultiImageLocations(image_locations[0],
959 boot_cp,
960 &image_locations);
961 }
962 }
963
964 Runtime::Current()->GetOatFileManager().RegisterOatFile(std::move(oat_file));
965 }
966 return true;
967 }
968
969
OpenDexFiles(const std::vector<std::string> & dex_filenames,const std::vector<std::string> & dex_locations,const std::string & image_location,std::vector<std::unique_ptr<const DexFile>> * dex_files)970 static size_t OpenDexFiles(const std::vector<std::string>& dex_filenames,
971 const std::vector<std::string>& dex_locations,
972 const std::string& image_location,
973 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
974 DCHECK(dex_files != nullptr) << "OpenDexFiles: out-param is nullptr";
975 size_t failure_count = 0;
976 if (!image_location.empty() && OpenDexFilesFromImage(image_location, dex_files, &failure_count)) {
977 return failure_count;
978 }
979 failure_count = 0;
980 for (size_t i = 0; i < dex_filenames.size(); i++) {
981 const char* dex_filename = dex_filenames[i].c_str();
982 const char* dex_location = dex_locations[i].c_str();
983 static constexpr bool kVerifyChecksum = true;
984 std::string error_msg;
985 if (!OS::FileExists(dex_filename)) {
986 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
987 continue;
988 }
989 if (!DexFile::Open(dex_filename, dex_location, kVerifyChecksum, &error_msg, dex_files)) {
990 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
991 ++failure_count;
992 }
993 }
994 return failure_count;
995 }
996
SetSentinel(mirror::Object * sentinel)997 void Runtime::SetSentinel(mirror::Object* sentinel) {
998 CHECK(sentinel_.Read() == nullptr);
999 CHECK(sentinel != nullptr);
1000 CHECK(!heap_->IsMovableObject(sentinel));
1001 sentinel_ = GcRoot<mirror::Object>(sentinel);
1002 }
1003
Init(RuntimeArgumentMap && runtime_options_in)1004 bool Runtime::Init(RuntimeArgumentMap&& runtime_options_in) {
1005 // (b/30160149): protect subprocesses from modifications to LD_LIBRARY_PATH, etc.
1006 // Take a snapshot of the environment at the time the runtime was created, for use by Exec, etc.
1007 env_snapshot_.TakeSnapshot();
1008
1009 RuntimeArgumentMap runtime_options(std::move(runtime_options_in));
1010 ScopedTrace trace(__FUNCTION__);
1011 CHECK_EQ(sysconf(_SC_PAGE_SIZE), kPageSize);
1012
1013 MemMap::Init();
1014
1015 using Opt = RuntimeArgumentMap;
1016 VLOG(startup) << "Runtime::Init -verbose:startup enabled";
1017
1018 QuasiAtomic::Startup();
1019
1020 oat_file_manager_ = new OatFileManager;
1021
1022 Thread::SetSensitiveThreadHook(runtime_options.GetOrDefault(Opt::HookIsSensitiveThread));
1023 Monitor::Init(runtime_options.GetOrDefault(Opt::LockProfThreshold));
1024
1025 boot_class_path_string_ = runtime_options.ReleaseOrDefault(Opt::BootClassPath);
1026 class_path_string_ = runtime_options.ReleaseOrDefault(Opt::ClassPath);
1027 properties_ = runtime_options.ReleaseOrDefault(Opt::PropertiesList);
1028
1029 compiler_callbacks_ = runtime_options.GetOrDefault(Opt::CompilerCallbacksPtr);
1030 patchoat_executable_ = runtime_options.ReleaseOrDefault(Opt::PatchOat);
1031 must_relocate_ = runtime_options.GetOrDefault(Opt::Relocate);
1032 is_zygote_ = runtime_options.Exists(Opt::Zygote);
1033 is_explicit_gc_disabled_ = runtime_options.Exists(Opt::DisableExplicitGC);
1034 dex2oat_enabled_ = runtime_options.GetOrDefault(Opt::Dex2Oat);
1035 image_dex2oat_enabled_ = runtime_options.GetOrDefault(Opt::ImageDex2Oat);
1036 dump_native_stack_on_sig_quit_ = runtime_options.GetOrDefault(Opt::DumpNativeStackOnSigQuit);
1037
1038 vfprintf_ = runtime_options.GetOrDefault(Opt::HookVfprintf);
1039 exit_ = runtime_options.GetOrDefault(Opt::HookExit);
1040 abort_ = runtime_options.GetOrDefault(Opt::HookAbort);
1041
1042 default_stack_size_ = runtime_options.GetOrDefault(Opt::StackSize);
1043 stack_trace_file_ = runtime_options.ReleaseOrDefault(Opt::StackTraceFile);
1044
1045 compiler_executable_ = runtime_options.ReleaseOrDefault(Opt::Compiler);
1046 compiler_options_ = runtime_options.ReleaseOrDefault(Opt::CompilerOptions);
1047 for (StringPiece option : Runtime::Current()->GetCompilerOptions()) {
1048 if (option.starts_with("--debuggable")) {
1049 SetJavaDebuggable(true);
1050 break;
1051 }
1052 }
1053 image_compiler_options_ = runtime_options.ReleaseOrDefault(Opt::ImageCompilerOptions);
1054 image_location_ = runtime_options.GetOrDefault(Opt::Image);
1055
1056 max_spins_before_thin_lock_inflation_ =
1057 runtime_options.GetOrDefault(Opt::MaxSpinsBeforeThinLockInflation);
1058
1059 monitor_list_ = new MonitorList;
1060 monitor_pool_ = MonitorPool::Create();
1061 thread_list_ = new ThreadList(runtime_options.GetOrDefault(Opt::ThreadSuspendTimeout));
1062 intern_table_ = new InternTable;
1063
1064 verify_ = runtime_options.GetOrDefault(Opt::Verify);
1065 allow_dex_file_fallback_ = !runtime_options.Exists(Opt::NoDexFileFallback);
1066
1067 no_sig_chain_ = runtime_options.Exists(Opt::NoSigChain);
1068 force_native_bridge_ = runtime_options.Exists(Opt::ForceNativeBridge);
1069
1070 Split(runtime_options.GetOrDefault(Opt::CpuAbiList), ',', &cpu_abilist_);
1071
1072 fingerprint_ = runtime_options.ReleaseOrDefault(Opt::Fingerprint);
1073
1074 if (runtime_options.GetOrDefault(Opt::Interpret)) {
1075 GetInstrumentation()->ForceInterpretOnly();
1076 }
1077
1078 zygote_max_failed_boots_ = runtime_options.GetOrDefault(Opt::ZygoteMaxFailedBoots);
1079 experimental_flags_ = runtime_options.GetOrDefault(Opt::Experimental);
1080 is_low_memory_mode_ = runtime_options.Exists(Opt::LowMemoryMode);
1081
1082 plugins_ = runtime_options.ReleaseOrDefault(Opt::Plugins);
1083 agents_ = runtime_options.ReleaseOrDefault(Opt::AgentPath);
1084 // TODO Add back in -agentlib
1085 // for (auto lib : runtime_options.ReleaseOrDefault(Opt::AgentLib)) {
1086 // agents_.push_back(lib);
1087 // }
1088
1089 XGcOption xgc_option = runtime_options.GetOrDefault(Opt::GcOption);
1090 heap_ = new gc::Heap(runtime_options.GetOrDefault(Opt::MemoryInitialSize),
1091 runtime_options.GetOrDefault(Opt::HeapGrowthLimit),
1092 runtime_options.GetOrDefault(Opt::HeapMinFree),
1093 runtime_options.GetOrDefault(Opt::HeapMaxFree),
1094 runtime_options.GetOrDefault(Opt::HeapTargetUtilization),
1095 runtime_options.GetOrDefault(Opt::ForegroundHeapGrowthMultiplier),
1096 runtime_options.GetOrDefault(Opt::MemoryMaximumSize),
1097 runtime_options.GetOrDefault(Opt::NonMovingSpaceCapacity),
1098 runtime_options.GetOrDefault(Opt::Image),
1099 runtime_options.GetOrDefault(Opt::ImageInstructionSet),
1100 // Override the collector type to CC if the read barrier config.
1101 kUseReadBarrier ? gc::kCollectorTypeCC : xgc_option.collector_type_,
1102 kUseReadBarrier ? BackgroundGcOption(gc::kCollectorTypeCCBackground)
1103 : runtime_options.GetOrDefault(Opt::BackgroundGc),
1104 runtime_options.GetOrDefault(Opt::LargeObjectSpace),
1105 runtime_options.GetOrDefault(Opt::LargeObjectThreshold),
1106 runtime_options.GetOrDefault(Opt::ParallelGCThreads),
1107 runtime_options.GetOrDefault(Opt::ConcGCThreads),
1108 runtime_options.Exists(Opt::LowMemoryMode),
1109 runtime_options.GetOrDefault(Opt::LongPauseLogThreshold),
1110 runtime_options.GetOrDefault(Opt::LongGCLogThreshold),
1111 runtime_options.Exists(Opt::IgnoreMaxFootprint),
1112 runtime_options.GetOrDefault(Opt::UseTLAB),
1113 xgc_option.verify_pre_gc_heap_,
1114 xgc_option.verify_pre_sweeping_heap_,
1115 xgc_option.verify_post_gc_heap_,
1116 xgc_option.verify_pre_gc_rosalloc_,
1117 xgc_option.verify_pre_sweeping_rosalloc_,
1118 xgc_option.verify_post_gc_rosalloc_,
1119 xgc_option.gcstress_,
1120 xgc_option.measure_,
1121 runtime_options.GetOrDefault(Opt::EnableHSpaceCompactForOOM),
1122 runtime_options.GetOrDefault(Opt::HSpaceCompactForOOMMinIntervalsMs));
1123
1124 if (!heap_->HasBootImageSpace() && !allow_dex_file_fallback_) {
1125 LOG(ERROR) << "Dex file fallback disabled, cannot continue without image.";
1126 return false;
1127 }
1128
1129 dump_gc_performance_on_shutdown_ = runtime_options.Exists(Opt::DumpGCPerformanceOnShutdown);
1130
1131 if (runtime_options.Exists(Opt::JdwpOptions)) {
1132 Dbg::ConfigureJdwp(runtime_options.GetOrDefault(Opt::JdwpOptions));
1133 }
1134 callbacks_->AddThreadLifecycleCallback(Dbg::GetThreadLifecycleCallback());
1135 callbacks_->AddClassLoadCallback(Dbg::GetClassLoadCallback());
1136
1137 jit_options_.reset(jit::JitOptions::CreateFromRuntimeArguments(runtime_options));
1138 if (IsAotCompiler()) {
1139 // If we are already the compiler at this point, we must be dex2oat. Don't create the jit in
1140 // this case.
1141 // If runtime_options doesn't have UseJIT set to true then CreateFromRuntimeArguments returns
1142 // null and we don't create the jit.
1143 jit_options_->SetUseJitCompilation(false);
1144 jit_options_->SetSaveProfilingInfo(false);
1145 }
1146
1147 // Use MemMap arena pool for jit, malloc otherwise. Malloc arenas are faster to allocate but
1148 // can't be trimmed as easily.
1149 const bool use_malloc = IsAotCompiler();
1150 arena_pool_.reset(new ArenaPool(use_malloc, /* low_4gb */ false));
1151 jit_arena_pool_.reset(
1152 new ArenaPool(/* use_malloc */ false, /* low_4gb */ false, "CompilerMetadata"));
1153
1154 if (IsAotCompiler() && Is64BitInstructionSet(kRuntimeISA)) {
1155 // 4gb, no malloc. Explanation in header.
1156 low_4gb_arena_pool_.reset(new ArenaPool(/* use_malloc */ false, /* low_4gb */ true));
1157 }
1158 linear_alloc_.reset(CreateLinearAlloc());
1159
1160 BlockSignals();
1161 InitPlatformSignalHandlers();
1162
1163 // Change the implicit checks flags based on runtime architecture.
1164 switch (kRuntimeISA) {
1165 case kArm:
1166 case kThumb2:
1167 case kX86:
1168 case kArm64:
1169 case kX86_64:
1170 case kMips:
1171 case kMips64:
1172 implicit_null_checks_ = true;
1173 // Installing stack protection does not play well with valgrind.
1174 implicit_so_checks_ = !(RUNNING_ON_MEMORY_TOOL && kMemoryToolIsValgrind);
1175 break;
1176 default:
1177 // Keep the defaults.
1178 break;
1179 }
1180
1181 if (!no_sig_chain_) {
1182 // Dex2Oat's Runtime does not need the signal chain or the fault handler.
1183 if (implicit_null_checks_ || implicit_so_checks_ || implicit_suspend_checks_) {
1184 fault_manager.Init();
1185
1186 // These need to be in a specific order. The null point check handler must be
1187 // after the suspend check and stack overflow check handlers.
1188 //
1189 // Note: the instances attach themselves to the fault manager and are handled by it. The manager
1190 // will delete the instance on Shutdown().
1191 if (implicit_suspend_checks_) {
1192 new SuspensionHandler(&fault_manager);
1193 }
1194
1195 if (implicit_so_checks_) {
1196 new StackOverflowHandler(&fault_manager);
1197 }
1198
1199 if (implicit_null_checks_) {
1200 new NullPointerHandler(&fault_manager);
1201 }
1202
1203 if (kEnableJavaStackTraceHandler) {
1204 new JavaStackTraceHandler(&fault_manager);
1205 }
1206 }
1207 }
1208
1209 std::string error_msg;
1210 java_vm_ = JavaVMExt::Create(this, runtime_options, &error_msg);
1211 if (java_vm_.get() == nullptr) {
1212 LOG(ERROR) << "Could not initialize JavaVMExt: " << error_msg;
1213 return false;
1214 }
1215
1216 // Add the JniEnv handler.
1217 // TODO Refactor this stuff.
1218 java_vm_->AddEnvironmentHook(JNIEnvExt::GetEnvHandler);
1219
1220 Thread::Startup();
1221
1222 // ClassLinker needs an attached thread, but we can't fully attach a thread without creating
1223 // objects. We can't supply a thread group yet; it will be fixed later. Since we are the main
1224 // thread, we do not get a java peer.
1225 Thread* self = Thread::Attach("main", false, nullptr, false);
1226 CHECK_EQ(self->GetThreadId(), ThreadList::kMainThreadId);
1227 CHECK(self != nullptr);
1228
1229 self->SetCanCallIntoJava(!IsAotCompiler());
1230
1231 // Set us to runnable so tools using a runtime can allocate and GC by default
1232 self->TransitionFromSuspendedToRunnable();
1233
1234 // Now we're attached, we can take the heap locks and validate the heap.
1235 GetHeap()->EnableObjectValidation();
1236
1237 CHECK_GE(GetHeap()->GetContinuousSpaces().size(), 1U);
1238 class_linker_ = new ClassLinker(intern_table_);
1239 cha_ = new ClassHierarchyAnalysis;
1240 if (GetHeap()->HasBootImageSpace()) {
1241 bool result = class_linker_->InitFromBootImage(&error_msg);
1242 if (!result) {
1243 LOG(ERROR) << "Could not initialize from image: " << error_msg;
1244 return false;
1245 }
1246 if (kIsDebugBuild) {
1247 for (auto image_space : GetHeap()->GetBootImageSpaces()) {
1248 image_space->VerifyImageAllocations();
1249 }
1250 }
1251 if (boot_class_path_string_.empty()) {
1252 // The bootclasspath is not explicitly specified: construct it from the loaded dex files.
1253 const std::vector<const DexFile*>& boot_class_path = GetClassLinker()->GetBootClassPath();
1254 std::vector<std::string> dex_locations;
1255 dex_locations.reserve(boot_class_path.size());
1256 for (const DexFile* dex_file : boot_class_path) {
1257 dex_locations.push_back(dex_file->GetLocation());
1258 }
1259 boot_class_path_string_ = android::base::Join(dex_locations, ':');
1260 }
1261 {
1262 ScopedTrace trace2("AddImageStringsToTable");
1263 GetInternTable()->AddImagesStringsToTable(heap_->GetBootImageSpaces());
1264 }
1265 if (IsJavaDebuggable()) {
1266 // Now that we have loaded the boot image, deoptimize its methods if we are running
1267 // debuggable, as the code may have been compiled non-debuggable.
1268 DeoptimizeBootImage();
1269 }
1270 } else {
1271 std::vector<std::string> dex_filenames;
1272 Split(boot_class_path_string_, ':', &dex_filenames);
1273
1274 std::vector<std::string> dex_locations;
1275 if (!runtime_options.Exists(Opt::BootClassPathLocations)) {
1276 dex_locations = dex_filenames;
1277 } else {
1278 dex_locations = runtime_options.GetOrDefault(Opt::BootClassPathLocations);
1279 CHECK_EQ(dex_filenames.size(), dex_locations.size());
1280 }
1281
1282 std::vector<std::unique_ptr<const DexFile>> boot_class_path;
1283 if (runtime_options.Exists(Opt::BootClassPathDexList)) {
1284 boot_class_path.swap(*runtime_options.GetOrDefault(Opt::BootClassPathDexList));
1285 } else {
1286 OpenDexFiles(dex_filenames,
1287 dex_locations,
1288 runtime_options.GetOrDefault(Opt::Image),
1289 &boot_class_path);
1290 }
1291 instruction_set_ = runtime_options.GetOrDefault(Opt::ImageInstructionSet);
1292 if (!class_linker_->InitWithoutImage(std::move(boot_class_path), &error_msg)) {
1293 LOG(ERROR) << "Could not initialize without image: " << error_msg;
1294 return false;
1295 }
1296
1297 // TODO: Should we move the following to InitWithoutImage?
1298 SetInstructionSet(instruction_set_);
1299 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
1300 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
1301 if (!HasCalleeSaveMethod(type)) {
1302 SetCalleeSaveMethod(CreateCalleeSaveMethod(), type);
1303 }
1304 }
1305 }
1306
1307 CHECK(class_linker_ != nullptr);
1308
1309 verifier::MethodVerifier::Init();
1310
1311 if (runtime_options.Exists(Opt::MethodTrace)) {
1312 trace_config_.reset(new TraceConfig());
1313 trace_config_->trace_file = runtime_options.ReleaseOrDefault(Opt::MethodTraceFile);
1314 trace_config_->trace_file_size = runtime_options.ReleaseOrDefault(Opt::MethodTraceFileSize);
1315 trace_config_->trace_mode = Trace::TraceMode::kMethodTracing;
1316 trace_config_->trace_output_mode = runtime_options.Exists(Opt::MethodTraceStreaming) ?
1317 Trace::TraceOutputMode::kStreaming :
1318 Trace::TraceOutputMode::kFile;
1319 }
1320
1321 // TODO: move this to just be an Trace::Start argument
1322 Trace::SetDefaultClockSource(runtime_options.GetOrDefault(Opt::ProfileClock));
1323
1324 // Pre-allocate an OutOfMemoryError for the double-OOME case.
1325 self->ThrowNewException("Ljava/lang/OutOfMemoryError;",
1326 "OutOfMemoryError thrown while trying to throw OutOfMemoryError; "
1327 "no stack trace available");
1328 pre_allocated_OutOfMemoryError_ = GcRoot<mirror::Throwable>(self->GetException());
1329 self->ClearException();
1330
1331 // Pre-allocate a NoClassDefFoundError for the common case of failing to find a system class
1332 // ahead of checking the application's class loader.
1333 self->ThrowNewException("Ljava/lang/NoClassDefFoundError;",
1334 "Class not found using the boot class loader; no stack trace available");
1335 pre_allocated_NoClassDefFoundError_ = GcRoot<mirror::Throwable>(self->GetException());
1336 self->ClearException();
1337
1338 // Runtime initialization is largely done now.
1339 // We load plugins first since that can modify the runtime state slightly.
1340 // Load all plugins
1341 for (auto& plugin : plugins_) {
1342 std::string err;
1343 if (!plugin.Load(&err)) {
1344 LOG(FATAL) << plugin << " failed to load: " << err;
1345 }
1346 }
1347
1348 // Look for a native bridge.
1349 //
1350 // The intended flow here is, in the case of a running system:
1351 //
1352 // Runtime::Init() (zygote):
1353 // LoadNativeBridge -> dlopen from cmd line parameter.
1354 // |
1355 // V
1356 // Runtime::Start() (zygote):
1357 // No-op wrt native bridge.
1358 // |
1359 // | start app
1360 // V
1361 // DidForkFromZygote(action)
1362 // action = kUnload -> dlclose native bridge.
1363 // action = kInitialize -> initialize library
1364 //
1365 //
1366 // The intended flow here is, in the case of a simple dalvikvm call:
1367 //
1368 // Runtime::Init():
1369 // LoadNativeBridge -> dlopen from cmd line parameter.
1370 // |
1371 // V
1372 // Runtime::Start():
1373 // DidForkFromZygote(kInitialize) -> try to initialize any native bridge given.
1374 // No-op wrt native bridge.
1375 {
1376 std::string native_bridge_file_name = runtime_options.ReleaseOrDefault(Opt::NativeBridge);
1377 is_native_bridge_loaded_ = LoadNativeBridge(native_bridge_file_name);
1378 }
1379
1380 // Startup agents
1381 // TODO Maybe we should start a new thread to run these on. Investigate RI behavior more.
1382 for (auto& agent : agents_) {
1383 // TODO Check err
1384 int res = 0;
1385 std::string err = "";
1386 ti::Agent::LoadError result = agent.Load(&res, &err);
1387 if (result == ti::Agent::kInitializationError) {
1388 LOG(FATAL) << "Unable to initialize agent!";
1389 } else if (result != ti::Agent::kNoError) {
1390 LOG(ERROR) << "Unable to load an agent: " << err;
1391 }
1392 }
1393 {
1394 ScopedObjectAccess soa(self);
1395 callbacks_->NextRuntimePhase(RuntimePhaseCallback::RuntimePhase::kInitialAgents);
1396 }
1397
1398 VLOG(startup) << "Runtime::Init exiting";
1399
1400 return true;
1401 }
1402
EnsureJvmtiPlugin(Runtime * runtime,std::vector<Plugin> * plugins,std::string * error_msg)1403 static bool EnsureJvmtiPlugin(Runtime* runtime,
1404 std::vector<Plugin>* plugins,
1405 std::string* error_msg) {
1406 constexpr const char* plugin_name = kIsDebugBuild ? "libopenjdkjvmtid.so" : "libopenjdkjvmti.so";
1407
1408 // Is the plugin already loaded?
1409 for (const Plugin& p : *plugins) {
1410 if (p.GetLibrary() == plugin_name) {
1411 return true;
1412 }
1413 }
1414
1415 // Is the process debuggable? Otherwise, do not attempt to load the plugin.
1416 if (!runtime->IsJavaDebuggable()) {
1417 *error_msg = "Process is not debuggable.";
1418 return false;
1419 }
1420
1421 Plugin new_plugin = Plugin::Create(plugin_name);
1422
1423 if (!new_plugin.Load(error_msg)) {
1424 return false;
1425 }
1426
1427 plugins->push_back(std::move(new_plugin));
1428 return true;
1429 }
1430
1431 // Attach a new agent and add it to the list of runtime agents
1432 //
1433 // TODO: once we decide on the threading model for agents,
1434 // revisit this and make sure we're doing this on the right thread
1435 // (and we synchronize access to any shared data structures like "agents_")
1436 //
AttachAgent(const std::string & agent_arg)1437 void Runtime::AttachAgent(const std::string& agent_arg) {
1438 std::string error_msg;
1439 if (!EnsureJvmtiPlugin(this, &plugins_, &error_msg)) {
1440 LOG(WARNING) << "Could not load plugin: " << error_msg;
1441 ScopedObjectAccess soa(Thread::Current());
1442 ThrowIOException("%s", error_msg.c_str());
1443 return;
1444 }
1445
1446 ti::Agent agent(agent_arg);
1447
1448 int res = 0;
1449 ti::Agent::LoadError result = agent.Attach(&res, &error_msg);
1450
1451 if (result == ti::Agent::kNoError) {
1452 agents_.push_back(std::move(agent));
1453 } else {
1454 LOG(WARNING) << "Agent attach failed (result=" << result << ") : " << error_msg;
1455 ScopedObjectAccess soa(Thread::Current());
1456 ThrowIOException("%s", error_msg.c_str());
1457 }
1458 }
1459
InitNativeMethods()1460 void Runtime::InitNativeMethods() {
1461 VLOG(startup) << "Runtime::InitNativeMethods entering";
1462 Thread* self = Thread::Current();
1463 JNIEnv* env = self->GetJniEnv();
1464
1465 // Must be in the kNative state for calling native methods (JNI_OnLoad code).
1466 CHECK_EQ(self->GetState(), kNative);
1467
1468 // First set up JniConstants, which is used by both the runtime's built-in native
1469 // methods and libcore.
1470 JniConstants::init(env);
1471
1472 // Then set up the native methods provided by the runtime itself.
1473 RegisterRuntimeNativeMethods(env);
1474
1475 // Initialize classes used in JNI. The initialization requires runtime native
1476 // methods to be loaded first.
1477 WellKnownClasses::Init(env);
1478
1479 // Then set up libjavacore / libopenjdk, which are just a regular JNI libraries with
1480 // a regular JNI_OnLoad. Most JNI libraries can just use System.loadLibrary, but
1481 // libcore can't because it's the library that implements System.loadLibrary!
1482 {
1483 std::string error_msg;
1484 if (!java_vm_->LoadNativeLibrary(env, "libjavacore.so", nullptr, nullptr, &error_msg)) {
1485 LOG(FATAL) << "LoadNativeLibrary failed for \"libjavacore.so\": " << error_msg;
1486 }
1487 }
1488 {
1489 constexpr const char* kOpenJdkLibrary = kIsDebugBuild
1490 ? "libopenjdkd.so"
1491 : "libopenjdk.so";
1492 std::string error_msg;
1493 if (!java_vm_->LoadNativeLibrary(env, kOpenJdkLibrary, nullptr, nullptr, &error_msg)) {
1494 LOG(FATAL) << "LoadNativeLibrary failed for \"" << kOpenJdkLibrary << "\": " << error_msg;
1495 }
1496 }
1497
1498 // Initialize well known classes that may invoke runtime native methods.
1499 WellKnownClasses::LateInit(env);
1500
1501 VLOG(startup) << "Runtime::InitNativeMethods exiting";
1502 }
1503
ReclaimArenaPoolMemory()1504 void Runtime::ReclaimArenaPoolMemory() {
1505 arena_pool_->LockReclaimMemory();
1506 }
1507
InitThreadGroups(Thread * self)1508 void Runtime::InitThreadGroups(Thread* self) {
1509 JNIEnvExt* env = self->GetJniEnv();
1510 ScopedJniEnvLocalRefState env_state(env);
1511 main_thread_group_ =
1512 env->NewGlobalRef(env->GetStaticObjectField(
1513 WellKnownClasses::java_lang_ThreadGroup,
1514 WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup));
1515 CHECK(main_thread_group_ != nullptr || IsAotCompiler());
1516 system_thread_group_ =
1517 env->NewGlobalRef(env->GetStaticObjectField(
1518 WellKnownClasses::java_lang_ThreadGroup,
1519 WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup));
1520 CHECK(system_thread_group_ != nullptr || IsAotCompiler());
1521 }
1522
GetMainThreadGroup() const1523 jobject Runtime::GetMainThreadGroup() const {
1524 CHECK(main_thread_group_ != nullptr || IsAotCompiler());
1525 return main_thread_group_;
1526 }
1527
GetSystemThreadGroup() const1528 jobject Runtime::GetSystemThreadGroup() const {
1529 CHECK(system_thread_group_ != nullptr || IsAotCompiler());
1530 return system_thread_group_;
1531 }
1532
GetSystemClassLoader() const1533 jobject Runtime::GetSystemClassLoader() const {
1534 CHECK(system_class_loader_ != nullptr || IsAotCompiler());
1535 return system_class_loader_;
1536 }
1537
RegisterRuntimeNativeMethods(JNIEnv * env)1538 void Runtime::RegisterRuntimeNativeMethods(JNIEnv* env) {
1539 register_dalvik_system_DexFile(env);
1540 register_dalvik_system_VMDebug(env);
1541 register_dalvik_system_VMRuntime(env);
1542 register_dalvik_system_VMStack(env);
1543 register_dalvik_system_ZygoteHooks(env);
1544 register_java_lang_Class(env);
1545 register_java_lang_Object(env);
1546 register_java_lang_invoke_MethodHandleImpl(env);
1547 register_java_lang_ref_FinalizerReference(env);
1548 register_java_lang_reflect_Array(env);
1549 register_java_lang_reflect_Constructor(env);
1550 register_java_lang_reflect_Executable(env);
1551 register_java_lang_reflect_Field(env);
1552 register_java_lang_reflect_Method(env);
1553 register_java_lang_reflect_Parameter(env);
1554 register_java_lang_reflect_Proxy(env);
1555 register_java_lang_ref_Reference(env);
1556 register_java_lang_String(env);
1557 register_java_lang_StringFactory(env);
1558 register_java_lang_System(env);
1559 register_java_lang_Thread(env);
1560 register_java_lang_Throwable(env);
1561 register_java_lang_VMClassLoader(env);
1562 register_java_lang_Void(env);
1563 register_java_util_concurrent_atomic_AtomicLong(env);
1564 register_libcore_util_CharsetUtils(env);
1565 register_org_apache_harmony_dalvik_ddmc_DdmServer(env);
1566 register_org_apache_harmony_dalvik_ddmc_DdmVmInternal(env);
1567 register_sun_misc_Unsafe(env);
1568 }
1569
operator <<(std::ostream & os,const DeoptimizationKind & kind)1570 std::ostream& operator<<(std::ostream& os, const DeoptimizationKind& kind) {
1571 os << GetDeoptimizationKindName(kind);
1572 return os;
1573 }
1574
DumpDeoptimizations(std::ostream & os)1575 void Runtime::DumpDeoptimizations(std::ostream& os) {
1576 for (size_t i = 0; i <= static_cast<size_t>(DeoptimizationKind::kLast); ++i) {
1577 if (deoptimization_counts_[i] != 0) {
1578 os << "Number of "
1579 << GetDeoptimizationKindName(static_cast<DeoptimizationKind>(i))
1580 << " deoptimizations: "
1581 << deoptimization_counts_[i]
1582 << "\n";
1583 }
1584 }
1585 }
1586
DumpForSigQuit(std::ostream & os)1587 void Runtime::DumpForSigQuit(std::ostream& os) {
1588 GetClassLinker()->DumpForSigQuit(os);
1589 GetInternTable()->DumpForSigQuit(os);
1590 GetJavaVM()->DumpForSigQuit(os);
1591 GetHeap()->DumpForSigQuit(os);
1592 oat_file_manager_->DumpForSigQuit(os);
1593 if (GetJit() != nullptr) {
1594 GetJit()->DumpForSigQuit(os);
1595 } else {
1596 os << "Running non JIT\n";
1597 }
1598 DumpDeoptimizations(os);
1599 TrackedAllocators::Dump(os);
1600 os << "\n";
1601
1602 thread_list_->DumpForSigQuit(os);
1603 BaseMutex::DumpAll(os);
1604
1605 // Inform anyone else who is interested in SigQuit.
1606 {
1607 ScopedObjectAccess soa(Thread::Current());
1608 callbacks_->SigQuit();
1609 }
1610 }
1611
DumpLockHolders(std::ostream & os)1612 void Runtime::DumpLockHolders(std::ostream& os) {
1613 uint64_t mutator_lock_owner = Locks::mutator_lock_->GetExclusiveOwnerTid();
1614 pid_t thread_list_lock_owner = GetThreadList()->GetLockOwner();
1615 pid_t classes_lock_owner = GetClassLinker()->GetClassesLockOwner();
1616 pid_t dex_lock_owner = GetClassLinker()->GetDexLockOwner();
1617 if ((thread_list_lock_owner | classes_lock_owner | dex_lock_owner) != 0) {
1618 os << "Mutator lock exclusive owner tid: " << mutator_lock_owner << "\n"
1619 << "ThreadList lock owner tid: " << thread_list_lock_owner << "\n"
1620 << "ClassLinker classes lock owner tid: " << classes_lock_owner << "\n"
1621 << "ClassLinker dex lock owner tid: " << dex_lock_owner << "\n";
1622 }
1623 }
1624
SetStatsEnabled(bool new_state)1625 void Runtime::SetStatsEnabled(bool new_state) {
1626 Thread* self = Thread::Current();
1627 MutexLock mu(self, *Locks::instrument_entrypoints_lock_);
1628 if (new_state == true) {
1629 GetStats()->Clear(~0);
1630 // TODO: wouldn't it make more sense to clear _all_ threads' stats?
1631 self->GetStats()->Clear(~0);
1632 if (stats_enabled_ != new_state) {
1633 GetInstrumentation()->InstrumentQuickAllocEntryPointsLocked();
1634 }
1635 } else if (stats_enabled_ != new_state) {
1636 GetInstrumentation()->UninstrumentQuickAllocEntryPointsLocked();
1637 }
1638 stats_enabled_ = new_state;
1639 }
1640
ResetStats(int kinds)1641 void Runtime::ResetStats(int kinds) {
1642 GetStats()->Clear(kinds & 0xffff);
1643 // TODO: wouldn't it make more sense to clear _all_ threads' stats?
1644 Thread::Current()->GetStats()->Clear(kinds >> 16);
1645 }
1646
GetStat(int kind)1647 int32_t Runtime::GetStat(int kind) {
1648 RuntimeStats* stats;
1649 if (kind < (1<<16)) {
1650 stats = GetStats();
1651 } else {
1652 stats = Thread::Current()->GetStats();
1653 kind >>= 16;
1654 }
1655 switch (kind) {
1656 case KIND_ALLOCATED_OBJECTS:
1657 return stats->allocated_objects;
1658 case KIND_ALLOCATED_BYTES:
1659 return stats->allocated_bytes;
1660 case KIND_FREED_OBJECTS:
1661 return stats->freed_objects;
1662 case KIND_FREED_BYTES:
1663 return stats->freed_bytes;
1664 case KIND_GC_INVOCATIONS:
1665 return stats->gc_for_alloc_count;
1666 case KIND_CLASS_INIT_COUNT:
1667 return stats->class_init_count;
1668 case KIND_CLASS_INIT_TIME:
1669 // Convert ns to us, reduce to 32 bits.
1670 return static_cast<int>(stats->class_init_time_ns / 1000);
1671 case KIND_EXT_ALLOCATED_OBJECTS:
1672 case KIND_EXT_ALLOCATED_BYTES:
1673 case KIND_EXT_FREED_OBJECTS:
1674 case KIND_EXT_FREED_BYTES:
1675 return 0; // backward compatibility
1676 default:
1677 LOG(FATAL) << "Unknown statistic " << kind;
1678 return -1; // unreachable
1679 }
1680 }
1681
BlockSignals()1682 void Runtime::BlockSignals() {
1683 SignalSet signals;
1684 signals.Add(SIGPIPE);
1685 // SIGQUIT is used to dump the runtime's state (including stack traces).
1686 signals.Add(SIGQUIT);
1687 // SIGUSR1 is used to initiate a GC.
1688 signals.Add(SIGUSR1);
1689 signals.Block();
1690 }
1691
AttachCurrentThread(const char * thread_name,bool as_daemon,jobject thread_group,bool create_peer)1692 bool Runtime::AttachCurrentThread(const char* thread_name, bool as_daemon, jobject thread_group,
1693 bool create_peer) {
1694 ScopedTrace trace(__FUNCTION__);
1695 return Thread::Attach(thread_name, as_daemon, thread_group, create_peer) != nullptr;
1696 }
1697
DetachCurrentThread()1698 void Runtime::DetachCurrentThread() {
1699 ScopedTrace trace(__FUNCTION__);
1700 Thread* self = Thread::Current();
1701 if (self == nullptr) {
1702 LOG(FATAL) << "attempting to detach thread that is not attached";
1703 }
1704 if (self->HasManagedStack()) {
1705 LOG(FATAL) << *Thread::Current() << " attempting to detach while still running code";
1706 }
1707 thread_list_->Unregister(self);
1708 }
1709
GetPreAllocatedOutOfMemoryError()1710 mirror::Throwable* Runtime::GetPreAllocatedOutOfMemoryError() {
1711 mirror::Throwable* oome = pre_allocated_OutOfMemoryError_.Read();
1712 if (oome == nullptr) {
1713 LOG(ERROR) << "Failed to return pre-allocated OOME";
1714 }
1715 return oome;
1716 }
1717
GetPreAllocatedNoClassDefFoundError()1718 mirror::Throwable* Runtime::GetPreAllocatedNoClassDefFoundError() {
1719 mirror::Throwable* ncdfe = pre_allocated_NoClassDefFoundError_.Read();
1720 if (ncdfe == nullptr) {
1721 LOG(ERROR) << "Failed to return pre-allocated NoClassDefFoundError";
1722 }
1723 return ncdfe;
1724 }
1725
VisitConstantRoots(RootVisitor * visitor)1726 void Runtime::VisitConstantRoots(RootVisitor* visitor) {
1727 // Visit the classes held as static in mirror classes, these can be visited concurrently and only
1728 // need to be visited once per GC since they never change.
1729 mirror::Class::VisitRoots(visitor);
1730 mirror::Constructor::VisitRoots(visitor);
1731 mirror::Reference::VisitRoots(visitor);
1732 mirror::Method::VisitRoots(visitor);
1733 mirror::StackTraceElement::VisitRoots(visitor);
1734 mirror::String::VisitRoots(visitor);
1735 mirror::Throwable::VisitRoots(visitor);
1736 mirror::Field::VisitRoots(visitor);
1737 mirror::MethodType::VisitRoots(visitor);
1738 mirror::MethodHandleImpl::VisitRoots(visitor);
1739 mirror::MethodHandlesLookup::VisitRoots(visitor);
1740 mirror::EmulatedStackFrame::VisitRoots(visitor);
1741 mirror::ClassExt::VisitRoots(visitor);
1742 mirror::CallSite::VisitRoots(visitor);
1743 // Visit all the primitive array types classes.
1744 mirror::PrimitiveArray<uint8_t>::VisitRoots(visitor); // BooleanArray
1745 mirror::PrimitiveArray<int8_t>::VisitRoots(visitor); // ByteArray
1746 mirror::PrimitiveArray<uint16_t>::VisitRoots(visitor); // CharArray
1747 mirror::PrimitiveArray<double>::VisitRoots(visitor); // DoubleArray
1748 mirror::PrimitiveArray<float>::VisitRoots(visitor); // FloatArray
1749 mirror::PrimitiveArray<int32_t>::VisitRoots(visitor); // IntArray
1750 mirror::PrimitiveArray<int64_t>::VisitRoots(visitor); // LongArray
1751 mirror::PrimitiveArray<int16_t>::VisitRoots(visitor); // ShortArray
1752 // Visiting the roots of these ArtMethods is not currently required since all the GcRoots are
1753 // null.
1754 BufferedRootVisitor<16> buffered_visitor(visitor, RootInfo(kRootVMInternal));
1755 const PointerSize pointer_size = GetClassLinker()->GetImagePointerSize();
1756 if (HasResolutionMethod()) {
1757 resolution_method_->VisitRoots(buffered_visitor, pointer_size);
1758 }
1759 if (HasImtConflictMethod()) {
1760 imt_conflict_method_->VisitRoots(buffered_visitor, pointer_size);
1761 }
1762 if (imt_unimplemented_method_ != nullptr) {
1763 imt_unimplemented_method_->VisitRoots(buffered_visitor, pointer_size);
1764 }
1765 for (size_t i = 0; i < kLastCalleeSaveType; ++i) {
1766 auto* m = reinterpret_cast<ArtMethod*>(callee_save_methods_[i]);
1767 if (m != nullptr) {
1768 m->VisitRoots(buffered_visitor, pointer_size);
1769 }
1770 }
1771 }
1772
VisitConcurrentRoots(RootVisitor * visitor,VisitRootFlags flags)1773 void Runtime::VisitConcurrentRoots(RootVisitor* visitor, VisitRootFlags flags) {
1774 intern_table_->VisitRoots(visitor, flags);
1775 class_linker_->VisitRoots(visitor, flags);
1776 heap_->VisitAllocationRecords(visitor);
1777 if ((flags & kVisitRootFlagNewRoots) == 0) {
1778 // Guaranteed to have no new roots in the constant roots.
1779 VisitConstantRoots(visitor);
1780 }
1781 Dbg::VisitRoots(visitor);
1782 }
1783
VisitTransactionRoots(RootVisitor * visitor)1784 void Runtime::VisitTransactionRoots(RootVisitor* visitor) {
1785 if (preinitialization_transaction_ != nullptr) {
1786 preinitialization_transaction_->VisitRoots(visitor);
1787 }
1788 }
1789
VisitNonThreadRoots(RootVisitor * visitor)1790 void Runtime::VisitNonThreadRoots(RootVisitor* visitor) {
1791 java_vm_->VisitRoots(visitor);
1792 sentinel_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
1793 pre_allocated_OutOfMemoryError_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
1794 pre_allocated_NoClassDefFoundError_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
1795 verifier::MethodVerifier::VisitStaticRoots(visitor);
1796 VisitTransactionRoots(visitor);
1797 }
1798
VisitNonConcurrentRoots(RootVisitor * visitor,VisitRootFlags flags)1799 void Runtime::VisitNonConcurrentRoots(RootVisitor* visitor, VisitRootFlags flags) {
1800 VisitThreadRoots(visitor, flags);
1801 VisitNonThreadRoots(visitor);
1802 }
1803
VisitThreadRoots(RootVisitor * visitor,VisitRootFlags flags)1804 void Runtime::VisitThreadRoots(RootVisitor* visitor, VisitRootFlags flags) {
1805 thread_list_->VisitRoots(visitor, flags);
1806 }
1807
FlipThreadRoots(Closure * thread_flip_visitor,Closure * flip_callback,gc::collector::GarbageCollector * collector)1808 size_t Runtime::FlipThreadRoots(Closure* thread_flip_visitor, Closure* flip_callback,
1809 gc::collector::GarbageCollector* collector) {
1810 return thread_list_->FlipThreadRoots(thread_flip_visitor, flip_callback, collector);
1811 }
1812
VisitRoots(RootVisitor * visitor,VisitRootFlags flags)1813 void Runtime::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
1814 VisitNonConcurrentRoots(visitor, flags);
1815 VisitConcurrentRoots(visitor, flags);
1816 }
1817
VisitImageRoots(RootVisitor * visitor)1818 void Runtime::VisitImageRoots(RootVisitor* visitor) {
1819 for (auto* space : GetHeap()->GetContinuousSpaces()) {
1820 if (space->IsImageSpace()) {
1821 auto* image_space = space->AsImageSpace();
1822 const auto& image_header = image_space->GetImageHeader();
1823 for (int32_t i = 0, size = image_header.GetImageRoots()->GetLength(); i != size; ++i) {
1824 auto* obj = image_header.GetImageRoot(static_cast<ImageHeader::ImageRoot>(i));
1825 if (obj != nullptr) {
1826 auto* after_obj = obj;
1827 visitor->VisitRoot(&after_obj, RootInfo(kRootStickyClass));
1828 CHECK_EQ(after_obj, obj);
1829 }
1830 }
1831 }
1832 }
1833 }
1834
CreateRuntimeMethod(ClassLinker * class_linker,LinearAlloc * linear_alloc)1835 static ArtMethod* CreateRuntimeMethod(ClassLinker* class_linker, LinearAlloc* linear_alloc) {
1836 const PointerSize image_pointer_size = class_linker->GetImagePointerSize();
1837 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size);
1838 const size_t method_size = ArtMethod::Size(image_pointer_size);
1839 LengthPrefixedArray<ArtMethod>* method_array = class_linker->AllocArtMethodArray(
1840 Thread::Current(),
1841 linear_alloc,
1842 1);
1843 ArtMethod* method = &method_array->At(0, method_size, method_alignment);
1844 CHECK(method != nullptr);
1845 method->SetDexMethodIndex(DexFile::kDexNoIndex);
1846 CHECK(method->IsRuntimeMethod());
1847 return method;
1848 }
1849
CreateImtConflictMethod(LinearAlloc * linear_alloc)1850 ArtMethod* Runtime::CreateImtConflictMethod(LinearAlloc* linear_alloc) {
1851 ClassLinker* const class_linker = GetClassLinker();
1852 ArtMethod* method = CreateRuntimeMethod(class_linker, linear_alloc);
1853 // When compiling, the code pointer will get set later when the image is loaded.
1854 const PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set_);
1855 if (IsAotCompiler()) {
1856 method->SetEntryPointFromQuickCompiledCodePtrSize(nullptr, pointer_size);
1857 } else {
1858 method->SetEntryPointFromQuickCompiledCode(GetQuickImtConflictStub());
1859 }
1860 // Create empty conflict table.
1861 method->SetImtConflictTable(class_linker->CreateImtConflictTable(/*count*/0u, linear_alloc),
1862 pointer_size);
1863 return method;
1864 }
1865
SetImtConflictMethod(ArtMethod * method)1866 void Runtime::SetImtConflictMethod(ArtMethod* method) {
1867 CHECK(method != nullptr);
1868 CHECK(method->IsRuntimeMethod());
1869 imt_conflict_method_ = method;
1870 }
1871
CreateResolutionMethod()1872 ArtMethod* Runtime::CreateResolutionMethod() {
1873 auto* method = CreateRuntimeMethod(GetClassLinker(), GetLinearAlloc());
1874 // When compiling, the code pointer will get set later when the image is loaded.
1875 if (IsAotCompiler()) {
1876 PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set_);
1877 method->SetEntryPointFromQuickCompiledCodePtrSize(nullptr, pointer_size);
1878 } else {
1879 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
1880 }
1881 return method;
1882 }
1883
CreateCalleeSaveMethod()1884 ArtMethod* Runtime::CreateCalleeSaveMethod() {
1885 auto* method = CreateRuntimeMethod(GetClassLinker(), GetLinearAlloc());
1886 PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set_);
1887 method->SetEntryPointFromQuickCompiledCodePtrSize(nullptr, pointer_size);
1888 DCHECK_NE(instruction_set_, kNone);
1889 DCHECK(method->IsRuntimeMethod());
1890 return method;
1891 }
1892
DisallowNewSystemWeaks()1893 void Runtime::DisallowNewSystemWeaks() {
1894 CHECK(!kUseReadBarrier);
1895 monitor_list_->DisallowNewMonitors();
1896 intern_table_->ChangeWeakRootState(gc::kWeakRootStateNoReadsOrWrites);
1897 java_vm_->DisallowNewWeakGlobals();
1898 heap_->DisallowNewAllocationRecords();
1899 if (GetJit() != nullptr) {
1900 GetJit()->GetCodeCache()->DisallowInlineCacheAccess();
1901 }
1902
1903 // All other generic system-weak holders.
1904 for (gc::AbstractSystemWeakHolder* holder : system_weak_holders_) {
1905 holder->Disallow();
1906 }
1907 }
1908
AllowNewSystemWeaks()1909 void Runtime::AllowNewSystemWeaks() {
1910 CHECK(!kUseReadBarrier);
1911 monitor_list_->AllowNewMonitors();
1912 intern_table_->ChangeWeakRootState(gc::kWeakRootStateNormal); // TODO: Do this in the sweeping.
1913 java_vm_->AllowNewWeakGlobals();
1914 heap_->AllowNewAllocationRecords();
1915 if (GetJit() != nullptr) {
1916 GetJit()->GetCodeCache()->AllowInlineCacheAccess();
1917 }
1918
1919 // All other generic system-weak holders.
1920 for (gc::AbstractSystemWeakHolder* holder : system_weak_holders_) {
1921 holder->Allow();
1922 }
1923 }
1924
BroadcastForNewSystemWeaks(bool broadcast_for_checkpoint)1925 void Runtime::BroadcastForNewSystemWeaks(bool broadcast_for_checkpoint) {
1926 // This is used for the read barrier case that uses the thread-local
1927 // Thread::GetWeakRefAccessEnabled() flag and the checkpoint while weak ref access is disabled
1928 // (see ThreadList::RunCheckpoint).
1929 monitor_list_->BroadcastForNewMonitors();
1930 intern_table_->BroadcastForNewInterns();
1931 java_vm_->BroadcastForNewWeakGlobals();
1932 heap_->BroadcastForNewAllocationRecords();
1933 if (GetJit() != nullptr) {
1934 GetJit()->GetCodeCache()->BroadcastForInlineCacheAccess();
1935 }
1936
1937 // All other generic system-weak holders.
1938 for (gc::AbstractSystemWeakHolder* holder : system_weak_holders_) {
1939 holder->Broadcast(broadcast_for_checkpoint);
1940 }
1941 }
1942
SetInstructionSet(InstructionSet instruction_set)1943 void Runtime::SetInstructionSet(InstructionSet instruction_set) {
1944 instruction_set_ = instruction_set;
1945 if ((instruction_set_ == kThumb2) || (instruction_set_ == kArm)) {
1946 for (int i = 0; i != kLastCalleeSaveType; ++i) {
1947 CalleeSaveType type = static_cast<CalleeSaveType>(i);
1948 callee_save_method_frame_infos_[i] = arm::ArmCalleeSaveMethodFrameInfo(type);
1949 }
1950 } else if (instruction_set_ == kMips) {
1951 for (int i = 0; i != kLastCalleeSaveType; ++i) {
1952 CalleeSaveType type = static_cast<CalleeSaveType>(i);
1953 callee_save_method_frame_infos_[i] = mips::MipsCalleeSaveMethodFrameInfo(type);
1954 }
1955 } else if (instruction_set_ == kMips64) {
1956 for (int i = 0; i != kLastCalleeSaveType; ++i) {
1957 CalleeSaveType type = static_cast<CalleeSaveType>(i);
1958 callee_save_method_frame_infos_[i] = mips64::Mips64CalleeSaveMethodFrameInfo(type);
1959 }
1960 } else if (instruction_set_ == kX86) {
1961 for (int i = 0; i != kLastCalleeSaveType; ++i) {
1962 CalleeSaveType type = static_cast<CalleeSaveType>(i);
1963 callee_save_method_frame_infos_[i] = x86::X86CalleeSaveMethodFrameInfo(type);
1964 }
1965 } else if (instruction_set_ == kX86_64) {
1966 for (int i = 0; i != kLastCalleeSaveType; ++i) {
1967 CalleeSaveType type = static_cast<CalleeSaveType>(i);
1968 callee_save_method_frame_infos_[i] = x86_64::X86_64CalleeSaveMethodFrameInfo(type);
1969 }
1970 } else if (instruction_set_ == kArm64) {
1971 for (int i = 0; i != kLastCalleeSaveType; ++i) {
1972 CalleeSaveType type = static_cast<CalleeSaveType>(i);
1973 callee_save_method_frame_infos_[i] = arm64::Arm64CalleeSaveMethodFrameInfo(type);
1974 }
1975 } else {
1976 UNIMPLEMENTED(FATAL) << instruction_set_;
1977 }
1978 }
1979
ClearInstructionSet()1980 void Runtime::ClearInstructionSet() {
1981 instruction_set_ = InstructionSet::kNone;
1982 }
1983
SetCalleeSaveMethod(ArtMethod * method,CalleeSaveType type)1984 void Runtime::SetCalleeSaveMethod(ArtMethod* method, CalleeSaveType type) {
1985 DCHECK_LT(static_cast<int>(type), static_cast<int>(kLastCalleeSaveType));
1986 CHECK(method != nullptr);
1987 callee_save_methods_[type] = reinterpret_cast<uintptr_t>(method);
1988 }
1989
ClearCalleeSaveMethods()1990 void Runtime::ClearCalleeSaveMethods() {
1991 for (size_t i = 0; i < static_cast<size_t>(kLastCalleeSaveType); ++i) {
1992 CalleeSaveType type = static_cast<CalleeSaveType>(i);
1993 callee_save_methods_[type] = reinterpret_cast<uintptr_t>(nullptr);
1994 }
1995 }
1996
RegisterAppInfo(const std::vector<std::string> & code_paths,const std::string & profile_output_filename)1997 void Runtime::RegisterAppInfo(const std::vector<std::string>& code_paths,
1998 const std::string& profile_output_filename) {
1999 if (jit_.get() == nullptr) {
2000 // We are not JITing. Nothing to do.
2001 return;
2002 }
2003
2004 VLOG(profiler) << "Register app with " << profile_output_filename
2005 << " " << android::base::Join(code_paths, ':');
2006
2007 if (profile_output_filename.empty()) {
2008 LOG(WARNING) << "JIT profile information will not be recorded: profile filename is empty.";
2009 return;
2010 }
2011 if (!FileExists(profile_output_filename)) {
2012 LOG(WARNING) << "JIT profile information will not be recorded: profile file does not exits.";
2013 return;
2014 }
2015 if (code_paths.empty()) {
2016 LOG(WARNING) << "JIT profile information will not be recorded: code paths is empty.";
2017 return;
2018 }
2019
2020 jit_->StartProfileSaver(profile_output_filename, code_paths);
2021 }
2022
2023 // Transaction support.
EnterTransactionMode(Transaction * transaction)2024 void Runtime::EnterTransactionMode(Transaction* transaction) {
2025 DCHECK(IsAotCompiler());
2026 DCHECK(transaction != nullptr);
2027 DCHECK(!IsActiveTransaction());
2028 preinitialization_transaction_ = transaction;
2029 }
2030
ExitTransactionMode()2031 void Runtime::ExitTransactionMode() {
2032 DCHECK(IsAotCompiler());
2033 DCHECK(IsActiveTransaction());
2034 preinitialization_transaction_ = nullptr;
2035 }
2036
IsTransactionAborted() const2037 bool Runtime::IsTransactionAborted() const {
2038 if (!IsActiveTransaction()) {
2039 return false;
2040 } else {
2041 DCHECK(IsAotCompiler());
2042 return preinitialization_transaction_->IsAborted();
2043 }
2044 }
2045
AbortTransactionAndThrowAbortError(Thread * self,const std::string & abort_message)2046 void Runtime::AbortTransactionAndThrowAbortError(Thread* self, const std::string& abort_message) {
2047 DCHECK(IsAotCompiler());
2048 DCHECK(IsActiveTransaction());
2049 // Throwing an exception may cause its class initialization. If we mark the transaction
2050 // aborted before that, we may warn with a false alarm. Throwing the exception before
2051 // marking the transaction aborted avoids that.
2052 preinitialization_transaction_->ThrowAbortError(self, &abort_message);
2053 preinitialization_transaction_->Abort(abort_message);
2054 }
2055
ThrowTransactionAbortError(Thread * self)2056 void Runtime::ThrowTransactionAbortError(Thread* self) {
2057 DCHECK(IsAotCompiler());
2058 DCHECK(IsActiveTransaction());
2059 // Passing nullptr means we rethrow an exception with the earlier transaction abort message.
2060 preinitialization_transaction_->ThrowAbortError(self, nullptr);
2061 }
2062
RecordWriteFieldBoolean(mirror::Object * obj,MemberOffset field_offset,uint8_t value,bool is_volatile) const2063 void Runtime::RecordWriteFieldBoolean(mirror::Object* obj, MemberOffset field_offset,
2064 uint8_t value, bool is_volatile) const {
2065 DCHECK(IsAotCompiler());
2066 DCHECK(IsActiveTransaction());
2067 preinitialization_transaction_->RecordWriteFieldBoolean(obj, field_offset, value, is_volatile);
2068 }
2069
RecordWriteFieldByte(mirror::Object * obj,MemberOffset field_offset,int8_t value,bool is_volatile) const2070 void Runtime::RecordWriteFieldByte(mirror::Object* obj, MemberOffset field_offset,
2071 int8_t value, bool is_volatile) const {
2072 DCHECK(IsAotCompiler());
2073 DCHECK(IsActiveTransaction());
2074 preinitialization_transaction_->RecordWriteFieldByte(obj, field_offset, value, is_volatile);
2075 }
2076
RecordWriteFieldChar(mirror::Object * obj,MemberOffset field_offset,uint16_t value,bool is_volatile) const2077 void Runtime::RecordWriteFieldChar(mirror::Object* obj, MemberOffset field_offset,
2078 uint16_t value, bool is_volatile) const {
2079 DCHECK(IsAotCompiler());
2080 DCHECK(IsActiveTransaction());
2081 preinitialization_transaction_->RecordWriteFieldChar(obj, field_offset, value, is_volatile);
2082 }
2083
RecordWriteFieldShort(mirror::Object * obj,MemberOffset field_offset,int16_t value,bool is_volatile) const2084 void Runtime::RecordWriteFieldShort(mirror::Object* obj, MemberOffset field_offset,
2085 int16_t value, bool is_volatile) const {
2086 DCHECK(IsAotCompiler());
2087 DCHECK(IsActiveTransaction());
2088 preinitialization_transaction_->RecordWriteFieldShort(obj, field_offset, value, is_volatile);
2089 }
2090
RecordWriteField32(mirror::Object * obj,MemberOffset field_offset,uint32_t value,bool is_volatile) const2091 void Runtime::RecordWriteField32(mirror::Object* obj, MemberOffset field_offset,
2092 uint32_t value, bool is_volatile) const {
2093 DCHECK(IsAotCompiler());
2094 DCHECK(IsActiveTransaction());
2095 preinitialization_transaction_->RecordWriteField32(obj, field_offset, value, is_volatile);
2096 }
2097
RecordWriteField64(mirror::Object * obj,MemberOffset field_offset,uint64_t value,bool is_volatile) const2098 void Runtime::RecordWriteField64(mirror::Object* obj, MemberOffset field_offset,
2099 uint64_t value, bool is_volatile) const {
2100 DCHECK(IsAotCompiler());
2101 DCHECK(IsActiveTransaction());
2102 preinitialization_transaction_->RecordWriteField64(obj, field_offset, value, is_volatile);
2103 }
2104
RecordWriteFieldReference(mirror::Object * obj,MemberOffset field_offset,ObjPtr<mirror::Object> value,bool is_volatile) const2105 void Runtime::RecordWriteFieldReference(mirror::Object* obj,
2106 MemberOffset field_offset,
2107 ObjPtr<mirror::Object> value,
2108 bool is_volatile) const {
2109 DCHECK(IsAotCompiler());
2110 DCHECK(IsActiveTransaction());
2111 preinitialization_transaction_->RecordWriteFieldReference(obj,
2112 field_offset,
2113 value.Ptr(),
2114 is_volatile);
2115 }
2116
RecordWriteArray(mirror::Array * array,size_t index,uint64_t value) const2117 void Runtime::RecordWriteArray(mirror::Array* array, size_t index, uint64_t value) const {
2118 DCHECK(IsAotCompiler());
2119 DCHECK(IsActiveTransaction());
2120 preinitialization_transaction_->RecordWriteArray(array, index, value);
2121 }
2122
RecordStrongStringInsertion(ObjPtr<mirror::String> s) const2123 void Runtime::RecordStrongStringInsertion(ObjPtr<mirror::String> s) const {
2124 DCHECK(IsAotCompiler());
2125 DCHECK(IsActiveTransaction());
2126 preinitialization_transaction_->RecordStrongStringInsertion(s);
2127 }
2128
RecordWeakStringInsertion(ObjPtr<mirror::String> s) const2129 void Runtime::RecordWeakStringInsertion(ObjPtr<mirror::String> s) const {
2130 DCHECK(IsAotCompiler());
2131 DCHECK(IsActiveTransaction());
2132 preinitialization_transaction_->RecordWeakStringInsertion(s);
2133 }
2134
RecordStrongStringRemoval(ObjPtr<mirror::String> s) const2135 void Runtime::RecordStrongStringRemoval(ObjPtr<mirror::String> s) const {
2136 DCHECK(IsAotCompiler());
2137 DCHECK(IsActiveTransaction());
2138 preinitialization_transaction_->RecordStrongStringRemoval(s);
2139 }
2140
RecordWeakStringRemoval(ObjPtr<mirror::String> s) const2141 void Runtime::RecordWeakStringRemoval(ObjPtr<mirror::String> s) const {
2142 DCHECK(IsAotCompiler());
2143 DCHECK(IsActiveTransaction());
2144 preinitialization_transaction_->RecordWeakStringRemoval(s);
2145 }
2146
RecordResolveString(ObjPtr<mirror::DexCache> dex_cache,dex::StringIndex string_idx) const2147 void Runtime::RecordResolveString(ObjPtr<mirror::DexCache> dex_cache,
2148 dex::StringIndex string_idx) const {
2149 DCHECK(IsAotCompiler());
2150 DCHECK(IsActiveTransaction());
2151 preinitialization_transaction_->RecordResolveString(dex_cache, string_idx);
2152 }
2153
SetFaultMessage(const std::string & message)2154 void Runtime::SetFaultMessage(const std::string& message) {
2155 MutexLock mu(Thread::Current(), fault_message_lock_);
2156 fault_message_ = message;
2157 }
2158
AddCurrentRuntimeFeaturesAsDex2OatArguments(std::vector<std::string> * argv) const2159 void Runtime::AddCurrentRuntimeFeaturesAsDex2OatArguments(std::vector<std::string>* argv)
2160 const {
2161 if (GetInstrumentation()->InterpretOnly()) {
2162 argv->push_back("--compiler-filter=quicken");
2163 }
2164
2165 // Make the dex2oat instruction set match that of the launching runtime. If we have multiple
2166 // architecture support, dex2oat may be compiled as a different instruction-set than that
2167 // currently being executed.
2168 std::string instruction_set("--instruction-set=");
2169 instruction_set += GetInstructionSetString(kRuntimeISA);
2170 argv->push_back(instruction_set);
2171
2172 std::unique_ptr<const InstructionSetFeatures> features(InstructionSetFeatures::FromCppDefines());
2173 std::string feature_string("--instruction-set-features=");
2174 feature_string += features->GetFeatureString();
2175 argv->push_back(feature_string);
2176 }
2177
CreateJit()2178 void Runtime::CreateJit() {
2179 CHECK(!IsAotCompiler());
2180 if (kIsDebugBuild && GetInstrumentation()->IsForcedInterpretOnly()) {
2181 DCHECK(!jit_options_->UseJitCompilation());
2182 }
2183 std::string error_msg;
2184 jit_.reset(jit::Jit::Create(jit_options_.get(), &error_msg));
2185 if (jit_.get() == nullptr) {
2186 LOG(WARNING) << "Failed to create JIT " << error_msg;
2187 return;
2188 }
2189
2190 // In case we have a profile path passed as a command line argument,
2191 // register the current class path for profiling now. Note that we cannot do
2192 // this before we create the JIT and having it here is the most convenient way.
2193 // This is used when testing profiles with dalvikvm command as there is no
2194 // framework to register the dex files for profiling.
2195 if (jit_options_->GetSaveProfilingInfo() &&
2196 !jit_options_->GetProfileSaverOptions().GetProfilePath().empty()) {
2197 std::vector<std::string> dex_filenames;
2198 Split(class_path_string_, ':', &dex_filenames);
2199 RegisterAppInfo(dex_filenames, jit_options_->GetProfileSaverOptions().GetProfilePath());
2200 }
2201 }
2202
CanRelocate() const2203 bool Runtime::CanRelocate() const {
2204 return !IsAotCompiler() || compiler_callbacks_->IsRelocationPossible();
2205 }
2206
IsCompilingBootImage() const2207 bool Runtime::IsCompilingBootImage() const {
2208 return IsCompiler() && compiler_callbacks_->IsBootImage();
2209 }
2210
SetResolutionMethod(ArtMethod * method)2211 void Runtime::SetResolutionMethod(ArtMethod* method) {
2212 CHECK(method != nullptr);
2213 CHECK(method->IsRuntimeMethod()) << method;
2214 resolution_method_ = method;
2215 }
2216
SetImtUnimplementedMethod(ArtMethod * method)2217 void Runtime::SetImtUnimplementedMethod(ArtMethod* method) {
2218 CHECK(method != nullptr);
2219 CHECK(method->IsRuntimeMethod());
2220 imt_unimplemented_method_ = method;
2221 }
2222
FixupConflictTables()2223 void Runtime::FixupConflictTables() {
2224 // We can only do this after the class linker is created.
2225 const PointerSize pointer_size = GetClassLinker()->GetImagePointerSize();
2226 if (imt_unimplemented_method_->GetImtConflictTable(pointer_size) == nullptr) {
2227 imt_unimplemented_method_->SetImtConflictTable(
2228 ClassLinker::CreateImtConflictTable(/*count*/0u, GetLinearAlloc(), pointer_size),
2229 pointer_size);
2230 }
2231 if (imt_conflict_method_->GetImtConflictTable(pointer_size) == nullptr) {
2232 imt_conflict_method_->SetImtConflictTable(
2233 ClassLinker::CreateImtConflictTable(/*count*/0u, GetLinearAlloc(), pointer_size),
2234 pointer_size);
2235 }
2236 }
2237
IsVerificationEnabled() const2238 bool Runtime::IsVerificationEnabled() const {
2239 return verify_ == verifier::VerifyMode::kEnable ||
2240 verify_ == verifier::VerifyMode::kSoftFail;
2241 }
2242
IsVerificationSoftFail() const2243 bool Runtime::IsVerificationSoftFail() const {
2244 return verify_ == verifier::VerifyMode::kSoftFail;
2245 }
2246
IsAsyncDeoptimizeable(uintptr_t code) const2247 bool Runtime::IsAsyncDeoptimizeable(uintptr_t code) const {
2248 // We only support async deopt (ie the compiled code is not explicitly asking for
2249 // deopt, but something else like the debugger) in debuggable JIT code.
2250 // We could look at the oat file where `code` is being defined,
2251 // and check whether it's been compiled debuggable, but we decided to
2252 // only rely on the JIT for debuggable apps.
2253 return IsJavaDebuggable() &&
2254 GetJit() != nullptr &&
2255 GetJit()->GetCodeCache()->ContainsPc(reinterpret_cast<const void*>(code));
2256 }
2257
CreateLinearAlloc()2258 LinearAlloc* Runtime::CreateLinearAlloc() {
2259 // For 64 bit compilers, it needs to be in low 4GB in the case where we are cross compiling for a
2260 // 32 bit target. In this case, we have 32 bit pointers in the dex cache arrays which can't hold
2261 // when we have 64 bit ArtMethod pointers.
2262 return (IsAotCompiler() && Is64BitInstructionSet(kRuntimeISA))
2263 ? new LinearAlloc(low_4gb_arena_pool_.get())
2264 : new LinearAlloc(arena_pool_.get());
2265 }
2266
GetHashTableMinLoadFactor() const2267 double Runtime::GetHashTableMinLoadFactor() const {
2268 return is_low_memory_mode_ ? kLowMemoryMinLoadFactor : kNormalMinLoadFactor;
2269 }
2270
GetHashTableMaxLoadFactor() const2271 double Runtime::GetHashTableMaxLoadFactor() const {
2272 return is_low_memory_mode_ ? kLowMemoryMaxLoadFactor : kNormalMaxLoadFactor;
2273 }
2274
UpdateProcessState(ProcessState process_state)2275 void Runtime::UpdateProcessState(ProcessState process_state) {
2276 ProcessState old_process_state = process_state_;
2277 process_state_ = process_state;
2278 GetHeap()->UpdateProcessState(old_process_state, process_state);
2279 }
2280
RegisterSensitiveThread() const2281 void Runtime::RegisterSensitiveThread() const {
2282 Thread::SetJitSensitiveThread();
2283 }
2284
2285 // Returns true if JIT compilations are enabled. GetJit() will be not null in this case.
UseJitCompilation() const2286 bool Runtime::UseJitCompilation() const {
2287 return (jit_ != nullptr) && jit_->UseJitCompilation();
2288 }
2289
TakeSnapshot()2290 void Runtime::EnvSnapshot::TakeSnapshot() {
2291 char** env = GetEnviron();
2292 for (size_t i = 0; env[i] != nullptr; ++i) {
2293 name_value_pairs_.emplace_back(new std::string(env[i]));
2294 }
2295 // The strings in name_value_pairs_ retain ownership of the c_str, but we assign pointers
2296 // for quick use by GetSnapshot. This avoids allocation and copying cost at Exec.
2297 c_env_vector_.reset(new char*[name_value_pairs_.size() + 1]);
2298 for (size_t i = 0; env[i] != nullptr; ++i) {
2299 c_env_vector_[i] = const_cast<char*>(name_value_pairs_[i]->c_str());
2300 }
2301 c_env_vector_[name_value_pairs_.size()] = nullptr;
2302 }
2303
GetSnapshot() const2304 char** Runtime::EnvSnapshot::GetSnapshot() const {
2305 return c_env_vector_.get();
2306 }
2307
AddSystemWeakHolder(gc::AbstractSystemWeakHolder * holder)2308 void Runtime::AddSystemWeakHolder(gc::AbstractSystemWeakHolder* holder) {
2309 gc::ScopedGCCriticalSection gcs(Thread::Current(),
2310 gc::kGcCauseAddRemoveSystemWeakHolder,
2311 gc::kCollectorTypeAddRemoveSystemWeakHolder);
2312 // Note: The ScopedGCCriticalSection also ensures that the rest of the function is in
2313 // a critical section.
2314 system_weak_holders_.push_back(holder);
2315 }
2316
RemoveSystemWeakHolder(gc::AbstractSystemWeakHolder * holder)2317 void Runtime::RemoveSystemWeakHolder(gc::AbstractSystemWeakHolder* holder) {
2318 gc::ScopedGCCriticalSection gcs(Thread::Current(),
2319 gc::kGcCauseAddRemoveSystemWeakHolder,
2320 gc::kCollectorTypeAddRemoveSystemWeakHolder);
2321 auto it = std::find(system_weak_holders_.begin(), system_weak_holders_.end(), holder);
2322 if (it != system_weak_holders_.end()) {
2323 system_weak_holders_.erase(it);
2324 }
2325 }
2326
2327 NO_RETURN
Aborter(const char * abort_message)2328 void Runtime::Aborter(const char* abort_message) {
2329 #ifdef ART_TARGET_ANDROID
2330 android_set_abort_message(abort_message);
2331 #endif
2332 Runtime::Abort(abort_message);
2333 }
2334
GetRuntimeCallbacks()2335 RuntimeCallbacks* Runtime::GetRuntimeCallbacks() {
2336 return callbacks_.get();
2337 }
2338
2339 // Used to patch boot image method entry point to interpreter bridge.
2340 class UpdateEntryPointsClassVisitor : public ClassVisitor {
2341 public:
UpdateEntryPointsClassVisitor(instrumentation::Instrumentation * instrumentation)2342 explicit UpdateEntryPointsClassVisitor(instrumentation::Instrumentation* instrumentation)
2343 : instrumentation_(instrumentation) {}
2344
operator ()(ObjPtr<mirror::Class> klass)2345 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES(Locks::mutator_lock_) {
2346 auto pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
2347 for (auto& m : klass->GetMethods(pointer_size)) {
2348 const void* code = m.GetEntryPointFromQuickCompiledCode();
2349 if (Runtime::Current()->GetHeap()->IsInBootImageOatFile(code) &&
2350 !m.IsNative() &&
2351 !m.IsProxyMethod()) {
2352 instrumentation_->UpdateMethodsCodeForJavaDebuggable(&m, GetQuickToInterpreterBridge());
2353 }
2354 }
2355 return true;
2356 }
2357
2358 private:
2359 instrumentation::Instrumentation* const instrumentation_;
2360 };
2361
SetJavaDebuggable(bool value)2362 void Runtime::SetJavaDebuggable(bool value) {
2363 is_java_debuggable_ = value;
2364 // Do not call DeoptimizeBootImage just yet, the runtime may still be starting up.
2365 }
2366
DeoptimizeBootImage()2367 void Runtime::DeoptimizeBootImage() {
2368 // If we've already started and we are setting this runtime to debuggable,
2369 // we patch entry points of methods in boot image to interpreter bridge, as
2370 // boot image code may be AOT compiled as not debuggable.
2371 if (!GetInstrumentation()->IsForcedInterpretOnly()) {
2372 ScopedObjectAccess soa(Thread::Current());
2373 UpdateEntryPointsClassVisitor visitor(GetInstrumentation());
2374 GetClassLinker()->VisitClasses(&visitor);
2375 }
2376 }
2377
2378 } // namespace art
2379