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