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