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