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