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