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