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