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