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