runtime.h revision 65af20b1aaa2b23abaae3e4a21d7b6cdcb156889
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 <set>
25#include <string>
26#include <utility>
27#include <vector>
28
29#include "arch/instruction_set.h"
30#include "base/macros.h"
31#include "base/mutex.h"
32#include "dex_file_types.h"
33#include "experimental_flags.h"
34#include "gc_root.h"
35#include "instrumentation.h"
36#include "jobject_comparator.h"
37#include "method_reference.h"
38#include "obj_ptr.h"
39#include "object_callbacks.h"
40#include "offsets.h"
41#include "process_state.h"
42#include "quick/quick_method_frame_info.h"
43#include "runtime_stats.h"
44
45namespace art {
46
47namespace gc {
48  class AbstractSystemWeakHolder;
49  class Heap;
50  namespace collector {
51    class GarbageCollector;
52  }  // namespace collector
53}  // namespace gc
54
55namespace jit {
56  class Jit;
57  class JitOptions;
58}  // namespace jit
59
60namespace mirror {
61  class Array;
62  class ClassLoader;
63  class DexCache;
64  template<class T> class ObjectArray;
65  template<class T> class PrimitiveArray;
66  typedef PrimitiveArray<int8_t> ByteArray;
67  class String;
68  class Throwable;
69}  // namespace mirror
70namespace ti {
71  class Agent;
72}  // namespace ti
73namespace verifier {
74  class MethodVerifier;
75  enum class VerifyMode : int8_t;
76}  // namespace verifier
77class ArenaPool;
78class ArtMethod;
79class ClassHierarchyAnalysis;
80class ClassLinker;
81class Closure;
82class CompilerCallbacks;
83class DexFile;
84class InternTable;
85class JavaVMExt;
86class LinearAlloc;
87class MonitorList;
88class MonitorPool;
89class NullPointerHandler;
90class OatFileManager;
91class Plugin;
92struct RuntimeArgumentMap;
93class RuntimeCallbacks;
94class SignalCatcher;
95class StackOverflowHandler;
96class SuspensionHandler;
97class ThreadList;
98class Trace;
99struct TraceConfig;
100class Transaction;
101
102typedef std::vector<std::pair<std::string, const void*>> RuntimeOptions;
103
104class Runtime {
105 public:
106  // Parse raw runtime options.
107  static bool ParseOptions(const RuntimeOptions& raw_options,
108                           bool ignore_unrecognized,
109                           RuntimeArgumentMap* runtime_options);
110
111  // Creates and initializes a new runtime.
112  static bool Create(RuntimeArgumentMap&& runtime_options)
113      SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_);
114
115  // Creates and initializes a new runtime.
116  static bool Create(const RuntimeOptions& raw_options, bool ignore_unrecognized)
117      SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_);
118
119  // IsAotCompiler for compilers that don't have a running runtime. Only dex2oat currently.
120  bool IsAotCompiler() const {
121    return !UseJitCompilation() && IsCompiler();
122  }
123
124  // IsCompiler is any runtime which has a running compiler, either dex2oat or JIT.
125  bool IsCompiler() const {
126    return compiler_callbacks_ != nullptr;
127  }
128
129  // If a compiler, are we compiling a boot image?
130  bool IsCompilingBootImage() const;
131
132  bool CanRelocate() const;
133
134  bool ShouldRelocate() const {
135    return must_relocate_ && CanRelocate();
136  }
137
138  bool MustRelocateIfPossible() const {
139    return must_relocate_;
140  }
141
142  bool IsDex2OatEnabled() const {
143    return dex2oat_enabled_ && IsImageDex2OatEnabled();
144  }
145
146  bool IsImageDex2OatEnabled() const {
147    return image_dex2oat_enabled_;
148  }
149
150  CompilerCallbacks* GetCompilerCallbacks() {
151    return compiler_callbacks_;
152  }
153
154  void SetCompilerCallbacks(CompilerCallbacks* callbacks) {
155    CHECK(callbacks != nullptr);
156    compiler_callbacks_ = callbacks;
157  }
158
159  bool IsZygote() const {
160    return is_zygote_;
161  }
162
163  bool IsExplicitGcDisabled() const {
164    return is_explicit_gc_disabled_;
165  }
166
167  std::string GetCompilerExecutable() const;
168  std::string GetPatchoatExecutable() const;
169
170  const std::vector<std::string>& GetCompilerOptions() const {
171    return compiler_options_;
172  }
173
174  void AddCompilerOption(const std::string& option) {
175    compiler_options_.push_back(option);
176  }
177
178  const std::vector<std::string>& GetImageCompilerOptions() const {
179    return image_compiler_options_;
180  }
181
182  const std::string& GetImageLocation() const {
183    return image_location_;
184  }
185
186  // Starts a runtime, which may cause threads to be started and code to run.
187  bool Start() UNLOCK_FUNCTION(Locks::mutator_lock_);
188
189  bool IsShuttingDown(Thread* self);
190  bool IsShuttingDownLocked() const REQUIRES(Locks::runtime_shutdown_lock_) {
191    return shutting_down_;
192  }
193
194  size_t NumberOfThreadsBeingBorn() const REQUIRES(Locks::runtime_shutdown_lock_) {
195    return threads_being_born_;
196  }
197
198  void StartThreadBirth() REQUIRES(Locks::runtime_shutdown_lock_) {
199    threads_being_born_++;
200  }
201
202  void EndThreadBirth() REQUIRES(Locks::runtime_shutdown_lock_);
203
204  bool IsStarted() const {
205    return started_;
206  }
207
208  bool IsFinishedStarting() const {
209    return finished_starting_;
210  }
211
212  static Runtime* Current() {
213    return instance_;
214  }
215
216  // Aborts semi-cleanly. Used in the implementation of LOG(FATAL), which most
217  // callers should prefer.
218  NO_RETURN static void Abort(const char* msg) REQUIRES(!Locks::abort_lock_);
219
220  // Returns the "main" ThreadGroup, used when attaching user threads.
221  jobject GetMainThreadGroup() const;
222
223  // Returns the "system" ThreadGroup, used when attaching our internal threads.
224  jobject GetSystemThreadGroup() const;
225
226  // Returns the system ClassLoader which represents the CLASSPATH.
227  jobject GetSystemClassLoader() const;
228
229  // Attaches the calling native thread to the runtime.
230  bool AttachCurrentThread(const char* thread_name, bool as_daemon, jobject thread_group,
231                           bool create_peer);
232
233  void CallExitHook(jint status);
234
235  // Detaches the current native thread from the runtime.
236  void DetachCurrentThread() REQUIRES(!Locks::mutator_lock_);
237
238  void DumpForSigQuit(std::ostream& os);
239  void DumpLockHolders(std::ostream& os);
240
241  ~Runtime();
242
243  const std::string& GetBootClassPathString() const {
244    return boot_class_path_string_;
245  }
246
247  const std::string& GetClassPathString() const {
248    return class_path_string_;
249  }
250
251  ClassLinker* GetClassLinker() const {
252    return class_linker_;
253  }
254
255  size_t GetDefaultStackSize() const {
256    return default_stack_size_;
257  }
258
259  gc::Heap* GetHeap() const {
260    return heap_;
261  }
262
263  InternTable* GetInternTable() const {
264    DCHECK(intern_table_ != nullptr);
265    return intern_table_;
266  }
267
268  JavaVMExt* GetJavaVM() const {
269    return java_vm_.get();
270  }
271
272  size_t GetMaxSpinsBeforeThinLockInflation() const {
273    return max_spins_before_thin_lock_inflation_;
274  }
275
276  MonitorList* GetMonitorList() const {
277    return monitor_list_;
278  }
279
280  MonitorPool* GetMonitorPool() const {
281    return monitor_pool_;
282  }
283
284  // Is the given object the special object used to mark a cleared JNI weak global?
285  bool IsClearedJniWeakGlobal(ObjPtr<mirror::Object> obj) REQUIRES_SHARED(Locks::mutator_lock_);
286
287  // Get the special object used to mark a cleared JNI weak global.
288  mirror::Object* GetClearedJniWeakGlobal() REQUIRES_SHARED(Locks::mutator_lock_);
289
290  mirror::Throwable* GetPreAllocatedOutOfMemoryError() REQUIRES_SHARED(Locks::mutator_lock_);
291
292  mirror::Throwable* GetPreAllocatedNoClassDefFoundError()
293      REQUIRES_SHARED(Locks::mutator_lock_);
294
295  const std::vector<std::string>& GetProperties() const {
296    return properties_;
297  }
298
299  ThreadList* GetThreadList() const {
300    return thread_list_;
301  }
302
303  static const char* GetVersion() {
304    return "2.1.0";
305  }
306
307  bool IsMethodHandlesEnabled() const {
308    return true;
309  }
310
311  void DisallowNewSystemWeaks() REQUIRES_SHARED(Locks::mutator_lock_);
312  void AllowNewSystemWeaks() REQUIRES_SHARED(Locks::mutator_lock_);
313  // broadcast_for_checkpoint is true when we broadcast for making blocking threads to respond to
314  // checkpoint requests. It's false when we broadcast to unblock blocking threads after system weak
315  // access is reenabled.
316  void BroadcastForNewSystemWeaks(bool broadcast_for_checkpoint = false);
317
318  // Visit all the roots. If only_dirty is true then non-dirty roots won't be visited. If
319  // clean_dirty is true then dirty roots will be marked as non-dirty after visiting.
320  void VisitRoots(RootVisitor* visitor, VisitRootFlags flags = kVisitRootFlagAllRoots)
321      REQUIRES(!Locks::classlinker_classes_lock_, !Locks::trace_lock_)
322      REQUIRES_SHARED(Locks::mutator_lock_);
323
324  // Visit image roots, only used for hprof since the GC uses the image space mod union table
325  // instead.
326  void VisitImageRoots(RootVisitor* visitor) REQUIRES_SHARED(Locks::mutator_lock_);
327
328  // Visit all of the roots we can do safely do concurrently.
329  void VisitConcurrentRoots(RootVisitor* visitor,
330                            VisitRootFlags flags = kVisitRootFlagAllRoots)
331      REQUIRES(!Locks::classlinker_classes_lock_, !Locks::trace_lock_)
332      REQUIRES_SHARED(Locks::mutator_lock_);
333
334  // Visit all of the non thread roots, we can do this with mutators unpaused.
335  void VisitNonThreadRoots(RootVisitor* visitor)
336      REQUIRES_SHARED(Locks::mutator_lock_);
337
338  void VisitTransactionRoots(RootVisitor* visitor)
339      REQUIRES_SHARED(Locks::mutator_lock_);
340
341  // Flip thread roots from from-space refs to to-space refs.
342  size_t FlipThreadRoots(Closure* thread_flip_visitor, Closure* flip_callback,
343                         gc::collector::GarbageCollector* collector)
344      REQUIRES(!Locks::mutator_lock_);
345
346  // Sweep system weaks, the system weak is deleted if the visitor return null. Otherwise, the
347  // system weak is updated to be the visitor's returned value.
348  void SweepSystemWeaks(IsMarkedVisitor* visitor)
349      REQUIRES_SHARED(Locks::mutator_lock_);
350
351  // Returns a special method that calls into a trampoline for runtime method resolution
352  ArtMethod* GetResolutionMethod();
353
354  bool HasResolutionMethod() const {
355    return resolution_method_ != nullptr;
356  }
357
358  void SetResolutionMethod(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_);
359
360  ArtMethod* CreateResolutionMethod() REQUIRES_SHARED(Locks::mutator_lock_);
361
362  // Returns a special method that calls into a trampoline for runtime imt conflicts.
363  ArtMethod* GetImtConflictMethod();
364  ArtMethod* GetImtUnimplementedMethod();
365
366  bool HasImtConflictMethod() const {
367    return imt_conflict_method_ != nullptr;
368  }
369
370  void FixupConflictTables();
371  void SetImtConflictMethod(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_);
372  void SetImtUnimplementedMethod(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_);
373
374  ArtMethod* CreateImtConflictMethod(LinearAlloc* linear_alloc)
375      REQUIRES_SHARED(Locks::mutator_lock_);
376
377  // Returns a special method that describes all callee saves being spilled to the stack.
378  enum CalleeSaveType {
379    kSaveAllCalleeSaves,  // All callee-save registers.
380    kSaveRefsOnly,        // Only those callee-save registers that can hold references.
381    kSaveRefsAndArgs,     // References (see above) and arguments (usually caller-save registers).
382    kSaveEverything,      // All registers, including both callee-save and caller-save.
383    kLastCalleeSaveType   // Value used for iteration
384  };
385
386  bool HasCalleeSaveMethod(CalleeSaveType type) const {
387    return callee_save_methods_[type] != 0u;
388  }
389
390  ArtMethod* GetCalleeSaveMethod(CalleeSaveType type)
391      REQUIRES_SHARED(Locks::mutator_lock_);
392
393  ArtMethod* GetCalleeSaveMethodUnchecked(CalleeSaveType type)
394      REQUIRES_SHARED(Locks::mutator_lock_);
395
396  QuickMethodFrameInfo GetCalleeSaveMethodFrameInfo(CalleeSaveType type) const {
397    return callee_save_method_frame_infos_[type];
398  }
399
400  QuickMethodFrameInfo GetRuntimeMethodFrameInfo(ArtMethod* method)
401      REQUIRES_SHARED(Locks::mutator_lock_);
402
403  static size_t GetCalleeSaveMethodOffset(CalleeSaveType type) {
404    return OFFSETOF_MEMBER(Runtime, callee_save_methods_[type]);
405  }
406
407  InstructionSet GetInstructionSet() const {
408    return instruction_set_;
409  }
410
411  void SetInstructionSet(InstructionSet instruction_set);
412
413  void SetCalleeSaveMethod(ArtMethod* method, CalleeSaveType type);
414
415  ArtMethod* CreateCalleeSaveMethod() REQUIRES_SHARED(Locks::mutator_lock_);
416
417  int32_t GetStat(int kind);
418
419  RuntimeStats* GetStats() {
420    return &stats_;
421  }
422
423  bool HasStatsEnabled() const {
424    return stats_enabled_;
425  }
426
427  void ResetStats(int kinds);
428
429  void SetStatsEnabled(bool new_state)
430      REQUIRES(!Locks::instrument_entrypoints_lock_, !Locks::mutator_lock_);
431
432  enum class NativeBridgeAction {  // private
433    kUnload,
434    kInitialize
435  };
436
437  jit::Jit* GetJit() const {
438    return jit_.get();
439  }
440
441  // Returns true if JIT compilations are enabled. GetJit() will be not null in this case.
442  bool UseJitCompilation() const;
443
444  void PreZygoteFork();
445  void InitNonZygoteOrPostFork(
446      JNIEnv* env, bool is_system_server, NativeBridgeAction action, const char* isa);
447
448  const instrumentation::Instrumentation* GetInstrumentation() const {
449    return &instrumentation_;
450  }
451
452  instrumentation::Instrumentation* GetInstrumentation() {
453    return &instrumentation_;
454  }
455
456  void RegisterAppInfo(const std::vector<std::string>& code_paths,
457                       const std::string& profile_output_filename);
458
459  // Transaction support.
460  bool IsActiveTransaction() const {
461    return preinitialization_transaction_ != nullptr;
462  }
463  void EnterTransactionMode(Transaction* transaction);
464  void ExitTransactionMode();
465  bool IsTransactionAborted() const;
466
467  void AbortTransactionAndThrowAbortError(Thread* self, const std::string& abort_message)
468      REQUIRES_SHARED(Locks::mutator_lock_);
469  void ThrowTransactionAbortError(Thread* self)
470      REQUIRES_SHARED(Locks::mutator_lock_);
471
472  void RecordWriteFieldBoolean(mirror::Object* obj, MemberOffset field_offset, uint8_t value,
473                               bool is_volatile) const;
474  void RecordWriteFieldByte(mirror::Object* obj, MemberOffset field_offset, int8_t value,
475                            bool is_volatile) const;
476  void RecordWriteFieldChar(mirror::Object* obj, MemberOffset field_offset, uint16_t value,
477                            bool is_volatile) const;
478  void RecordWriteFieldShort(mirror::Object* obj, MemberOffset field_offset, int16_t value,
479                          bool is_volatile) const;
480  void RecordWriteField32(mirror::Object* obj, MemberOffset field_offset, uint32_t value,
481                          bool is_volatile) const;
482  void RecordWriteField64(mirror::Object* obj, MemberOffset field_offset, uint64_t value,
483                          bool is_volatile) const;
484  void RecordWriteFieldReference(mirror::Object* obj,
485                                 MemberOffset field_offset,
486                                 ObjPtr<mirror::Object> value,
487                                 bool is_volatile) const
488      REQUIRES_SHARED(Locks::mutator_lock_);
489  void RecordWriteArray(mirror::Array* array, size_t index, uint64_t value) const
490      REQUIRES_SHARED(Locks::mutator_lock_);
491  void RecordStrongStringInsertion(ObjPtr<mirror::String> s) const
492      REQUIRES(Locks::intern_table_lock_);
493  void RecordWeakStringInsertion(ObjPtr<mirror::String> s) const
494      REQUIRES(Locks::intern_table_lock_);
495  void RecordStrongStringRemoval(ObjPtr<mirror::String> s) const
496      REQUIRES(Locks::intern_table_lock_);
497  void RecordWeakStringRemoval(ObjPtr<mirror::String> s) const
498      REQUIRES(Locks::intern_table_lock_);
499  void RecordResolveString(ObjPtr<mirror::DexCache> dex_cache, dex::StringIndex string_idx) const
500      REQUIRES_SHARED(Locks::mutator_lock_);
501
502  void SetFaultMessage(const std::string& message) REQUIRES(!fault_message_lock_);
503  // Only read by the signal handler, NO_THREAD_SAFETY_ANALYSIS to prevent lock order violations
504  // with the unexpected_signal_lock_.
505  const std::string& GetFaultMessage() NO_THREAD_SAFETY_ANALYSIS {
506    return fault_message_;
507  }
508
509  void AddCurrentRuntimeFeaturesAsDex2OatArguments(std::vector<std::string>* arg_vector) const;
510
511  bool ExplicitStackOverflowChecks() const {
512    return !implicit_so_checks_;
513  }
514
515  bool IsVerificationEnabled() const;
516  bool IsVerificationSoftFail() const;
517
518  bool IsDexFileFallbackEnabled() const {
519    return allow_dex_file_fallback_;
520  }
521
522  const std::vector<std::string>& GetCpuAbilist() const {
523    return cpu_abilist_;
524  }
525
526  bool IsRunningOnMemoryTool() const {
527    return is_running_on_memory_tool_;
528  }
529
530  void SetTargetSdkVersion(int32_t version) {
531    target_sdk_version_ = version;
532  }
533
534  int32_t GetTargetSdkVersion() const {
535    return target_sdk_version_;
536  }
537
538  uint32_t GetZygoteMaxFailedBoots() const {
539    return zygote_max_failed_boots_;
540  }
541
542  bool AreExperimentalFlagsEnabled(ExperimentalFlags flags) {
543    return (experimental_flags_ & flags) != ExperimentalFlags::kNone;
544  }
545
546  // Create the JIT and instrumentation and code cache.
547  void CreateJit();
548
549  ArenaPool* GetArenaPool() {
550    return arena_pool_.get();
551  }
552  ArenaPool* GetJitArenaPool() {
553    return jit_arena_pool_.get();
554  }
555  const ArenaPool* GetArenaPool() const {
556    return arena_pool_.get();
557  }
558
559  void ReclaimArenaPoolMemory();
560
561  LinearAlloc* GetLinearAlloc() {
562    return linear_alloc_.get();
563  }
564
565  jit::JitOptions* GetJITOptions() {
566    return jit_options_.get();
567  }
568
569  bool IsJavaDebuggable() const {
570    return is_java_debuggable_;
571  }
572
573  void SetJavaDebuggable(bool value);
574
575  // Deoptimize the boot image, called for Java debuggable apps.
576  void DeoptimizeBootImage();
577
578  bool IsNativeDebuggable() const {
579    return is_native_debuggable_;
580  }
581
582  void SetNativeDebuggable(bool value) {
583    is_native_debuggable_ = value;
584  }
585
586  // Returns the build fingerprint, if set. Otherwise an empty string is returned.
587  std::string GetFingerprint() {
588    return fingerprint_;
589  }
590
591  // Called from class linker.
592  void SetSentinel(mirror::Object* sentinel) REQUIRES_SHARED(Locks::mutator_lock_);
593
594  // Create a normal LinearAlloc or low 4gb version if we are 64 bit AOT compiler.
595  LinearAlloc* CreateLinearAlloc();
596
597  OatFileManager& GetOatFileManager() const {
598    DCHECK(oat_file_manager_ != nullptr);
599    return *oat_file_manager_;
600  }
601
602  double GetHashTableMinLoadFactor() const;
603  double GetHashTableMaxLoadFactor() const;
604
605  void SetSafeMode(bool mode) {
606    safe_mode_ = mode;
607  }
608
609  bool GetDumpNativeStackOnSigQuit() const {
610    return dump_native_stack_on_sig_quit_;
611  }
612
613  bool GetPrunedDalvikCache() const {
614    return pruned_dalvik_cache_;
615  }
616
617  void SetPrunedDalvikCache(bool pruned) {
618    pruned_dalvik_cache_ = pruned;
619  }
620
621  void UpdateProcessState(ProcessState process_state);
622
623  // Returns true if we currently care about long mutator pause.
624  bool InJankPerceptibleProcessState() const {
625    return process_state_ == kProcessStateJankPerceptible;
626  }
627
628  void RegisterSensitiveThread() const;
629
630  void SetZygoteNoThreadSection(bool val) {
631    zygote_no_threads_ = val;
632  }
633
634  bool IsZygoteNoThreadSection() const {
635    return zygote_no_threads_;
636  }
637
638  // Returns if the code can be deoptimized asynchronously. Code may be compiled with some
639  // optimization that makes it impossible to deoptimize.
640  bool IsAsyncDeoptimizeable(uintptr_t code) const REQUIRES_SHARED(Locks::mutator_lock_);
641
642  // Returns a saved copy of the environment (getenv/setenv values).
643  // Used by Fork to protect against overwriting LD_LIBRARY_PATH, etc.
644  char** GetEnvSnapshot() const {
645    return env_snapshot_.GetSnapshot();
646  }
647
648  void AddSystemWeakHolder(gc::AbstractSystemWeakHolder* holder);
649  void RemoveSystemWeakHolder(gc::AbstractSystemWeakHolder* holder);
650
651  ClassHierarchyAnalysis* GetClassHierarchyAnalysis() {
652    return cha_;
653  }
654
655  NO_RETURN
656  static void Aborter(const char* abort_message);
657
658  void AttachAgent(const std::string& agent_arg);
659
660  const std::list<ti::Agent>& GetAgents() const {
661    return agents_;
662  }
663
664  RuntimeCallbacks* GetRuntimeCallbacks();
665
666  void InitThreadGroups(Thread* self);
667
668  void SetDumpGCPerformanceOnShutdown(bool value) {
669    dump_gc_performance_on_shutdown_ = value;
670  }
671
672 private:
673  static void InitPlatformSignalHandlers();
674
675  Runtime();
676
677  void BlockSignals();
678
679  bool Init(RuntimeArgumentMap&& runtime_options)
680      SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_);
681  void InitNativeMethods() REQUIRES(!Locks::mutator_lock_);
682  void RegisterRuntimeNativeMethods(JNIEnv* env);
683
684  void StartDaemonThreads();
685  void StartSignalCatcher();
686
687  void MaybeSaveJitProfilingInfo();
688
689  // Visit all of the thread roots.
690  void VisitThreadRoots(RootVisitor* visitor, VisitRootFlags flags)
691      REQUIRES_SHARED(Locks::mutator_lock_);
692
693  // Visit all other roots which must be done with mutators suspended.
694  void VisitNonConcurrentRoots(RootVisitor* visitor, VisitRootFlags flags)
695      REQUIRES_SHARED(Locks::mutator_lock_);
696
697  // Constant roots are the roots which never change after the runtime is initialized, they only
698  // need to be visited once per GC cycle.
699  void VisitConstantRoots(RootVisitor* visitor)
700      REQUIRES_SHARED(Locks::mutator_lock_);
701
702  // A pointer to the active runtime or null.
703  static Runtime* instance_;
704
705  // NOTE: these must match the gc::ProcessState values as they come directly from the framework.
706  static constexpr int kProfileForground = 0;
707  static constexpr int kProfileBackground = 1;
708
709  // 64 bit so that we can share the same asm offsets for both 32 and 64 bits.
710  uint64_t callee_save_methods_[kLastCalleeSaveType];
711  GcRoot<mirror::Throwable> pre_allocated_OutOfMemoryError_;
712  GcRoot<mirror::Throwable> pre_allocated_NoClassDefFoundError_;
713  ArtMethod* resolution_method_;
714  ArtMethod* imt_conflict_method_;
715  // Unresolved method has the same behavior as the conflict method, it is used by the class linker
716  // for differentiating between unfilled imt slots vs conflict slots in superclasses.
717  ArtMethod* imt_unimplemented_method_;
718
719  // Special sentinel object used to invalid conditions in JNI (cleared weak references) and
720  // JDWP (invalid references).
721  GcRoot<mirror::Object> sentinel_;
722
723  InstructionSet instruction_set_;
724  QuickMethodFrameInfo callee_save_method_frame_infos_[kLastCalleeSaveType];
725
726  CompilerCallbacks* compiler_callbacks_;
727  bool is_zygote_;
728  bool must_relocate_;
729  bool is_concurrent_gc_enabled_;
730  bool is_explicit_gc_disabled_;
731  bool dex2oat_enabled_;
732  bool image_dex2oat_enabled_;
733
734  std::string compiler_executable_;
735  std::string patchoat_executable_;
736  std::vector<std::string> compiler_options_;
737  std::vector<std::string> image_compiler_options_;
738  std::string image_location_;
739
740  std::string boot_class_path_string_;
741  std::string class_path_string_;
742  std::vector<std::string> properties_;
743
744  std::list<ti::Agent> agents_;
745  std::vector<Plugin> plugins_;
746
747  // The default stack size for managed threads created by the runtime.
748  size_t default_stack_size_;
749
750  gc::Heap* heap_;
751
752  std::unique_ptr<ArenaPool> jit_arena_pool_;
753  std::unique_ptr<ArenaPool> arena_pool_;
754  // Special low 4gb pool for compiler linear alloc. We need ArtFields to be in low 4gb if we are
755  // compiling using a 32 bit image on a 64 bit compiler in case we resolve things in the image
756  // since the field arrays are int arrays in this case.
757  std::unique_ptr<ArenaPool> low_4gb_arena_pool_;
758
759  // Shared linear alloc for now.
760  std::unique_ptr<LinearAlloc> linear_alloc_;
761
762  // The number of spins that are done before thread suspension is used to forcibly inflate.
763  size_t max_spins_before_thin_lock_inflation_;
764  MonitorList* monitor_list_;
765  MonitorPool* monitor_pool_;
766
767  ThreadList* thread_list_;
768
769  InternTable* intern_table_;
770
771  ClassLinker* class_linker_;
772
773  SignalCatcher* signal_catcher_;
774  std::string stack_trace_file_;
775
776  std::unique_ptr<JavaVMExt> java_vm_;
777
778  std::unique_ptr<jit::Jit> jit_;
779  std::unique_ptr<jit::JitOptions> jit_options_;
780
781  // Fault message, printed when we get a SIGSEGV.
782  Mutex fault_message_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
783  std::string fault_message_ GUARDED_BY(fault_message_lock_);
784
785  // A non-zero value indicates that a thread has been created but not yet initialized. Guarded by
786  // the shutdown lock so that threads aren't born while we're shutting down.
787  size_t threads_being_born_ GUARDED_BY(Locks::runtime_shutdown_lock_);
788
789  // Waited upon until no threads are being born.
790  std::unique_ptr<ConditionVariable> shutdown_cond_ GUARDED_BY(Locks::runtime_shutdown_lock_);
791
792  // Set when runtime shutdown is past the point that new threads may attach.
793  bool shutting_down_ GUARDED_BY(Locks::runtime_shutdown_lock_);
794
795  // The runtime is starting to shutdown but is blocked waiting on shutdown_cond_.
796  bool shutting_down_started_ GUARDED_BY(Locks::runtime_shutdown_lock_);
797
798  bool started_;
799
800  // New flag added which tells us if the runtime has finished starting. If
801  // this flag is set then the Daemon threads are created and the class loader
802  // is created. This flag is needed for knowing if its safe to request CMS.
803  bool finished_starting_;
804
805  // Hooks supported by JNI_CreateJavaVM
806  jint (*vfprintf_)(FILE* stream, const char* format, va_list ap);
807  void (*exit_)(jint status);
808  void (*abort_)();
809
810  bool stats_enabled_;
811  RuntimeStats stats_;
812
813  const bool is_running_on_memory_tool_;
814
815  std::unique_ptr<TraceConfig> trace_config_;
816
817  instrumentation::Instrumentation instrumentation_;
818
819  jobject main_thread_group_;
820  jobject system_thread_group_;
821
822  // As returned by ClassLoader.getSystemClassLoader().
823  jobject system_class_loader_;
824
825  // If true, then we dump the GC cumulative timings on shutdown.
826  bool dump_gc_performance_on_shutdown_;
827
828  // Transaction used for pre-initializing classes at compilation time.
829  Transaction* preinitialization_transaction_;
830
831  // If kNone, verification is disabled. kEnable by default.
832  verifier::VerifyMode verify_;
833
834  // If true, the runtime may use dex files directly with the interpreter if an oat file is not
835  // available/usable.
836  bool allow_dex_file_fallback_;
837
838  // List of supported cpu abis.
839  std::vector<std::string> cpu_abilist_;
840
841  // Specifies target SDK version to allow workarounds for certain API levels.
842  int32_t target_sdk_version_;
843
844  // Implicit checks flags.
845  bool implicit_null_checks_;       // NullPointer checks are implicit.
846  bool implicit_so_checks_;         // StackOverflow checks are implicit.
847  bool implicit_suspend_checks_;    // Thread suspension checks are implicit.
848
849  // Whether or not the sig chain (and implicitly the fault handler) should be
850  // disabled. Tools like dex2oat or patchoat don't need them. This enables
851  // building a statically link version of dex2oat.
852  bool no_sig_chain_;
853
854  // Force the use of native bridge even if the app ISA matches the runtime ISA.
855  bool force_native_bridge_;
856
857  // Whether or not a native bridge has been loaded.
858  //
859  // The native bridge allows running native code compiled for a foreign ISA. The way it works is,
860  // if standard dlopen fails to load native library associated with native activity, it calls to
861  // the native bridge to load it and then gets the trampoline for the entry to native activity.
862  //
863  // The option 'native_bridge_library_filename' specifies the name of the native bridge.
864  // When non-empty the native bridge will be loaded from the given file. An empty value means
865  // that there's no native bridge.
866  bool is_native_bridge_loaded_;
867
868  // Whether we are running under native debugger.
869  bool is_native_debuggable_;
870
871  // Whether Java code needs to be debuggable.
872  bool is_java_debuggable_;
873
874  // The maximum number of failed boots we allow before pruning the dalvik cache
875  // and trying again. This option is only inspected when we're running as a
876  // zygote.
877  uint32_t zygote_max_failed_boots_;
878
879  // Enable experimental opcodes that aren't fully specified yet. The intent is to
880  // eventually publish them as public-usable opcodes, but they aren't ready yet.
881  //
882  // Experimental opcodes should not be used by other production code.
883  ExperimentalFlags experimental_flags_;
884
885  // Contains the build fingerprint, if given as a parameter.
886  std::string fingerprint_;
887
888  // Oat file manager, keeps track of what oat files are open.
889  OatFileManager* oat_file_manager_;
890
891  // Whether or not we are on a low RAM device.
892  bool is_low_memory_mode_;
893
894  // Whether the application should run in safe mode, that is, interpreter only.
895  bool safe_mode_;
896
897  // Whether threads should dump their native stack on SIGQUIT.
898  bool dump_native_stack_on_sig_quit_;
899
900  // Whether the dalvik cache was pruned when initializing the runtime.
901  bool pruned_dalvik_cache_;
902
903  // Whether or not we currently care about pause times.
904  ProcessState process_state_;
905
906  // Whether zygote code is in a section that should not start threads.
907  bool zygote_no_threads_;
908
909  // Saved environment.
910  class EnvSnapshot {
911   public:
912    EnvSnapshot() = default;
913    void TakeSnapshot();
914    char** GetSnapshot() const;
915
916   private:
917    std::unique_ptr<char*[]> c_env_vector_;
918    std::vector<std::unique_ptr<std::string>> name_value_pairs_;
919
920    DISALLOW_COPY_AND_ASSIGN(EnvSnapshot);
921  } env_snapshot_;
922
923  // Generic system-weak holders.
924  std::vector<gc::AbstractSystemWeakHolder*> system_weak_holders_;
925
926  ClassHierarchyAnalysis* cha_;
927
928  std::unique_ptr<RuntimeCallbacks> callbacks_;
929
930  DISALLOW_COPY_AND_ASSIGN(Runtime);
931};
932std::ostream& operator<<(std::ostream& os, const Runtime::CalleeSaveType& rhs);
933
934}  // namespace art
935
936#endif  // ART_RUNTIME_RUNTIME_H_
937