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