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