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