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