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