runtime.h revision 433b79a9130df5f2375b9d3d7518c1f3fb84a467
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                       const std::string& foreign_dex_profile_path,
459                       const std::string& app_dir);
460  void NotifyDexLoaded(const std::string& dex_location);
461
462  // Transaction support.
463  bool IsActiveTransaction() const {
464    return preinitialization_transaction_ != nullptr;
465  }
466  void EnterTransactionMode(Transaction* transaction);
467  void ExitTransactionMode();
468  bool IsTransactionAborted() const;
469
470  void AbortTransactionAndThrowAbortError(Thread* self, const std::string& abort_message)
471      REQUIRES_SHARED(Locks::mutator_lock_);
472  void ThrowTransactionAbortError(Thread* self)
473      REQUIRES_SHARED(Locks::mutator_lock_);
474
475  void RecordWriteFieldBoolean(mirror::Object* obj, MemberOffset field_offset, uint8_t value,
476                               bool is_volatile) const;
477  void RecordWriteFieldByte(mirror::Object* obj, MemberOffset field_offset, int8_t value,
478                            bool is_volatile) const;
479  void RecordWriteFieldChar(mirror::Object* obj, MemberOffset field_offset, uint16_t value,
480                            bool is_volatile) const;
481  void RecordWriteFieldShort(mirror::Object* obj, MemberOffset field_offset, int16_t value,
482                          bool is_volatile) const;
483  void RecordWriteField32(mirror::Object* obj, MemberOffset field_offset, uint32_t value,
484                          bool is_volatile) const;
485  void RecordWriteField64(mirror::Object* obj, MemberOffset field_offset, uint64_t value,
486                          bool is_volatile) const;
487  void RecordWriteFieldReference(mirror::Object* obj,
488                                 MemberOffset field_offset,
489                                 ObjPtr<mirror::Object> value,
490                                 bool is_volatile) const
491      REQUIRES_SHARED(Locks::mutator_lock_);
492  void RecordWriteArray(mirror::Array* array, size_t index, uint64_t value) const
493      REQUIRES_SHARED(Locks::mutator_lock_);
494  void RecordStrongStringInsertion(ObjPtr<mirror::String> s) const
495      REQUIRES(Locks::intern_table_lock_);
496  void RecordWeakStringInsertion(ObjPtr<mirror::String> s) const
497      REQUIRES(Locks::intern_table_lock_);
498  void RecordStrongStringRemoval(ObjPtr<mirror::String> s) const
499      REQUIRES(Locks::intern_table_lock_);
500  void RecordWeakStringRemoval(ObjPtr<mirror::String> s) const
501      REQUIRES(Locks::intern_table_lock_);
502  void RecordResolveString(ObjPtr<mirror::DexCache> dex_cache, dex::StringIndex string_idx) const
503      REQUIRES_SHARED(Locks::mutator_lock_);
504
505  void SetFaultMessage(const std::string& message) REQUIRES(!fault_message_lock_);
506  // Only read by the signal handler, NO_THREAD_SAFETY_ANALYSIS to prevent lock order violations
507  // with the unexpected_signal_lock_.
508  const std::string& GetFaultMessage() NO_THREAD_SAFETY_ANALYSIS {
509    return fault_message_;
510  }
511
512  void AddCurrentRuntimeFeaturesAsDex2OatArguments(std::vector<std::string>* arg_vector) const;
513
514  bool ExplicitStackOverflowChecks() const {
515    return !implicit_so_checks_;
516  }
517
518  bool IsVerificationEnabled() const;
519  bool IsVerificationSoftFail() const;
520
521  bool IsDexFileFallbackEnabled() const {
522    return allow_dex_file_fallback_;
523  }
524
525  const std::vector<std::string>& GetCpuAbilist() const {
526    return cpu_abilist_;
527  }
528
529  bool IsRunningOnMemoryTool() const {
530    return is_running_on_memory_tool_;
531  }
532
533  void SetTargetSdkVersion(int32_t version) {
534    target_sdk_version_ = version;
535  }
536
537  int32_t GetTargetSdkVersion() const {
538    return target_sdk_version_;
539  }
540
541  uint32_t GetZygoteMaxFailedBoots() const {
542    return zygote_max_failed_boots_;
543  }
544
545  bool AreExperimentalFlagsEnabled(ExperimentalFlags flags) {
546    return (experimental_flags_ & flags) != ExperimentalFlags::kNone;
547  }
548
549  // Create the JIT and instrumentation and code cache.
550  void CreateJit();
551
552  ArenaPool* GetArenaPool() {
553    return arena_pool_.get();
554  }
555  ArenaPool* GetJitArenaPool() {
556    return jit_arena_pool_.get();
557  }
558  const ArenaPool* GetArenaPool() const {
559    return arena_pool_.get();
560  }
561
562  void ReclaimArenaPoolMemory();
563
564  LinearAlloc* GetLinearAlloc() {
565    return linear_alloc_.get();
566  }
567
568  jit::JitOptions* GetJITOptions() {
569    return jit_options_.get();
570  }
571
572  bool IsJavaDebuggable() const {
573    return is_java_debuggable_;
574  }
575
576  void SetJavaDebuggable(bool value);
577
578  // Deoptimize the boot image, called for Java debuggable apps.
579  void DeoptimizeBootImage();
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 asynchronously. Code may be compiled with some
642  // optimization that makes it impossible to deoptimize.
643  bool IsAsyncDeoptimizeable(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  RuntimeCallbacks* GetRuntimeCallbacks();
664
665 private:
666  static void InitPlatformSignalHandlers();
667
668  Runtime();
669
670  void BlockSignals();
671
672  bool Init(RuntimeArgumentMap&& runtime_options)
673      SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_);
674  void InitNativeMethods() REQUIRES(!Locks::mutator_lock_);
675  void InitThreadGroups(Thread* self);
676  void RegisterRuntimeNativeMethods(JNIEnv* env);
677
678  void StartDaemonThreads();
679  void StartSignalCatcher();
680
681  void MaybeSaveJitProfilingInfo();
682
683  // Visit all of the thread roots.
684  void VisitThreadRoots(RootVisitor* visitor, VisitRootFlags flags)
685      REQUIRES_SHARED(Locks::mutator_lock_);
686
687  // Visit all other roots which must be done with mutators suspended.
688  void VisitNonConcurrentRoots(RootVisitor* visitor, VisitRootFlags flags)
689      REQUIRES_SHARED(Locks::mutator_lock_);
690
691  // Constant roots are the roots which never change after the runtime is initialized, they only
692  // need to be visited once per GC cycle.
693  void VisitConstantRoots(RootVisitor* visitor)
694      REQUIRES_SHARED(Locks::mutator_lock_);
695
696  // A pointer to the active runtime or null.
697  static Runtime* instance_;
698
699  // NOTE: these must match the gc::ProcessState values as they come directly from the framework.
700  static constexpr int kProfileForground = 0;
701  static constexpr int kProfileBackground = 1;
702
703  // 64 bit so that we can share the same asm offsets for both 32 and 64 bits.
704  uint64_t callee_save_methods_[kLastCalleeSaveType];
705  GcRoot<mirror::Throwable> pre_allocated_OutOfMemoryError_;
706  GcRoot<mirror::Throwable> pre_allocated_NoClassDefFoundError_;
707  ArtMethod* resolution_method_;
708  ArtMethod* imt_conflict_method_;
709  // Unresolved method has the same behavior as the conflict method, it is used by the class linker
710  // for differentiating between unfilled imt slots vs conflict slots in superclasses.
711  ArtMethod* imt_unimplemented_method_;
712
713  // Special sentinel object used to invalid conditions in JNI (cleared weak references) and
714  // JDWP (invalid references).
715  GcRoot<mirror::Object> sentinel_;
716
717  InstructionSet instruction_set_;
718  QuickMethodFrameInfo callee_save_method_frame_infos_[kLastCalleeSaveType];
719
720  CompilerCallbacks* compiler_callbacks_;
721  bool is_zygote_;
722  bool must_relocate_;
723  bool is_concurrent_gc_enabled_;
724  bool is_explicit_gc_disabled_;
725  bool dex2oat_enabled_;
726  bool image_dex2oat_enabled_;
727
728  std::string compiler_executable_;
729  std::string patchoat_executable_;
730  std::vector<std::string> compiler_options_;
731  std::vector<std::string> image_compiler_options_;
732  std::string image_location_;
733
734  std::string boot_class_path_string_;
735  std::string class_path_string_;
736  std::vector<std::string> properties_;
737
738  std::vector<ti::Agent> agents_;
739  std::vector<Plugin> plugins_;
740
741  // The default stack size for managed threads created by the runtime.
742  size_t default_stack_size_;
743
744  gc::Heap* heap_;
745
746  std::unique_ptr<ArenaPool> jit_arena_pool_;
747  std::unique_ptr<ArenaPool> arena_pool_;
748  // Special low 4gb pool for compiler linear alloc. We need ArtFields to be in low 4gb if we are
749  // compiling using a 32 bit image on a 64 bit compiler in case we resolve things in the image
750  // since the field arrays are int arrays in this case.
751  std::unique_ptr<ArenaPool> low_4gb_arena_pool_;
752
753  // Shared linear alloc for now.
754  std::unique_ptr<LinearAlloc> linear_alloc_;
755
756  // The number of spins that are done before thread suspension is used to forcibly inflate.
757  size_t max_spins_before_thin_lock_inflation_;
758  MonitorList* monitor_list_;
759  MonitorPool* monitor_pool_;
760
761  ThreadList* thread_list_;
762
763  InternTable* intern_table_;
764
765  ClassLinker* class_linker_;
766
767  SignalCatcher* signal_catcher_;
768  std::string stack_trace_file_;
769
770  std::unique_ptr<JavaVMExt> java_vm_;
771
772  std::unique_ptr<jit::Jit> jit_;
773  std::unique_ptr<jit::JitOptions> jit_options_;
774
775  // Fault message, printed when we get a SIGSEGV.
776  Mutex fault_message_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
777  std::string fault_message_ GUARDED_BY(fault_message_lock_);
778
779  // A non-zero value indicates that a thread has been created but not yet initialized. Guarded by
780  // the shutdown lock so that threads aren't born while we're shutting down.
781  size_t threads_being_born_ GUARDED_BY(Locks::runtime_shutdown_lock_);
782
783  // Waited upon until no threads are being born.
784  std::unique_ptr<ConditionVariable> shutdown_cond_ GUARDED_BY(Locks::runtime_shutdown_lock_);
785
786  // Set when runtime shutdown is past the point that new threads may attach.
787  bool shutting_down_ GUARDED_BY(Locks::runtime_shutdown_lock_);
788
789  // The runtime is starting to shutdown but is blocked waiting on shutdown_cond_.
790  bool shutting_down_started_ GUARDED_BY(Locks::runtime_shutdown_lock_);
791
792  bool started_;
793
794  // New flag added which tells us if the runtime has finished starting. If
795  // this flag is set then the Daemon threads are created and the class loader
796  // is created. This flag is needed for knowing if its safe to request CMS.
797  bool finished_starting_;
798
799  // Hooks supported by JNI_CreateJavaVM
800  jint (*vfprintf_)(FILE* stream, const char* format, va_list ap);
801  void (*exit_)(jint status);
802  void (*abort_)();
803
804  bool stats_enabled_;
805  RuntimeStats stats_;
806
807  const bool is_running_on_memory_tool_;
808
809  std::unique_ptr<TraceConfig> trace_config_;
810
811  instrumentation::Instrumentation instrumentation_;
812
813  jobject main_thread_group_;
814  jobject system_thread_group_;
815
816  // As returned by ClassLoader.getSystemClassLoader().
817  jobject system_class_loader_;
818
819  // If true, then we dump the GC cumulative timings on shutdown.
820  bool dump_gc_performance_on_shutdown_;
821
822  // Transaction used for pre-initializing classes at compilation time.
823  Transaction* preinitialization_transaction_;
824
825  // If kNone, verification is disabled. kEnable by default.
826  verifier::VerifyMode verify_;
827
828  // If true, the runtime may use dex files directly with the interpreter if an oat file is not
829  // available/usable.
830  bool allow_dex_file_fallback_;
831
832  // List of supported cpu abis.
833  std::vector<std::string> cpu_abilist_;
834
835  // Specifies target SDK version to allow workarounds for certain API levels.
836  int32_t target_sdk_version_;
837
838  // Implicit checks flags.
839  bool implicit_null_checks_;       // NullPointer checks are implicit.
840  bool implicit_so_checks_;         // StackOverflow checks are implicit.
841  bool implicit_suspend_checks_;    // Thread suspension checks are implicit.
842
843  // Whether or not the sig chain (and implicitly the fault handler) should be
844  // disabled. Tools like dex2oat or patchoat don't need them. This enables
845  // building a statically link version of dex2oat.
846  bool no_sig_chain_;
847
848  // Force the use of native bridge even if the app ISA matches the runtime ISA.
849  bool force_native_bridge_;
850
851  // Whether or not a native bridge has been loaded.
852  //
853  // The native bridge allows running native code compiled for a foreign ISA. The way it works is,
854  // if standard dlopen fails to load native library associated with native activity, it calls to
855  // the native bridge to load it and then gets the trampoline for the entry to native activity.
856  //
857  // The option 'native_bridge_library_filename' specifies the name of the native bridge.
858  // When non-empty the native bridge will be loaded from the given file. An empty value means
859  // that there's no native bridge.
860  bool is_native_bridge_loaded_;
861
862  // Whether we are running under native debugger.
863  bool is_native_debuggable_;
864
865  // Whether Java code needs to be debuggable.
866  bool is_java_debuggable_;
867
868  // The maximum number of failed boots we allow before pruning the dalvik cache
869  // and trying again. This option is only inspected when we're running as a
870  // zygote.
871  uint32_t zygote_max_failed_boots_;
872
873  // Enable experimental opcodes that aren't fully specified yet. The intent is to
874  // eventually publish them as public-usable opcodes, but they aren't ready yet.
875  //
876  // Experimental opcodes should not be used by other production code.
877  ExperimentalFlags experimental_flags_;
878
879  // Contains the build fingerprint, if given as a parameter.
880  std::string fingerprint_;
881
882  // Oat file manager, keeps track of what oat files are open.
883  OatFileManager* oat_file_manager_;
884
885  // Whether or not we are on a low RAM device.
886  bool is_low_memory_mode_;
887
888  // Whether the application should run in safe mode, that is, interpreter only.
889  bool safe_mode_;
890
891  // Whether threads should dump their native stack on SIGQUIT.
892  bool dump_native_stack_on_sig_quit_;
893
894  // Whether the dalvik cache was pruned when initializing the runtime.
895  bool pruned_dalvik_cache_;
896
897  // Whether or not we currently care about pause times.
898  ProcessState process_state_;
899
900  // Whether zygote code is in a section that should not start threads.
901  bool zygote_no_threads_;
902
903  // Saved environment.
904  class EnvSnapshot {
905   public:
906    EnvSnapshot() = default;
907    void TakeSnapshot();
908    char** GetSnapshot() const;
909
910   private:
911    std::unique_ptr<char*[]> c_env_vector_;
912    std::vector<std::unique_ptr<std::string>> name_value_pairs_;
913
914    DISALLOW_COPY_AND_ASSIGN(EnvSnapshot);
915  } env_snapshot_;
916
917  // Generic system-weak holders.
918  std::vector<gc::AbstractSystemWeakHolder*> system_weak_holders_;
919
920  ClassHierarchyAnalysis* cha_;
921
922  std::unique_ptr<RuntimeCallbacks> callbacks_;
923
924  DISALLOW_COPY_AND_ASSIGN(Runtime);
925};
926std::ostream& operator<<(std::ostream& os, const Runtime::CalleeSaveType& rhs);
927
928}  // namespace art
929
930#endif  // ART_RUNTIME_RUNTIME_H_
931