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 if (kIsDebugBuild) {
635 DCheckNoTransactionCheckAllowed();
636 }
637 return active_transaction_;
638 }
639
640 void SetFaultMessage(const std::string& message);
641
642 void AddCurrentRuntimeFeaturesAsDex2OatArguments(std::vector<std::string>* arg_vector) const;
643
GetImplicitStackOverflowChecks()644 bool GetImplicitStackOverflowChecks() const {
645 return implicit_so_checks_;
646 }
647
GetImplicitSuspendChecks()648 bool GetImplicitSuspendChecks() const {
649 return implicit_suspend_checks_;
650 }
651
GetImplicitNullChecks()652 bool GetImplicitNullChecks() const {
653 return implicit_null_checks_;
654 }
655
656 void DisableVerifier();
657 bool IsVerificationEnabled() const;
658 EXPORT bool IsVerificationSoftFail() const;
659
SetHiddenApiEnforcementPolicy(hiddenapi::EnforcementPolicy policy)660 void SetHiddenApiEnforcementPolicy(hiddenapi::EnforcementPolicy policy) {
661 hidden_api_policy_ = policy;
662 }
663
GetHiddenApiEnforcementPolicy()664 hiddenapi::EnforcementPolicy GetHiddenApiEnforcementPolicy() const {
665 return hidden_api_policy_;
666 }
667
SetCorePlatformApiEnforcementPolicy(hiddenapi::EnforcementPolicy policy)668 void SetCorePlatformApiEnforcementPolicy(hiddenapi::EnforcementPolicy policy) {
669 core_platform_api_policy_ = policy;
670 }
671
GetCorePlatformApiEnforcementPolicy()672 hiddenapi::EnforcementPolicy GetCorePlatformApiEnforcementPolicy() const {
673 return core_platform_api_policy_;
674 }
675
SetTestApiEnforcementPolicy(hiddenapi::EnforcementPolicy policy)676 void SetTestApiEnforcementPolicy(hiddenapi::EnforcementPolicy policy) {
677 test_api_policy_ = policy;
678 }
679
GetTestApiEnforcementPolicy()680 hiddenapi::EnforcementPolicy GetTestApiEnforcementPolicy() const {
681 return test_api_policy_;
682 }
683
SetHiddenApiExemptions(const std::vector<std::string> & exemptions)684 void SetHiddenApiExemptions(const std::vector<std::string>& exemptions) {
685 hidden_api_exemptions_ = exemptions;
686 }
687
GetHiddenApiExemptions()688 const std::vector<std::string>& GetHiddenApiExemptions() {
689 return hidden_api_exemptions_;
690 }
691
SetDedupeHiddenApiWarnings(bool value)692 void SetDedupeHiddenApiWarnings(bool value) {
693 dedupe_hidden_api_warnings_ = value;
694 }
695
ShouldDedupeHiddenApiWarnings()696 bool ShouldDedupeHiddenApiWarnings() {
697 return dedupe_hidden_api_warnings_;
698 }
699
SetHiddenApiEventLogSampleRate(uint32_t rate)700 void SetHiddenApiEventLogSampleRate(uint32_t rate) {
701 hidden_api_access_event_log_rate_ = rate;
702 }
703
GetHiddenApiEventLogSampleRate()704 uint32_t GetHiddenApiEventLogSampleRate() const {
705 return hidden_api_access_event_log_rate_;
706 }
707
GetProcessPackageName()708 const std::string& GetProcessPackageName() const {
709 return process_package_name_;
710 }
711
SetProcessPackageName(const char * package_name)712 void SetProcessPackageName(const char* package_name) {
713 if (package_name == nullptr) {
714 process_package_name_.clear();
715 } else {
716 process_package_name_ = package_name;
717 }
718 }
719
GetProcessDataDirectory()720 const std::string& GetProcessDataDirectory() const {
721 return process_data_directory_;
722 }
723
SetProcessDataDirectory(const char * data_dir)724 void SetProcessDataDirectory(const char* data_dir) {
725 if (data_dir == nullptr) {
726 process_data_directory_.clear();
727 } else {
728 process_data_directory_ = data_dir;
729 }
730 }
731
GetCpuAbilist()732 const std::vector<std::string>& GetCpuAbilist() const {
733 return cpu_abilist_;
734 }
735
IsRunningOnMemoryTool()736 bool IsRunningOnMemoryTool() const {
737 return is_running_on_memory_tool_;
738 }
739
SetTargetSdkVersion(uint32_t version)740 void SetTargetSdkVersion(uint32_t version) {
741 target_sdk_version_ = version;
742 }
743
GetTargetSdkVersion()744 uint32_t GetTargetSdkVersion() const {
745 return target_sdk_version_;
746 }
747
GetCompatFramework()748 CompatFramework& GetCompatFramework() {
749 return compat_framework_;
750 }
751
GetZygoteMaxFailedBoots()752 uint32_t GetZygoteMaxFailedBoots() const {
753 return zygote_max_failed_boots_;
754 }
755
AreExperimentalFlagsEnabled(ExperimentalFlags flags)756 bool AreExperimentalFlagsEnabled(ExperimentalFlags flags) {
757 return (experimental_flags_ & flags) != ExperimentalFlags::kNone;
758 }
759
760 void CreateJitCodeCache(bool rwx_memory_allowed);
761
762 // Create the JIT and instrumentation and code cache.
763 void CreateJit();
764
GetLinearAllocArenaPool()765 ArenaPool* GetLinearAllocArenaPool() {
766 return linear_alloc_arena_pool_.get();
767 }
GetArenaPool()768 ArenaPool* GetArenaPool() {
769 return arena_pool_.get();
770 }
GetArenaPool()771 const ArenaPool* GetArenaPool() const {
772 return arena_pool_.get();
773 }
GetJitArenaPool()774 ArenaPool* GetJitArenaPool() {
775 return jit_arena_pool_.get();
776 }
777
778 EXPORT void ReclaimArenaPoolMemory();
779
GetLinearAlloc()780 LinearAlloc* GetLinearAlloc() {
781 return linear_alloc_.get();
782 }
783
GetStartupLinearAlloc()784 LinearAlloc* GetStartupLinearAlloc() {
785 return startup_linear_alloc_.load(std::memory_order_relaxed);
786 }
787
GetJITOptions()788 jit::JitOptions* GetJITOptions() {
789 return jit_options_.get();
790 }
791
IsJavaDebuggable()792 bool IsJavaDebuggable() const {
793 return runtime_debug_state_ == RuntimeDebugState::kJavaDebuggable ||
794 runtime_debug_state_ == RuntimeDebugState::kJavaDebuggableAtInit;
795 }
796
IsJavaDebuggableAtInit()797 bool IsJavaDebuggableAtInit() const {
798 return runtime_debug_state_ == RuntimeDebugState::kJavaDebuggableAtInit;
799 }
800
SetProfileableFromShell(bool value)801 void SetProfileableFromShell(bool value) {
802 is_profileable_from_shell_ = value;
803 }
804
IsProfileableFromShell()805 bool IsProfileableFromShell() const {
806 return is_profileable_from_shell_;
807 }
808
SetProfileable(bool value)809 void SetProfileable(bool value) {
810 is_profileable_ = value;
811 }
812
IsProfileable()813 bool IsProfileable() const {
814 return is_profileable_;
815 }
816
817 EXPORT void SetRuntimeDebugState(RuntimeDebugState state);
818
819 // Deoptimize the boot image, called for Java debuggable apps.
820 EXPORT void DeoptimizeBootImage() REQUIRES(Locks::mutator_lock_);
821
IsNativeDebuggable()822 bool IsNativeDebuggable() const {
823 return is_native_debuggable_;
824 }
825
SetNativeDebuggable(bool value)826 void SetNativeDebuggable(bool value) {
827 is_native_debuggable_ = value;
828 }
829
830 void SetSignalHookDebuggable(bool value);
831
AreNonStandardExitsEnabled()832 bool AreNonStandardExitsEnabled() const {
833 return non_standard_exits_enabled_;
834 }
835
SetNonStandardExitsEnabled()836 void SetNonStandardExitsEnabled() {
837 non_standard_exits_enabled_ = true;
838 }
839
AreAsyncExceptionsThrown()840 bool AreAsyncExceptionsThrown() const {
841 return async_exceptions_thrown_;
842 }
843
SetAsyncExceptionsThrown()844 void SetAsyncExceptionsThrown() {
845 async_exceptions_thrown_ = true;
846 }
847
848 // Returns the build fingerprint, if set. Otherwise an empty string is returned.
GetFingerprint()849 std::string GetFingerprint() {
850 return fingerprint_;
851 }
852
853 // Called from class linker.
854 void SetSentinel(ObjPtr<mirror::Object> sentinel) REQUIRES_SHARED(Locks::mutator_lock_);
855 // For testing purpose only.
856 // TODO: Remove this when this is no longer needed (b/116087961).
857 EXPORT GcRoot<mirror::Object> GetSentinel() REQUIRES_SHARED(Locks::mutator_lock_);
858
859 // Use a sentinel for marking entries in a table that have been cleared.
860 // This helps diagnosing in case code tries to wrongly access such
861 // entries.
GetWeakClassSentinel()862 static mirror::Class* GetWeakClassSentinel() {
863 return reinterpret_cast<mirror::Class*>(0xebadbeef);
864 }
865
866 // Create a normal LinearAlloc or low 4gb version if we are 64 bit AOT compiler.
867 EXPORT LinearAlloc* CreateLinearAlloc();
868 // Setup linear-alloc allocators to stop using the current arena so that the
869 // next allocations, which would be after zygote fork, happens in userfaultfd
870 // visited space.
871 void SetupLinearAllocForPostZygoteFork(Thread* self)
872 REQUIRES(!Locks::mutator_lock_, !Locks::classlinker_classes_lock_);
873
GetOatFileManager()874 OatFileManager& GetOatFileManager() const {
875 DCHECK(oat_file_manager_ != nullptr);
876 return *oat_file_manager_;
877 }
878
879 double GetHashTableMinLoadFactor() const;
880 double GetHashTableMaxLoadFactor() const;
881
IsSafeMode()882 bool IsSafeMode() const {
883 return safe_mode_;
884 }
885
SetSafeMode(bool mode)886 void SetSafeMode(bool mode) {
887 safe_mode_ = mode;
888 }
889
GetDumpNativeStackOnSigQuit()890 bool GetDumpNativeStackOnSigQuit() const {
891 return dump_native_stack_on_sig_quit_;
892 }
893
894 EXPORT void UpdateProcessState(ProcessState process_state);
895
896 // Returns true if we currently care about long mutator pause.
InJankPerceptibleProcessState()897 bool InJankPerceptibleProcessState() const {
898 return process_state_ == kProcessStateJankPerceptible;
899 }
900
901 void RegisterSensitiveThread() const;
902
SetZygoteNoThreadSection(bool val)903 void SetZygoteNoThreadSection(bool val) {
904 zygote_no_threads_ = val;
905 }
906
IsZygoteNoThreadSection()907 bool IsZygoteNoThreadSection() const {
908 return zygote_no_threads_;
909 }
910
911 // Returns if the code can be deoptimized asynchronously. Code may be compiled with some
912 // optimization that makes it impossible to deoptimize.
913 EXPORT bool IsAsyncDeoptimizeable(ArtMethod* method, uintptr_t code) const
914 REQUIRES_SHARED(Locks::mutator_lock_);
915
916 // Returns a saved copy of the environment (getenv/setenv values).
917 // Used by Fork to protect against overwriting LD_LIBRARY_PATH, etc.
GetEnvSnapshot()918 char** GetEnvSnapshot() const {
919 return env_snapshot_.GetSnapshot();
920 }
921
922 EXPORT void AddSystemWeakHolder(gc::AbstractSystemWeakHolder* holder);
923 EXPORT void RemoveSystemWeakHolder(gc::AbstractSystemWeakHolder* holder);
924
925 EXPORT void AttachAgent(JNIEnv* env, const std::string& agent_arg, jobject class_loader);
926
GetAgents()927 const std::list<std::unique_ptr<ti::Agent>>& GetAgents() const {
928 return agents_;
929 }
930
931 EXPORT RuntimeCallbacks* GetRuntimeCallbacks();
932
HasLoadedPlugins()933 bool HasLoadedPlugins() const {
934 return !plugins_.empty();
935 }
936
937 void InitThreadGroups(Thread* self);
938
SetDumpGCPerformanceOnShutdown(bool value)939 void SetDumpGCPerformanceOnShutdown(bool value) {
940 dump_gc_performance_on_shutdown_ = value;
941 }
942
GetDumpGCPerformanceOnShutdown()943 bool GetDumpGCPerformanceOnShutdown() const {
944 return dump_gc_performance_on_shutdown_;
945 }
946
IncrementDeoptimizationCount(DeoptimizationKind kind)947 void IncrementDeoptimizationCount(DeoptimizationKind kind) {
948 DCHECK_LE(kind, DeoptimizationKind::kLast);
949 deoptimization_counts_[static_cast<size_t>(kind)]++;
950 }
951
GetNumberOfDeoptimizations()952 uint32_t GetNumberOfDeoptimizations() const {
953 uint32_t result = 0;
954 for (size_t i = 0; i <= static_cast<size_t>(DeoptimizationKind::kLast); ++i) {
955 result += deoptimization_counts_[i];
956 }
957 return result;
958 }
959
DenyArtApexDataFiles()960 bool DenyArtApexDataFiles() const {
961 return deny_art_apex_data_files_;
962 }
963
GetMadviseWillNeedTotalDexSize()964 size_t GetMadviseWillNeedTotalDexSize() const {
965 return madvise_willneed_total_dex_size_;
966 }
967
GetMadviseWillNeedSizeOdex()968 size_t GetMadviseWillNeedSizeOdex() const {
969 return madvise_willneed_odex_filesize_;
970 }
971
GetMadviseWillNeedSizeArt()972 size_t GetMadviseWillNeedSizeArt() const {
973 return madvise_willneed_art_filesize_;
974 }
975
GetJdwpOptions()976 const std::string& GetJdwpOptions() {
977 return jdwp_options_;
978 }
979
GetJdwpProvider()980 JdwpProvider GetJdwpProvider() const {
981 return jdwp_provider_;
982 }
983
GetJniIdType()984 JniIdType GetJniIdType() const {
985 return jni_ids_indirection_;
986 }
987
CanSetJniIdType()988 bool CanSetJniIdType() const {
989 return GetJniIdType() == JniIdType::kSwapablePointer;
990 }
991
992 // Changes the JniIdType to the given type. Only allowed if CanSetJniIdType(). All threads must be
993 // suspended to call this function.
994 EXPORT void SetJniIdType(JniIdType t);
995
GetVerifierLoggingThresholdMs()996 uint32_t GetVerifierLoggingThresholdMs() const {
997 return verifier_logging_threshold_ms_;
998 }
999
1000 // Atomically delete the thread pool if the reference count is 0.
1001 bool DeleteThreadPool() REQUIRES(!Locks::runtime_thread_pool_lock_);
1002
1003 // Wait for all the thread workers to be attached.
1004 void WaitForThreadPoolWorkersToStart() REQUIRES(!Locks::runtime_thread_pool_lock_);
1005
1006 // Scoped usage of the runtime thread pool. Prevents the pool from being
1007 // deleted. Note that the thread pool is only for startup and gets deleted after.
1008 class ScopedThreadPoolUsage {
1009 public:
1010 ScopedThreadPoolUsage();
1011 ~ScopedThreadPoolUsage();
1012
1013 // Return the thread pool.
GetThreadPool()1014 ThreadPool* GetThreadPool() const {
1015 return thread_pool_;
1016 }
1017
1018 private:
1019 ThreadPool* const thread_pool_;
1020 };
1021
ReleaseStartupLinearAlloc()1022 LinearAlloc* ReleaseStartupLinearAlloc() {
1023 return startup_linear_alloc_.exchange(nullptr, std::memory_order_relaxed);
1024 }
1025
LoadAppImageStartupCache()1026 bool LoadAppImageStartupCache() const {
1027 return load_app_image_startup_cache_;
1028 }
1029
SetLoadAppImageStartupCacheEnabled(bool enabled)1030 void SetLoadAppImageStartupCacheEnabled(bool enabled) {
1031 load_app_image_startup_cache_ = enabled;
1032 }
1033
1034 // Reset the startup completed status so that we can call NotifyStartupCompleted again. Should
1035 // only be used for testing.
1036 EXPORT void ResetStartupCompleted();
1037
1038 // Notify the runtime that application startup is considered completed. Only has effect for the
1039 // first call. Returns whether this was the first call.
1040 bool NotifyStartupCompleted();
1041
1042 // Notify the runtime that the application finished loading some dex/odex files. This is
1043 // called everytime we load a set of dex files in a class loader.
1044 void NotifyDexFileLoaded();
1045
1046 // Return true if startup is already completed.
1047 EXPORT bool GetStartupCompleted() const;
1048
IsVerifierMissingKThrowFatal()1049 bool IsVerifierMissingKThrowFatal() const {
1050 return verifier_missing_kthrow_fatal_;
1051 }
1052
IsJavaZygoteForkLoopRequired()1053 bool IsJavaZygoteForkLoopRequired() const {
1054 return force_java_zygote_fork_loop_;
1055 }
1056
IsPerfettoHprofEnabled()1057 bool IsPerfettoHprofEnabled() const {
1058 return perfetto_hprof_enabled_;
1059 }
1060
IsPerfettoJavaHeapStackProfEnabled()1061 bool IsPerfettoJavaHeapStackProfEnabled() const {
1062 return perfetto_javaheapprof_enabled_;
1063 }
1064
IsMonitorTimeoutEnabled()1065 bool IsMonitorTimeoutEnabled() const {
1066 return monitor_timeout_enable_;
1067 }
1068
GetMonitorTimeoutNs()1069 uint64_t GetMonitorTimeoutNs() const {
1070 return monitor_timeout_ns_;
1071 }
1072
1073 // Return whether this is system server and it is being profiled.
1074 bool IsSystemServerProfiled() const;
1075
1076 // Return whether we should load oat files as executable or not.
1077 bool GetOatFilesExecutable() const;
1078
GetMetrics()1079 metrics::ArtMetrics* GetMetrics() { return &metrics_; }
1080
GetAppInfo()1081 AppInfo* GetAppInfo() { return &app_info_; }
1082
1083 void RequestMetricsReport(bool synchronous = true);
1084
1085 static void MadviseFileForRange(size_t madvise_size_limit_bytes,
1086 size_t map_size_bytes,
1087 const uint8_t* map_begin,
1088 const uint8_t* map_end,
1089 const std::string& file_name);
1090
GetApexVersions()1091 const std::string& GetApexVersions() const {
1092 return apex_versions_;
1093 }
1094
1095 // Return whether a boot image has a profile. This means it's an in-memory
1096 // image rather that an image loaded from disk.
1097 bool HasImageWithProfile() const;
1098
GetNoSigChain()1099 bool GetNoSigChain() const {
1100 return no_sig_chain_;
1101 }
1102
1103 void AddGeneratedCodeRange(const void* start, size_t size);
1104 void RemoveGeneratedCodeRange(const void* start, size_t size)
1105 REQUIRES_SHARED(Locks::mutator_lock_);
1106
1107 // Trigger a flag reload from system properties or device congfigs.
1108 //
1109 // Should only be called from runtime init and zygote post fork as
1110 // we don't want to change the runtime config midway during execution.
1111 //
1112 // The caller argument should be the name of the function making this call
1113 // and will be used to enforce the appropriate names.
1114 //
1115 // See Flags::ReloadAllFlags as well.
1116 static void ReloadAllFlags(const std::string& caller);
1117
1118 // Parses /apex/apex-info-list.xml to build a string containing apex versions of boot classpath
1119 // jars, which is encoded into .oat files.
1120 static std::string GetApexVersions(ArrayRef<const std::string> boot_class_path_locations);
1121
AllowInMemoryCompilation()1122 bool AllowInMemoryCompilation() const { return allow_in_memory_compilation_; }
1123
1124 // Used by plugin code to attach a hook for OOME.
SetOutOfMemoryErrorHook(void (* hook)())1125 void SetOutOfMemoryErrorHook(void (*hook)()) {
1126 out_of_memory_error_hook_ = hook;
1127 }
1128
OutOfMemoryErrorHook()1129 void OutOfMemoryErrorHook() {
1130 if (out_of_memory_error_hook_ != nullptr) {
1131 out_of_memory_error_hook_();
1132 }
1133 }
1134
AreMetricsInitialized()1135 bool AreMetricsInitialized() const { return metrics_reporter_ != nullptr; }
1136
1137 // For `artd` only.
1138 EXPORT static void AllowPageSizeAccess();
1139
1140 private:
1141 static void InitPlatformSignalHandlers();
1142
1143 Runtime();
1144
HandlesSignalsInCompiledCode()1145 bool HandlesSignalsInCompiledCode() const {
1146 return !no_sig_chain_ &&
1147 (implicit_null_checks_ || implicit_so_checks_ || implicit_suspend_checks_);
1148 }
1149
1150 void BlockSignals();
1151
1152 bool Init(RuntimeArgumentMap&& runtime_options)
1153 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_);
1154 void InitNativeMethods() REQUIRES(!Locks::mutator_lock_);
1155 void RegisterRuntimeNativeMethods(JNIEnv* env);
1156 void InitMetrics();
1157
1158 void StartDaemonThreads() REQUIRES_SHARED(Locks::mutator_lock_);
1159 void StartSignalCatcher();
1160
1161 void MaybeSaveJitProfilingInfo();
1162
1163 // Visit all of the thread roots.
1164 void VisitThreadRoots(RootVisitor* visitor, VisitRootFlags flags)
1165 REQUIRES_SHARED(Locks::mutator_lock_);
1166
1167 // Visit all other roots which must be done with mutators suspended.
1168 void VisitNonConcurrentRoots(RootVisitor* visitor, VisitRootFlags flags)
1169 REQUIRES_SHARED(Locks::mutator_lock_);
1170
1171 // Constant roots are the roots which never change after the runtime is initialized, they only
1172 // need to be visited once per GC cycle.
1173 void VisitConstantRoots(RootVisitor* visitor)
1174 REQUIRES_SHARED(Locks::mutator_lock_);
1175
1176 // Note: To be lock-free, GetFaultMessage temporarily replaces the lock message with null.
1177 // As such, there is a window where a call will return an empty string. In general,
1178 // only aborting code should retrieve this data (via GetFaultMessageForAbortLogging
1179 // friend).
1180 std::string GetFaultMessage();
1181
1182 ThreadPool* AcquireThreadPool() REQUIRES(!Locks::runtime_thread_pool_lock_);
1183 void ReleaseThreadPool() REQUIRES(!Locks::runtime_thread_pool_lock_);
1184
1185 // Caches the apex versions produced by `GetApexVersions`.
1186 void InitializeApexVersions();
1187
1188 void AppendToBootClassPath(const std::string& filename, const std::string& location);
1189
1190 void DCheckNoTransactionCheckAllowed();
1191
1192 // Don't use EXPORT ("default" visibility), because quick_entrypoints_x86.o
1193 // refers to this symbol and it can't link with R_386_PC32 relocation.
1194 // A pointer to the active runtime or null.
1195 LIBART_PROTECTED static Runtime* instance_;
1196
1197 static constexpr uint32_t kCalleeSaveSize = 6u;
1198
1199 // 64 bit so that we can share the same asm offsets for both 32 and 64 bits.
1200 uint64_t callee_save_methods_[kCalleeSaveSize];
1201 // Pre-allocated exceptions (see Runtime::Init).
1202 GcRoot<mirror::Throwable> pre_allocated_OutOfMemoryError_when_throwing_exception_;
1203 GcRoot<mirror::Throwable> pre_allocated_OutOfMemoryError_when_throwing_oome_;
1204 GcRoot<mirror::Throwable> pre_allocated_OutOfMemoryError_when_handling_stack_overflow_;
1205 GcRoot<mirror::Throwable> pre_allocated_NoClassDefFoundError_;
1206 ArtMethod* resolution_method_;
1207 ArtMethod* imt_conflict_method_;
1208 // Unresolved method has the same behavior as the conflict method, it is used by the class linker
1209 // for differentiating between unfilled imt slots vs conflict slots in superclasses.
1210 ArtMethod* imt_unimplemented_method_;
1211
1212 // Special sentinel object used to invalid conditions in JNI (cleared weak references) and
1213 // JDWP (invalid references).
1214 GcRoot<mirror::Object> sentinel_;
1215
1216 InstructionSet instruction_set_;
1217
1218 CompilerCallbacks* compiler_callbacks_;
1219 bool is_zygote_;
1220 bool is_primary_zygote_;
1221 bool is_system_server_;
1222 bool must_relocate_;
1223 bool is_concurrent_gc_enabled_;
1224 bool is_explicit_gc_disabled_;
1225 bool is_eagerly_release_explicit_gc_disabled_;
1226 bool image_dex2oat_enabled_;
1227
1228 std::string compiler_executable_;
1229 std::vector<std::string> compiler_options_;
1230 std::vector<std::string> image_compiler_options_;
1231 std::vector<std::string> image_locations_;
1232
1233 std::vector<std::string> boot_class_path_;
1234 std::vector<std::string> boot_class_path_locations_;
1235 std::string boot_class_path_checksums_;
1236 std::vector<File> boot_class_path_files_;
1237 std::vector<File> boot_class_path_image_files_;
1238 std::vector<File> boot_class_path_vdex_files_;
1239 std::vector<File> boot_class_path_oat_files_;
1240 std::string class_path_string_;
1241 std::vector<std::string> properties_;
1242
1243 std::list<ti::AgentSpec> agent_specs_;
1244 std::list<std::unique_ptr<ti::Agent>> agents_;
1245 std::vector<Plugin> plugins_;
1246
1247 // The default stack size for managed threads created by the runtime.
1248 size_t default_stack_size_;
1249
1250 // Finalizers running for longer than this many milliseconds abort the runtime.
1251 unsigned int finalizer_timeout_ms_;
1252
1253 gc::Heap* heap_;
1254
1255 std::unique_ptr<ArenaPool> jit_arena_pool_;
1256 std::unique_ptr<ArenaPool> arena_pool_;
1257 // This pool is used for linear alloc if we are using userfaultfd GC, or if
1258 // low 4gb pool is required for compiler linear alloc. Otherwise, use
1259 // arena_pool_.
1260 // We need ArtFields to be in low 4gb if we are compiling using a 32 bit image
1261 // on a 64 bit compiler in case we resolve things in the image since the field
1262 // arrays are int arrays in this case.
1263 std::unique_ptr<ArenaPool> linear_alloc_arena_pool_;
1264
1265 // Shared linear alloc for now.
1266 std::unique_ptr<LinearAlloc> linear_alloc_;
1267
1268 // Linear alloc used for allocations during startup. Will be deleted after
1269 // startup. Atomic because the pointer can be concurrently updated to null.
1270 std::atomic<LinearAlloc*> startup_linear_alloc_;
1271
1272 // The number of spins that are done before thread suspension is used to forcibly inflate.
1273 size_t max_spins_before_thin_lock_inflation_;
1274 MonitorList* monitor_list_;
1275 MonitorPool* monitor_pool_;
1276
1277 ThreadList* thread_list_;
1278
1279 InternTable* intern_table_;
1280
1281 ClassLinker* class_linker_;
1282
1283 SignalCatcher* signal_catcher_;
1284
1285 jni::SmallLrtAllocator* small_lrt_allocator_;
1286
1287 std::unique_ptr<jni::JniIdManager> jni_id_manager_;
1288
1289 std::unique_ptr<JavaVMExt> java_vm_;
1290
1291 std::unique_ptr<jit::Jit> jit_;
1292 std::unique_ptr<jit::JitCodeCache> jit_code_cache_;
1293 std::unique_ptr<jit::JitOptions> jit_options_;
1294
1295 // Runtime thread pool. The pool is only for startup and gets deleted after.
1296 std::unique_ptr<ThreadPool> thread_pool_ GUARDED_BY(Locks::runtime_thread_pool_lock_);
1297 size_t thread_pool_ref_count_ GUARDED_BY(Locks::runtime_thread_pool_lock_);
1298
1299 // Fault message, printed when we get a SIGSEGV. Stored as a native-heap object and accessed
1300 // lock-free, so needs to be atomic.
1301 std::atomic<std::string*> fault_message_;
1302
1303 // A non-zero value indicates that a thread has been created but not yet initialized. Guarded by
1304 // the shutdown lock so that threads aren't born while we're shutting down.
1305 size_t threads_being_born_ GUARDED_BY(Locks::runtime_shutdown_lock_);
1306
1307 // Waited upon until no threads are being born.
1308 std::unique_ptr<ConditionVariable> shutdown_cond_ GUARDED_BY(Locks::runtime_shutdown_lock_);
1309
1310 // Set when runtime shutdown is past the point that new threads may attach. Usually
1311 // GUARDED_BY(Locks::runtime_shutdown_lock_). But we need to check it in Abort without the
1312 // lock, because we may already own it.
1313 std::atomic<bool> shutting_down_;
1314
1315 // The runtime is starting to shutdown but is blocked waiting on shutdown_cond_.
1316 bool shutting_down_started_ GUARDED_BY(Locks::runtime_shutdown_lock_);
1317
1318 bool started_;
1319
1320 // New flag added which tells us if the runtime has finished starting. If
1321 // this flag is set then the Daemon threads are created and the class loader
1322 // is created. This flag is needed for knowing if its safe to request CMS.
1323 bool finished_starting_;
1324
1325 // Hooks supported by JNI_CreateJavaVM
1326 jint (*vfprintf_)(FILE* stream, const char* format, va_list ap);
1327 void (*exit_)(jint status);
1328 void (*abort_)();
1329
1330 bool stats_enabled_;
1331 RuntimeStats stats_;
1332
1333 const bool is_running_on_memory_tool_;
1334
1335 std::unique_ptr<TraceConfig> trace_config_;
1336
1337 instrumentation::Instrumentation instrumentation_;
1338
1339 jobject main_thread_group_;
1340 jobject system_thread_group_;
1341
1342 // As returned by ClassLoader.getSystemClassLoader().
1343 jobject system_class_loader_;
1344
1345 // If true, then we dump the GC cumulative timings on shutdown.
1346 bool dump_gc_performance_on_shutdown_;
1347
1348 // Transactions are handled by the `AotClassLinker` but we keep a simple flag
1349 // in the `Runtime` for quick transaction checks.
1350 // Code that's not AOT-specific but needs some transaction-specific behavior
1351 // shall check this flag and, for an active transaction, make virtual calls
1352 // through `ClassLinker` to `AotClassLinker` to implement that behavior.
1353 bool active_transaction_;
1354
1355 // If kNone, verification is disabled. kEnable by default.
1356 verifier::VerifyMode verify_;
1357
1358 // List of supported cpu abis.
1359 std::vector<std::string> cpu_abilist_;
1360
1361 // Specifies target SDK version to allow workarounds for certain API levels.
1362 uint32_t target_sdk_version_;
1363
1364 // ART counterpart for the compat framework (go/compat-framework).
1365 CompatFramework compat_framework_;
1366
1367 // Implicit checks flags.
1368 bool implicit_null_checks_; // NullPointer checks are implicit.
1369 bool implicit_so_checks_; // StackOverflow checks are implicit.
1370 bool implicit_suspend_checks_; // Thread suspension checks are implicit.
1371
1372 // Whether or not the sig chain (and implicitly the fault handler) should be
1373 // disabled. Tools like dex2oat don't need them. This enables
1374 // building a statically link version of dex2oat.
1375 bool no_sig_chain_;
1376
1377 // Force the use of native bridge even if the app ISA matches the runtime ISA.
1378 bool force_native_bridge_;
1379
1380 // Whether or not a native bridge has been loaded.
1381 //
1382 // The native bridge allows running native code compiled for a foreign ISA. The way it works is,
1383 // if standard dlopen fails to load native library associated with native activity, it calls to
1384 // the native bridge to load it and then gets the trampoline for the entry to native activity.
1385 //
1386 // The option 'native_bridge_library_filename' specifies the name of the native bridge.
1387 // When non-empty the native bridge will be loaded from the given file. An empty value means
1388 // that there's no native bridge.
1389 bool is_native_bridge_loaded_;
1390
1391 // Whether we are running under native debugger.
1392 bool is_native_debuggable_;
1393
1394 // whether or not any async exceptions have ever been thrown. This is used to speed up the
1395 // MterpShouldSwitchInterpreters function.
1396 bool async_exceptions_thrown_;
1397
1398 // Whether anything is going to be using the shadow-frame APIs to force a function to return
1399 // early. Doing this requires that (1) we be debuggable and (2) that mterp is exited.
1400 bool non_standard_exits_enabled_;
1401
1402 // Whether Java code needs to be debuggable.
1403 RuntimeDebugState runtime_debug_state_;
1404
1405 bool monitor_timeout_enable_;
1406 uint64_t monitor_timeout_ns_;
1407
1408 // Whether or not this application can be profiled by the shell user,
1409 // even when running on a device that is running in user mode.
1410 bool is_profileable_from_shell_ = false;
1411
1412 // Whether or not this application can be profiled by system services on a
1413 // device running in user mode, but not necessarily by the shell user.
1414 bool is_profileable_ = false;
1415
1416 // The maximum number of failed boots we allow before pruning the dalvik cache
1417 // and trying again. This option is only inspected when we're running as a
1418 // zygote.
1419 uint32_t zygote_max_failed_boots_;
1420
1421 // Enable experimental opcodes that aren't fully specified yet. The intent is to
1422 // eventually publish them as public-usable opcodes, but they aren't ready yet.
1423 //
1424 // Experimental opcodes should not be used by other production code.
1425 ExperimentalFlags experimental_flags_;
1426
1427 // Contains the build fingerprint, if given as a parameter.
1428 std::string fingerprint_;
1429
1430 // Oat file manager, keeps track of what oat files are open.
1431 OatFileManager* oat_file_manager_;
1432
1433 // Whether or not we are on a low RAM device.
1434 bool is_low_memory_mode_;
1435
1436 // Limiting size (in bytes) for applying MADV_WILLNEED on vdex files
1437 // or uncompressed dex files in APKs.
1438 // A 0 for this will turn off madvising to MADV_WILLNEED
1439 size_t madvise_willneed_total_dex_size_;
1440
1441 // Limiting size (in bytes) for applying MADV_WILLNEED on odex files
1442 // A 0 for this will turn off madvising to MADV_WILLNEED
1443 size_t madvise_willneed_odex_filesize_;
1444
1445 // Limiting size (in bytes) for applying MADV_WILLNEED on art files
1446 // A 0 for this will turn off madvising to MADV_WILLNEED
1447 size_t madvise_willneed_art_filesize_;
1448
1449 // Whether the application should run in safe mode, that is, interpreter only.
1450 bool safe_mode_;
1451
1452 // Whether access checks on hidden API should be performed.
1453 hiddenapi::EnforcementPolicy hidden_api_policy_;
1454
1455 // Whether access checks on core platform API should be performed.
1456 hiddenapi::EnforcementPolicy core_platform_api_policy_;
1457
1458 // Whether access checks on test API should be performed.
1459 hiddenapi::EnforcementPolicy test_api_policy_;
1460
1461 // List of signature prefixes of methods that have been removed from the blocklist, and treated
1462 // as if SDK.
1463 std::vector<std::string> hidden_api_exemptions_;
1464
1465 // Do not warn about the same hidden API access violation twice.
1466 // This is only used for testing.
1467 bool dedupe_hidden_api_warnings_;
1468
1469 // How often to log hidden API access to the event log. An integer between 0
1470 // (never) and 0x10000 (always).
1471 uint32_t hidden_api_access_event_log_rate_;
1472
1473 // The package of the app running in this process.
1474 std::string process_package_name_;
1475
1476 // The data directory of the app running in this process.
1477 std::string process_data_directory_;
1478
1479 // Whether threads should dump their native stack on SIGQUIT.
1480 bool dump_native_stack_on_sig_quit_;
1481
1482 // Whether or not we currently care about pause times.
1483 ProcessState process_state_;
1484
1485 // Whether zygote code is in a section that should not start threads.
1486 bool zygote_no_threads_;
1487
1488 // The string containing requested jdwp options
1489 std::string jdwp_options_;
1490
1491 // The jdwp provider we were configured with.
1492 JdwpProvider jdwp_provider_;
1493
1494 // True if jmethodID and jfieldID are opaque Indices. When false (the default) these are simply
1495 // pointers. This is set by -Xopaque-jni-ids:{true,false}.
1496 JniIdType jni_ids_indirection_;
1497
1498 // Set to false in cases where we want to directly control when jni-id
1499 // indirection is changed. This is intended only for testing JNI id swapping.
1500 bool automatically_set_jni_ids_indirection_;
1501
1502 // True if files in /data/misc/apexdata/com.android.art are considered untrustworthy.
1503 bool deny_art_apex_data_files_;
1504
1505 // Whether to allow compiling the boot classpath in memory when the given boot image is unusable.
1506 bool allow_in_memory_compilation_ = false;
1507
1508 // Saved environment.
1509 class EnvSnapshot {
1510 public:
1511 EnvSnapshot() = default;
1512 void TakeSnapshot();
1513 char** GetSnapshot() const;
1514
1515 private:
1516 std::unique_ptr<char*[]> c_env_vector_;
1517 std::vector<std::unique_ptr<std::string>> name_value_pairs_;
1518
1519 DISALLOW_COPY_AND_ASSIGN(EnvSnapshot);
1520 } env_snapshot_;
1521
1522 // Generic system-weak holders.
1523 std::vector<gc::AbstractSystemWeakHolder*> system_weak_holders_;
1524
1525 std::unique_ptr<RuntimeCallbacks> callbacks_;
1526
1527 std::atomic<uint32_t> deoptimization_counts_[
1528 static_cast<uint32_t>(DeoptimizationKind::kLast) + 1];
1529
1530 MemMap protected_fault_page_;
1531
1532 uint32_t verifier_logging_threshold_ms_;
1533
1534 bool load_app_image_startup_cache_ = false;
1535
1536 // If startup has completed, must happen at most once.
1537 std::atomic<bool> startup_completed_ = false;
1538
1539 bool verifier_missing_kthrow_fatal_;
1540 bool force_java_zygote_fork_loop_;
1541 bool perfetto_hprof_enabled_;
1542 bool perfetto_javaheapprof_enabled_;
1543
1544 // Called on out of memory error
1545 void (*out_of_memory_error_hook_)();
1546
1547 metrics::ArtMetrics metrics_;
1548 std::unique_ptr<metrics::MetricsReporter> metrics_reporter_;
1549
1550 // Apex versions of boot classpath jars concatenated in a string. The format
1551 // is of the type:
1552 // '/apex1_version/apex2_version//'
1553 //
1554 // When the apex is the factory version, we don't encode it (for example in
1555 // the third entry in the example above).
1556 std::string apex_versions_;
1557
1558 // The info about the application code paths.
1559 AppInfo app_info_;
1560
1561 // Note: See comments on GetFaultMessage.
1562 friend std::string GetFaultMessageForAbortLogging();
1563 friend class Dex2oatImageTest;
1564 friend class ScopedThreadPoolUsage;
1565 friend class OatFileAssistantTest;
1566 class SetupLinearAllocForZygoteFork;
1567
1568 DISALLOW_COPY_AND_ASSIGN(Runtime);
1569 };
1570
GetMetrics()1571 inline metrics::ArtMetrics* GetMetrics() { return Runtime::Current()->GetMetrics(); }
1572
1573 } // namespace art
1574
1575 #endif // ART_RUNTIME_RUNTIME_H_
1576