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