runtime.h revision 3d74bf45706429f0cbfce0c1e7d213416c5ecf50
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  }
321
322  void DisallowNewSystemWeaks() REQUIRES_SHARED(Locks::mutator_lock_);
323  void AllowNewSystemWeaks() REQUIRES_SHARED(Locks::mutator_lock_);
324  void BroadcastForNewSystemWeaks() REQUIRES_SHARED(Locks::mutator_lock_);
325
326  // Visit all the roots. If only_dirty is true then non-dirty roots won't be visited. If
327  // clean_dirty is true then dirty roots will be marked as non-dirty after visiting.
328  void VisitRoots(RootVisitor* visitor, VisitRootFlags flags = kVisitRootFlagAllRoots)
329      REQUIRES_SHARED(Locks::mutator_lock_);
330
331  // Visit image roots, only used for hprof since the GC uses the image space mod union table
332  // instead.
333  void VisitImageRoots(RootVisitor* visitor) REQUIRES_SHARED(Locks::mutator_lock_);
334
335  // Visit all of the roots we can do safely do concurrently.
336  void VisitConcurrentRoots(RootVisitor* visitor,
337                            VisitRootFlags flags = kVisitRootFlagAllRoots)
338      REQUIRES_SHARED(Locks::mutator_lock_);
339
340  // Visit all of the non thread roots, we can do this with mutators unpaused.
341  void VisitNonThreadRoots(RootVisitor* visitor)
342      REQUIRES_SHARED(Locks::mutator_lock_);
343
344  void VisitTransactionRoots(RootVisitor* visitor)
345      REQUIRES_SHARED(Locks::mutator_lock_);
346
347  // Visit all of the thread roots.
348  void VisitThreadRoots(RootVisitor* visitor) REQUIRES_SHARED(Locks::mutator_lock_);
349
350  // Flip thread roots from from-space refs to to-space refs.
351  size_t FlipThreadRoots(Closure* thread_flip_visitor, Closure* flip_callback,
352                         gc::collector::GarbageCollector* collector)
353      REQUIRES(!Locks::mutator_lock_);
354
355  // Visit all other roots which must be done with mutators suspended.
356  void VisitNonConcurrentRoots(RootVisitor* visitor)
357      REQUIRES_SHARED(Locks::mutator_lock_);
358
359  // Sweep system weaks, the system weak is deleted if the visitor return null. Otherwise, the
360  // system weak is updated to be the visitor's returned value.
361  void SweepSystemWeaks(IsMarkedVisitor* visitor)
362      REQUIRES_SHARED(Locks::mutator_lock_);
363
364  // Constant roots are the roots which never change after the runtime is initialized, they only
365  // need to be visited once per GC cycle.
366  void VisitConstantRoots(RootVisitor* visitor)
367      REQUIRES_SHARED(Locks::mutator_lock_);
368
369  // Returns a special method that calls into a trampoline for runtime method resolution
370  ArtMethod* GetResolutionMethod();
371
372  bool HasResolutionMethod() const {
373    return resolution_method_ != nullptr;
374  }
375
376  void SetResolutionMethod(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_);
377
378  ArtMethod* CreateResolutionMethod() REQUIRES_SHARED(Locks::mutator_lock_);
379
380  // Returns a special method that calls into a trampoline for runtime imt conflicts.
381  ArtMethod* GetImtConflictMethod();
382  ArtMethod* GetImtUnimplementedMethod();
383
384  bool HasImtConflictMethod() const {
385    return imt_conflict_method_ != nullptr;
386  }
387
388  void FixupConflictTables();
389  void SetImtConflictMethod(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_);
390  void SetImtUnimplementedMethod(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_);
391
392  ArtMethod* CreateImtConflictMethod(LinearAlloc* linear_alloc)
393      REQUIRES_SHARED(Locks::mutator_lock_);
394
395  // Returns a special method that describes all callee saves being spilled to the stack.
396  enum CalleeSaveType {
397    kSaveAllCalleeSaves,  // All callee-save registers.
398    kSaveRefsOnly,        // Only those callee-save registers that can hold references.
399    kSaveRefsAndArgs,     // References (see above) and arguments (usually caller-save registers).
400    kSaveEverything,      // All registers, including both callee-save and caller-save.
401    kLastCalleeSaveType   // Value used for iteration
402  };
403
404  bool HasCalleeSaveMethod(CalleeSaveType type) const {
405    return callee_save_methods_[type] != 0u;
406  }
407
408  ArtMethod* GetCalleeSaveMethod(CalleeSaveType type)
409      REQUIRES_SHARED(Locks::mutator_lock_);
410
411  ArtMethod* GetCalleeSaveMethodUnchecked(CalleeSaveType type)
412      REQUIRES_SHARED(Locks::mutator_lock_);
413
414  QuickMethodFrameInfo GetCalleeSaveMethodFrameInfo(CalleeSaveType type) const {
415    return callee_save_method_frame_infos_[type];
416  }
417
418  QuickMethodFrameInfo GetRuntimeMethodFrameInfo(ArtMethod* method)
419      REQUIRES_SHARED(Locks::mutator_lock_);
420
421  static size_t GetCalleeSaveMethodOffset(CalleeSaveType type) {
422    return OFFSETOF_MEMBER(Runtime, callee_save_methods_[type]);
423  }
424
425  InstructionSet GetInstructionSet() const {
426    return instruction_set_;
427  }
428
429  void SetInstructionSet(InstructionSet instruction_set);
430
431  void SetCalleeSaveMethod(ArtMethod* method, CalleeSaveType type);
432
433  ArtMethod* CreateCalleeSaveMethod() REQUIRES_SHARED(Locks::mutator_lock_);
434
435  int32_t GetStat(int kind);
436
437  RuntimeStats* GetStats() {
438    return &stats_;
439  }
440
441  bool HasStatsEnabled() const {
442    return stats_enabled_;
443  }
444
445  void ResetStats(int kinds);
446
447  void SetStatsEnabled(bool new_state)
448      REQUIRES(!Locks::instrument_entrypoints_lock_, !Locks::mutator_lock_);
449
450  enum class NativeBridgeAction {  // private
451    kUnload,
452    kInitialize
453  };
454
455  jit::Jit* GetJit() {
456    return jit_.get();
457  }
458
459  // Returns true if JIT compilations are enabled. GetJit() will be not null in this case.
460  bool UseJitCompilation() const;
461
462  void PreZygoteFork();
463  void InitNonZygoteOrPostFork(
464      JNIEnv* env, bool is_system_server, NativeBridgeAction action, const char* isa);
465
466  const instrumentation::Instrumentation* GetInstrumentation() const {
467    return &instrumentation_;
468  }
469
470  instrumentation::Instrumentation* GetInstrumentation() {
471    return &instrumentation_;
472  }
473
474  void RegisterAppInfo(const std::vector<std::string>& code_paths,
475                       const std::string& profile_output_filename,
476                       const std::string& foreign_dex_profile_path,
477                       const std::string& app_dir);
478  void NotifyDexLoaded(const std::string& dex_location);
479
480  // Transaction support.
481  bool IsActiveTransaction() const {
482    return preinitialization_transaction_ != nullptr;
483  }
484  void EnterTransactionMode(Transaction* transaction);
485  void ExitTransactionMode();
486  bool IsTransactionAborted() const;
487
488  void AbortTransactionAndThrowAbortError(Thread* self, const std::string& abort_message)
489      REQUIRES_SHARED(Locks::mutator_lock_);
490  void ThrowTransactionAbortError(Thread* self)
491      REQUIRES_SHARED(Locks::mutator_lock_);
492
493  void RecordWriteFieldBoolean(mirror::Object* obj, MemberOffset field_offset, uint8_t value,
494                               bool is_volatile) const;
495  void RecordWriteFieldByte(mirror::Object* obj, MemberOffset field_offset, int8_t value,
496                            bool is_volatile) const;
497  void RecordWriteFieldChar(mirror::Object* obj, MemberOffset field_offset, uint16_t value,
498                            bool is_volatile) const;
499  void RecordWriteFieldShort(mirror::Object* obj, MemberOffset field_offset, int16_t value,
500                          bool is_volatile) const;
501  void RecordWriteField32(mirror::Object* obj, MemberOffset field_offset, uint32_t value,
502                          bool is_volatile) const;
503  void RecordWriteField64(mirror::Object* obj, MemberOffset field_offset, uint64_t value,
504                          bool is_volatile) const;
505  void RecordWriteFieldReference(mirror::Object* obj,
506                                 MemberOffset field_offset,
507                                 ObjPtr<mirror::Object> value,
508                                 bool is_volatile) const
509      REQUIRES_SHARED(Locks::mutator_lock_);
510  void RecordWriteArray(mirror::Array* array, size_t index, uint64_t value) const
511      REQUIRES_SHARED(Locks::mutator_lock_);
512  void RecordStrongStringInsertion(ObjPtr<mirror::String> s) const
513      REQUIRES(Locks::intern_table_lock_);
514  void RecordWeakStringInsertion(ObjPtr<mirror::String> s) const
515      REQUIRES(Locks::intern_table_lock_);
516  void RecordStrongStringRemoval(ObjPtr<mirror::String> s) const
517      REQUIRES(Locks::intern_table_lock_);
518  void RecordWeakStringRemoval(ObjPtr<mirror::String> s) const
519      REQUIRES(Locks::intern_table_lock_);
520  void RecordResolveString(ObjPtr<mirror::DexCache> dex_cache, uint32_t string_idx) const
521      REQUIRES_SHARED(Locks::mutator_lock_);
522
523  void SetFaultMessage(const std::string& message) REQUIRES(!fault_message_lock_);
524  // Only read by the signal handler, NO_THREAD_SAFETY_ANALYSIS to prevent lock order violations
525  // with the unexpected_signal_lock_.
526  const std::string& GetFaultMessage() NO_THREAD_SAFETY_ANALYSIS {
527    return fault_message_;
528  }
529
530  void AddCurrentRuntimeFeaturesAsDex2OatArguments(std::vector<std::string>* arg_vector) const;
531
532  bool ExplicitStackOverflowChecks() const {
533    return !implicit_so_checks_;
534  }
535
536  bool IsVerificationEnabled() const;
537  bool IsVerificationSoftFail() const;
538
539  bool IsDexFileFallbackEnabled() const {
540    return allow_dex_file_fallback_;
541  }
542
543  const std::vector<std::string>& GetCpuAbilist() const {
544    return cpu_abilist_;
545  }
546
547  bool IsRunningOnMemoryTool() const {
548    return is_running_on_memory_tool_;
549  }
550
551  void SetTargetSdkVersion(int32_t version) {
552    target_sdk_version_ = version;
553  }
554
555  int32_t GetTargetSdkVersion() const {
556    return target_sdk_version_;
557  }
558
559  uint32_t GetZygoteMaxFailedBoots() const {
560    return zygote_max_failed_boots_;
561  }
562
563  bool AreExperimentalFlagsEnabled(ExperimentalFlags flags) {
564    return (experimental_flags_ & flags) != ExperimentalFlags::kNone;
565  }
566
567  // Create the JIT and instrumentation and code cache.
568  void CreateJit();
569
570  ArenaPool* GetArenaPool() {
571    return arena_pool_.get();
572  }
573  ArenaPool* GetJitArenaPool() {
574    return jit_arena_pool_.get();
575  }
576  const ArenaPool* GetArenaPool() const {
577    return arena_pool_.get();
578  }
579
580  void ReclaimArenaPoolMemory();
581
582  LinearAlloc* GetLinearAlloc() {
583    return linear_alloc_.get();
584  }
585
586  jit::JitOptions* GetJITOptions() {
587    return jit_options_.get();
588  }
589
590  bool IsDebuggable() const;
591
592  bool IsNativeDebuggable() const {
593    return is_native_debuggable_;
594  }
595
596  void SetNativeDebuggable(bool value) {
597    is_native_debuggable_ = value;
598  }
599
600  // Returns the build fingerprint, if set. Otherwise an empty string is returned.
601  std::string GetFingerprint() {
602    return fingerprint_;
603  }
604
605  // Called from class linker.
606  void SetSentinel(mirror::Object* sentinel) REQUIRES_SHARED(Locks::mutator_lock_);
607
608  // Create a normal LinearAlloc or low 4gb version if we are 64 bit AOT compiler.
609  LinearAlloc* CreateLinearAlloc();
610
611  OatFileManager& GetOatFileManager() const {
612    DCHECK(oat_file_manager_ != nullptr);
613    return *oat_file_manager_;
614  }
615
616  double GetHashTableMinLoadFactor() const;
617  double GetHashTableMaxLoadFactor() const;
618
619  void SetSafeMode(bool mode) {
620    safe_mode_ = mode;
621  }
622
623  bool GetDumpNativeStackOnSigQuit() const {
624    return dump_native_stack_on_sig_quit_;
625  }
626
627  bool GetPrunedDalvikCache() const {
628    return pruned_dalvik_cache_;
629  }
630
631  void SetPrunedDalvikCache(bool pruned) {
632    pruned_dalvik_cache_ = pruned;
633  }
634
635  void UpdateProcessState(ProcessState process_state);
636
637  // Returns true if we currently care about long mutator pause.
638  bool InJankPerceptibleProcessState() const {
639    return process_state_ == kProcessStateJankPerceptible;
640  }
641
642  void RegisterSensitiveThread() const;
643
644  void SetZygoteNoThreadSection(bool val) {
645    zygote_no_threads_ = val;
646  }
647
648  bool IsZygoteNoThreadSection() const {
649    return zygote_no_threads_;
650  }
651
652  // Returns if the code can be deoptimized. Code may be compiled with some
653  // optimization that makes it impossible to deoptimize.
654  bool IsDeoptimizeable(uintptr_t code) const REQUIRES_SHARED(Locks::mutator_lock_);
655
656  // Returns a saved copy of the environment (getenv/setenv values).
657  // Used by Fork to protect against overwriting LD_LIBRARY_PATH, etc.
658  char** GetEnvSnapshot() const {
659    return env_snapshot_.GetSnapshot();
660  }
661
662  void AddSystemWeakHolder(gc::AbstractSystemWeakHolder* holder);
663  void RemoveSystemWeakHolder(gc::AbstractSystemWeakHolder* holder);
664
665  NO_RETURN
666  static void Aborter(const char* abort_message);
667
668  void AttachAgent(const std::string& agent_arg);
669
670 private:
671  static void InitPlatformSignalHandlers();
672
673  Runtime();
674
675  void BlockSignals();
676
677  bool Init(RuntimeArgumentMap&& runtime_options)
678      SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_);
679  void InitNativeMethods() REQUIRES(!Locks::mutator_lock_);
680  void InitThreadGroups(Thread* self);
681  void RegisterRuntimeNativeMethods(JNIEnv* env);
682
683  void StartDaemonThreads();
684  void StartSignalCatcher();
685
686  void MaybeSaveJitProfilingInfo();
687
688  // A pointer to the active runtime or null.
689  static Runtime* instance_;
690
691  // NOTE: these must match the gc::ProcessState values as they come directly from the framework.
692  static constexpr int kProfileForground = 0;
693  static constexpr int kProfileBackground = 1;
694
695  // 64 bit so that we can share the same asm offsets for both 32 and 64 bits.
696  uint64_t callee_save_methods_[kLastCalleeSaveType];
697  GcRoot<mirror::Throwable> pre_allocated_OutOfMemoryError_;
698  GcRoot<mirror::Throwable> pre_allocated_NoClassDefFoundError_;
699  ArtMethod* resolution_method_;
700  ArtMethod* imt_conflict_method_;
701  // Unresolved method has the same behavior as the conflict method, it is used by the class linker
702  // for differentiating between unfilled imt slots vs conflict slots in superclasses.
703  ArtMethod* imt_unimplemented_method_;
704
705  // Special sentinel object used to invalid conditions in JNI (cleared weak references) and
706  // JDWP (invalid references).
707  GcRoot<mirror::Object> sentinel_;
708
709  InstructionSet instruction_set_;
710  QuickMethodFrameInfo callee_save_method_frame_infos_[kLastCalleeSaveType];
711
712  CompilerCallbacks* compiler_callbacks_;
713  bool is_zygote_;
714  bool must_relocate_;
715  bool is_concurrent_gc_enabled_;
716  bool is_explicit_gc_disabled_;
717  bool dex2oat_enabled_;
718  bool image_dex2oat_enabled_;
719
720  std::string compiler_executable_;
721  std::string patchoat_executable_;
722  std::vector<std::string> compiler_options_;
723  std::vector<std::string> image_compiler_options_;
724  std::string image_location_;
725
726  std::string boot_class_path_string_;
727  std::string class_path_string_;
728  std::vector<std::string> properties_;
729
730  std::vector<ti::Agent> agents_;
731  std::vector<Plugin> plugins_;
732
733  // The default stack size for managed threads created by the runtime.
734  size_t default_stack_size_;
735
736  gc::Heap* heap_;
737
738  std::unique_ptr<ArenaPool> jit_arena_pool_;
739  std::unique_ptr<ArenaPool> arena_pool_;
740  // Special low 4gb pool for compiler linear alloc. We need ArtFields to be in low 4gb if we are
741  // compiling using a 32 bit image on a 64 bit compiler in case we resolve things in the image
742  // since the field arrays are int arrays in this case.
743  std::unique_ptr<ArenaPool> low_4gb_arena_pool_;
744
745  // Shared linear alloc for now.
746  std::unique_ptr<LinearAlloc> linear_alloc_;
747
748  // The number of spins that are done before thread suspension is used to forcibly inflate.
749  size_t max_spins_before_thin_lock_inflation_;
750  MonitorList* monitor_list_;
751  MonitorPool* monitor_pool_;
752
753  ThreadList* thread_list_;
754
755  InternTable* intern_table_;
756
757  ClassLinker* class_linker_;
758
759  SignalCatcher* signal_catcher_;
760  std::string stack_trace_file_;
761
762  std::unique_ptr<JavaVMExt> java_vm_;
763
764  std::unique_ptr<jit::Jit> jit_;
765  std::unique_ptr<jit::JitOptions> jit_options_;
766
767  // Fault message, printed when we get a SIGSEGV.
768  Mutex fault_message_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
769  std::string fault_message_ GUARDED_BY(fault_message_lock_);
770
771  // A non-zero value indicates that a thread has been created but not yet initialized. Guarded by
772  // the shutdown lock so that threads aren't born while we're shutting down.
773  size_t threads_being_born_ GUARDED_BY(Locks::runtime_shutdown_lock_);
774
775  // Waited upon until no threads are being born.
776  std::unique_ptr<ConditionVariable> shutdown_cond_ GUARDED_BY(Locks::runtime_shutdown_lock_);
777
778  // Set when runtime shutdown is past the point that new threads may attach.
779  bool shutting_down_ GUARDED_BY(Locks::runtime_shutdown_lock_);
780
781  // The runtime is starting to shutdown but is blocked waiting on shutdown_cond_.
782  bool shutting_down_started_ GUARDED_BY(Locks::runtime_shutdown_lock_);
783
784  bool started_;
785
786  // New flag added which tells us if the runtime has finished starting. If
787  // this flag is set then the Daemon threads are created and the class loader
788  // is created. This flag is needed for knowing if its safe to request CMS.
789  bool finished_starting_;
790
791  // Hooks supported by JNI_CreateJavaVM
792  jint (*vfprintf_)(FILE* stream, const char* format, va_list ap);
793  void (*exit_)(jint status);
794  void (*abort_)();
795
796  bool stats_enabled_;
797  RuntimeStats stats_;
798
799  const bool is_running_on_memory_tool_;
800
801  std::unique_ptr<TraceConfig> trace_config_;
802
803  instrumentation::Instrumentation instrumentation_;
804
805  jobject main_thread_group_;
806  jobject system_thread_group_;
807
808  // As returned by ClassLoader.getSystemClassLoader().
809  jobject system_class_loader_;
810
811  // If true, then we dump the GC cumulative timings on shutdown.
812  bool dump_gc_performance_on_shutdown_;
813
814  // Transaction used for pre-initializing classes at compilation time.
815  Transaction* preinitialization_transaction_;
816
817  // If kNone, verification is disabled. kEnable by default.
818  verifier::VerifyMode verify_;
819
820  // If true, the runtime may use dex files directly with the interpreter if an oat file is not
821  // available/usable.
822  bool allow_dex_file_fallback_;
823
824  // List of supported cpu abis.
825  std::vector<std::string> cpu_abilist_;
826
827  // Specifies target SDK version to allow workarounds for certain API levels.
828  int32_t target_sdk_version_;
829
830  // Implicit checks flags.
831  bool implicit_null_checks_;       // NullPointer checks are implicit.
832  bool implicit_so_checks_;         // StackOverflow checks are implicit.
833  bool implicit_suspend_checks_;    // Thread suspension checks are implicit.
834
835  // Whether or not the sig chain (and implicitly the fault handler) should be
836  // disabled. Tools like dex2oat or patchoat don't need them. This enables
837  // building a statically link version of dex2oat.
838  bool no_sig_chain_;
839
840  // Force the use of native bridge even if the app ISA matches the runtime ISA.
841  bool force_native_bridge_;
842
843  // Whether or not a native bridge has been loaded.
844  //
845  // The native bridge allows running native code compiled for a foreign ISA. The way it works is,
846  // if standard dlopen fails to load native library associated with native activity, it calls to
847  // the native bridge to load it and then gets the trampoline for the entry to native activity.
848  //
849  // The option 'native_bridge_library_filename' specifies the name of the native bridge.
850  // When non-empty the native bridge will be loaded from the given file. An empty value means
851  // that there's no native bridge.
852  bool is_native_bridge_loaded_;
853
854  // Whether we are running under native debugger.
855  bool is_native_debuggable_;
856
857  // The maximum number of failed boots we allow before pruning the dalvik cache
858  // and trying again. This option is only inspected when we're running as a
859  // zygote.
860  uint32_t zygote_max_failed_boots_;
861
862  // Enable experimental opcodes that aren't fully specified yet. The intent is to
863  // eventually publish them as public-usable opcodes, but they aren't ready yet.
864  //
865  // Experimental opcodes should not be used by other production code.
866  ExperimentalFlags experimental_flags_;
867
868  // Contains the build fingerprint, if given as a parameter.
869  std::string fingerprint_;
870
871  // Oat file manager, keeps track of what oat files are open.
872  OatFileManager* oat_file_manager_;
873
874  // Whether or not we are on a low RAM device.
875  bool is_low_memory_mode_;
876
877  // Whether the application should run in safe mode, that is, interpreter only.
878  bool safe_mode_;
879
880  // Whether threads should dump their native stack on SIGQUIT.
881  bool dump_native_stack_on_sig_quit_;
882
883  // Whether the dalvik cache was pruned when initializing the runtime.
884  bool pruned_dalvik_cache_;
885
886  // Whether or not we currently care about pause times.
887  ProcessState process_state_;
888
889  // Whether zygote code is in a section that should not start threads.
890  bool zygote_no_threads_;
891
892  // Saved environment.
893  class EnvSnapshot {
894   public:
895    EnvSnapshot() = default;
896    void TakeSnapshot();
897    char** GetSnapshot() const;
898
899   private:
900    std::unique_ptr<char*[]> c_env_vector_;
901    std::vector<std::unique_ptr<std::string>> name_value_pairs_;
902
903    DISALLOW_COPY_AND_ASSIGN(EnvSnapshot);
904  } env_snapshot_;
905
906  // Generic system-weak holders.
907  std::vector<gc::AbstractSystemWeakHolder*> system_weak_holders_;
908
909  DISALLOW_COPY_AND_ASSIGN(Runtime);
910};
911std::ostream& operator<<(std::ostream& os, const Runtime::CalleeSaveType& rhs);
912
913}  // namespace art
914
915#endif  // ART_RUNTIME_RUNTIME_H_
916