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 #ifndef ART_RUNTIME_RUNTIME_H_ 18 #define ART_RUNTIME_RUNTIME_H_ 19 20 #include <jni.h> 21 #include <stdio.h> 22 23 #include <forward_list> 24 #include <iosfwd> 25 #include <memory> 26 #include <set> 27 #include <string> 28 #include <utility> 29 #include <vector> 30 31 #include "app_info.h" 32 #include "base/locks.h" 33 #include "base/macros.h" 34 #include "base/mem_map.h" 35 #include "base/metrics/metrics.h" 36 #include "base/string_view_cpp20.h" 37 #include "compat_framework.h" 38 #include "deoptimization_kind.h" 39 #include "dex/dex_file_types.h" 40 #include "experimental_flags.h" 41 #include "gc_root.h" 42 #include "instrumentation.h" 43 #include "jdwp_provider.h" 44 #include "jni/jni_id_manager.h" 45 #include "jni_id_type.h" 46 #include "metrics/reporter.h" 47 #include "obj_ptr.h" 48 #include "offsets.h" 49 #include "process_state.h" 50 #include "quick/quick_method_frame_info.h" 51 #include "reflective_value_visitor.h" 52 #include "runtime_stats.h" 53 54 namespace art { 55 56 namespace gc { 57 class AbstractSystemWeakHolder; 58 class Heap; 59 } // namespace gc 60 61 namespace hiddenapi { 62 enum class EnforcementPolicy; 63 } // namespace hiddenapi 64 65 namespace jit { 66 class Jit; 67 class JitCodeCache; 68 class JitOptions; 69 } // namespace jit 70 71 namespace jni { 72 class SmallLrtAllocator; 73 } // namespace jni 74 75 namespace mirror { 76 class Array; 77 class ClassLoader; 78 class DexCache; 79 template<class T> class ObjectArray; 80 template<class T> class PrimitiveArray; 81 using ByteArray = PrimitiveArray<int8_t>; 82 class String; 83 class Throwable; 84 } // namespace mirror 85 namespace ti { 86 class Agent; 87 class AgentSpec; 88 } // namespace ti 89 namespace verifier { 90 class MethodVerifier; 91 enum class VerifyMode : int8_t; 92 } // namespace verifier 93 class ArenaPool; 94 class ArtMethod; 95 enum class CalleeSaveType: uint32_t; 96 class ClassLinker; 97 class CompilerCallbacks; 98 class Dex2oatImageTest; 99 class DexFile; 100 enum class InstructionSet; 101 class InternTable; 102 class IsMarkedVisitor; 103 class JavaVMExt; 104 class LinearAlloc; 105 class MonitorList; 106 class MonitorPool; 107 class NullPointerHandler; 108 class OatFileAssistantTest; 109 class OatFileManager; 110 class Plugin; 111 struct RuntimeArgumentMap; 112 class RuntimeCallbacks; 113 class SignalCatcher; 114 class StackOverflowHandler; 115 class SuspensionHandler; 116 class ThreadList; 117 class ThreadPool; 118 class Trace; 119 struct TraceConfig; 120 class Transaction; 121 122 using RuntimeOptions = std::vector<std::pair<std::string, const void*>>; 123 124 class Runtime { 125 public: 126 // Parse raw runtime options. 127 static bool ParseOptions(const RuntimeOptions& raw_options, 128 bool ignore_unrecognized, 129 RuntimeArgumentMap* runtime_options); 130 131 // Creates and initializes a new runtime. 132 static bool Create(RuntimeArgumentMap&& runtime_options) 133 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_); 134 135 // Creates and initializes a new runtime. 136 static bool Create(const RuntimeOptions& raw_options, bool ignore_unrecognized) 137 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_); 138 139 enum class RuntimeDebugState { 140 // This doesn't support any debug features / method tracing. This is the expected state usually. 141 kNonJavaDebuggable, 142 // This supports method tracing and a restricted set of debug features (for ex: redefinition 143 // isn't supported). We transition to this state when method tracing has started or when the 144 // debugger was attached and transition back to NonDebuggable once the tracing has stopped / 145 // the debugger agent has detached.. 146 kJavaDebuggable, 147 // The runtime was started as a debuggable runtime. This allows us to support the extended set 148 // of debug features (for ex: redefinition). We never transition out of this state. 149 kJavaDebuggableAtInit 150 }; 151 152 bool EnsurePluginLoaded(const char* plugin_name, std::string* error_msg); 153 bool EnsurePerfettoPlugin(std::string* error_msg); 154 155 // IsAotCompiler for compilers that don't have a running runtime. Only dex2oat currently. IsAotCompiler()156 bool IsAotCompiler() const { 157 return !UseJitCompilation() && IsCompiler(); 158 } 159 160 // IsCompiler is any runtime which has a running compiler, either dex2oat or JIT. IsCompiler()161 bool IsCompiler() const { 162 return compiler_callbacks_ != nullptr; 163 } 164 165 // If a compiler, are we compiling a boot image? 166 bool IsCompilingBootImage() const; 167 168 bool CanRelocate() const; 169 ShouldRelocate()170 bool ShouldRelocate() const { 171 return must_relocate_ && CanRelocate(); 172 } 173 MustRelocateIfPossible()174 bool MustRelocateIfPossible() const { 175 return must_relocate_; 176 } 177 IsImageDex2OatEnabled()178 bool IsImageDex2OatEnabled() const { 179 return image_dex2oat_enabled_; 180 } 181 GetCompilerCallbacks()182 CompilerCallbacks* GetCompilerCallbacks() { 183 return compiler_callbacks_; 184 } 185 SetCompilerCallbacks(CompilerCallbacks * callbacks)186 void SetCompilerCallbacks(CompilerCallbacks* callbacks) { 187 CHECK(callbacks != nullptr); 188 compiler_callbacks_ = callbacks; 189 } 190 IsZygote()191 bool IsZygote() const { 192 return is_zygote_; 193 } 194 IsPrimaryZygote()195 bool IsPrimaryZygote() const { 196 return is_primary_zygote_; 197 } 198 IsSystemServer()199 bool IsSystemServer() const { 200 return is_system_server_; 201 } 202 SetAsSystemServer()203 void SetAsSystemServer() { 204 is_system_server_ = true; 205 is_zygote_ = false; 206 is_primary_zygote_ = false; 207 } 208 SetAsZygoteChild(bool is_system_server,bool is_zygote)209 void SetAsZygoteChild(bool is_system_server, bool is_zygote) { 210 // System server should have been set earlier in SetAsSystemServer. 211 CHECK_EQ(is_system_server_, is_system_server); 212 is_zygote_ = is_zygote; 213 is_primary_zygote_ = false; 214 } 215 IsExplicitGcDisabled()216 bool IsExplicitGcDisabled() const { 217 return is_explicit_gc_disabled_; 218 } 219 220 std::string GetCompilerExecutable() const; 221 GetCompilerOptions()222 const std::vector<std::string>& GetCompilerOptions() const { 223 return compiler_options_; 224 } 225 AddCompilerOption(const std::string & option)226 void AddCompilerOption(const std::string& option) { 227 compiler_options_.push_back(option); 228 } 229 GetImageCompilerOptions()230 const std::vector<std::string>& GetImageCompilerOptions() const { 231 return image_compiler_options_; 232 } 233 GetImageLocations()234 const std::vector<std::string>& GetImageLocations() const { 235 return image_locations_; 236 } 237 238 // Starts a runtime, which may cause threads to be started and code to run. 239 bool Start() UNLOCK_FUNCTION(Locks::mutator_lock_); 240 241 bool IsShuttingDown(Thread* self); IsShuttingDownLocked()242 bool IsShuttingDownLocked() const REQUIRES(Locks::runtime_shutdown_lock_) { 243 return shutting_down_.load(std::memory_order_relaxed); 244 } IsShuttingDownUnsafe()245 bool IsShuttingDownUnsafe() const { 246 return shutting_down_.load(std::memory_order_relaxed); 247 } SetShuttingDown()248 void SetShuttingDown() REQUIRES(Locks::runtime_shutdown_lock_) { 249 shutting_down_.store(true, std::memory_order_relaxed); 250 } 251 NumberOfThreadsBeingBorn()252 size_t NumberOfThreadsBeingBorn() const REQUIRES(Locks::runtime_shutdown_lock_) { 253 return threads_being_born_; 254 } 255 StartThreadBirth()256 void StartThreadBirth() REQUIRES(Locks::runtime_shutdown_lock_) { 257 threads_being_born_++; 258 } 259 260 void EndThreadBirth() REQUIRES(Locks::runtime_shutdown_lock_); 261 IsStarted()262 bool IsStarted() const { 263 return started_; 264 } 265 IsFinishedStarting()266 bool IsFinishedStarting() const { 267 return finished_starting_; 268 } 269 270 void RunRootClinits(Thread* self) REQUIRES_SHARED(Locks::mutator_lock_); 271 Current()272 static Runtime* Current() { 273 return instance_; 274 } 275 276 // Set the current runtime to be the given instance. 277 // Note that this function is not responsible for cleaning up the old instance or taking the 278 // ownership of the new instance. 279 // 280 // For test use only. TestOnlySetCurrent(Runtime * instance)281 static void TestOnlySetCurrent(Runtime* instance) { instance_ = instance; } 282 283 // Aborts semi-cleanly. Used in the implementation of LOG(FATAL), which most 284 // callers should prefer. 285 NO_RETURN static void Abort(const char* msg) REQUIRES(!Locks::abort_lock_); 286 287 // Returns the "main" ThreadGroup, used when attaching user threads. 288 jobject GetMainThreadGroup() const; 289 290 // Returns the "system" ThreadGroup, used when attaching our internal threads. 291 jobject GetSystemThreadGroup() const; 292 293 // Returns the system ClassLoader which represents the CLASSPATH. 294 jobject GetSystemClassLoader() const; 295 296 // Attaches the calling native thread to the runtime. 297 bool AttachCurrentThread(const char* thread_name, 298 bool as_daemon, 299 jobject thread_group, 300 bool create_peer, 301 bool should_run_callbacks = true); 302 303 void CallExitHook(jint status); 304 305 // Detaches the current native thread from the runtime. 306 void DetachCurrentThread(bool should_run_callbacks = true) REQUIRES(!Locks::mutator_lock_); 307 308 void DumpDeoptimizations(std::ostream& os); 309 void DumpForSigQuit(std::ostream& os); 310 void DumpLockHolders(std::ostream& os); 311 312 ~Runtime(); 313 GetBootClassPath()314 const std::vector<std::string>& GetBootClassPath() const { 315 return boot_class_path_; 316 } 317 GetBootClassPathLocations()318 const std::vector<std::string>& GetBootClassPathLocations() const { 319 DCHECK(boot_class_path_locations_.empty() || 320 boot_class_path_locations_.size() == boot_class_path_.size()); 321 return boot_class_path_locations_.empty() ? boot_class_path_ : boot_class_path_locations_; 322 } 323 324 // Dynamically adds an element to boot class path. 325 void AppendToBootClassPath(const std::string& filename, 326 const std::string& location, 327 const std::vector<std::unique_ptr<const art::DexFile>>& dex_files); 328 329 // Same as above, but takes raw pointers. 330 void AppendToBootClassPath(const std::string& filename, 331 const std::string& location, 332 const std::vector<const art::DexFile*>& dex_files); 333 334 // Same as above, but also takes a dex cache for each dex file. 335 void AppendToBootClassPath( 336 const std::string& filename, 337 const std::string& location, 338 const std::vector<std::pair<const art::DexFile*, ObjPtr<mirror::DexCache>>>& 339 dex_files_and_cache); 340 341 // Dynamically adds an element to boot class path and takes ownership of the dex files. 342 void AddExtraBootDexFiles(const std::string& filename, 343 const std::string& location, 344 std::vector<std::unique_ptr<const art::DexFile>>&& dex_files); 345 GetBootClassPathFds()346 const std::vector<int>& GetBootClassPathFds() const { 347 return boot_class_path_fds_; 348 } 349 GetBootClassPathImageFds()350 const std::vector<int>& GetBootClassPathImageFds() const { 351 return boot_class_path_image_fds_; 352 } 353 GetBootClassPathVdexFds()354 const std::vector<int>& GetBootClassPathVdexFds() const { 355 return boot_class_path_vdex_fds_; 356 } 357 GetBootClassPathOatFds()358 const std::vector<int>& GetBootClassPathOatFds() const { 359 return boot_class_path_oat_fds_; 360 } 361 362 // Returns the checksums for the boot image, extensions and extra boot class path dex files, 363 // based on the image spaces and boot class path dex files loaded in memory. GetBootClassPathChecksums()364 const std::string& GetBootClassPathChecksums() const { 365 return boot_class_path_checksums_; 366 } 367 GetClassPathString()368 const std::string& GetClassPathString() const { 369 return class_path_string_; 370 } 371 GetClassLinker()372 ClassLinker* GetClassLinker() const { 373 return class_linker_; 374 } 375 GetSmallLrtAllocator()376 jni::SmallLrtAllocator* GetSmallLrtAllocator() const { 377 return small_lrt_allocator_; 378 } 379 GetJniIdManager()380 jni::JniIdManager* GetJniIdManager() const { 381 return jni_id_manager_.get(); 382 } 383 GetDefaultStackSize()384 size_t GetDefaultStackSize() const { 385 return default_stack_size_; 386 } 387 GetFinalizerTimeoutMs()388 unsigned int GetFinalizerTimeoutMs() const { 389 return finalizer_timeout_ms_; 390 } 391 GetHeap()392 gc::Heap* GetHeap() const { 393 return heap_; 394 } 395 GetInternTable()396 InternTable* GetInternTable() const { 397 DCHECK(intern_table_ != nullptr); 398 return intern_table_; 399 } 400 GetJavaVM()401 JavaVMExt* GetJavaVM() const { 402 return java_vm_.get(); 403 } 404 GetMaxSpinsBeforeThinLockInflation()405 size_t GetMaxSpinsBeforeThinLockInflation() const { 406 return max_spins_before_thin_lock_inflation_; 407 } 408 GetMonitorList()409 MonitorList* GetMonitorList() const { 410 return monitor_list_; 411 } 412 GetMonitorPool()413 MonitorPool* GetMonitorPool() const { 414 return monitor_pool_; 415 } 416 417 // Is the given object the special object used to mark a cleared JNI weak global? 418 bool IsClearedJniWeakGlobal(ObjPtr<mirror::Object> obj) REQUIRES_SHARED(Locks::mutator_lock_); 419 420 // Get the special object used to mark a cleared JNI weak global. 421 mirror::Object* GetClearedJniWeakGlobal() REQUIRES_SHARED(Locks::mutator_lock_); 422 423 mirror::Throwable* GetPreAllocatedOutOfMemoryErrorWhenThrowingException() 424 REQUIRES_SHARED(Locks::mutator_lock_); 425 mirror::Throwable* GetPreAllocatedOutOfMemoryErrorWhenThrowingOOME() 426 REQUIRES_SHARED(Locks::mutator_lock_); 427 mirror::Throwable* GetPreAllocatedOutOfMemoryErrorWhenHandlingStackOverflow() 428 REQUIRES_SHARED(Locks::mutator_lock_); 429 430 mirror::Throwable* GetPreAllocatedNoClassDefFoundError() 431 REQUIRES_SHARED(Locks::mutator_lock_); 432 GetProperties()433 const std::vector<std::string>& GetProperties() const { 434 return properties_; 435 } 436 GetThreadList()437 ThreadList* GetThreadList() const { 438 return thread_list_; 439 } 440 GetVersion()441 static const char* GetVersion() { 442 return "2.1.0"; 443 } 444 IsMethodHandlesEnabled()445 bool IsMethodHandlesEnabled() const { 446 return true; 447 } 448 449 void DisallowNewSystemWeaks() REQUIRES_SHARED(Locks::mutator_lock_); 450 void AllowNewSystemWeaks() REQUIRES_SHARED(Locks::mutator_lock_); 451 // broadcast_for_checkpoint is true when we broadcast for making blocking threads to respond to 452 // checkpoint requests. It's false when we broadcast to unblock blocking threads after system weak 453 // access is reenabled. 454 void BroadcastForNewSystemWeaks(bool broadcast_for_checkpoint = false); 455 456 // Visit all the roots. If only_dirty is true then non-dirty roots won't be visited. If 457 // clean_dirty is true then dirty roots will be marked as non-dirty after visiting. 458 void VisitRoots(RootVisitor* visitor, VisitRootFlags flags = kVisitRootFlagAllRoots) 459 REQUIRES(!Locks::classlinker_classes_lock_, !Locks::trace_lock_) 460 REQUIRES_SHARED(Locks::mutator_lock_); 461 462 // Visit image roots, only used for hprof since the GC uses the image space mod union table 463 // instead. 464 void VisitImageRoots(RootVisitor* visitor) REQUIRES_SHARED(Locks::mutator_lock_); 465 466 // Visit all of the roots we can safely visit concurrently. 467 void VisitConcurrentRoots(RootVisitor* visitor, 468 VisitRootFlags flags = kVisitRootFlagAllRoots) 469 REQUIRES(!Locks::classlinker_classes_lock_, !Locks::trace_lock_) 470 REQUIRES_SHARED(Locks::mutator_lock_); 471 472 // Visit all of the non thread roots, we can do this with mutators unpaused. 473 void VisitNonThreadRoots(RootVisitor* visitor) 474 REQUIRES_SHARED(Locks::mutator_lock_); 475 476 void VisitTransactionRoots(RootVisitor* visitor) 477 REQUIRES_SHARED(Locks::mutator_lock_); 478 479 // Sweep system weaks, the system weak is deleted if the visitor return null. Otherwise, the 480 // system weak is updated to be the visitor's returned value. 481 void SweepSystemWeaks(IsMarkedVisitor* visitor) REQUIRES_SHARED(Locks::mutator_lock_); 482 483 // Walk all reflective objects and visit their targets as well as any method/fields held by the 484 // runtime threads that are marked as being reflective. 485 void VisitReflectiveTargets(ReflectiveValueVisitor* visitor) REQUIRES(Locks::mutator_lock_); 486 // Helper for visiting reflective targets with lambdas for both field and method reflective 487 // targets. 488 template <typename FieldVis, typename MethodVis> VisitReflectiveTargets(FieldVis && fv,MethodVis && mv)489 void VisitReflectiveTargets(FieldVis&& fv, MethodVis&& mv) REQUIRES(Locks::mutator_lock_) { 490 FunctionReflectiveValueVisitor frvv(fv, mv); 491 VisitReflectiveTargets(&frvv); 492 } 493 494 // Returns a special method that calls into a trampoline for runtime method resolution 495 ArtMethod* GetResolutionMethod(); 496 HasResolutionMethod()497 bool HasResolutionMethod() const { 498 return resolution_method_ != nullptr; 499 } 500 501 void SetResolutionMethod(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_); ClearResolutionMethod()502 void ClearResolutionMethod() { 503 resolution_method_ = nullptr; 504 } 505 506 ArtMethod* CreateResolutionMethod() REQUIRES_SHARED(Locks::mutator_lock_); 507 508 // Returns a special method that calls into a trampoline for runtime imt conflicts. 509 ArtMethod* GetImtConflictMethod(); 510 ArtMethod* GetImtUnimplementedMethod(); 511 HasImtConflictMethod()512 bool HasImtConflictMethod() const { 513 return imt_conflict_method_ != nullptr; 514 } 515 ClearImtConflictMethod()516 void ClearImtConflictMethod() { 517 imt_conflict_method_ = nullptr; 518 } 519 520 void FixupConflictTables() REQUIRES_SHARED(Locks::mutator_lock_); 521 void SetImtConflictMethod(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_); 522 void SetImtUnimplementedMethod(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_); 523 524 ArtMethod* CreateImtConflictMethod(LinearAlloc* linear_alloc) 525 REQUIRES_SHARED(Locks::mutator_lock_); 526 ClearImtUnimplementedMethod()527 void ClearImtUnimplementedMethod() { 528 imt_unimplemented_method_ = nullptr; 529 } 530 HasCalleeSaveMethod(CalleeSaveType type)531 bool HasCalleeSaveMethod(CalleeSaveType type) const { 532 return callee_save_methods_[static_cast<size_t>(type)] != 0u; 533 } 534 535 ArtMethod* GetCalleeSaveMethod(CalleeSaveType type) 536 REQUIRES_SHARED(Locks::mutator_lock_); 537 538 ArtMethod* GetCalleeSaveMethodUnchecked(CalleeSaveType type) 539 REQUIRES_SHARED(Locks::mutator_lock_); 540 541 QuickMethodFrameInfo GetRuntimeMethodFrameInfo(ArtMethod* method) 542 REQUIRES_SHARED(Locks::mutator_lock_); 543 GetCalleeSaveMethodOffset(CalleeSaveType type)544 static constexpr size_t GetCalleeSaveMethodOffset(CalleeSaveType type) { 545 return OFFSETOF_MEMBER(Runtime, callee_save_methods_[static_cast<size_t>(type)]); 546 } 547 GetInstrumentationOffset()548 static constexpr MemberOffset GetInstrumentationOffset() { 549 return MemberOffset(OFFSETOF_MEMBER(Runtime, instrumentation_)); 550 } 551 GetInstructionSet()552 InstructionSet GetInstructionSet() const { 553 return instruction_set_; 554 } 555 556 void SetInstructionSet(InstructionSet instruction_set); 557 void ClearInstructionSet(); 558 559 void SetCalleeSaveMethod(ArtMethod* method, CalleeSaveType type); 560 void ClearCalleeSaveMethods(); 561 562 ArtMethod* CreateCalleeSaveMethod() REQUIRES_SHARED(Locks::mutator_lock_); 563 564 uint64_t GetStat(int kind); 565 GetStats()566 RuntimeStats* GetStats() { 567 return &stats_; 568 } 569 HasStatsEnabled()570 bool HasStatsEnabled() const { 571 return stats_enabled_; 572 } 573 574 void ResetStats(int kinds); 575 576 void SetStatsEnabled(bool new_state) 577 REQUIRES(!Locks::instrument_entrypoints_lock_, !Locks::mutator_lock_); 578 579 enum class NativeBridgeAction { // private 580 kUnload, 581 kInitialize 582 }; 583 GetJit()584 jit::Jit* GetJit() const { 585 return jit_.get(); 586 } 587 GetJitCodeCache()588 jit::JitCodeCache* GetJitCodeCache() const { 589 return jit_code_cache_.get(); 590 } 591 592 // Returns true if JIT compilations are enabled. GetJit() will be not null in this case. 593 bool UseJitCompilation() const; 594 595 void PreZygoteFork(); 596 void PostZygoteFork(); 597 void InitNonZygoteOrPostFork( 598 JNIEnv* env, 599 bool is_system_server, 600 bool is_child_zygote, 601 NativeBridgeAction action, 602 const char* isa, 603 bool profile_system_server = false); 604 GetInstrumentation()605 const instrumentation::Instrumentation* GetInstrumentation() const { 606 return &instrumentation_; 607 } 608 GetInstrumentation()609 instrumentation::Instrumentation* GetInstrumentation() { 610 return &instrumentation_; 611 } 612 613 void RegisterAppInfo(const std::string& package_name, 614 const std::vector<std::string>& code_paths, 615 const std::string& profile_output_filename, 616 const std::string& ref_profile_filename, 617 int32_t code_type); 618 619 // Transaction support. 620 bool IsActiveTransaction() const; 621 // EnterTransactionMode may suspend. 622 void EnterTransactionMode(bool strict, mirror::Class* root) REQUIRES_SHARED(Locks::mutator_lock_); 623 void ExitTransactionMode(); 624 void RollbackAllTransactions() REQUIRES_SHARED(Locks::mutator_lock_); 625 // Transaction rollback and exit transaction are always done together, it's convenience to 626 // do them in one function. 627 void RollbackAndExitTransactionMode() REQUIRES_SHARED(Locks::mutator_lock_); 628 bool IsTransactionAborted() const; 629 const Transaction* GetTransaction() const; 630 Transaction* GetTransaction(); 631 bool IsActiveStrictTransactionMode() const; 632 633 void AbortTransactionAndThrowAbortError(Thread* self, const std::string& abort_message) 634 REQUIRES_SHARED(Locks::mutator_lock_); 635 void ThrowTransactionAbortError(Thread* self) 636 REQUIRES_SHARED(Locks::mutator_lock_); 637 638 void RecordWriteFieldBoolean(mirror::Object* obj, 639 MemberOffset field_offset, 640 uint8_t value, 641 bool is_volatile); 642 void RecordWriteFieldByte(mirror::Object* obj, 643 MemberOffset field_offset, 644 int8_t value, 645 bool is_volatile); 646 void RecordWriteFieldChar(mirror::Object* obj, 647 MemberOffset field_offset, 648 uint16_t value, 649 bool is_volatile); 650 void RecordWriteFieldShort(mirror::Object* obj, 651 MemberOffset field_offset, 652 int16_t value, 653 bool is_volatile); 654 void RecordWriteField32(mirror::Object* obj, 655 MemberOffset field_offset, 656 uint32_t value, 657 bool is_volatile); 658 void RecordWriteField64(mirror::Object* obj, 659 MemberOffset field_offset, 660 uint64_t value, 661 bool is_volatile); 662 void RecordWriteFieldReference(mirror::Object* obj, 663 MemberOffset field_offset, 664 ObjPtr<mirror::Object> value, 665 bool is_volatile) 666 REQUIRES_SHARED(Locks::mutator_lock_); 667 void RecordWriteArray(mirror::Array* array, size_t index, uint64_t value) 668 REQUIRES_SHARED(Locks::mutator_lock_); 669 void RecordStrongStringInsertion(ObjPtr<mirror::String> s) 670 REQUIRES(Locks::intern_table_lock_); 671 void RecordWeakStringInsertion(ObjPtr<mirror::String> s) 672 REQUIRES(Locks::intern_table_lock_); 673 void RecordStrongStringRemoval(ObjPtr<mirror::String> s) 674 REQUIRES(Locks::intern_table_lock_); 675 void RecordWeakStringRemoval(ObjPtr<mirror::String> s) 676 REQUIRES(Locks::intern_table_lock_); 677 void RecordResolveString(ObjPtr<mirror::DexCache> dex_cache, dex::StringIndex string_idx) 678 REQUIRES_SHARED(Locks::mutator_lock_); 679 void RecordResolveMethodType(ObjPtr<mirror::DexCache> dex_cache, dex::ProtoIndex proto_idx) 680 REQUIRES_SHARED(Locks::mutator_lock_); 681 682 void SetFaultMessage(const std::string& message); 683 684 void AddCurrentRuntimeFeaturesAsDex2OatArguments(std::vector<std::string>* arg_vector) const; 685 GetImplicitStackOverflowChecks()686 bool GetImplicitStackOverflowChecks() const { 687 return implicit_so_checks_; 688 } 689 GetImplicitSuspendChecks()690 bool GetImplicitSuspendChecks() const { 691 return implicit_suspend_checks_; 692 } 693 GetImplicitNullChecks()694 bool GetImplicitNullChecks() const { 695 return implicit_null_checks_; 696 } 697 698 void DisableVerifier(); 699 bool IsVerificationEnabled() const; 700 bool IsVerificationSoftFail() const; 701 SetHiddenApiEnforcementPolicy(hiddenapi::EnforcementPolicy policy)702 void SetHiddenApiEnforcementPolicy(hiddenapi::EnforcementPolicy policy) { 703 hidden_api_policy_ = policy; 704 } 705 GetHiddenApiEnforcementPolicy()706 hiddenapi::EnforcementPolicy GetHiddenApiEnforcementPolicy() const { 707 return hidden_api_policy_; 708 } 709 SetCorePlatformApiEnforcementPolicy(hiddenapi::EnforcementPolicy policy)710 void SetCorePlatformApiEnforcementPolicy(hiddenapi::EnforcementPolicy policy) { 711 core_platform_api_policy_ = policy; 712 } 713 GetCorePlatformApiEnforcementPolicy()714 hiddenapi::EnforcementPolicy GetCorePlatformApiEnforcementPolicy() const { 715 return core_platform_api_policy_; 716 } 717 SetTestApiEnforcementPolicy(hiddenapi::EnforcementPolicy policy)718 void SetTestApiEnforcementPolicy(hiddenapi::EnforcementPolicy policy) { 719 test_api_policy_ = policy; 720 } 721 GetTestApiEnforcementPolicy()722 hiddenapi::EnforcementPolicy GetTestApiEnforcementPolicy() const { 723 return test_api_policy_; 724 } 725 SetHiddenApiExemptions(const std::vector<std::string> & exemptions)726 void SetHiddenApiExemptions(const std::vector<std::string>& exemptions) { 727 hidden_api_exemptions_ = exemptions; 728 } 729 GetHiddenApiExemptions()730 const std::vector<std::string>& GetHiddenApiExemptions() { 731 return hidden_api_exemptions_; 732 } 733 SetDedupeHiddenApiWarnings(bool value)734 void SetDedupeHiddenApiWarnings(bool value) { 735 dedupe_hidden_api_warnings_ = value; 736 } 737 ShouldDedupeHiddenApiWarnings()738 bool ShouldDedupeHiddenApiWarnings() { 739 return dedupe_hidden_api_warnings_; 740 } 741 SetHiddenApiEventLogSampleRate(uint32_t rate)742 void SetHiddenApiEventLogSampleRate(uint32_t rate) { 743 hidden_api_access_event_log_rate_ = rate; 744 } 745 GetHiddenApiEventLogSampleRate()746 uint32_t GetHiddenApiEventLogSampleRate() const { 747 return hidden_api_access_event_log_rate_; 748 } 749 GetProcessPackageName()750 const std::string& GetProcessPackageName() const { 751 return process_package_name_; 752 } 753 SetProcessPackageName(const char * package_name)754 void SetProcessPackageName(const char* package_name) { 755 if (package_name == nullptr) { 756 process_package_name_.clear(); 757 } else { 758 process_package_name_ = package_name; 759 } 760 } 761 GetProcessDataDirectory()762 const std::string& GetProcessDataDirectory() const { 763 return process_data_directory_; 764 } 765 SetProcessDataDirectory(const char * data_dir)766 void SetProcessDataDirectory(const char* data_dir) { 767 if (data_dir == nullptr) { 768 process_data_directory_.clear(); 769 } else { 770 process_data_directory_ = data_dir; 771 } 772 } 773 GetCpuAbilist()774 const std::vector<std::string>& GetCpuAbilist() const { 775 return cpu_abilist_; 776 } 777 IsRunningOnMemoryTool()778 bool IsRunningOnMemoryTool() const { 779 return is_running_on_memory_tool_; 780 } 781 SetTargetSdkVersion(uint32_t version)782 void SetTargetSdkVersion(uint32_t version) { 783 target_sdk_version_ = version; 784 } 785 GetTargetSdkVersion()786 uint32_t GetTargetSdkVersion() const { 787 return target_sdk_version_; 788 } 789 GetCompatFramework()790 CompatFramework& GetCompatFramework() { 791 return compat_framework_; 792 } 793 GetZygoteMaxFailedBoots()794 uint32_t GetZygoteMaxFailedBoots() const { 795 return zygote_max_failed_boots_; 796 } 797 AreExperimentalFlagsEnabled(ExperimentalFlags flags)798 bool AreExperimentalFlagsEnabled(ExperimentalFlags flags) { 799 return (experimental_flags_ & flags) != ExperimentalFlags::kNone; 800 } 801 802 void CreateJitCodeCache(bool rwx_memory_allowed); 803 804 // Create the JIT and instrumentation and code cache. 805 void CreateJit(); 806 GetLinearAllocArenaPool()807 ArenaPool* GetLinearAllocArenaPool() { 808 return linear_alloc_arena_pool_.get(); 809 } GetArenaPool()810 ArenaPool* GetArenaPool() { 811 return arena_pool_.get(); 812 } GetArenaPool()813 const ArenaPool* GetArenaPool() const { 814 return arena_pool_.get(); 815 } GetJitArenaPool()816 ArenaPool* GetJitArenaPool() { 817 return jit_arena_pool_.get(); 818 } 819 820 void ReclaimArenaPoolMemory(); 821 GetLinearAlloc()822 LinearAlloc* GetLinearAlloc() { 823 return linear_alloc_.get(); 824 } 825 GetStartupLinearAlloc()826 LinearAlloc* GetStartupLinearAlloc() { 827 return startup_linear_alloc_.load(std::memory_order_relaxed); 828 } 829 GetJITOptions()830 jit::JitOptions* GetJITOptions() { 831 return jit_options_.get(); 832 } 833 IsJavaDebuggable()834 bool IsJavaDebuggable() const { 835 return runtime_debug_state_ == RuntimeDebugState::kJavaDebuggable || 836 runtime_debug_state_ == RuntimeDebugState::kJavaDebuggableAtInit; 837 } 838 IsJavaDebuggableAtInit()839 bool IsJavaDebuggableAtInit() const { 840 return runtime_debug_state_ == RuntimeDebugState::kJavaDebuggableAtInit; 841 } 842 SetProfileableFromShell(bool value)843 void SetProfileableFromShell(bool value) { 844 is_profileable_from_shell_ = value; 845 } 846 IsProfileableFromShell()847 bool IsProfileableFromShell() const { 848 return is_profileable_from_shell_; 849 } 850 SetProfileable(bool value)851 void SetProfileable(bool value) { 852 is_profileable_ = value; 853 } 854 IsProfileable()855 bool IsProfileable() const { 856 return is_profileable_; 857 } 858 859 void SetRuntimeDebugState(RuntimeDebugState state); 860 861 // Deoptimize the boot image, called for Java debuggable apps. 862 void DeoptimizeBootImage() REQUIRES(Locks::mutator_lock_); 863 IsNativeDebuggable()864 bool IsNativeDebuggable() const { 865 return is_native_debuggable_; 866 } 867 SetNativeDebuggable(bool value)868 void SetNativeDebuggable(bool value) { 869 is_native_debuggable_ = value; 870 } 871 872 void SetSignalHookDebuggable(bool value); 873 AreNonStandardExitsEnabled()874 bool AreNonStandardExitsEnabled() const { 875 return non_standard_exits_enabled_; 876 } 877 SetNonStandardExitsEnabled()878 void SetNonStandardExitsEnabled() { 879 non_standard_exits_enabled_ = true; 880 } 881 AreAsyncExceptionsThrown()882 bool AreAsyncExceptionsThrown() const { 883 return async_exceptions_thrown_; 884 } 885 SetAsyncExceptionsThrown()886 void SetAsyncExceptionsThrown() { 887 async_exceptions_thrown_ = true; 888 } 889 890 // Returns the build fingerprint, if set. Otherwise an empty string is returned. GetFingerprint()891 std::string GetFingerprint() { 892 return fingerprint_; 893 } 894 895 // Called from class linker. 896 void SetSentinel(ObjPtr<mirror::Object> sentinel) REQUIRES_SHARED(Locks::mutator_lock_); 897 // For testing purpose only. 898 // TODO: Remove this when this is no longer needed (b/116087961). 899 GcRoot<mirror::Object> GetSentinel() REQUIRES_SHARED(Locks::mutator_lock_); 900 901 902 // Use a sentinel for marking entries in a table that have been cleared. 903 // This helps diagnosing in case code tries to wrongly access such 904 // entries. GetWeakClassSentinel()905 static mirror::Class* GetWeakClassSentinel() { 906 return reinterpret_cast<mirror::Class*>(0xebadbeef); 907 } 908 909 // Create a normal LinearAlloc or low 4gb version if we are 64 bit AOT compiler. 910 LinearAlloc* CreateLinearAlloc(); 911 // Setup linear-alloc allocators to stop using the current arena so that the 912 // next allocations, which would be after zygote fork, happens in userfaultfd 913 // visited space. 914 void SetupLinearAllocForPostZygoteFork(Thread* self) 915 REQUIRES(!Locks::mutator_lock_, !Locks::classlinker_classes_lock_); 916 GetOatFileManager()917 OatFileManager& GetOatFileManager() const { 918 DCHECK(oat_file_manager_ != nullptr); 919 return *oat_file_manager_; 920 } 921 922 double GetHashTableMinLoadFactor() const; 923 double GetHashTableMaxLoadFactor() const; 924 IsSafeMode()925 bool IsSafeMode() const { 926 return safe_mode_; 927 } 928 SetSafeMode(bool mode)929 void SetSafeMode(bool mode) { 930 safe_mode_ = mode; 931 } 932 GetDumpNativeStackOnSigQuit()933 bool GetDumpNativeStackOnSigQuit() const { 934 return dump_native_stack_on_sig_quit_; 935 } 936 937 void UpdateProcessState(ProcessState process_state); 938 939 // Returns true if we currently care about long mutator pause. InJankPerceptibleProcessState()940 bool InJankPerceptibleProcessState() const { 941 return process_state_ == kProcessStateJankPerceptible; 942 } 943 944 void RegisterSensitiveThread() const; 945 SetZygoteNoThreadSection(bool val)946 void SetZygoteNoThreadSection(bool val) { 947 zygote_no_threads_ = val; 948 } 949 IsZygoteNoThreadSection()950 bool IsZygoteNoThreadSection() const { 951 return zygote_no_threads_; 952 } 953 954 // Returns if the code can be deoptimized asynchronously. Code may be compiled with some 955 // optimization that makes it impossible to deoptimize. 956 bool IsAsyncDeoptimizeable(ArtMethod* method, uintptr_t code) const 957 REQUIRES_SHARED(Locks::mutator_lock_); 958 959 // Returns a saved copy of the environment (getenv/setenv values). 960 // Used by Fork to protect against overwriting LD_LIBRARY_PATH, etc. GetEnvSnapshot()961 char** GetEnvSnapshot() const { 962 return env_snapshot_.GetSnapshot(); 963 } 964 965 void AddSystemWeakHolder(gc::AbstractSystemWeakHolder* holder); 966 void RemoveSystemWeakHolder(gc::AbstractSystemWeakHolder* holder); 967 968 void AttachAgent(JNIEnv* env, const std::string& agent_arg, jobject class_loader); 969 GetAgents()970 const std::list<std::unique_ptr<ti::Agent>>& GetAgents() const { 971 return agents_; 972 } 973 974 RuntimeCallbacks* GetRuntimeCallbacks(); 975 HasLoadedPlugins()976 bool HasLoadedPlugins() const { 977 return !plugins_.empty(); 978 } 979 980 void InitThreadGroups(Thread* self); 981 SetDumpGCPerformanceOnShutdown(bool value)982 void SetDumpGCPerformanceOnShutdown(bool value) { 983 dump_gc_performance_on_shutdown_ = value; 984 } 985 GetDumpGCPerformanceOnShutdown()986 bool GetDumpGCPerformanceOnShutdown() const { 987 return dump_gc_performance_on_shutdown_; 988 } 989 IncrementDeoptimizationCount(DeoptimizationKind kind)990 void IncrementDeoptimizationCount(DeoptimizationKind kind) { 991 DCHECK_LE(kind, DeoptimizationKind::kLast); 992 deoptimization_counts_[static_cast<size_t>(kind)]++; 993 } 994 GetNumberOfDeoptimizations()995 uint32_t GetNumberOfDeoptimizations() const { 996 uint32_t result = 0; 997 for (size_t i = 0; i <= static_cast<size_t>(DeoptimizationKind::kLast); ++i) { 998 result += deoptimization_counts_[i]; 999 } 1000 return result; 1001 } 1002 DenyArtApexDataFiles()1003 bool DenyArtApexDataFiles() const { 1004 return deny_art_apex_data_files_; 1005 } 1006 GetMadviseWillNeedTotalDexSize()1007 size_t GetMadviseWillNeedTotalDexSize() const { 1008 return madvise_willneed_total_dex_size_; 1009 } 1010 GetMadviseWillNeedSizeOdex()1011 size_t GetMadviseWillNeedSizeOdex() const { 1012 return madvise_willneed_odex_filesize_; 1013 } 1014 GetMadviseWillNeedSizeArt()1015 size_t GetMadviseWillNeedSizeArt() const { 1016 return madvise_willneed_art_filesize_; 1017 } 1018 GetJdwpOptions()1019 const std::string& GetJdwpOptions() { 1020 return jdwp_options_; 1021 } 1022 GetJdwpProvider()1023 JdwpProvider GetJdwpProvider() const { 1024 return jdwp_provider_; 1025 } 1026 GetJniIdType()1027 JniIdType GetJniIdType() const { 1028 return jni_ids_indirection_; 1029 } 1030 CanSetJniIdType()1031 bool CanSetJniIdType() const { 1032 return GetJniIdType() == JniIdType::kSwapablePointer; 1033 } 1034 1035 // Changes the JniIdType to the given type. Only allowed if CanSetJniIdType(). All threads must be 1036 // suspended to call this function. 1037 void SetJniIdType(JniIdType t); 1038 GetVerifierLoggingThresholdMs()1039 uint32_t GetVerifierLoggingThresholdMs() const { 1040 return verifier_logging_threshold_ms_; 1041 } 1042 1043 // Atomically delete the thread pool if the reference count is 0. 1044 bool DeleteThreadPool() REQUIRES(!Locks::runtime_thread_pool_lock_); 1045 1046 // Wait for all the thread workers to be attached. 1047 void WaitForThreadPoolWorkersToStart() REQUIRES(!Locks::runtime_thread_pool_lock_); 1048 1049 // Scoped usage of the runtime thread pool. Prevents the pool from being 1050 // deleted. Note that the thread pool is only for startup and gets deleted after. 1051 class ScopedThreadPoolUsage { 1052 public: 1053 ScopedThreadPoolUsage(); 1054 ~ScopedThreadPoolUsage(); 1055 1056 // Return the thread pool. GetThreadPool()1057 ThreadPool* GetThreadPool() const { 1058 return thread_pool_; 1059 } 1060 1061 private: 1062 ThreadPool* const thread_pool_; 1063 }; 1064 ReleaseStartupLinearAlloc()1065 LinearAlloc* ReleaseStartupLinearAlloc() { 1066 return startup_linear_alloc_.exchange(nullptr, std::memory_order_relaxed); 1067 } 1068 LoadAppImageStartupCache()1069 bool LoadAppImageStartupCache() const { 1070 return load_app_image_startup_cache_; 1071 } 1072 SetLoadAppImageStartupCacheEnabled(bool enabled)1073 void SetLoadAppImageStartupCacheEnabled(bool enabled) { 1074 load_app_image_startup_cache_ = enabled; 1075 } 1076 1077 // Reset the startup completed status so that we can call NotifyStartupCompleted again. Should 1078 // only be used for testing. 1079 void ResetStartupCompleted(); 1080 1081 // Notify the runtime that application startup is considered completed. Only has effect for the 1082 // first call. Returns whether this was the first call. 1083 bool NotifyStartupCompleted(); 1084 1085 // Notify the runtime that the application finished loading some dex/odex files. This is 1086 // called everytime we load a set of dex files in a class loader. 1087 void NotifyDexFileLoaded(); 1088 1089 // Return true if startup is already completed. 1090 bool GetStartupCompleted() const; 1091 IsVerifierMissingKThrowFatal()1092 bool IsVerifierMissingKThrowFatal() const { 1093 return verifier_missing_kthrow_fatal_; 1094 } 1095 IsJavaZygoteForkLoopRequired()1096 bool IsJavaZygoteForkLoopRequired() const { 1097 return force_java_zygote_fork_loop_; 1098 } 1099 IsPerfettoHprofEnabled()1100 bool IsPerfettoHprofEnabled() const { 1101 return perfetto_hprof_enabled_; 1102 } 1103 IsPerfettoJavaHeapStackProfEnabled()1104 bool IsPerfettoJavaHeapStackProfEnabled() const { 1105 return perfetto_javaheapprof_enabled_; 1106 } 1107 IsMonitorTimeoutEnabled()1108 bool IsMonitorTimeoutEnabled() const { 1109 return monitor_timeout_enable_; 1110 } 1111 GetMonitorTimeoutNs()1112 uint64_t GetMonitorTimeoutNs() const { 1113 return monitor_timeout_ns_; 1114 } 1115 1116 // Return whether this is system server and it is being profiled. 1117 bool IsSystemServerProfiled() const; 1118 1119 // Return whether we should load oat files as executable or not. 1120 bool GetOatFilesExecutable() const; 1121 GetMetrics()1122 metrics::ArtMetrics* GetMetrics() { return &metrics_; } 1123 GetAppInfo()1124 AppInfo* GetAppInfo() { return &app_info_; } 1125 1126 void RequestMetricsReport(bool synchronous = true); 1127 1128 static void MadviseFileForRange(size_t madvise_size_limit_bytes, 1129 size_t map_size_bytes, 1130 const uint8_t* map_begin, 1131 const uint8_t* map_end, 1132 const std::string& file_name); 1133 GetApexVersions()1134 const std::string& GetApexVersions() const { 1135 return apex_versions_; 1136 } 1137 1138 // Return whether a boot image has a profile. This means it's an in-memory 1139 // image rather that an image loaded from disk. 1140 bool HasImageWithProfile() const; 1141 GetNoSigChain()1142 bool GetNoSigChain() const { 1143 return no_sig_chain_; 1144 } 1145 1146 void AddGeneratedCodeRange(const void* start, size_t size); 1147 void RemoveGeneratedCodeRange(const void* start, size_t size) 1148 REQUIRES_SHARED(Locks::mutator_lock_); 1149 1150 // Trigger a flag reload from system properties or device congfigs. 1151 // 1152 // Should only be called from runtime init and zygote post fork as 1153 // we don't want to change the runtime config midway during execution. 1154 // 1155 // The caller argument should be the name of the function making this call 1156 // and will be used to enforce the appropriate names. 1157 // 1158 // See Flags::ReloadAllFlags as well. 1159 static void ReloadAllFlags(const std::string& caller); 1160 1161 // Parses /apex/apex-info-list.xml to build a string containing apex versions of boot classpath 1162 // jars, which is encoded into .oat files. 1163 static std::string GetApexVersions(ArrayRef<const std::string> boot_class_path_locations); 1164 AllowInMemoryCompilation()1165 bool AllowInMemoryCompilation() const { return allow_in_memory_compilation_; } 1166 1167 // Used by plugin code to attach a hook for OOME. SetOutOfMemoryErrorHook(void (* hook)())1168 void SetOutOfMemoryErrorHook(void (*hook)()) { 1169 out_of_memory_error_hook_ = hook; 1170 } 1171 OutOfMemoryErrorHook()1172 void OutOfMemoryErrorHook() { 1173 if (out_of_memory_error_hook_ != nullptr) { 1174 out_of_memory_error_hook_(); 1175 } 1176 } 1177 1178 private: 1179 static void InitPlatformSignalHandlers(); 1180 1181 Runtime(); 1182 HandlesSignalsInCompiledCode()1183 bool HandlesSignalsInCompiledCode() const { 1184 return !no_sig_chain_ && 1185 (implicit_null_checks_ || implicit_so_checks_ || implicit_suspend_checks_); 1186 } 1187 1188 void BlockSignals(); 1189 1190 bool Init(RuntimeArgumentMap&& runtime_options) 1191 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_); 1192 void InitNativeMethods() REQUIRES(!Locks::mutator_lock_); 1193 void RegisterRuntimeNativeMethods(JNIEnv* env); 1194 void InitMetrics(); 1195 1196 void StartDaemonThreads() REQUIRES_SHARED(Locks::mutator_lock_); 1197 void StartSignalCatcher(); 1198 1199 void MaybeSaveJitProfilingInfo(); 1200 1201 // Visit all of the thread roots. 1202 void VisitThreadRoots(RootVisitor* visitor, VisitRootFlags flags) 1203 REQUIRES_SHARED(Locks::mutator_lock_); 1204 1205 // Visit all other roots which must be done with mutators suspended. 1206 void VisitNonConcurrentRoots(RootVisitor* visitor, VisitRootFlags flags) 1207 REQUIRES_SHARED(Locks::mutator_lock_); 1208 1209 // Constant roots are the roots which never change after the runtime is initialized, they only 1210 // need to be visited once per GC cycle. 1211 void VisitConstantRoots(RootVisitor* visitor) 1212 REQUIRES_SHARED(Locks::mutator_lock_); 1213 1214 // Note: To be lock-free, GetFaultMessage temporarily replaces the lock message with null. 1215 // As such, there is a window where a call will return an empty string. In general, 1216 // only aborting code should retrieve this data (via GetFaultMessageForAbortLogging 1217 // friend). 1218 std::string GetFaultMessage(); 1219 1220 ThreadPool* AcquireThreadPool() REQUIRES(!Locks::runtime_thread_pool_lock_); 1221 void ReleaseThreadPool() REQUIRES(!Locks::runtime_thread_pool_lock_); 1222 1223 // Caches the apex versions produced by `GetApexVersions`. 1224 void InitializeApexVersions(); 1225 1226 void AppendToBootClassPath(const std::string& filename, const std::string& location); 1227 1228 // A pointer to the active runtime or null. 1229 static Runtime* instance_; 1230 1231 // NOTE: these must match the gc::ProcessState values as they come directly from the framework. 1232 static constexpr int kProfileForground = 0; 1233 static constexpr int kProfileBackground = 1; 1234 1235 static constexpr uint32_t kCalleeSaveSize = 6u; 1236 1237 // 64 bit so that we can share the same asm offsets for both 32 and 64 bits. 1238 uint64_t callee_save_methods_[kCalleeSaveSize]; 1239 // Pre-allocated exceptions (see Runtime::Init). 1240 GcRoot<mirror::Throwable> pre_allocated_OutOfMemoryError_when_throwing_exception_; 1241 GcRoot<mirror::Throwable> pre_allocated_OutOfMemoryError_when_throwing_oome_; 1242 GcRoot<mirror::Throwable> pre_allocated_OutOfMemoryError_when_handling_stack_overflow_; 1243 GcRoot<mirror::Throwable> pre_allocated_NoClassDefFoundError_; 1244 ArtMethod* resolution_method_; 1245 ArtMethod* imt_conflict_method_; 1246 // Unresolved method has the same behavior as the conflict method, it is used by the class linker 1247 // for differentiating between unfilled imt slots vs conflict slots in superclasses. 1248 ArtMethod* imt_unimplemented_method_; 1249 1250 // Special sentinel object used to invalid conditions in JNI (cleared weak references) and 1251 // JDWP (invalid references). 1252 GcRoot<mirror::Object> sentinel_; 1253 1254 InstructionSet instruction_set_; 1255 1256 CompilerCallbacks* compiler_callbacks_; 1257 bool is_zygote_; 1258 bool is_primary_zygote_; 1259 bool is_system_server_; 1260 bool must_relocate_; 1261 bool is_concurrent_gc_enabled_; 1262 bool is_explicit_gc_disabled_; 1263 bool image_dex2oat_enabled_; 1264 1265 std::string compiler_executable_; 1266 std::vector<std::string> compiler_options_; 1267 std::vector<std::string> image_compiler_options_; 1268 std::vector<std::string> image_locations_; 1269 1270 std::vector<std::string> boot_class_path_; 1271 std::vector<std::string> boot_class_path_locations_; 1272 std::string boot_class_path_checksums_; 1273 std::vector<int> boot_class_path_fds_; 1274 std::vector<int> boot_class_path_image_fds_; 1275 std::vector<int> boot_class_path_vdex_fds_; 1276 std::vector<int> boot_class_path_oat_fds_; 1277 std::string class_path_string_; 1278 std::vector<std::string> properties_; 1279 1280 std::list<ti::AgentSpec> agent_specs_; 1281 std::list<std::unique_ptr<ti::Agent>> agents_; 1282 std::vector<Plugin> plugins_; 1283 1284 // The default stack size for managed threads created by the runtime. 1285 size_t default_stack_size_; 1286 1287 // Finalizers running for longer than this many milliseconds abort the runtime. 1288 unsigned int finalizer_timeout_ms_; 1289 1290 gc::Heap* heap_; 1291 1292 std::unique_ptr<ArenaPool> jit_arena_pool_; 1293 std::unique_ptr<ArenaPool> arena_pool_; 1294 // This pool is used for linear alloc if we are using userfaultfd GC, or if 1295 // low 4gb pool is required for compiler linear alloc. Otherwise, use 1296 // arena_pool_. 1297 // We need ArtFields to be in low 4gb if we are compiling using a 32 bit image 1298 // on a 64 bit compiler in case we resolve things in the image since the field 1299 // arrays are int arrays in this case. 1300 std::unique_ptr<ArenaPool> linear_alloc_arena_pool_; 1301 1302 // Shared linear alloc for now. 1303 std::unique_ptr<LinearAlloc> linear_alloc_; 1304 1305 // Linear alloc used for allocations during startup. Will be deleted after 1306 // startup. Atomic because the pointer can be concurrently updated to null. 1307 std::atomic<LinearAlloc*> startup_linear_alloc_; 1308 1309 // The number of spins that are done before thread suspension is used to forcibly inflate. 1310 size_t max_spins_before_thin_lock_inflation_; 1311 MonitorList* monitor_list_; 1312 MonitorPool* monitor_pool_; 1313 1314 ThreadList* thread_list_; 1315 1316 InternTable* intern_table_; 1317 1318 ClassLinker* class_linker_; 1319 1320 SignalCatcher* signal_catcher_; 1321 1322 jni::SmallLrtAllocator* small_lrt_allocator_; 1323 1324 std::unique_ptr<jni::JniIdManager> jni_id_manager_; 1325 1326 std::unique_ptr<JavaVMExt> java_vm_; 1327 1328 std::unique_ptr<jit::Jit> jit_; 1329 std::unique_ptr<jit::JitCodeCache> jit_code_cache_; 1330 std::unique_ptr<jit::JitOptions> jit_options_; 1331 1332 // Runtime thread pool. The pool is only for startup and gets deleted after. 1333 std::unique_ptr<ThreadPool> thread_pool_ GUARDED_BY(Locks::runtime_thread_pool_lock_); 1334 size_t thread_pool_ref_count_ GUARDED_BY(Locks::runtime_thread_pool_lock_); 1335 1336 // Fault message, printed when we get a SIGSEGV. Stored as a native-heap object and accessed 1337 // lock-free, so needs to be atomic. 1338 std::atomic<std::string*> fault_message_; 1339 1340 // A non-zero value indicates that a thread has been created but not yet initialized. Guarded by 1341 // the shutdown lock so that threads aren't born while we're shutting down. 1342 size_t threads_being_born_ GUARDED_BY(Locks::runtime_shutdown_lock_); 1343 1344 // Waited upon until no threads are being born. 1345 std::unique_ptr<ConditionVariable> shutdown_cond_ GUARDED_BY(Locks::runtime_shutdown_lock_); 1346 1347 // Set when runtime shutdown is past the point that new threads may attach. Usually 1348 // GUARDED_BY(Locks::runtime_shutdown_lock_). But we need to check it in Abort without the 1349 // lock, because we may already own it. 1350 std::atomic<bool> shutting_down_; 1351 1352 // The runtime is starting to shutdown but is blocked waiting on shutdown_cond_. 1353 bool shutting_down_started_ GUARDED_BY(Locks::runtime_shutdown_lock_); 1354 1355 bool started_; 1356 1357 // New flag added which tells us if the runtime has finished starting. If 1358 // this flag is set then the Daemon threads are created and the class loader 1359 // is created. This flag is needed for knowing if its safe to request CMS. 1360 bool finished_starting_; 1361 1362 // Hooks supported by JNI_CreateJavaVM 1363 jint (*vfprintf_)(FILE* stream, const char* format, va_list ap); 1364 void (*exit_)(jint status); 1365 void (*abort_)(); 1366 1367 bool stats_enabled_; 1368 RuntimeStats stats_; 1369 1370 const bool is_running_on_memory_tool_; 1371 1372 std::unique_ptr<TraceConfig> trace_config_; 1373 1374 instrumentation::Instrumentation instrumentation_; 1375 1376 jobject main_thread_group_; 1377 jobject system_thread_group_; 1378 1379 // As returned by ClassLoader.getSystemClassLoader(). 1380 jobject system_class_loader_; 1381 1382 // If true, then we dump the GC cumulative timings on shutdown. 1383 bool dump_gc_performance_on_shutdown_; 1384 1385 // Transactions used for pre-initializing classes at compilation time. 1386 // Support nested transactions, maintain a list containing all transactions. Transactions are 1387 // handled under a stack discipline. Because GC needs to go over all transactions, we choose list 1388 // as substantial data structure instead of stack. 1389 std::forward_list<Transaction> preinitialization_transactions_; 1390 1391 // If kNone, verification is disabled. kEnable by default. 1392 verifier::VerifyMode verify_; 1393 1394 // List of supported cpu abis. 1395 std::vector<std::string> cpu_abilist_; 1396 1397 // Specifies target SDK version to allow workarounds for certain API levels. 1398 uint32_t target_sdk_version_; 1399 1400 // ART counterpart for the compat framework (go/compat-framework). 1401 CompatFramework compat_framework_; 1402 1403 // Implicit checks flags. 1404 bool implicit_null_checks_; // NullPointer checks are implicit. 1405 bool implicit_so_checks_; // StackOverflow checks are implicit. 1406 bool implicit_suspend_checks_; // Thread suspension checks are implicit. 1407 1408 // Whether or not the sig chain (and implicitly the fault handler) should be 1409 // disabled. Tools like dex2oat don't need them. This enables 1410 // building a statically link version of dex2oat. 1411 bool no_sig_chain_; 1412 1413 // Force the use of native bridge even if the app ISA matches the runtime ISA. 1414 bool force_native_bridge_; 1415 1416 // Whether or not a native bridge has been loaded. 1417 // 1418 // The native bridge allows running native code compiled for a foreign ISA. The way it works is, 1419 // if standard dlopen fails to load native library associated with native activity, it calls to 1420 // the native bridge to load it and then gets the trampoline for the entry to native activity. 1421 // 1422 // The option 'native_bridge_library_filename' specifies the name of the native bridge. 1423 // When non-empty the native bridge will be loaded from the given file. An empty value means 1424 // that there's no native bridge. 1425 bool is_native_bridge_loaded_; 1426 1427 // Whether we are running under native debugger. 1428 bool is_native_debuggable_; 1429 1430 // whether or not any async exceptions have ever been thrown. This is used to speed up the 1431 // MterpShouldSwitchInterpreters function. 1432 bool async_exceptions_thrown_; 1433 1434 // Whether anything is going to be using the shadow-frame APIs to force a function to return 1435 // early. Doing this requires that (1) we be debuggable and (2) that mterp is exited. 1436 bool non_standard_exits_enabled_; 1437 1438 // Whether Java code needs to be debuggable. 1439 RuntimeDebugState runtime_debug_state_; 1440 1441 bool monitor_timeout_enable_; 1442 uint64_t monitor_timeout_ns_; 1443 1444 // Whether or not this application can be profiled by the shell user, 1445 // even when running on a device that is running in user mode. 1446 bool is_profileable_from_shell_ = false; 1447 1448 // Whether or not this application can be profiled by system services on a 1449 // device running in user mode, but not necessarily by the shell user. 1450 bool is_profileable_ = false; 1451 1452 // The maximum number of failed boots we allow before pruning the dalvik cache 1453 // and trying again. This option is only inspected when we're running as a 1454 // zygote. 1455 uint32_t zygote_max_failed_boots_; 1456 1457 // Enable experimental opcodes that aren't fully specified yet. The intent is to 1458 // eventually publish them as public-usable opcodes, but they aren't ready yet. 1459 // 1460 // Experimental opcodes should not be used by other production code. 1461 ExperimentalFlags experimental_flags_; 1462 1463 // Contains the build fingerprint, if given as a parameter. 1464 std::string fingerprint_; 1465 1466 // Oat file manager, keeps track of what oat files are open. 1467 OatFileManager* oat_file_manager_; 1468 1469 // Whether or not we are on a low RAM device. 1470 bool is_low_memory_mode_; 1471 1472 // Limiting size (in bytes) for applying MADV_WILLNEED on vdex files 1473 // or uncompressed dex files in APKs. 1474 // A 0 for this will turn off madvising to MADV_WILLNEED 1475 size_t madvise_willneed_total_dex_size_; 1476 1477 // Limiting size (in bytes) for applying MADV_WILLNEED on odex files 1478 // A 0 for this will turn off madvising to MADV_WILLNEED 1479 size_t madvise_willneed_odex_filesize_; 1480 1481 // Limiting size (in bytes) for applying MADV_WILLNEED on art files 1482 // A 0 for this will turn off madvising to MADV_WILLNEED 1483 size_t madvise_willneed_art_filesize_; 1484 1485 // Whether the application should run in safe mode, that is, interpreter only. 1486 bool safe_mode_; 1487 1488 // Whether access checks on hidden API should be performed. 1489 hiddenapi::EnforcementPolicy hidden_api_policy_; 1490 1491 // Whether access checks on core platform API should be performed. 1492 hiddenapi::EnforcementPolicy core_platform_api_policy_; 1493 1494 // Whether access checks on test API should be performed. 1495 hiddenapi::EnforcementPolicy test_api_policy_; 1496 1497 // List of signature prefixes of methods that have been removed from the blocklist, and treated 1498 // as if SDK. 1499 std::vector<std::string> hidden_api_exemptions_; 1500 1501 // Do not warn about the same hidden API access violation twice. 1502 // This is only used for testing. 1503 bool dedupe_hidden_api_warnings_; 1504 1505 // How often to log hidden API access to the event log. An integer between 0 1506 // (never) and 0x10000 (always). 1507 uint32_t hidden_api_access_event_log_rate_; 1508 1509 // The package of the app running in this process. 1510 std::string process_package_name_; 1511 1512 // The data directory of the app running in this process. 1513 std::string process_data_directory_; 1514 1515 // Whether threads should dump their native stack on SIGQUIT. 1516 bool dump_native_stack_on_sig_quit_; 1517 1518 // Whether or not we currently care about pause times. 1519 ProcessState process_state_; 1520 1521 // Whether zygote code is in a section that should not start threads. 1522 bool zygote_no_threads_; 1523 1524 // The string containing requested jdwp options 1525 std::string jdwp_options_; 1526 1527 // The jdwp provider we were configured with. 1528 JdwpProvider jdwp_provider_; 1529 1530 // True if jmethodID and jfieldID are opaque Indices. When false (the default) these are simply 1531 // pointers. This is set by -Xopaque-jni-ids:{true,false}. 1532 JniIdType jni_ids_indirection_; 1533 1534 // Set to false in cases where we want to directly control when jni-id 1535 // indirection is changed. This is intended only for testing JNI id swapping. 1536 bool automatically_set_jni_ids_indirection_; 1537 1538 // True if files in /data/misc/apexdata/com.android.art are considered untrustworthy. 1539 bool deny_art_apex_data_files_; 1540 1541 // Whether to allow compiling the boot classpath in memory when the given boot image is unusable. 1542 bool allow_in_memory_compilation_ = false; 1543 1544 // Saved environment. 1545 class EnvSnapshot { 1546 public: 1547 EnvSnapshot() = default; 1548 void TakeSnapshot(); 1549 char** GetSnapshot() const; 1550 1551 private: 1552 std::unique_ptr<char*[]> c_env_vector_; 1553 std::vector<std::unique_ptr<std::string>> name_value_pairs_; 1554 1555 DISALLOW_COPY_AND_ASSIGN(EnvSnapshot); 1556 } env_snapshot_; 1557 1558 // Generic system-weak holders. 1559 std::vector<gc::AbstractSystemWeakHolder*> system_weak_holders_; 1560 1561 std::unique_ptr<RuntimeCallbacks> callbacks_; 1562 1563 std::atomic<uint32_t> deoptimization_counts_[ 1564 static_cast<uint32_t>(DeoptimizationKind::kLast) + 1]; 1565 1566 MemMap protected_fault_page_; 1567 1568 uint32_t verifier_logging_threshold_ms_; 1569 1570 bool load_app_image_startup_cache_ = false; 1571 1572 // If startup has completed, must happen at most once. 1573 std::atomic<bool> startup_completed_ = false; 1574 1575 bool verifier_missing_kthrow_fatal_; 1576 bool force_java_zygote_fork_loop_; 1577 bool perfetto_hprof_enabled_; 1578 bool perfetto_javaheapprof_enabled_; 1579 1580 // Called on out of memory error 1581 void (*out_of_memory_error_hook_)(); 1582 1583 metrics::ArtMetrics metrics_; 1584 std::unique_ptr<metrics::MetricsReporter> metrics_reporter_; 1585 1586 // Apex versions of boot classpath jars concatenated in a string. The format 1587 // is of the type: 1588 // '/apex1_version/apex2_version//' 1589 // 1590 // When the apex is the factory version, we don't encode it (for example in 1591 // the third entry in the example above). 1592 std::string apex_versions_; 1593 1594 // The info about the application code paths. 1595 AppInfo app_info_; 1596 1597 // Note: See comments on GetFaultMessage. 1598 friend std::string GetFaultMessageForAbortLogging(); 1599 friend class Dex2oatImageTest; 1600 friend class ScopedThreadPoolUsage; 1601 friend class OatFileAssistantTest; 1602 class SetupLinearAllocForZygoteFork; 1603 1604 DISALLOW_COPY_AND_ASSIGN(Runtime); 1605 }; 1606 GetMetrics()1607 inline metrics::ArtMetrics* GetMetrics() { return Runtime::Current()->GetMetrics(); } 1608 1609 } // namespace art 1610 1611 #endif // ART_RUNTIME_RUNTIME_H_ 1612