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