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