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