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