runtime.cc revision 787ae8eb018d46b4b464e3a7c8de37d9262deb61
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#include <sys/prctl.h> 24#endif 25 26#define ATRACE_TAG ATRACE_TAG_DALVIK 27#include <cutils/trace.h> 28#include <signal.h> 29#include <sys/syscall.h> 30#include "base/memory_tool.h" 31 32#include <cstdio> 33#include <cstdlib> 34#include <limits> 35#include <memory_representation.h> 36#include <vector> 37#include <fcntl.h> 38 39#include "JniConstants.h" 40#include "ScopedLocalRef.h" 41#include "arch/arm/quick_method_frame_info_arm.h" 42#include "arch/arm/registers_arm.h" 43#include "arch/arm64/quick_method_frame_info_arm64.h" 44#include "arch/arm64/registers_arm64.h" 45#include "arch/instruction_set_features.h" 46#include "arch/mips/quick_method_frame_info_mips.h" 47#include "arch/mips/registers_mips.h" 48#include "arch/mips64/quick_method_frame_info_mips64.h" 49#include "arch/mips64/registers_mips64.h" 50#include "arch/x86/quick_method_frame_info_x86.h" 51#include "arch/x86/registers_x86.h" 52#include "arch/x86_64/quick_method_frame_info_x86_64.h" 53#include "arch/x86_64/registers_x86_64.h" 54#include "art_field-inl.h" 55#include "art_method-inl.h" 56#include "asm_support.h" 57#include "atomic.h" 58#include "base/arena_allocator.h" 59#include "base/dumpable.h" 60#include "base/stl_util.h" 61#include "base/unix_file/fd_file.h" 62#include "class_linker-inl.h" 63#include "compiler_callbacks.h" 64#include "debugger.h" 65#include "elf_file.h" 66#include "entrypoints/runtime_asm_entrypoints.h" 67#include "experimental_flags.h" 68#include "fault_handler.h" 69#include "gc/accounting/card_table-inl.h" 70#include "gc/heap.h" 71#include "gc/space/image_space.h" 72#include "gc/space/space-inl.h" 73#include "handle_scope-inl.h" 74#include "image.h" 75#include "instrumentation.h" 76#include "intern_table.h" 77#include "interpreter/interpreter.h" 78#include "jit/jit.h" 79#include "jni_internal.h" 80#include "linear_alloc.h" 81#include "lambda/box_table.h" 82#include "mirror/array.h" 83#include "mirror/class-inl.h" 84#include "mirror/class_loader.h" 85#include "mirror/field.h" 86#include "mirror/method.h" 87#include "mirror/stack_trace_element.h" 88#include "mirror/throwable.h" 89#include "monitor.h" 90#include "native/dalvik_system_DexFile.h" 91#include "native/dalvik_system_VMDebug.h" 92#include "native/dalvik_system_VMRuntime.h" 93#include "native/dalvik_system_VMStack.h" 94#include "native/dalvik_system_ZygoteHooks.h" 95#include "native/java_lang_Class.h" 96#include "native/java_lang_DexCache.h" 97#include "native/java_lang_Object.h" 98#include "native/java_lang_Runtime.h" 99#include "native/java_lang_String.h" 100#include "native/java_lang_StringFactory.h" 101#include "native/java_lang_System.h" 102#include "native/java_lang_Thread.h" 103#include "native/java_lang_Throwable.h" 104#include "native/java_lang_VMClassLoader.h" 105#include "native/java_lang_ref_FinalizerReference.h" 106#include "native/java_lang_ref_Reference.h" 107#include "native/java_lang_reflect_Array.h" 108#include "native/java_lang_reflect_Constructor.h" 109#include "native/java_lang_reflect_Field.h" 110#include "native/java_lang_reflect_Method.h" 111#include "native/java_lang_reflect_Proxy.h" 112#include "native/java_util_concurrent_atomic_AtomicLong.h" 113#include "native/libcore_util_CharsetUtils.h" 114#include "native/org_apache_harmony_dalvik_ddmc_DdmServer.h" 115#include "native/org_apache_harmony_dalvik_ddmc_DdmVmInternal.h" 116#include "native/sun_misc_Unsafe.h" 117#include "native_bridge_art_interface.h" 118#include "oat_file.h" 119#include "oat_file_manager.h" 120#include "os.h" 121#include "parsed_options.h" 122#include "profiler.h" 123#include "quick/quick_method_frame_info.h" 124#include "reflection.h" 125#include "runtime_options.h" 126#include "ScopedLocalRef.h" 127#include "scoped_thread_state_change.h" 128#include "sigchain.h" 129#include "signal_catcher.h" 130#include "signal_set.h" 131#include "thread.h" 132#include "thread_list.h" 133#include "trace.h" 134#include "transaction.h" 135#include "utils.h" 136#include "verifier/method_verifier.h" 137#include "well_known_classes.h" 138 139namespace art { 140 141// If a signal isn't handled properly, enable a handler that attempts to dump the Java stack. 142static constexpr bool kEnableJavaStackTraceHandler = false; 143// Tuned by compiling GmsCore under perf and measuring time spent in DescriptorEquals for class 144// linking. 145static constexpr double kLowMemoryMinLoadFactor = 0.5; 146static constexpr double kLowMemoryMaxLoadFactor = 0.8; 147static constexpr double kNormalMinLoadFactor = 0.4; 148static constexpr double kNormalMaxLoadFactor = 0.7; 149Runtime* Runtime::instance_ = nullptr; 150 151struct TraceConfig { 152 Trace::TraceMode trace_mode; 153 Trace::TraceOutputMode trace_output_mode; 154 std::string trace_file; 155 size_t trace_file_size; 156}; 157 158Runtime::Runtime() 159 : resolution_method_(nullptr), 160 imt_conflict_method_(nullptr), 161 imt_unimplemented_method_(nullptr), 162 instruction_set_(kNone), 163 compiler_callbacks_(nullptr), 164 is_zygote_(false), 165 must_relocate_(false), 166 is_concurrent_gc_enabled_(true), 167 is_explicit_gc_disabled_(false), 168 dex2oat_enabled_(true), 169 image_dex2oat_enabled_(true), 170 default_stack_size_(0), 171 heap_(nullptr), 172 max_spins_before_thin_lock_inflation_(Monitor::kDefaultMaxSpinsBeforeThinLockInflation), 173 monitor_list_(nullptr), 174 monitor_pool_(nullptr), 175 thread_list_(nullptr), 176 intern_table_(nullptr), 177 class_linker_(nullptr), 178 signal_catcher_(nullptr), 179 java_vm_(nullptr), 180 fault_message_lock_("Fault message lock"), 181 fault_message_(""), 182 threads_being_born_(0), 183 shutdown_cond_(new ConditionVariable("Runtime shutdown", *Locks::runtime_shutdown_lock_)), 184 shutting_down_(false), 185 shutting_down_started_(false), 186 started_(false), 187 finished_starting_(false), 188 vfprintf_(nullptr), 189 exit_(nullptr), 190 abort_(nullptr), 191 stats_enabled_(false), 192 is_running_on_memory_tool_(RUNNING_ON_MEMORY_TOOL), 193 profiler_started_(false), 194 instrumentation_(), 195 main_thread_group_(nullptr), 196 system_thread_group_(nullptr), 197 system_class_loader_(nullptr), 198 dump_gc_performance_on_shutdown_(false), 199 preinitialization_transaction_(nullptr), 200 verify_(verifier::VerifyMode::kNone), 201 allow_dex_file_fallback_(true), 202 target_sdk_version_(0), 203 implicit_null_checks_(false), 204 implicit_so_checks_(false), 205 implicit_suspend_checks_(false), 206 no_sig_chain_(false), 207 is_native_bridge_loaded_(false), 208 zygote_max_failed_boots_(0), 209 experimental_flags_(ExperimentalFlags::kNone), 210 oat_file_manager_(nullptr), 211 is_low_memory_mode_(false), 212 safe_mode_(false) { 213 CheckAsmSupportOffsetsAndSizes(); 214 std::fill(callee_save_methods_, callee_save_methods_ + arraysize(callee_save_methods_), 0u); 215} 216 217Runtime::~Runtime() { 218 if (is_native_bridge_loaded_) { 219 UnloadNativeBridge(); 220 } 221 if (dump_gc_performance_on_shutdown_) { 222 // This can't be called from the Heap destructor below because it 223 // could call RosAlloc::InspectAll() which needs the thread_list 224 // to be still alive. 225 heap_->DumpGcPerformanceInfo(LOG(INFO)); 226 } 227 228 Thread* self = Thread::Current(); 229 const bool attach_shutdown_thread = self == nullptr; 230 if (attach_shutdown_thread) { 231 CHECK(AttachCurrentThread("Shutdown thread", false, nullptr, false)); 232 self = Thread::Current(); 233 } else { 234 LOG(WARNING) << "Current thread not detached in Runtime shutdown"; 235 } 236 237 { 238 MutexLock mu(self, *Locks::runtime_shutdown_lock_); 239 shutting_down_started_ = true; 240 while (threads_being_born_ > 0) { 241 shutdown_cond_->Wait(self); 242 } 243 shutting_down_ = true; 244 } 245 // Shutdown and wait for the daemons. 246 CHECK(self != nullptr); 247 if (IsFinishedStarting()) { 248 self->ClearException(); 249 self->GetJniEnv()->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons, 250 WellKnownClasses::java_lang_Daemons_stop); 251 } 252 253 Trace::Shutdown(); 254 255 if (attach_shutdown_thread) { 256 DetachCurrentThread(); 257 self = nullptr; 258 } 259 260 // Shut down background profiler before the runtime exits. 261 if (profiler_started_) { 262 BackgroundMethodSamplingProfiler::Shutdown(); 263 } 264 265 // Make sure to let the GC complete if it is running. 266 heap_->WaitForGcToComplete(gc::kGcCauseBackground, self); 267 heap_->DeleteThreadPool(); 268 if (jit_.get() != nullptr) { 269 VLOG(jit) << "Deleting jit thread pool"; 270 // Delete thread pool before the thread list since we don't want to wait forever on the 271 // JIT compiler threads. 272 jit_->DeleteThreadPool(); 273 } 274 275 // Make sure our internal threads are dead before we start tearing down things they're using. 276 Dbg::StopJdwp(); 277 delete signal_catcher_; 278 279 // Make sure all other non-daemon threads have terminated, and all daemon threads are suspended. 280 delete thread_list_; 281 282 // Delete the JIT after thread list to ensure that there is no remaining threads which could be 283 // accessing the instrumentation when we delete it. 284 if (jit_.get() != nullptr) { 285 VLOG(jit) << "Deleting jit"; 286 jit_.reset(nullptr); 287 } 288 289 // Shutdown the fault manager if it was initialized. 290 fault_manager.Shutdown(); 291 292 delete monitor_list_; 293 delete monitor_pool_; 294 delete class_linker_; 295 delete heap_; 296 delete intern_table_; 297 delete java_vm_; 298 delete oat_file_manager_; 299 Thread::Shutdown(); 300 QuasiAtomic::Shutdown(); 301 verifier::MethodVerifier::Shutdown(); 302 303 // Destroy allocators before shutting down the MemMap because they may use it. 304 linear_alloc_.reset(); 305 low_4gb_arena_pool_.reset(); 306 arena_pool_.reset(); 307 MemMap::Shutdown(); 308 309 // TODO: acquire a static mutex on Runtime to avoid racing. 310 CHECK(instance_ == nullptr || instance_ == this); 311 instance_ = nullptr; 312} 313 314struct AbortState { 315 void Dump(std::ostream& os) const { 316 if (gAborting > 1) { 317 os << "Runtime aborting --- recursively, so no thread-specific detail!\n"; 318 return; 319 } 320 gAborting++; 321 os << "Runtime aborting...\n"; 322 if (Runtime::Current() == nullptr) { 323 os << "(Runtime does not yet exist!)\n"; 324 return; 325 } 326 Thread* self = Thread::Current(); 327 if (self == nullptr) { 328 os << "(Aborting thread was not attached to runtime!)\n"; 329 DumpKernelStack(os, GetTid(), " kernel: ", false); 330 DumpNativeStack(os, GetTid(), nullptr, " native: ", nullptr); 331 } else { 332 os << "Aborting thread:\n"; 333 if (Locks::mutator_lock_->IsExclusiveHeld(self) || Locks::mutator_lock_->IsSharedHeld(self)) { 334 DumpThread(os, self); 335 } else { 336 if (Locks::mutator_lock_->SharedTryLock(self)) { 337 DumpThread(os, self); 338 Locks::mutator_lock_->SharedUnlock(self); 339 } 340 } 341 } 342 DumpAllThreads(os, self); 343 } 344 345 // No thread-safety analysis as we do explicitly test for holding the mutator lock. 346 void DumpThread(std::ostream& os, Thread* self) const NO_THREAD_SAFETY_ANALYSIS { 347 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self) || Locks::mutator_lock_->IsSharedHeld(self)); 348 self->Dump(os); 349 if (self->IsExceptionPending()) { 350 mirror::Throwable* exception = self->GetException(); 351 os << "Pending exception " << exception->Dump(); 352 } 353 } 354 355 void DumpAllThreads(std::ostream& os, Thread* self) const { 356 Runtime* runtime = Runtime::Current(); 357 if (runtime != nullptr) { 358 ThreadList* thread_list = runtime->GetThreadList(); 359 if (thread_list != nullptr) { 360 bool tll_already_held = Locks::thread_list_lock_->IsExclusiveHeld(self); 361 bool ml_already_held = Locks::mutator_lock_->IsSharedHeld(self); 362 if (!tll_already_held || !ml_already_held) { 363 os << "Dumping all threads without appropriate locks held:" 364 << (!tll_already_held ? " thread list lock" : "") 365 << (!ml_already_held ? " mutator lock" : "") 366 << "\n"; 367 } 368 os << "All threads:\n"; 369 thread_list->Dump(os); 370 } 371 } 372 } 373}; 374 375void Runtime::Abort() { 376 gAborting++; // set before taking any locks 377 378 // Ensure that we don't have multiple threads trying to abort at once, 379 // which would result in significantly worse diagnostics. 380 MutexLock mu(Thread::Current(), *Locks::abort_lock_); 381 382 // Get any pending output out of the way. 383 fflush(nullptr); 384 385 // Many people have difficulty distinguish aborts from crashes, 386 // so be explicit. 387 AbortState state; 388 LOG(INTERNAL_FATAL) << Dumpable<AbortState>(state); 389 390 // Call the abort hook if we have one. 391 if (Runtime::Current() != nullptr && Runtime::Current()->abort_ != nullptr) { 392 LOG(INTERNAL_FATAL) << "Calling abort hook..."; 393 Runtime::Current()->abort_(); 394 // notreached 395 LOG(INTERNAL_FATAL) << "Unexpectedly returned from abort hook!"; 396 } 397 398#if defined(__GLIBC__) 399 // TODO: we ought to be able to use pthread_kill(3) here (or abort(3), 400 // which POSIX defines in terms of raise(3), which POSIX defines in terms 401 // of pthread_kill(3)). On Linux, though, libcorkscrew can't unwind through 402 // libpthread, which means the stacks we dump would be useless. Calling 403 // tgkill(2) directly avoids that. 404 syscall(__NR_tgkill, getpid(), GetTid(), SIGABRT); 405 // TODO: LLVM installs it's own SIGABRT handler so exit to be safe... Can we disable that in LLVM? 406 // If not, we could use sigaction(3) before calling tgkill(2) and lose this call to exit(3). 407 exit(1); 408#else 409 abort(); 410#endif 411 // notreached 412} 413 414void Runtime::PreZygoteFork() { 415 heap_->PreZygoteFork(); 416} 417 418void Runtime::CallExitHook(jint status) { 419 if (exit_ != nullptr) { 420 ScopedThreadStateChange tsc(Thread::Current(), kNative); 421 exit_(status); 422 LOG(WARNING) << "Exit hook returned instead of exiting!"; 423 } 424} 425 426void Runtime::SweepSystemWeaks(IsMarkedVisitor* visitor) { 427 GetInternTable()->SweepInternTableWeaks(visitor); 428 GetMonitorList()->SweepMonitorList(visitor); 429 GetJavaVM()->SweepJniWeakGlobals(visitor); 430 GetHeap()->SweepAllocationRecords(visitor); 431 GetLambdaBoxTable()->SweepWeakBoxedLambdas(visitor); 432} 433 434bool Runtime::Create(const RuntimeOptions& options, bool ignore_unrecognized) { 435 // TODO: acquire a static mutex on Runtime to avoid racing. 436 if (Runtime::instance_ != nullptr) { 437 return false; 438 } 439 InitLogging(nullptr); // Calls Locks::Init() as a side effect. 440 instance_ = new Runtime; 441 if (!instance_->Init(options, ignore_unrecognized)) { 442 // TODO: Currently deleting the instance will abort the runtime on destruction. Now This will 443 // leak memory, instead. Fix the destructor. b/19100793. 444 // delete instance_; 445 instance_ = nullptr; 446 return false; 447 } 448 return true; 449} 450 451static jobject CreateSystemClassLoader(Runtime* runtime) { 452 if (runtime->IsAotCompiler() && !runtime->GetCompilerCallbacks()->IsBootImage()) { 453 return nullptr; 454 } 455 456 ScopedObjectAccess soa(Thread::Current()); 457 ClassLinker* cl = Runtime::Current()->GetClassLinker(); 458 auto pointer_size = cl->GetImagePointerSize(); 459 460 StackHandleScope<2> hs(soa.Self()); 461 Handle<mirror::Class> class_loader_class( 462 hs.NewHandle(soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ClassLoader))); 463 CHECK(cl->EnsureInitialized(soa.Self(), class_loader_class, true, true)); 464 465 ArtMethod* getSystemClassLoader = class_loader_class->FindDirectMethod( 466 "getSystemClassLoader", "()Ljava/lang/ClassLoader;", pointer_size); 467 CHECK(getSystemClassLoader != nullptr); 468 469 JValue result = InvokeWithJValues(soa, nullptr, soa.EncodeMethod(getSystemClassLoader), nullptr); 470 JNIEnv* env = soa.Self()->GetJniEnv(); 471 ScopedLocalRef<jobject> system_class_loader(env, soa.AddLocalReference<jobject>(result.GetL())); 472 CHECK(system_class_loader.get() != nullptr); 473 474 soa.Self()->SetClassLoaderOverride(system_class_loader.get()); 475 476 Handle<mirror::Class> thread_class( 477 hs.NewHandle(soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread))); 478 CHECK(cl->EnsureInitialized(soa.Self(), thread_class, true, true)); 479 480 ArtField* contextClassLoader = 481 thread_class->FindDeclaredInstanceField("contextClassLoader", "Ljava/lang/ClassLoader;"); 482 CHECK(contextClassLoader != nullptr); 483 484 // We can't run in a transaction yet. 485 contextClassLoader->SetObject<false>(soa.Self()->GetPeer(), 486 soa.Decode<mirror::ClassLoader*>(system_class_loader.get())); 487 488 return env->NewGlobalRef(system_class_loader.get()); 489} 490 491std::string Runtime::GetPatchoatExecutable() const { 492 if (!patchoat_executable_.empty()) { 493 return patchoat_executable_; 494 } 495 std::string patchoat_executable(GetAndroidRoot()); 496 patchoat_executable += (kIsDebugBuild ? "/bin/patchoatd" : "/bin/patchoat"); 497 return patchoat_executable; 498} 499 500std::string Runtime::GetCompilerExecutable() const { 501 if (!compiler_executable_.empty()) { 502 return compiler_executable_; 503 } 504 std::string compiler_executable(GetAndroidRoot()); 505 compiler_executable += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat"); 506 return compiler_executable; 507} 508 509bool Runtime::Start() { 510 VLOG(startup) << "Runtime::Start entering"; 511 512 CHECK(!no_sig_chain_) << "A started runtime should have sig chain enabled"; 513 514 // If a debug host build, disable ptrace restriction for debugging and test timeout thread dump. 515 // Only 64-bit as prctl() may fail in 32 bit userspace on a 64-bit kernel. 516#if defined(__linux__) && !defined(__ANDROID__) && defined(__x86_64__) 517 if (kIsDebugBuild) { 518 CHECK_EQ(prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY), 0); 519 } 520#endif 521 522 // Restore main thread state to kNative as expected by native code. 523 Thread* self = Thread::Current(); 524 525 self->TransitionFromRunnableToSuspended(kNative); 526 527 started_ = true; 528 529 // Use !IsAotCompiler so that we get test coverage, tests are never the zygote. 530 if (!IsAotCompiler()) { 531 ScopedObjectAccess soa(self); 532 gc::space::ImageSpace* image_space = heap_->GetBootImageSpace(); 533 if (image_space != nullptr) { 534 ATRACE_BEGIN("AddImageStringsToTable"); 535 GetInternTable()->AddImageStringsToTable(image_space); 536 ATRACE_END(); 537 ATRACE_BEGIN("MoveImageClassesToClassTable"); 538 GetClassLinker()->AddBootImageClassesToClassTable(); 539 ATRACE_END(); 540 } 541 } 542 543 // If we are the zygote then we need to wait until after forking to create the code cache 544 // due to SELinux restrictions on r/w/x memory regions. 545 if (!IsZygote() && jit_options_->UseJIT()) { 546 CreateJit(); 547 } 548 549 if (!IsImageDex2OatEnabled() || !GetHeap()->HasImageSpace()) { 550 ScopedObjectAccess soa(self); 551 StackHandleScope<1> hs(soa.Self()); 552 auto klass(hs.NewHandle<mirror::Class>(mirror::Class::GetJavaLangClass())); 553 class_linker_->EnsureInitialized(soa.Self(), klass, true, true); 554 } 555 556 // InitNativeMethods needs to be after started_ so that the classes 557 // it touches will have methods linked to the oat file if necessary. 558 ATRACE_BEGIN("InitNativeMethods"); 559 InitNativeMethods(); 560 ATRACE_END(); 561 562 // Initialize well known thread group values that may be accessed threads while attaching. 563 InitThreadGroups(self); 564 565 Thread::FinishStartup(); 566 567 system_class_loader_ = CreateSystemClassLoader(this); 568 569 if (is_zygote_) { 570 if (!InitZygote()) { 571 return false; 572 } 573 } else { 574 if (is_native_bridge_loaded_) { 575 PreInitializeNativeBridge("."); 576 } 577 DidForkFromZygote(self->GetJniEnv(), NativeBridgeAction::kInitialize, 578 GetInstructionSetString(kRuntimeISA)); 579 } 580 581 ATRACE_BEGIN("StartDaemonThreads"); 582 StartDaemonThreads(); 583 ATRACE_END(); 584 585 { 586 ScopedObjectAccess soa(self); 587 self->GetJniEnv()->locals.AssertEmpty(); 588 } 589 590 VLOG(startup) << "Runtime::Start exiting"; 591 finished_starting_ = true; 592 593 if (profiler_options_.IsEnabled() && !profile_output_filename_.empty()) { 594 // User has asked for a profile using -Xenable-profiler. 595 // Create the profile file if it doesn't exist. 596 int fd = open(profile_output_filename_.c_str(), O_RDWR|O_CREAT|O_EXCL, 0660); 597 if (fd >= 0) { 598 close(fd); 599 } else if (errno != EEXIST) { 600 LOG(INFO) << "Failed to access the profile file. Profiler disabled."; 601 return true; 602 } 603 StartProfiler(profile_output_filename_.c_str()); 604 } 605 606 if (trace_config_.get() != nullptr && trace_config_->trace_file != "") { 607 ScopedThreadStateChange tsc(self, kWaitingForMethodTracingStart); 608 Trace::Start(trace_config_->trace_file.c_str(), 609 -1, 610 static_cast<int>(trace_config_->trace_file_size), 611 0, 612 trace_config_->trace_output_mode, 613 trace_config_->trace_mode, 614 0); 615 } 616 617 return true; 618} 619 620void Runtime::EndThreadBirth() REQUIRES(Locks::runtime_shutdown_lock_) { 621 DCHECK_GT(threads_being_born_, 0U); 622 threads_being_born_--; 623 if (shutting_down_started_ && threads_being_born_ == 0) { 624 shutdown_cond_->Broadcast(Thread::Current()); 625 } 626} 627 628// Do zygote-mode-only initialization. 629bool Runtime::InitZygote() { 630#ifdef __linux__ 631 // zygote goes into its own process group 632 setpgid(0, 0); 633 634 // See storage config details at http://source.android.com/tech/storage/ 635 // Create private mount namespace shared by all children 636 if (unshare(CLONE_NEWNS) == -1) { 637 PLOG(ERROR) << "Failed to unshare()"; 638 return false; 639 } 640 641 // Mark rootfs as being a slave so that changes from default 642 // namespace only flow into our children. 643 if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) { 644 PLOG(ERROR) << "Failed to mount() rootfs as MS_SLAVE"; 645 return false; 646 } 647 648 // Create a staging tmpfs that is shared by our children; they will 649 // bind mount storage into their respective private namespaces, which 650 // are isolated from each other. 651 const char* target_base = getenv("EMULATED_STORAGE_TARGET"); 652 if (target_base != nullptr) { 653 if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV, 654 "uid=0,gid=1028,mode=0751") == -1) { 655 PLOG(ERROR) << "Failed to mount tmpfs to " << target_base; 656 return false; 657 } 658 } 659 660 return true; 661#else 662 UNIMPLEMENTED(FATAL); 663 return false; 664#endif 665} 666 667void Runtime::DidForkFromZygote(JNIEnv* env, NativeBridgeAction action, const char* isa) { 668 is_zygote_ = false; 669 670 if (is_native_bridge_loaded_) { 671 switch (action) { 672 case NativeBridgeAction::kUnload: 673 UnloadNativeBridge(); 674 is_native_bridge_loaded_ = false; 675 break; 676 677 case NativeBridgeAction::kInitialize: 678 InitializeNativeBridge(env, isa); 679 break; 680 } 681 } 682 683 // Create the thread pools. 684 heap_->CreateThreadPool(); 685 // Reset the gc performance data at zygote fork so that the GCs 686 // before fork aren't attributed to an app. 687 heap_->ResetGcPerformanceInfo(); 688 689 if (!safe_mode_ && jit_options_->UseJIT()) { 690 DCHECK(jit_.get() == nullptr) << "The zygote should not JIT"; 691 // Create the JIT if the flag is set. 692 CreateJit(); 693 } 694 695 StartSignalCatcher(); 696 697 // Start the JDWP thread. If the command-line debugger flags specified "suspend=y", 698 // this will pause the runtime, so we probably want this to come last. 699 Dbg::StartJdwp(); 700} 701 702void Runtime::StartSignalCatcher() { 703 if (!is_zygote_) { 704 signal_catcher_ = new SignalCatcher(stack_trace_file_); 705 } 706} 707 708bool Runtime::IsShuttingDown(Thread* self) { 709 MutexLock mu(self, *Locks::runtime_shutdown_lock_); 710 return IsShuttingDownLocked(); 711} 712 713bool Runtime::IsDebuggable() const { 714 const OatFile* oat_file = GetOatFileManager().GetPrimaryOatFile(); 715 return oat_file != nullptr && oat_file->IsDebuggable(); 716} 717 718void Runtime::StartDaemonThreads() { 719 VLOG(startup) << "Runtime::StartDaemonThreads entering"; 720 721 Thread* self = Thread::Current(); 722 723 // Must be in the kNative state for calling native methods. 724 CHECK_EQ(self->GetState(), kNative); 725 726 JNIEnv* env = self->GetJniEnv(); 727 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons, 728 WellKnownClasses::java_lang_Daemons_start); 729 if (env->ExceptionCheck()) { 730 env->ExceptionDescribe(); 731 LOG(FATAL) << "Error starting java.lang.Daemons"; 732 } 733 734 VLOG(startup) << "Runtime::StartDaemonThreads exiting"; 735} 736 737static bool OpenDexFilesFromImage(const std::string& image_location, 738 std::vector<std::unique_ptr<const DexFile>>* dex_files, 739 size_t* failures) { 740 DCHECK(dex_files != nullptr) << "OpenDexFilesFromImage: out-param is nullptr"; 741 std::string system_filename; 742 bool has_system = false; 743 std::string cache_filename_unused; 744 bool dalvik_cache_exists_unused; 745 bool has_cache_unused; 746 bool is_global_cache_unused; 747 bool found_image = gc::space::ImageSpace::FindImageFilename(image_location.c_str(), 748 kRuntimeISA, 749 &system_filename, 750 &has_system, 751 &cache_filename_unused, 752 &dalvik_cache_exists_unused, 753 &has_cache_unused, 754 &is_global_cache_unused); 755 *failures = 0; 756 if (!found_image || !has_system) { 757 return false; 758 } 759 std::string error_msg; 760 // We are falling back to non-executable use of the oat file because patching failed, presumably 761 // due to lack of space. 762 std::string oat_filename = ImageHeader::GetOatLocationFromImageLocation(system_filename.c_str()); 763 std::string oat_location = ImageHeader::GetOatLocationFromImageLocation(image_location.c_str()); 764 std::unique_ptr<File> file(OS::OpenFileForReading(oat_filename.c_str())); 765 if (file.get() == nullptr) { 766 return false; 767 } 768 std::unique_ptr<ElfFile> elf_file(ElfFile::Open(file.release(), false, false, &error_msg)); 769 if (elf_file.get() == nullptr) { 770 return false; 771 } 772 std::unique_ptr<const OatFile> oat_file( 773 OatFile::OpenWithElfFile(elf_file.release(), oat_location, nullptr, &error_msg)); 774 if (oat_file == nullptr) { 775 LOG(INFO) << "Unable to use '" << oat_filename << "' because " << error_msg; 776 return false; 777 } 778 779 for (const OatFile::OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) { 780 if (oat_dex_file == nullptr) { 781 *failures += 1; 782 continue; 783 } 784 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg); 785 if (dex_file.get() == nullptr) { 786 *failures += 1; 787 } else { 788 dex_files->push_back(std::move(dex_file)); 789 } 790 } 791 Runtime::Current()->GetOatFileManager().RegisterOatFile(std::move(oat_file)); 792 return true; 793} 794 795 796static size_t OpenDexFiles(const std::vector<std::string>& dex_filenames, 797 const std::vector<std::string>& dex_locations, 798 const std::string& image_location, 799 std::vector<std::unique_ptr<const DexFile>>* dex_files) { 800 DCHECK(dex_files != nullptr) << "OpenDexFiles: out-param is nullptr"; 801 size_t failure_count = 0; 802 if (!image_location.empty() && OpenDexFilesFromImage(image_location, dex_files, &failure_count)) { 803 return failure_count; 804 } 805 failure_count = 0; 806 for (size_t i = 0; i < dex_filenames.size(); i++) { 807 const char* dex_filename = dex_filenames[i].c_str(); 808 const char* dex_location = dex_locations[i].c_str(); 809 std::string error_msg; 810 if (!OS::FileExists(dex_filename)) { 811 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'"; 812 continue; 813 } 814 if (!DexFile::Open(dex_filename, dex_location, &error_msg, dex_files)) { 815 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg; 816 ++failure_count; 817 } 818 } 819 return failure_count; 820} 821 822void Runtime::SetSentinel(mirror::Object* sentinel) { 823 CHECK(sentinel_.Read() == nullptr); 824 CHECK(sentinel != nullptr); 825 CHECK(!heap_->IsMovableObject(sentinel)); 826 sentinel_ = GcRoot<mirror::Object>(sentinel); 827} 828 829bool Runtime::Init(const RuntimeOptions& raw_options, bool ignore_unrecognized) { 830 ATRACE_BEGIN("Runtime::Init"); 831 CHECK_EQ(sysconf(_SC_PAGE_SIZE), kPageSize); 832 833 MemMap::Init(); 834 835 using Opt = RuntimeArgumentMap; 836 RuntimeArgumentMap runtime_options; 837 std::unique_ptr<ParsedOptions> parsed_options( 838 ParsedOptions::Create(raw_options, ignore_unrecognized, &runtime_options)); 839 if (parsed_options.get() == nullptr) { 840 LOG(ERROR) << "Failed to parse options"; 841 ATRACE_END(); 842 return false; 843 } 844 VLOG(startup) << "Runtime::Init -verbose:startup enabled"; 845 846 QuasiAtomic::Startup(); 847 848 oat_file_manager_ = new OatFileManager; 849 850 Monitor::Init(runtime_options.GetOrDefault(Opt::LockProfThreshold), 851 runtime_options.GetOrDefault(Opt::HookIsSensitiveThread)); 852 853 boot_class_path_string_ = runtime_options.ReleaseOrDefault(Opt::BootClassPath); 854 class_path_string_ = runtime_options.ReleaseOrDefault(Opt::ClassPath); 855 properties_ = runtime_options.ReleaseOrDefault(Opt::PropertiesList); 856 857 compiler_callbacks_ = runtime_options.GetOrDefault(Opt::CompilerCallbacksPtr); 858 patchoat_executable_ = runtime_options.ReleaseOrDefault(Opt::PatchOat); 859 must_relocate_ = runtime_options.GetOrDefault(Opt::Relocate); 860 is_zygote_ = runtime_options.Exists(Opt::Zygote); 861 is_explicit_gc_disabled_ = runtime_options.Exists(Opt::DisableExplicitGC); 862 dex2oat_enabled_ = runtime_options.GetOrDefault(Opt::Dex2Oat); 863 image_dex2oat_enabled_ = runtime_options.GetOrDefault(Opt::ImageDex2Oat); 864 865 vfprintf_ = runtime_options.GetOrDefault(Opt::HookVfprintf); 866 exit_ = runtime_options.GetOrDefault(Opt::HookExit); 867 abort_ = runtime_options.GetOrDefault(Opt::HookAbort); 868 869 default_stack_size_ = runtime_options.GetOrDefault(Opt::StackSize); 870 stack_trace_file_ = runtime_options.ReleaseOrDefault(Opt::StackTraceFile); 871 872 compiler_executable_ = runtime_options.ReleaseOrDefault(Opt::Compiler); 873 compiler_options_ = runtime_options.ReleaseOrDefault(Opt::CompilerOptions); 874 image_compiler_options_ = runtime_options.ReleaseOrDefault(Opt::ImageCompilerOptions); 875 image_location_ = runtime_options.GetOrDefault(Opt::Image); 876 877 max_spins_before_thin_lock_inflation_ = 878 runtime_options.GetOrDefault(Opt::MaxSpinsBeforeThinLockInflation); 879 880 monitor_list_ = new MonitorList; 881 monitor_pool_ = MonitorPool::Create(); 882 thread_list_ = new ThreadList; 883 intern_table_ = new InternTable; 884 885 verify_ = runtime_options.GetOrDefault(Opt::Verify); 886 allow_dex_file_fallback_ = !runtime_options.Exists(Opt::NoDexFileFallback); 887 888 no_sig_chain_ = runtime_options.Exists(Opt::NoSigChain); 889 890 Split(runtime_options.GetOrDefault(Opt::CpuAbiList), ',', &cpu_abilist_); 891 892 fingerprint_ = runtime_options.ReleaseOrDefault(Opt::Fingerprint); 893 894 if (runtime_options.GetOrDefault(Opt::Interpret)) { 895 GetInstrumentation()->ForceInterpretOnly(); 896 } 897 898 zygote_max_failed_boots_ = runtime_options.GetOrDefault(Opt::ZygoteMaxFailedBoots); 899 experimental_flags_ = runtime_options.GetOrDefault(Opt::Experimental); 900 is_low_memory_mode_ = runtime_options.Exists(Opt::LowMemoryMode); 901 902 XGcOption xgc_option = runtime_options.GetOrDefault(Opt::GcOption); 903 ATRACE_BEGIN("CreateHeap"); 904 heap_ = new gc::Heap(runtime_options.GetOrDefault(Opt::MemoryInitialSize), 905 runtime_options.GetOrDefault(Opt::HeapGrowthLimit), 906 runtime_options.GetOrDefault(Opt::HeapMinFree), 907 runtime_options.GetOrDefault(Opt::HeapMaxFree), 908 runtime_options.GetOrDefault(Opt::HeapTargetUtilization), 909 runtime_options.GetOrDefault(Opt::ForegroundHeapGrowthMultiplier), 910 runtime_options.GetOrDefault(Opt::MemoryMaximumSize), 911 runtime_options.GetOrDefault(Opt::NonMovingSpaceCapacity), 912 runtime_options.GetOrDefault(Opt::Image), 913 runtime_options.GetOrDefault(Opt::ImageInstructionSet), 914 xgc_option.collector_type_, 915 runtime_options.GetOrDefault(Opt::BackgroundGc), 916 runtime_options.GetOrDefault(Opt::LargeObjectSpace), 917 runtime_options.GetOrDefault(Opt::LargeObjectThreshold), 918 runtime_options.GetOrDefault(Opt::ParallelGCThreads), 919 runtime_options.GetOrDefault(Opt::ConcGCThreads), 920 runtime_options.Exists(Opt::LowMemoryMode), 921 runtime_options.GetOrDefault(Opt::LongPauseLogThreshold), 922 runtime_options.GetOrDefault(Opt::LongGCLogThreshold), 923 runtime_options.Exists(Opt::IgnoreMaxFootprint), 924 runtime_options.GetOrDefault(Opt::UseTLAB), 925 xgc_option.verify_pre_gc_heap_, 926 xgc_option.verify_pre_sweeping_heap_, 927 xgc_option.verify_post_gc_heap_, 928 xgc_option.verify_pre_gc_rosalloc_, 929 xgc_option.verify_pre_sweeping_rosalloc_, 930 xgc_option.verify_post_gc_rosalloc_, 931 xgc_option.gcstress_, 932 runtime_options.GetOrDefault(Opt::EnableHSpaceCompactForOOM), 933 runtime_options.GetOrDefault(Opt::HSpaceCompactForOOMMinIntervalsMs)); 934 ATRACE_END(); 935 936 if (heap_->GetBootImageSpace() == nullptr && !allow_dex_file_fallback_) { 937 LOG(ERROR) << "Dex file fallback disabled, cannot continue without image."; 938 ATRACE_END(); 939 return false; 940 } 941 942 dump_gc_performance_on_shutdown_ = runtime_options.Exists(Opt::DumpGCPerformanceOnShutdown); 943 944 if (runtime_options.Exists(Opt::JdwpOptions)) { 945 Dbg::ConfigureJdwp(runtime_options.GetOrDefault(Opt::JdwpOptions)); 946 } 947 948 jit_options_.reset(jit::JitOptions::CreateFromRuntimeArguments(runtime_options)); 949 if (IsAotCompiler()) { 950 // If we are already the compiler at this point, we must be dex2oat. Don't create the jit in 951 // this case. 952 // If runtime_options doesn't have UseJIT set to true then CreateFromRuntimeArguments returns 953 // null and we don't create the jit. 954 jit_options_->SetUseJIT(false); 955 } 956 957 // Allocate a global table of boxed lambda objects <-> closures. 958 lambda_box_table_ = MakeUnique<lambda::BoxTable>(); 959 960 // Use MemMap arena pool for jit, malloc otherwise. Malloc arenas are faster to allocate but 961 // can't be trimmed as easily. 962 const bool use_malloc = IsAotCompiler(); 963 arena_pool_.reset(new ArenaPool(use_malloc, false)); 964 if (IsAotCompiler() && Is64BitInstructionSet(kRuntimeISA)) { 965 // 4gb, no malloc. Explanation in header. 966 low_4gb_arena_pool_.reset(new ArenaPool(false, true)); 967 } 968 linear_alloc_.reset(CreateLinearAlloc()); 969 970 BlockSignals(); 971 InitPlatformSignalHandlers(); 972 973 // Change the implicit checks flags based on runtime architecture. 974 switch (kRuntimeISA) { 975 case kArm: 976 case kThumb2: 977 case kX86: 978 case kArm64: 979 case kX86_64: 980 case kMips: 981 case kMips64: 982 implicit_null_checks_ = true; 983 // Installing stack protection does not play well with valgrind. 984 implicit_so_checks_ = !(RUNNING_ON_MEMORY_TOOL && kMemoryToolIsValgrind); 985 break; 986 default: 987 // Keep the defaults. 988 break; 989 } 990 991 if (!no_sig_chain_) { 992 // Dex2Oat's Runtime does not need the signal chain or the fault handler. 993 994 // Initialize the signal chain so that any calls to sigaction get 995 // correctly routed to the next in the chain regardless of whether we 996 // have claimed the signal or not. 997 InitializeSignalChain(); 998 999 if (implicit_null_checks_ || implicit_so_checks_ || implicit_suspend_checks_) { 1000 fault_manager.Init(); 1001 1002 // These need to be in a specific order. The null point check handler must be 1003 // after the suspend check and stack overflow check handlers. 1004 // 1005 // Note: the instances attach themselves to the fault manager and are handled by it. The manager 1006 // will delete the instance on Shutdown(). 1007 if (implicit_suspend_checks_) { 1008 new SuspensionHandler(&fault_manager); 1009 } 1010 1011 if (implicit_so_checks_) { 1012 new StackOverflowHandler(&fault_manager); 1013 } 1014 1015 if (implicit_null_checks_) { 1016 new NullPointerHandler(&fault_manager); 1017 } 1018 1019 if (kEnableJavaStackTraceHandler) { 1020 new JavaStackTraceHandler(&fault_manager); 1021 } 1022 } 1023 } 1024 1025 java_vm_ = new JavaVMExt(this, runtime_options); 1026 1027 Thread::Startup(); 1028 1029 // ClassLinker needs an attached thread, but we can't fully attach a thread without creating 1030 // objects. We can't supply a thread group yet; it will be fixed later. Since we are the main 1031 // thread, we do not get a java peer. 1032 Thread* self = Thread::Attach("main", false, nullptr, false); 1033 CHECK_EQ(self->GetThreadId(), ThreadList::kMainThreadId); 1034 CHECK(self != nullptr); 1035 1036 // Set us to runnable so tools using a runtime can allocate and GC by default 1037 self->TransitionFromSuspendedToRunnable(); 1038 1039 // Now we're attached, we can take the heap locks and validate the heap. 1040 GetHeap()->EnableObjectValidation(); 1041 1042 CHECK_GE(GetHeap()->GetContinuousSpaces().size(), 1U); 1043 class_linker_ = new ClassLinker(intern_table_); 1044 if (GetHeap()->HasImageSpace()) { 1045 ATRACE_BEGIN("InitFromImage"); 1046 class_linker_->InitFromImage(); 1047 ATRACE_END(); 1048 if (kIsDebugBuild) { 1049 GetHeap()->GetBootImageSpace()->VerifyImageAllocations(); 1050 } 1051 if (boot_class_path_string_.empty()) { 1052 // The bootclasspath is not explicitly specified: construct it from the loaded dex files. 1053 const std::vector<const DexFile*>& boot_class_path = GetClassLinker()->GetBootClassPath(); 1054 std::vector<std::string> dex_locations; 1055 dex_locations.reserve(boot_class_path.size()); 1056 for (const DexFile* dex_file : boot_class_path) { 1057 dex_locations.push_back(dex_file->GetLocation()); 1058 } 1059 boot_class_path_string_ = Join(dex_locations, ':'); 1060 } 1061 } else { 1062 std::vector<std::string> dex_filenames; 1063 Split(boot_class_path_string_, ':', &dex_filenames); 1064 1065 std::vector<std::string> dex_locations; 1066 if (!runtime_options.Exists(Opt::BootClassPathLocations)) { 1067 dex_locations = dex_filenames; 1068 } else { 1069 dex_locations = runtime_options.GetOrDefault(Opt::BootClassPathLocations); 1070 CHECK_EQ(dex_filenames.size(), dex_locations.size()); 1071 } 1072 1073 std::vector<std::unique_ptr<const DexFile>> boot_class_path; 1074 OpenDexFiles(dex_filenames, 1075 dex_locations, 1076 runtime_options.GetOrDefault(Opt::Image), 1077 &boot_class_path); 1078 instruction_set_ = runtime_options.GetOrDefault(Opt::ImageInstructionSet); 1079 class_linker_->InitWithoutImage(std::move(boot_class_path)); 1080 1081 // TODO: Should we move the following to InitWithoutImage? 1082 SetInstructionSet(instruction_set_); 1083 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) { 1084 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i); 1085 if (!HasCalleeSaveMethod(type)) { 1086 SetCalleeSaveMethod(CreateCalleeSaveMethod(), type); 1087 } 1088 } 1089 } 1090 1091 CHECK(class_linker_ != nullptr); 1092 1093 verifier::MethodVerifier::Init(); 1094 1095 if (runtime_options.Exists(Opt::MethodTrace)) { 1096 trace_config_.reset(new TraceConfig()); 1097 trace_config_->trace_file = runtime_options.ReleaseOrDefault(Opt::MethodTraceFile); 1098 trace_config_->trace_file_size = runtime_options.ReleaseOrDefault(Opt::MethodTraceFileSize); 1099 trace_config_->trace_mode = Trace::TraceMode::kMethodTracing; 1100 trace_config_->trace_output_mode = runtime_options.Exists(Opt::MethodTraceStreaming) ? 1101 Trace::TraceOutputMode::kStreaming : 1102 Trace::TraceOutputMode::kFile; 1103 } 1104 1105 { 1106 auto&& profiler_options = runtime_options.ReleaseOrDefault(Opt::ProfilerOpts); 1107 profile_output_filename_ = profiler_options.output_file_name_; 1108 1109 // TODO: Don't do this, just change ProfilerOptions to include the output file name? 1110 ProfilerOptions other_options( 1111 profiler_options.enabled_, 1112 profiler_options.period_s_, 1113 profiler_options.duration_s_, 1114 profiler_options.interval_us_, 1115 profiler_options.backoff_coefficient_, 1116 profiler_options.start_immediately_, 1117 profiler_options.top_k_threshold_, 1118 profiler_options.top_k_change_threshold_, 1119 profiler_options.profile_type_, 1120 profiler_options.max_stack_depth_); 1121 1122 profiler_options_ = other_options; 1123 } 1124 1125 // TODO: move this to just be an Trace::Start argument 1126 Trace::SetDefaultClockSource(runtime_options.GetOrDefault(Opt::ProfileClock)); 1127 1128 // Pre-allocate an OutOfMemoryError for the double-OOME case. 1129 self->ThrowNewException("Ljava/lang/OutOfMemoryError;", 1130 "OutOfMemoryError thrown while trying to throw OutOfMemoryError; " 1131 "no stack trace available"); 1132 pre_allocated_OutOfMemoryError_ = GcRoot<mirror::Throwable>(self->GetException()); 1133 self->ClearException(); 1134 1135 // Pre-allocate a NoClassDefFoundError for the common case of failing to find a system class 1136 // ahead of checking the application's class loader. 1137 self->ThrowNewException("Ljava/lang/NoClassDefFoundError;", 1138 "Class not found using the boot class loader; no stack trace available"); 1139 pre_allocated_NoClassDefFoundError_ = GcRoot<mirror::Throwable>(self->GetException()); 1140 self->ClearException(); 1141 1142 // Look for a native bridge. 1143 // 1144 // The intended flow here is, in the case of a running system: 1145 // 1146 // Runtime::Init() (zygote): 1147 // LoadNativeBridge -> dlopen from cmd line parameter. 1148 // | 1149 // V 1150 // Runtime::Start() (zygote): 1151 // No-op wrt native bridge. 1152 // | 1153 // | start app 1154 // V 1155 // DidForkFromZygote(action) 1156 // action = kUnload -> dlclose native bridge. 1157 // action = kInitialize -> initialize library 1158 // 1159 // 1160 // The intended flow here is, in the case of a simple dalvikvm call: 1161 // 1162 // Runtime::Init(): 1163 // LoadNativeBridge -> dlopen from cmd line parameter. 1164 // | 1165 // V 1166 // Runtime::Start(): 1167 // DidForkFromZygote(kInitialize) -> try to initialize any native bridge given. 1168 // No-op wrt native bridge. 1169 { 1170 std::string native_bridge_file_name = runtime_options.ReleaseOrDefault(Opt::NativeBridge); 1171 is_native_bridge_loaded_ = LoadNativeBridge(native_bridge_file_name); 1172 } 1173 1174 VLOG(startup) << "Runtime::Init exiting"; 1175 1176 ATRACE_END(); 1177 1178 return true; 1179} 1180 1181void Runtime::InitNativeMethods() { 1182 VLOG(startup) << "Runtime::InitNativeMethods entering"; 1183 Thread* self = Thread::Current(); 1184 JNIEnv* env = self->GetJniEnv(); 1185 1186 // Must be in the kNative state for calling native methods (JNI_OnLoad code). 1187 CHECK_EQ(self->GetState(), kNative); 1188 1189 // First set up JniConstants, which is used by both the runtime's built-in native 1190 // methods and libcore. 1191 JniConstants::init(env); 1192 WellKnownClasses::Init(env); 1193 1194 // Then set up the native methods provided by the runtime itself. 1195 RegisterRuntimeNativeMethods(env); 1196 1197 // Then set up libcore, which is just a regular JNI library with a regular JNI_OnLoad. 1198 // Most JNI libraries can just use System.loadLibrary, but libcore can't because it's 1199 // the library that implements System.loadLibrary! 1200 { 1201 std::string reason; 1202 if (!java_vm_->LoadNativeLibrary(env, "libjavacore.so", nullptr, &reason)) { 1203 LOG(FATAL) << "LoadNativeLibrary failed for \"libjavacore.so\": " << reason; 1204 } 1205 } 1206 1207 // Initialize well known classes that may invoke runtime native methods. 1208 WellKnownClasses::LateInit(env); 1209 1210 VLOG(startup) << "Runtime::InitNativeMethods exiting"; 1211} 1212 1213void Runtime::InitThreadGroups(Thread* self) { 1214 JNIEnvExt* env = self->GetJniEnv(); 1215 ScopedJniEnvLocalRefState env_state(env); 1216 main_thread_group_ = 1217 env->NewGlobalRef(env->GetStaticObjectField( 1218 WellKnownClasses::java_lang_ThreadGroup, 1219 WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup)); 1220 CHECK(main_thread_group_ != nullptr || IsAotCompiler()); 1221 system_thread_group_ = 1222 env->NewGlobalRef(env->GetStaticObjectField( 1223 WellKnownClasses::java_lang_ThreadGroup, 1224 WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup)); 1225 CHECK(system_thread_group_ != nullptr || IsAotCompiler()); 1226} 1227 1228jobject Runtime::GetMainThreadGroup() const { 1229 CHECK(main_thread_group_ != nullptr || IsAotCompiler()); 1230 return main_thread_group_; 1231} 1232 1233jobject Runtime::GetSystemThreadGroup() const { 1234 CHECK(system_thread_group_ != nullptr || IsAotCompiler()); 1235 return system_thread_group_; 1236} 1237 1238jobject Runtime::GetSystemClassLoader() const { 1239 CHECK(system_class_loader_ != nullptr || IsAotCompiler()); 1240 return system_class_loader_; 1241} 1242 1243void Runtime::RegisterRuntimeNativeMethods(JNIEnv* env) { 1244 register_dalvik_system_DexFile(env); 1245 register_dalvik_system_VMDebug(env); 1246 register_dalvik_system_VMRuntime(env); 1247 register_dalvik_system_VMStack(env); 1248 register_dalvik_system_ZygoteHooks(env); 1249 register_java_lang_Class(env); 1250 register_java_lang_DexCache(env); 1251 register_java_lang_Object(env); 1252 register_java_lang_ref_FinalizerReference(env); 1253 register_java_lang_reflect_Array(env); 1254 register_java_lang_reflect_Constructor(env); 1255 register_java_lang_reflect_Field(env); 1256 register_java_lang_reflect_Method(env); 1257 register_java_lang_reflect_Proxy(env); 1258 register_java_lang_ref_Reference(env); 1259 register_java_lang_Runtime(env); 1260 register_java_lang_String(env); 1261 register_java_lang_StringFactory(env); 1262 register_java_lang_System(env); 1263 register_java_lang_Thread(env); 1264 register_java_lang_Throwable(env); 1265 register_java_lang_VMClassLoader(env); 1266 register_java_util_concurrent_atomic_AtomicLong(env); 1267 register_libcore_util_CharsetUtils(env); 1268 register_org_apache_harmony_dalvik_ddmc_DdmServer(env); 1269 register_org_apache_harmony_dalvik_ddmc_DdmVmInternal(env); 1270 register_sun_misc_Unsafe(env); 1271} 1272 1273void Runtime::DumpForSigQuit(std::ostream& os) { 1274 GetClassLinker()->DumpForSigQuit(os); 1275 GetInternTable()->DumpForSigQuit(os); 1276 GetJavaVM()->DumpForSigQuit(os); 1277 GetHeap()->DumpForSigQuit(os); 1278 TrackedAllocators::Dump(os); 1279 os << "\n"; 1280 1281 thread_list_->DumpForSigQuit(os); 1282 BaseMutex::DumpAll(os); 1283} 1284 1285void Runtime::DumpLockHolders(std::ostream& os) { 1286 uint64_t mutator_lock_owner = Locks::mutator_lock_->GetExclusiveOwnerTid(); 1287 pid_t thread_list_lock_owner = GetThreadList()->GetLockOwner(); 1288 pid_t classes_lock_owner = GetClassLinker()->GetClassesLockOwner(); 1289 pid_t dex_lock_owner = GetClassLinker()->GetDexLockOwner(); 1290 if ((thread_list_lock_owner | classes_lock_owner | dex_lock_owner) != 0) { 1291 os << "Mutator lock exclusive owner tid: " << mutator_lock_owner << "\n" 1292 << "ThreadList lock owner tid: " << thread_list_lock_owner << "\n" 1293 << "ClassLinker classes lock owner tid: " << classes_lock_owner << "\n" 1294 << "ClassLinker dex lock owner tid: " << dex_lock_owner << "\n"; 1295 } 1296} 1297 1298void Runtime::SetStatsEnabled(bool new_state) { 1299 Thread* self = Thread::Current(); 1300 MutexLock mu(self, *Locks::instrument_entrypoints_lock_); 1301 if (new_state == true) { 1302 GetStats()->Clear(~0); 1303 // TODO: wouldn't it make more sense to clear _all_ threads' stats? 1304 self->GetStats()->Clear(~0); 1305 if (stats_enabled_ != new_state) { 1306 GetInstrumentation()->InstrumentQuickAllocEntryPointsLocked(); 1307 } 1308 } else if (stats_enabled_ != new_state) { 1309 GetInstrumentation()->UninstrumentQuickAllocEntryPointsLocked(); 1310 } 1311 stats_enabled_ = new_state; 1312} 1313 1314void Runtime::ResetStats(int kinds) { 1315 GetStats()->Clear(kinds & 0xffff); 1316 // TODO: wouldn't it make more sense to clear _all_ threads' stats? 1317 Thread::Current()->GetStats()->Clear(kinds >> 16); 1318} 1319 1320int32_t Runtime::GetStat(int kind) { 1321 RuntimeStats* stats; 1322 if (kind < (1<<16)) { 1323 stats = GetStats(); 1324 } else { 1325 stats = Thread::Current()->GetStats(); 1326 kind >>= 16; 1327 } 1328 switch (kind) { 1329 case KIND_ALLOCATED_OBJECTS: 1330 return stats->allocated_objects; 1331 case KIND_ALLOCATED_BYTES: 1332 return stats->allocated_bytes; 1333 case KIND_FREED_OBJECTS: 1334 return stats->freed_objects; 1335 case KIND_FREED_BYTES: 1336 return stats->freed_bytes; 1337 case KIND_GC_INVOCATIONS: 1338 return stats->gc_for_alloc_count; 1339 case KIND_CLASS_INIT_COUNT: 1340 return stats->class_init_count; 1341 case KIND_CLASS_INIT_TIME: 1342 // Convert ns to us, reduce to 32 bits. 1343 return static_cast<int>(stats->class_init_time_ns / 1000); 1344 case KIND_EXT_ALLOCATED_OBJECTS: 1345 case KIND_EXT_ALLOCATED_BYTES: 1346 case KIND_EXT_FREED_OBJECTS: 1347 case KIND_EXT_FREED_BYTES: 1348 return 0; // backward compatibility 1349 default: 1350 LOG(FATAL) << "Unknown statistic " << kind; 1351 return -1; // unreachable 1352 } 1353} 1354 1355void Runtime::BlockSignals() { 1356 SignalSet signals; 1357 signals.Add(SIGPIPE); 1358 // SIGQUIT is used to dump the runtime's state (including stack traces). 1359 signals.Add(SIGQUIT); 1360 // SIGUSR1 is used to initiate a GC. 1361 signals.Add(SIGUSR1); 1362 signals.Block(); 1363} 1364 1365bool Runtime::AttachCurrentThread(const char* thread_name, bool as_daemon, jobject thread_group, 1366 bool create_peer) { 1367 return Thread::Attach(thread_name, as_daemon, thread_group, create_peer) != nullptr; 1368} 1369 1370void Runtime::DetachCurrentThread() { 1371 Thread* self = Thread::Current(); 1372 if (self == nullptr) { 1373 LOG(FATAL) << "attempting to detach thread that is not attached"; 1374 } 1375 if (self->HasManagedStack()) { 1376 LOG(FATAL) << *Thread::Current() << " attempting to detach while still running code"; 1377 } 1378 thread_list_->Unregister(self); 1379} 1380 1381mirror::Throwable* Runtime::GetPreAllocatedOutOfMemoryError() { 1382 mirror::Throwable* oome = pre_allocated_OutOfMemoryError_.Read(); 1383 if (oome == nullptr) { 1384 LOG(ERROR) << "Failed to return pre-allocated OOME"; 1385 } 1386 return oome; 1387} 1388 1389mirror::Throwable* Runtime::GetPreAllocatedNoClassDefFoundError() { 1390 mirror::Throwable* ncdfe = pre_allocated_NoClassDefFoundError_.Read(); 1391 if (ncdfe == nullptr) { 1392 LOG(ERROR) << "Failed to return pre-allocated NoClassDefFoundError"; 1393 } 1394 return ncdfe; 1395} 1396 1397void Runtime::VisitConstantRoots(RootVisitor* visitor) { 1398 // Visit the classes held as static in mirror classes, these can be visited concurrently and only 1399 // need to be visited once per GC since they never change. 1400 mirror::Class::VisitRoots(visitor); 1401 mirror::Constructor::VisitRoots(visitor); 1402 mirror::Reference::VisitRoots(visitor); 1403 mirror::Method::VisitRoots(visitor); 1404 mirror::StackTraceElement::VisitRoots(visitor); 1405 mirror::String::VisitRoots(visitor); 1406 mirror::Throwable::VisitRoots(visitor); 1407 mirror::Field::VisitRoots(visitor); 1408 // Visit all the primitive array types classes. 1409 mirror::PrimitiveArray<uint8_t>::VisitRoots(visitor); // BooleanArray 1410 mirror::PrimitiveArray<int8_t>::VisitRoots(visitor); // ByteArray 1411 mirror::PrimitiveArray<uint16_t>::VisitRoots(visitor); // CharArray 1412 mirror::PrimitiveArray<double>::VisitRoots(visitor); // DoubleArray 1413 mirror::PrimitiveArray<float>::VisitRoots(visitor); // FloatArray 1414 mirror::PrimitiveArray<int32_t>::VisitRoots(visitor); // IntArray 1415 mirror::PrimitiveArray<int64_t>::VisitRoots(visitor); // LongArray 1416 mirror::PrimitiveArray<int16_t>::VisitRoots(visitor); // ShortArray 1417 // Visiting the roots of these ArtMethods is not currently required since all the GcRoots are 1418 // null. 1419 BufferedRootVisitor<16> buffered_visitor(visitor, RootInfo(kRootVMInternal)); 1420 const size_t pointer_size = GetClassLinker()->GetImagePointerSize(); 1421 if (HasResolutionMethod()) { 1422 resolution_method_->VisitRoots(buffered_visitor, pointer_size); 1423 } 1424 if (HasImtConflictMethod()) { 1425 imt_conflict_method_->VisitRoots(buffered_visitor, pointer_size); 1426 } 1427 if (imt_unimplemented_method_ != nullptr) { 1428 imt_unimplemented_method_->VisitRoots(buffered_visitor, pointer_size); 1429 } 1430 for (size_t i = 0; i < kLastCalleeSaveType; ++i) { 1431 auto* m = reinterpret_cast<ArtMethod*>(callee_save_methods_[i]); 1432 if (m != nullptr) { 1433 m->VisitRoots(buffered_visitor, pointer_size); 1434 } 1435 } 1436} 1437 1438void Runtime::VisitConcurrentRoots(RootVisitor* visitor, VisitRootFlags flags) { 1439 intern_table_->VisitRoots(visitor, flags); 1440 class_linker_->VisitRoots(visitor, flags); 1441 heap_->VisitAllocationRecords(visitor); 1442 if ((flags & kVisitRootFlagNewRoots) == 0) { 1443 // Guaranteed to have no new roots in the constant roots. 1444 VisitConstantRoots(visitor); 1445 } 1446 Dbg::VisitRoots(visitor); 1447} 1448 1449void Runtime::VisitTransactionRoots(RootVisitor* visitor) { 1450 if (preinitialization_transaction_ != nullptr) { 1451 preinitialization_transaction_->VisitRoots(visitor); 1452 } 1453} 1454 1455void Runtime::VisitNonThreadRoots(RootVisitor* visitor) { 1456 java_vm_->VisitRoots(visitor); 1457 sentinel_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal)); 1458 pre_allocated_OutOfMemoryError_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal)); 1459 pre_allocated_NoClassDefFoundError_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal)); 1460 verifier::MethodVerifier::VisitStaticRoots(visitor); 1461 VisitTransactionRoots(visitor); 1462} 1463 1464void Runtime::VisitNonConcurrentRoots(RootVisitor* visitor) { 1465 thread_list_->VisitRoots(visitor); 1466 VisitNonThreadRoots(visitor); 1467} 1468 1469void Runtime::VisitThreadRoots(RootVisitor* visitor) { 1470 thread_list_->VisitRoots(visitor); 1471} 1472 1473size_t Runtime::FlipThreadRoots(Closure* thread_flip_visitor, Closure* flip_callback, 1474 gc::collector::GarbageCollector* collector) { 1475 return thread_list_->FlipThreadRoots(thread_flip_visitor, flip_callback, collector); 1476} 1477 1478void Runtime::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) { 1479 VisitNonConcurrentRoots(visitor); 1480 VisitConcurrentRoots(visitor, flags); 1481} 1482 1483void Runtime::VisitImageRoots(RootVisitor* visitor) { 1484 for (auto* space : GetHeap()->GetContinuousSpaces()) { 1485 if (space->IsImageSpace()) { 1486 auto* image_space = space->AsImageSpace(); 1487 const auto& image_header = image_space->GetImageHeader(); 1488 for (size_t i = 0; i < ImageHeader::kImageRootsMax; ++i) { 1489 auto* obj = image_header.GetImageRoot(static_cast<ImageHeader::ImageRoot>(i)); 1490 if (obj != nullptr) { 1491 auto* after_obj = obj; 1492 visitor->VisitRoot(&after_obj, RootInfo(kRootStickyClass)); 1493 CHECK_EQ(after_obj, obj); 1494 } 1495 } 1496 } 1497 } 1498} 1499 1500ArtMethod* Runtime::CreateImtConflictMethod() { 1501 auto* method = Runtime::Current()->GetClassLinker()->CreateRuntimeMethod(); 1502 // When compiling, the code pointer will get set later when the image is loaded. 1503 if (IsAotCompiler()) { 1504 size_t pointer_size = GetInstructionSetPointerSize(instruction_set_); 1505 method->SetEntryPointFromQuickCompiledCodePtrSize(nullptr, pointer_size); 1506 } else { 1507 method->SetEntryPointFromQuickCompiledCode(GetQuickImtConflictStub()); 1508 } 1509 return method; 1510} 1511 1512void Runtime::SetImtConflictMethod(ArtMethod* method) { 1513 CHECK(method != nullptr); 1514 CHECK(method->IsRuntimeMethod()); 1515 imt_conflict_method_ = method; 1516} 1517 1518ArtMethod* Runtime::CreateResolutionMethod() { 1519 auto* method = Runtime::Current()->GetClassLinker()->CreateRuntimeMethod(); 1520 // When compiling, the code pointer will get set later when the image is loaded. 1521 if (IsAotCompiler()) { 1522 size_t pointer_size = GetInstructionSetPointerSize(instruction_set_); 1523 method->SetEntryPointFromQuickCompiledCodePtrSize(nullptr, pointer_size); 1524 } else { 1525 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub()); 1526 } 1527 return method; 1528} 1529 1530ArtMethod* Runtime::CreateCalleeSaveMethod() { 1531 auto* method = Runtime::Current()->GetClassLinker()->CreateRuntimeMethod(); 1532 size_t pointer_size = GetInstructionSetPointerSize(instruction_set_); 1533 method->SetEntryPointFromQuickCompiledCodePtrSize(nullptr, pointer_size); 1534 DCHECK_NE(instruction_set_, kNone); 1535 DCHECK(method->IsRuntimeMethod()); 1536 return method; 1537} 1538 1539void Runtime::DisallowNewSystemWeaks() { 1540 CHECK(!kUseReadBarrier); 1541 monitor_list_->DisallowNewMonitors(); 1542 intern_table_->ChangeWeakRootState(gc::kWeakRootStateNoReadsOrWrites); 1543 java_vm_->DisallowNewWeakGlobals(); 1544 heap_->DisallowNewAllocationRecords(); 1545 lambda_box_table_->DisallowNewWeakBoxedLambdas(); 1546} 1547 1548void Runtime::AllowNewSystemWeaks() { 1549 CHECK(!kUseReadBarrier); 1550 monitor_list_->AllowNewMonitors(); 1551 intern_table_->ChangeWeakRootState(gc::kWeakRootStateNormal); // TODO: Do this in the sweeping. 1552 java_vm_->AllowNewWeakGlobals(); 1553 heap_->AllowNewAllocationRecords(); 1554 lambda_box_table_->AllowNewWeakBoxedLambdas(); 1555} 1556 1557void Runtime::BroadcastForNewSystemWeaks() { 1558 // This is used for the read barrier case that uses the thread-local 1559 // Thread::GetWeakRefAccessEnabled() flag. 1560 CHECK(kUseReadBarrier); 1561 monitor_list_->BroadcastForNewMonitors(); 1562 intern_table_->BroadcastForNewInterns(); 1563 java_vm_->BroadcastForNewWeakGlobals(); 1564 heap_->BroadcastForNewAllocationRecords(); 1565 lambda_box_table_->BroadcastForNewWeakBoxedLambdas(); 1566} 1567 1568void Runtime::SetInstructionSet(InstructionSet instruction_set) { 1569 instruction_set_ = instruction_set; 1570 if ((instruction_set_ == kThumb2) || (instruction_set_ == kArm)) { 1571 for (int i = 0; i != kLastCalleeSaveType; ++i) { 1572 CalleeSaveType type = static_cast<CalleeSaveType>(i); 1573 callee_save_method_frame_infos_[i] = arm::ArmCalleeSaveMethodFrameInfo(type); 1574 } 1575 } else if (instruction_set_ == kMips) { 1576 for (int i = 0; i != kLastCalleeSaveType; ++i) { 1577 CalleeSaveType type = static_cast<CalleeSaveType>(i); 1578 callee_save_method_frame_infos_[i] = mips::MipsCalleeSaveMethodFrameInfo(type); 1579 } 1580 } else if (instruction_set_ == kMips64) { 1581 for (int i = 0; i != kLastCalleeSaveType; ++i) { 1582 CalleeSaveType type = static_cast<CalleeSaveType>(i); 1583 callee_save_method_frame_infos_[i] = mips64::Mips64CalleeSaveMethodFrameInfo(type); 1584 } 1585 } else if (instruction_set_ == kX86) { 1586 for (int i = 0; i != kLastCalleeSaveType; ++i) { 1587 CalleeSaveType type = static_cast<CalleeSaveType>(i); 1588 callee_save_method_frame_infos_[i] = x86::X86CalleeSaveMethodFrameInfo(type); 1589 } 1590 } else if (instruction_set_ == kX86_64) { 1591 for (int i = 0; i != kLastCalleeSaveType; ++i) { 1592 CalleeSaveType type = static_cast<CalleeSaveType>(i); 1593 callee_save_method_frame_infos_[i] = x86_64::X86_64CalleeSaveMethodFrameInfo(type); 1594 } 1595 } else if (instruction_set_ == kArm64) { 1596 for (int i = 0; i != kLastCalleeSaveType; ++i) { 1597 CalleeSaveType type = static_cast<CalleeSaveType>(i); 1598 callee_save_method_frame_infos_[i] = arm64::Arm64CalleeSaveMethodFrameInfo(type); 1599 } 1600 } else { 1601 UNIMPLEMENTED(FATAL) << instruction_set_; 1602 } 1603} 1604 1605void Runtime::SetCalleeSaveMethod(ArtMethod* method, CalleeSaveType type) { 1606 DCHECK_LT(static_cast<int>(type), static_cast<int>(kLastCalleeSaveType)); 1607 CHECK(method != nullptr); 1608 callee_save_methods_[type] = reinterpret_cast<uintptr_t>(method); 1609} 1610 1611void Runtime::StartProfiler(const char* profile_output_filename) { 1612 profile_output_filename_ = profile_output_filename; 1613 profiler_started_ = 1614 BackgroundMethodSamplingProfiler::Start(profile_output_filename_, profiler_options_); 1615} 1616 1617// Transaction support. 1618void Runtime::EnterTransactionMode(Transaction* transaction) { 1619 DCHECK(IsAotCompiler()); 1620 DCHECK(transaction != nullptr); 1621 DCHECK(!IsActiveTransaction()); 1622 preinitialization_transaction_ = transaction; 1623} 1624 1625void Runtime::ExitTransactionMode() { 1626 DCHECK(IsAotCompiler()); 1627 DCHECK(IsActiveTransaction()); 1628 preinitialization_transaction_ = nullptr; 1629} 1630 1631bool Runtime::IsTransactionAborted() const { 1632 if (!IsActiveTransaction()) { 1633 return false; 1634 } else { 1635 DCHECK(IsAotCompiler()); 1636 return preinitialization_transaction_->IsAborted(); 1637 } 1638} 1639 1640void Runtime::AbortTransactionAndThrowAbortError(Thread* self, const std::string& abort_message) { 1641 DCHECK(IsAotCompiler()); 1642 DCHECK(IsActiveTransaction()); 1643 // Throwing an exception may cause its class initialization. If we mark the transaction 1644 // aborted before that, we may warn with a false alarm. Throwing the exception before 1645 // marking the transaction aborted avoids that. 1646 preinitialization_transaction_->ThrowAbortError(self, &abort_message); 1647 preinitialization_transaction_->Abort(abort_message); 1648} 1649 1650void Runtime::ThrowTransactionAbortError(Thread* self) { 1651 DCHECK(IsAotCompiler()); 1652 DCHECK(IsActiveTransaction()); 1653 // Passing nullptr means we rethrow an exception with the earlier transaction abort message. 1654 preinitialization_transaction_->ThrowAbortError(self, nullptr); 1655} 1656 1657void Runtime::RecordWriteFieldBoolean(mirror::Object* obj, MemberOffset field_offset, 1658 uint8_t value, bool is_volatile) const { 1659 DCHECK(IsAotCompiler()); 1660 DCHECK(IsActiveTransaction()); 1661 preinitialization_transaction_->RecordWriteFieldBoolean(obj, field_offset, value, is_volatile); 1662} 1663 1664void Runtime::RecordWriteFieldByte(mirror::Object* obj, MemberOffset field_offset, 1665 int8_t value, bool is_volatile) const { 1666 DCHECK(IsAotCompiler()); 1667 DCHECK(IsActiveTransaction()); 1668 preinitialization_transaction_->RecordWriteFieldByte(obj, field_offset, value, is_volatile); 1669} 1670 1671void Runtime::RecordWriteFieldChar(mirror::Object* obj, MemberOffset field_offset, 1672 uint16_t value, bool is_volatile) const { 1673 DCHECK(IsAotCompiler()); 1674 DCHECK(IsActiveTransaction()); 1675 preinitialization_transaction_->RecordWriteFieldChar(obj, field_offset, value, is_volatile); 1676} 1677 1678void Runtime::RecordWriteFieldShort(mirror::Object* obj, MemberOffset field_offset, 1679 int16_t value, bool is_volatile) const { 1680 DCHECK(IsAotCompiler()); 1681 DCHECK(IsActiveTransaction()); 1682 preinitialization_transaction_->RecordWriteFieldShort(obj, field_offset, value, is_volatile); 1683} 1684 1685void Runtime::RecordWriteField32(mirror::Object* obj, MemberOffset field_offset, 1686 uint32_t value, bool is_volatile) const { 1687 DCHECK(IsAotCompiler()); 1688 DCHECK(IsActiveTransaction()); 1689 preinitialization_transaction_->RecordWriteField32(obj, field_offset, value, is_volatile); 1690} 1691 1692void Runtime::RecordWriteField64(mirror::Object* obj, MemberOffset field_offset, 1693 uint64_t value, bool is_volatile) const { 1694 DCHECK(IsAotCompiler()); 1695 DCHECK(IsActiveTransaction()); 1696 preinitialization_transaction_->RecordWriteField64(obj, field_offset, value, is_volatile); 1697} 1698 1699void Runtime::RecordWriteFieldReference(mirror::Object* obj, MemberOffset field_offset, 1700 mirror::Object* value, bool is_volatile) const { 1701 DCHECK(IsAotCompiler()); 1702 DCHECK(IsActiveTransaction()); 1703 preinitialization_transaction_->RecordWriteFieldReference(obj, field_offset, value, is_volatile); 1704} 1705 1706void Runtime::RecordWriteArray(mirror::Array* array, size_t index, uint64_t value) const { 1707 DCHECK(IsAotCompiler()); 1708 DCHECK(IsActiveTransaction()); 1709 preinitialization_transaction_->RecordWriteArray(array, index, value); 1710} 1711 1712void Runtime::RecordStrongStringInsertion(mirror::String* s) const { 1713 DCHECK(IsAotCompiler()); 1714 DCHECK(IsActiveTransaction()); 1715 preinitialization_transaction_->RecordStrongStringInsertion(s); 1716} 1717 1718void Runtime::RecordWeakStringInsertion(mirror::String* s) const { 1719 DCHECK(IsAotCompiler()); 1720 DCHECK(IsActiveTransaction()); 1721 preinitialization_transaction_->RecordWeakStringInsertion(s); 1722} 1723 1724void Runtime::RecordStrongStringRemoval(mirror::String* s) const { 1725 DCHECK(IsAotCompiler()); 1726 DCHECK(IsActiveTransaction()); 1727 preinitialization_transaction_->RecordStrongStringRemoval(s); 1728} 1729 1730void Runtime::RecordWeakStringRemoval(mirror::String* s) const { 1731 DCHECK(IsAotCompiler()); 1732 DCHECK(IsActiveTransaction()); 1733 preinitialization_transaction_->RecordWeakStringRemoval(s); 1734} 1735 1736void Runtime::SetFaultMessage(const std::string& message) { 1737 MutexLock mu(Thread::Current(), fault_message_lock_); 1738 fault_message_ = message; 1739} 1740 1741void Runtime::AddCurrentRuntimeFeaturesAsDex2OatArguments(std::vector<std::string>* argv) 1742 const { 1743 if (GetInstrumentation()->InterpretOnly() || UseJit()) { 1744 argv->push_back("--compiler-filter=interpret-only"); 1745 } 1746 1747 // Make the dex2oat instruction set match that of the launching runtime. If we have multiple 1748 // architecture support, dex2oat may be compiled as a different instruction-set than that 1749 // currently being executed. 1750 std::string instruction_set("--instruction-set="); 1751 instruction_set += GetInstructionSetString(kRuntimeISA); 1752 argv->push_back(instruction_set); 1753 1754 std::unique_ptr<const InstructionSetFeatures> features(InstructionSetFeatures::FromCppDefines()); 1755 std::string feature_string("--instruction-set-features="); 1756 feature_string += features->GetFeatureString(); 1757 argv->push_back(feature_string); 1758} 1759 1760void Runtime::UpdateProfilerState(int state) { 1761 VLOG(profiler) << "Profiler state updated to " << state; 1762} 1763 1764void Runtime::CreateJit() { 1765 CHECK(!IsAotCompiler()); 1766 if (GetInstrumentation()->IsForcedInterpretOnly()) { 1767 // Don't create JIT if forced interpret only. 1768 return; 1769 } 1770 std::string error_msg; 1771 jit_.reset(jit::Jit::Create(jit_options_.get(), &error_msg)); 1772 if (jit_.get() != nullptr) { 1773 compiler_callbacks_ = jit_->GetCompilerCallbacks(); 1774 jit_->CreateInstrumentationCache(jit_options_->GetCompileThreshold(), 1775 jit_options_->GetWarmupThreshold()); 1776 jit_->CreateThreadPool(); 1777 } else { 1778 LOG(WARNING) << "Failed to create JIT " << error_msg; 1779 } 1780} 1781 1782bool Runtime::CanRelocate() const { 1783 return !IsAotCompiler() || compiler_callbacks_->IsRelocationPossible(); 1784} 1785 1786bool Runtime::IsCompilingBootImage() const { 1787 return IsCompiler() && compiler_callbacks_->IsBootImage(); 1788} 1789 1790void Runtime::SetResolutionMethod(ArtMethod* method) { 1791 CHECK(method != nullptr); 1792 CHECK(method->IsRuntimeMethod()) << method; 1793 resolution_method_ = method; 1794} 1795 1796void Runtime::SetImtUnimplementedMethod(ArtMethod* method) { 1797 CHECK(method != nullptr); 1798 CHECK(method->IsRuntimeMethod()); 1799 imt_unimplemented_method_ = method; 1800} 1801 1802bool Runtime::IsVerificationEnabled() const { 1803 return verify_ == verifier::VerifyMode::kEnable; 1804} 1805 1806bool Runtime::IsVerificationSoftFail() const { 1807 return verify_ == verifier::VerifyMode::kSoftFail; 1808} 1809 1810LinearAlloc* Runtime::CreateLinearAlloc() { 1811 // For 64 bit compilers, it needs to be in low 4GB in the case where we are cross compiling for a 1812 // 32 bit target. In this case, we have 32 bit pointers in the dex cache arrays which can't hold 1813 // when we have 64 bit ArtMethod pointers. 1814 return (IsAotCompiler() && Is64BitInstructionSet(kRuntimeISA)) 1815 ? new LinearAlloc(low_4gb_arena_pool_.get()) 1816 : new LinearAlloc(arena_pool_.get()); 1817} 1818 1819double Runtime::GetHashTableMinLoadFactor() const { 1820 return is_low_memory_mode_ ? kLowMemoryMinLoadFactor : kNormalMinLoadFactor; 1821} 1822 1823double Runtime::GetHashTableMaxLoadFactor() const { 1824 return is_low_memory_mode_ ? kLowMemoryMaxLoadFactor : kNormalMaxLoadFactor; 1825} 1826 1827} // namespace art 1828