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