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