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