runtime.h revision b363f666883860d40823d5528df3c98c897f74f4
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 "compiler_callbacks.h"
30#include "instrumentation.h"
31#include "instruction_set.h"
32#include "jobject_comparator.h"
33#include "object_callbacks.h"
34#include "offsets.h"
35#include "profiler_options.h"
36#include "quick/quick_method_frame_info.h"
37#include "runtime_stats.h"
38#include "safe_map.h"
39
40namespace art {
41
42namespace gc {
43  class Heap;
44}  // namespace gc
45namespace mirror {
46  class ArtMethod;
47  class ClassLoader;
48  class Array;
49  template<class T> class ObjectArray;
50  template<class T> class PrimitiveArray;
51  typedef PrimitiveArray<int8_t> ByteArray;
52  class String;
53  class Throwable;
54}  // namespace mirror
55namespace verifier {
56class MethodVerifier;
57}
58class ClassLinker;
59class DexFile;
60class InternTable;
61class JavaVMExt;
62class MonitorList;
63class MonitorPool;
64class NullPointerHandler;
65class SignalCatcher;
66class StackOverflowHandler;
67class SuspensionHandler;
68class ThreadList;
69class Trace;
70class Transaction;
71
72typedef std::vector<std::pair<std::string, const void*>> RuntimeOptions;
73
74// Not all combinations of flags are valid. You may not visit all roots as well as the new roots
75// (no logical reason to do this). You also may not start logging new roots and stop logging new
76// roots (also no logical reason to do this).
77enum VisitRootFlags : uint8_t {
78  kVisitRootFlagAllRoots = 0x1,
79  kVisitRootFlagNewRoots = 0x2,
80  kVisitRootFlagStartLoggingNewRoots = 0x4,
81  kVisitRootFlagStopLoggingNewRoots = 0x8,
82  kVisitRootFlagClearRootLog = 0x10,
83};
84
85class Runtime {
86 public:
87  // Creates and initializes a new runtime.
88  static bool Create(const RuntimeOptions& options, bool ignore_unrecognized)
89      SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_);
90
91  bool IsCompiler() const {
92    return compiler_callbacks_ != nullptr;
93  }
94
95  bool CanRelocate() const {
96    return !IsCompiler() || compiler_callbacks_->IsRelocationPossible();
97  }
98
99  bool ShouldRelocate() const {
100    return must_relocate_ && CanRelocate();
101  }
102
103  bool MustRelocateIfPossible() const {
104    return must_relocate_;
105  }
106
107  CompilerCallbacks* GetCompilerCallbacks() {
108    return compiler_callbacks_;
109  }
110
111  bool IsZygote() const {
112    return is_zygote_;
113  }
114
115  bool IsExplicitGcDisabled() const {
116    return is_explicit_gc_disabled_;
117  }
118
119  std::string GetCompilerExecutable() const;
120  std::string GetPatchoatExecutable() const;
121
122  const std::vector<std::string>& GetCompilerOptions() const {
123    return compiler_options_;
124  }
125
126  const std::vector<std::string>& GetImageCompilerOptions() const {
127    return image_compiler_options_;
128  }
129
130  const ProfilerOptions& GetProfilerOptions() const {
131    return profiler_options_;
132  }
133
134  // Starts a runtime, which may cause threads to be started and code to run.
135  bool Start() UNLOCK_FUNCTION(Locks::mutator_lock_);
136
137  bool IsShuttingDown(Thread* self);
138  bool IsShuttingDownLocked() const EXCLUSIVE_LOCKS_REQUIRED(Locks::runtime_shutdown_lock_) {
139    return shutting_down_;
140  }
141
142  size_t NumberOfThreadsBeingBorn() const EXCLUSIVE_LOCKS_REQUIRED(Locks::runtime_shutdown_lock_) {
143    return threads_being_born_;
144  }
145
146  void StartThreadBirth() EXCLUSIVE_LOCKS_REQUIRED(Locks::runtime_shutdown_lock_) {
147    threads_being_born_++;
148  }
149
150  void EndThreadBirth() EXCLUSIVE_LOCKS_REQUIRED(Locks::runtime_shutdown_lock_);
151
152  bool IsStarted() const {
153    return started_;
154  }
155
156  bool IsFinishedStarting() const {
157    return finished_starting_;
158  }
159
160  static Runtime* Current() {
161    return instance_;
162  }
163
164  // Aborts semi-cleanly. Used in the implementation of LOG(FATAL), which most
165  // callers should prefer.
166  // This isn't marked ((noreturn)) because then gcc will merge multiple calls
167  // in a single function together. This reduces code size slightly, but means
168  // that the native stack trace we get may point at the wrong call site.
169  static void Abort() LOCKS_EXCLUDED(Locks::abort_lock_);
170
171  // Returns the "main" ThreadGroup, used when attaching user threads.
172  jobject GetMainThreadGroup() const;
173
174  // Returns the "system" ThreadGroup, used when attaching our internal threads.
175  jobject GetSystemThreadGroup() const;
176
177  // Returns the system ClassLoader which represents the CLASSPATH.
178  jobject GetSystemClassLoader() const;
179
180  // Attaches the calling native thread to the runtime.
181  bool AttachCurrentThread(const char* thread_name, bool as_daemon, jobject thread_group,
182                           bool create_peer);
183
184  void CallExitHook(jint status);
185
186  // Detaches the current native thread from the runtime.
187  void DetachCurrentThread() LOCKS_EXCLUDED(Locks::mutator_lock_);
188
189  void DumpForSigQuit(std::ostream& os)
190      EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_);
191  void DumpLockHolders(std::ostream& os);
192
193  ~Runtime();
194
195  const std::string& GetBootClassPathString() const {
196    return boot_class_path_string_;
197  }
198
199  const std::string& GetClassPathString() const {
200    return class_path_string_;
201  }
202
203  ClassLinker* GetClassLinker() const {
204    return class_linker_;
205  }
206
207  size_t GetDefaultStackSize() const {
208    return default_stack_size_;
209  }
210
211  gc::Heap* GetHeap() const {
212    return heap_;
213  }
214
215  InternTable* GetInternTable() const {
216    DCHECK(intern_table_ != NULL);
217    return intern_table_;
218  }
219
220  JavaVMExt* GetJavaVM() const {
221    return java_vm_;
222  }
223
224  size_t GetMaxSpinsBeforeThinkLockInflation() const {
225    return max_spins_before_thin_lock_inflation_;
226  }
227
228  MonitorList* GetMonitorList() const {
229    return monitor_list_;
230  }
231
232  MonitorPool* GetMonitorPool() const {
233    return monitor_pool_;
234  }
235
236  mirror::Throwable* GetPreAllocatedOutOfMemoryError() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
237
238  const std::vector<std::string>& GetProperties() const {
239    return properties_;
240  }
241
242  ThreadList* GetThreadList() const {
243    return thread_list_;
244  }
245
246  static const char* GetVersion() {
247    return "2.1.0";
248  }
249
250  void DisallowNewSystemWeaks() EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_);
251  void AllowNewSystemWeaks() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
252
253  // Visit all the roots. If only_dirty is true then non-dirty roots won't be visited. If
254  // clean_dirty is true then dirty roots will be marked as non-dirty after visiting.
255  void VisitRoots(RootCallback* visitor, void* arg, VisitRootFlags flags = kVisitRootFlagAllRoots)
256      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
257
258  // Visit all of the roots we can do safely do concurrently.
259  void VisitConcurrentRoots(RootCallback* visitor, void* arg,
260                            VisitRootFlags flags = kVisitRootFlagAllRoots)
261      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
262
263  // Visit all of the non thread roots, we can do this with mutators unpaused.
264  void VisitNonThreadRoots(RootCallback* visitor, void* arg)
265      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
266
267  // Visit all other roots which must be done with mutators suspended.
268  void VisitNonConcurrentRoots(RootCallback* visitor, void* arg)
269      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
270
271  // Sweep system weaks, the system weak is deleted if the visitor return nullptr. Otherwise, the
272  // system weak is updated to be the visitor's returned value.
273  void SweepSystemWeaks(IsMarkedCallback* visitor, void* arg)
274      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
275
276  // Constant roots are the roots which never change after the runtime is initialized, they only
277  // need to be visited once per GC cycle.
278  void VisitConstantRoots(RootCallback* callback, void* arg)
279      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
280
281  // Returns a special method that calls into a trampoline for runtime method resolution
282  mirror::ArtMethod* GetResolutionMethod() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
283
284  bool HasResolutionMethod() const {
285    return resolution_method_ != nullptr;
286  }
287
288  void SetResolutionMethod(mirror::ArtMethod* method) {
289    resolution_method_ = method;
290  }
291
292  mirror::ArtMethod* CreateResolutionMethod() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
293
294  // Returns a special method that calls into a trampoline for runtime imt conflicts.
295  mirror::ArtMethod* GetImtConflictMethod() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
296
297  bool HasImtConflictMethod() const {
298    return imt_conflict_method_ != nullptr;
299  }
300
301  void SetImtConflictMethod(mirror::ArtMethod* method) {
302    imt_conflict_method_ = method;
303  }
304
305  mirror::ArtMethod* CreateImtConflictMethod() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
306
307  // Returns an imt with every entry set to conflict, used as default imt for all classes.
308  mirror::ObjectArray<mirror::ArtMethod>* GetDefaultImt()
309      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
310
311  bool HasDefaultImt() const {
312    return default_imt_ != nullptr;
313  }
314
315  void SetDefaultImt(mirror::ObjectArray<mirror::ArtMethod>* imt) {
316    default_imt_ = imt;
317  }
318
319  mirror::ObjectArray<mirror::ArtMethod>* CreateDefaultImt(ClassLinker* cl)
320      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
321
322  // Returns a special method that describes all callee saves being spilled to the stack.
323  enum CalleeSaveType {
324    kSaveAll,
325    kRefsOnly,
326    kRefsAndArgs,
327    kLastCalleeSaveType  // Value used for iteration
328  };
329
330  bool HasCalleeSaveMethod(CalleeSaveType type) const {
331    return callee_save_methods_[type] != NULL;
332  }
333
334  mirror::ArtMethod* GetCalleeSaveMethod(CalleeSaveType type)
335      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
336
337  mirror::ArtMethod* GetCalleeSaveMethodUnchecked(CalleeSaveType type)
338      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
339
340  QuickMethodFrameInfo GetCalleeSaveMethodFrameInfo(CalleeSaveType type) const {
341    return callee_save_method_frame_infos_[type];
342  }
343
344  QuickMethodFrameInfo GetRuntimeMethodFrameInfo(mirror::ArtMethod* method)
345      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
346
347  static size_t GetCalleeSaveMethodOffset(CalleeSaveType type) {
348    return OFFSETOF_MEMBER(Runtime, callee_save_methods_[type]);
349  }
350
351  InstructionSet GetInstructionSet() const {
352    return instruction_set_;
353  }
354
355  void SetInstructionSet(InstructionSet instruction_set);
356
357  void SetCalleeSaveMethod(mirror::ArtMethod* method, CalleeSaveType type);
358
359  mirror::ArtMethod* CreateCalleeSaveMethod(CalleeSaveType type)
360      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
361
362  int32_t GetStat(int kind);
363
364  RuntimeStats* GetStats() {
365    return &stats_;
366  }
367
368  bool HasStatsEnabled() const {
369    return stats_enabled_;
370  }
371
372  void ResetStats(int kinds);
373
374  void SetStatsEnabled(bool new_state);
375
376  void PreZygoteFork();
377  bool InitZygote();
378  void DidForkFromZygote();
379
380  const instrumentation::Instrumentation* GetInstrumentation() const {
381    return &instrumentation_;
382  }
383
384  instrumentation::Instrumentation* GetInstrumentation() {
385    return &instrumentation_;
386  }
387
388  bool UseCompileTimeClassPath() const {
389    return use_compile_time_class_path_;
390  }
391
392  void AddMethodVerifier(verifier::MethodVerifier* verifier) LOCKS_EXCLUDED(method_verifier_lock_);
393  void RemoveMethodVerifier(verifier::MethodVerifier* verifier)
394      LOCKS_EXCLUDED(method_verifier_lock_);
395
396  const std::vector<const DexFile*>& GetCompileTimeClassPath(jobject class_loader);
397  void SetCompileTimeClassPath(jobject class_loader, std::vector<const DexFile*>& class_path);
398
399  void StartProfiler(const char* profile_output_filename);
400  void UpdateProfilerState(int state);
401
402  // Transaction support.
403  bool IsActiveTransaction() const {
404    return preinitialization_transaction_ != nullptr;
405  }
406  void EnterTransactionMode(Transaction* transaction);
407  void ExitTransactionMode();
408  void RecordWriteField32(mirror::Object* obj, MemberOffset field_offset, uint32_t value,
409                          bool is_volatile) const;
410  void RecordWriteField64(mirror::Object* obj, MemberOffset field_offset, uint64_t value,
411                          bool is_volatile) const;
412  void RecordWriteFieldReference(mirror::Object* obj, MemberOffset field_offset,
413                                 mirror::Object* value, bool is_volatile) const;
414  void RecordWriteArray(mirror::Array* array, size_t index, uint64_t value) const
415      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
416  void RecordStrongStringInsertion(mirror::String* s, uint32_t hash_code) const
417      EXCLUSIVE_LOCKS_REQUIRED(Locks::intern_table_lock_);
418  void RecordWeakStringInsertion(mirror::String* s, uint32_t hash_code) const
419      EXCLUSIVE_LOCKS_REQUIRED(Locks::intern_table_lock_);
420  void RecordStrongStringRemoval(mirror::String* s, uint32_t hash_code) const
421      EXCLUSIVE_LOCKS_REQUIRED(Locks::intern_table_lock_);
422  void RecordWeakStringRemoval(mirror::String* s, uint32_t hash_code) const
423      EXCLUSIVE_LOCKS_REQUIRED(Locks::intern_table_lock_);
424
425  void SetFaultMessage(const std::string& message);
426  // Only read by the signal handler, NO_THREAD_SAFETY_ANALYSIS to prevent lock order violations
427  // with the unexpected_signal_lock_.
428  const std::string& GetFaultMessage() NO_THREAD_SAFETY_ANALYSIS {
429    return fault_message_;
430  }
431
432  void AddCurrentRuntimeFeaturesAsDex2OatArguments(std::vector<std::string>* arg_vector) const;
433
434  bool ExplicitNullChecks() const {
435    return null_pointer_handler_ == nullptr;
436  }
437
438  bool ExplicitSuspendChecks() const {
439    return suspend_handler_ == nullptr;
440  }
441
442  bool ExplicitStackOverflowChecks() const {
443    return stack_overflow_handler_ == nullptr;
444  }
445
446  bool IsVerificationEnabled() const {
447    return verify_;
448  }
449
450  bool RunningOnValgrind() const {
451    return running_on_valgrind_;
452  }
453
454  void SetTargetSdkVersion(int32_t version) {
455    target_sdk_version_ = version;
456  }
457
458  int32_t GetTargetSdkVersion() const {
459    return target_sdk_version_;
460  }
461
462  static const char* GetDefaultInstructionSetFeatures() {
463    return kDefaultInstructionSetFeatures;
464  }
465
466 private:
467  static void InitPlatformSignalHandlers();
468
469  Runtime();
470
471  void BlockSignals();
472
473  bool Init(const RuntimeOptions& options, bool ignore_unrecognized)
474      SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_);
475  void InitNativeMethods() LOCKS_EXCLUDED(Locks::mutator_lock_);
476  void InitThreadGroups(Thread* self);
477  void RegisterRuntimeNativeMethods(JNIEnv* env);
478
479  void StartDaemonThreads();
480  void StartSignalCatcher();
481
482  // A pointer to the active runtime or NULL.
483  static Runtime* instance_;
484
485  static const char* kDefaultInstructionSetFeatures;
486
487  // NOTE: these must match the gc::ProcessState values as they come directly from the framework.
488  static constexpr int kProfileForground = 0;
489  static constexpr int kProfileBackgrouud = 1;
490
491  mirror::ArtMethod* callee_save_methods_[kLastCalleeSaveType];
492  mirror::Throwable* pre_allocated_OutOfMemoryError_;
493  mirror::ArtMethod* resolution_method_;
494  mirror::ArtMethod* imt_conflict_method_;
495  mirror::ObjectArray<mirror::ArtMethod>* default_imt_;
496
497  InstructionSet instruction_set_;
498  QuickMethodFrameInfo callee_save_method_frame_infos_[kLastCalleeSaveType];
499
500  CompilerCallbacks* compiler_callbacks_;
501  bool is_zygote_;
502  bool must_relocate_;
503  bool is_concurrent_gc_enabled_;
504  bool is_explicit_gc_disabled_;
505
506  std::string compiler_executable_;
507  std::string patchoat_executable_;
508  std::vector<std::string> compiler_options_;
509  std::vector<std::string> image_compiler_options_;
510
511  std::string boot_class_path_string_;
512  std::string class_path_string_;
513  std::vector<std::string> properties_;
514
515  // The default stack size for managed threads created by the runtime.
516  size_t default_stack_size_;
517
518  gc::Heap* heap_;
519
520  // The number of spins that are done before thread suspension is used to forcibly inflate.
521  size_t max_spins_before_thin_lock_inflation_;
522  MonitorList* monitor_list_;
523  MonitorPool* monitor_pool_;
524
525  ThreadList* thread_list_;
526
527  InternTable* intern_table_;
528
529  ClassLinker* class_linker_;
530
531  SignalCatcher* signal_catcher_;
532  std::string stack_trace_file_;
533
534  JavaVMExt* java_vm_;
535
536  // Fault message, printed when we get a SIGSEGV.
537  Mutex fault_message_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
538  std::string fault_message_ GUARDED_BY(fault_message_lock_);
539
540  // Method verifier set, used so that we can update their GC roots.
541  Mutex method_verifier_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
542  std::set<verifier::MethodVerifier*> method_verifiers_;
543
544  // A non-zero value indicates that a thread has been created but not yet initialized. Guarded by
545  // the shutdown lock so that threads aren't born while we're shutting down.
546  size_t threads_being_born_ GUARDED_BY(Locks::runtime_shutdown_lock_);
547
548  // Waited upon until no threads are being born.
549  std::unique_ptr<ConditionVariable> shutdown_cond_ GUARDED_BY(Locks::runtime_shutdown_lock_);
550
551  // Set when runtime shutdown is past the point that new threads may attach.
552  bool shutting_down_ GUARDED_BY(Locks::runtime_shutdown_lock_);
553
554  // The runtime is starting to shutdown but is blocked waiting on shutdown_cond_.
555  bool shutting_down_started_ GUARDED_BY(Locks::runtime_shutdown_lock_);
556
557  bool started_;
558
559  // New flag added which tells us if the runtime has finished starting. If
560  // this flag is set then the Daemon threads are created and the class loader
561  // is created. This flag is needed for knowing if its safe to request CMS.
562  bool finished_starting_;
563
564  // Hooks supported by JNI_CreateJavaVM
565  jint (*vfprintf_)(FILE* stream, const char* format, va_list ap);
566  void (*exit_)(jint status);
567  void (*abort_)();
568
569  bool stats_enabled_;
570  RuntimeStats stats_;
571
572  const bool running_on_valgrind_;
573
574  std::string profile_output_filename_;
575  ProfilerOptions profiler_options_;
576  bool profiler_started_;
577
578  bool method_trace_;
579  std::string method_trace_file_;
580  size_t method_trace_file_size_;
581  instrumentation::Instrumentation instrumentation_;
582
583  typedef SafeMap<jobject, std::vector<const DexFile*>, JobjectComparator> CompileTimeClassPaths;
584  CompileTimeClassPaths compile_time_class_paths_;
585  bool use_compile_time_class_path_;
586
587  jobject main_thread_group_;
588  jobject system_thread_group_;
589
590  // As returned by ClassLoader.getSystemClassLoader().
591  jobject system_class_loader_;
592
593  // If true, then we dump the GC cumulative timings on shutdown.
594  bool dump_gc_performance_on_shutdown_;
595
596  // Transaction used for pre-initializing classes at compilation time.
597  Transaction* preinitialization_transaction_;
598  NullPointerHandler* null_pointer_handler_;
599  SuspensionHandler* suspend_handler_;
600  StackOverflowHandler* stack_overflow_handler_;
601
602  // If false, verification is disabled. True by default.
603  bool verify_;
604
605  // Specifies target SDK version to allow workarounds for certain API levels.
606  int32_t target_sdk_version_;
607
608  // Implicit checks flags.
609  bool implicit_null_checks_;       // NullPointer checks are implicit.
610  bool implicit_so_checks_;         // StackOverflow checks are implicit.
611  bool implicit_suspend_checks_;    // Thread suspension checks are implicit.
612
613  DISALLOW_COPY_AND_ASSIGN(Runtime);
614};
615
616}  // namespace art
617
618#endif  // ART_RUNTIME_RUNTIME_H_
619