runtime.h revision 2775ee4f82dff260663ca16adddc0b15327aaa42
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/heap.h"
31#include "globals.h"
32#include "instruction_set.h"
33#include "instrumentation.h"
34#include "jobject_comparator.h"
35#include "locks.h"
36#include "root_visitor.h"
37#include "runtime_stats.h"
38#include "safe_map.h"
39
40namespace art {
41
42namespace gc {
43  class Heap;
44}
45namespace mirror {
46  class ArtMethod;
47  class ClassLoader;
48  template<class T> class PrimitiveArray;
49  typedef PrimitiveArray<int8_t> ByteArray;
50  class String;
51  class Throwable;
52}  // namespace mirror
53class ClassLinker;
54class DexFile;
55class InternTable;
56struct JavaVMExt;
57class MonitorList;
58class SignalCatcher;
59class ThreadList;
60class Trace;
61
62class Runtime {
63 public:
64  typedef std::vector<std::pair<std::string, const void*> > Options;
65
66  enum CompilerFilter {
67    kInterpretOnly,       // Compile nothing.
68    kDeferCompilation,    // Temporary minimal compilation, will redo during device idle time.
69    kSpace,               // Maximize space savings.
70    kBalanced,            // Try to get the best performance return on compilation investment.
71    kSpeed                // Compile all methods.
72  };
73
74  // Guide heuristics to determine whether to compile method if profile data not available.
75#if ART_SMALL_MODE
76  static const CompilerFilter kDefaultCompilerFilter = kInterpretOnly;
77#else
78  static const CompilerFilter kDefaultCompilerFilter = kSpeed;
79#endif
80  static const size_t kDefaultHugeMethodThreshold = 6000;
81  static const size_t kDefaultLargeMethodThreshold = 1000;
82  static const size_t kDefaultSmallMethodThreshold = 200;
83  static const size_t kDefaultTinyMethodThreshold = 10;
84  static const size_t kDefaultNumDexMethodsThreshold = 900;
85
86  class ParsedOptions {
87   public:
88    // returns null if problem parsing and ignore_unrecognized is false
89    static ParsedOptions* Create(const Options& options, bool ignore_unrecognized);
90
91    const std::vector<const DexFile*>* boot_class_path_;
92    std::string boot_class_path_string_;
93    std::string class_path_string_;
94    std::string host_prefix_;
95    std::string image_;
96    bool check_jni_;
97    std::string jni_trace_;
98    bool is_compiler_;
99    bool is_zygote_;
100    bool interpreter_only_;
101    bool is_concurrent_gc_enabled_;
102    bool is_explicit_gc_disabled_;
103    size_t long_pause_log_threshold_;
104    size_t long_gc_log_threshold_;
105    bool ignore_max_footprint_;
106    size_t heap_initial_size_;
107    size_t heap_maximum_size_;
108    size_t heap_growth_limit_;
109    size_t heap_min_free_;
110    size_t heap_max_free_;
111    double heap_target_utilization_;
112    size_t parallel_gc_threads_;
113    size_t conc_gc_threads_;
114    size_t stack_size_;
115    bool low_memory_mode_;
116    size_t lock_profiling_threshold_;
117    std::string stack_trace_file_;
118    bool method_trace_;
119    std::string method_trace_file_;
120    size_t method_trace_file_size_;
121    bool (*hook_is_sensitive_thread_)();
122    jint (*hook_vfprintf_)(FILE* stream, const char* format, va_list ap);
123    void (*hook_exit_)(jint status);
124    void (*hook_abort_)();
125    std::vector<std::string> properties_;
126    CompilerFilter compiler_filter_;
127    size_t huge_method_threshold_;
128    size_t large_method_threshold_;
129    size_t small_method_threshold_;
130    size_t tiny_method_threshold_;
131    size_t num_dex_methods_threshold_;
132    bool sea_ir_mode_;
133
134   private:
135    ParsedOptions() {}
136  };
137
138  // Creates and initializes a new runtime.
139  static bool Create(const Options& options, bool ignore_unrecognized)
140      SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_);
141
142  bool IsCompiler() const {
143    return is_compiler_;
144  }
145
146  bool IsZygote() const {
147    return is_zygote_;
148  }
149
150  bool IsConcurrentGcEnabled() const {
151    return is_concurrent_gc_enabled_;
152  }
153
154  bool IsExplicitGcDisabled() const {
155    return is_explicit_gc_disabled_;
156  }
157
158#ifdef ART_SEA_IR_MODE
159  bool IsSeaIRMode() const {
160    return sea_ir_mode_;
161  }
162#endif
163
164  void SetSeaIRMode(bool sea_ir_mode) {
165    sea_ir_mode_ = sea_ir_mode;
166  }
167
168  CompilerFilter GetCompilerFilter() const {
169    return compiler_filter_;
170  }
171
172  void SetCompilerFilter(CompilerFilter compiler_filter) {
173    compiler_filter_ = compiler_filter;
174  }
175
176  size_t GetHugeMethodThreshold() const {
177    return huge_method_threshold_;
178  }
179
180  size_t GetLargeMethodThreshold() const {
181    return large_method_threshold_;
182  }
183
184  size_t GetSmallMethodThreshold() const {
185    return small_method_threshold_;
186  }
187
188  size_t GetTinyMethodThreshold() const {
189    return tiny_method_threshold_;
190  }
191
192  size_t GetNumDexMethodsThreshold() const {
193      return num_dex_methods_threshold_;
194  }
195
196  const std::string& GetHostPrefix() const {
197    DCHECK(!IsStarted());
198    return host_prefix_;
199  }
200
201  // Starts a runtime, which may cause threads to be started and code to run.
202  bool Start() UNLOCK_FUNCTION(Locks::mutator_lock_);
203
204  bool IsShuttingDown() const EXCLUSIVE_LOCKS_REQUIRED(Locks::runtime_shutdown_lock_) {
205    return shutting_down_;
206  }
207
208  size_t NumberOfThreadsBeingBorn() const EXCLUSIVE_LOCKS_REQUIRED(Locks::runtime_shutdown_lock_) {
209    return threads_being_born_;
210  }
211
212  void StartThreadBirth() EXCLUSIVE_LOCKS_REQUIRED(Locks::runtime_shutdown_lock_) {
213    threads_being_born_++;
214  }
215
216  void EndThreadBirth() EXCLUSIVE_LOCKS_REQUIRED(Locks::runtime_shutdown_lock_);
217
218  bool IsStarted() const {
219    return started_;
220  }
221
222  bool IsFinishedStarting() const {
223    return finished_starting_;
224  }
225
226  static Runtime* Current() {
227    return instance_;
228  }
229
230  // Aborts semi-cleanly. Used in the implementation of LOG(FATAL), which most
231  // callers should prefer.
232  // This isn't marked ((noreturn)) because then gcc will merge multiple calls
233  // in a single function together. This reduces code size slightly, but means
234  // that the native stack trace we get may point at the wrong call site.
235  static void Abort() LOCKS_EXCLUDED(Locks::abort_lock_);
236
237  // Returns the "main" ThreadGroup, used when attaching user threads.
238  jobject GetMainThreadGroup() const;
239
240  // Returns the "system" ThreadGroup, used when attaching our internal threads.
241  jobject GetSystemThreadGroup() const;
242
243  // Attaches the calling native thread to the runtime.
244  bool AttachCurrentThread(const char* thread_name, bool as_daemon, jobject thread_group,
245                           bool create_peer);
246
247  void CallExitHook(jint status);
248
249  // Detaches the current native thread from the runtime.
250  void DetachCurrentThread() LOCKS_EXCLUDED(Locks::mutator_lock_);
251
252  void DumpForSigQuit(std::ostream& os)
253      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
254  void DumpLockHolders(std::ostream& os);
255
256  ~Runtime();
257
258  const std::string& GetBootClassPathString() const {
259    return boot_class_path_string_;
260  }
261
262  const std::string& GetClassPathString() const {
263    return class_path_string_;
264  }
265
266  ClassLinker* GetClassLinker() const {
267    return class_linker_;
268  }
269
270  size_t GetDefaultStackSize() const {
271    return default_stack_size_;
272  }
273
274  gc::Heap* GetHeap() const {
275    return heap_;
276  }
277
278  InternTable* GetInternTable() const {
279    return intern_table_;
280  }
281
282  JavaVMExt* GetJavaVM() const {
283    return java_vm_;
284  }
285
286  MonitorList* GetMonitorList() const {
287    return monitor_list_;
288  }
289
290  mirror::Throwable* GetPreAllocatedOutOfMemoryError() {
291    return pre_allocated_OutOfMemoryError_;
292  }
293
294  const std::vector<std::string>& GetProperties() const {
295    return properties_;
296  }
297
298  ThreadList* GetThreadList() const {
299    return thread_list_;
300  }
301
302  const char* GetVersion() const {
303    return "2.0.0";
304  }
305
306  // Visit all the roots. If only_dirty is true then non-dirty roots won't be visited. If
307  // clean_dirty is true then dirty roots will be marked as non-dirty after visiting.
308  void VisitRoots(RootVisitor* visitor, void* arg, bool only_dirty, bool clean_dirty)
309      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
310
311  // Visit all of the roots we can do safely do concurrently.
312  void VisitConcurrentRoots(RootVisitor* visitor, void* arg, bool only_dirty, bool clean_dirty);
313
314  // Visit all of the non thread roots, we can do this with mutators unpaused.
315  void VisitNonThreadRoots(RootVisitor* visitor, void* arg);
316
317  // Visit all other roots which must be done with mutators suspended.
318  void VisitNonConcurrentRoots(RootVisitor* visitor, void* arg)
319    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
320
321  // Returns a special method that calls into a trampoline for runtime method resolution
322  mirror::ArtMethod* GetResolutionMethod() const {
323    CHECK(HasResolutionMethod());
324    return resolution_method_;
325  }
326
327  bool HasResolutionMethod() const {
328    return resolution_method_ != NULL;
329  }
330
331  void SetResolutionMethod(mirror::ArtMethod* method) {
332    resolution_method_ = method;
333  }
334
335  mirror::ArtMethod* CreateResolutionMethod() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
336
337  // Returns a special method that describes all callee saves being spilled to the stack.
338  enum CalleeSaveType {
339    kSaveAll,
340    kRefsOnly,
341    kRefsAndArgs,
342    kLastCalleeSaveType  // Value used for iteration
343  };
344
345  bool HasCalleeSaveMethod(CalleeSaveType type) const {
346    return callee_save_methods_[type] != NULL;
347  }
348
349  mirror::ArtMethod* GetCalleeSaveMethod(CalleeSaveType type) const {
350    DCHECK(HasCalleeSaveMethod(type));
351    return callee_save_methods_[type];
352  }
353
354  void SetCalleeSaveMethod(mirror::ArtMethod* method, CalleeSaveType type);
355
356  mirror::ArtMethod* CreateCalleeSaveMethod(InstructionSet instruction_set,
357                                                 CalleeSaveType type)
358      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
359
360  mirror::ArtMethod* CreateRefOnlyCalleeSaveMethod(InstructionSet instruction_set)
361      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
362
363  mirror::ArtMethod* CreateRefAndArgsCalleeSaveMethod(InstructionSet instruction_set)
364      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
365
366  int32_t GetStat(int kind);
367
368  RuntimeStats* GetStats() {
369    return &stats_;
370  }
371
372  bool HasStatsEnabled() const {
373    return stats_enabled_;
374  }
375
376  void ResetStats(int kinds);
377
378  void SetStatsEnabled(bool new_state);
379
380  bool PreZygoteFork();
381  bool InitZygote();
382  void DidForkFromZygote();
383
384  instrumentation::Instrumentation* GetInstrumentation() {
385    return &instrumentation_;
386  }
387
388  bool UseCompileTimeClassPath() const {
389    return use_compile_time_class_path_;
390  }
391
392  const std::vector<const DexFile*>& GetCompileTimeClassPath(jobject class_loader);
393  void SetCompileTimeClassPath(jobject class_loader, std::vector<const DexFile*>& class_path);
394
395 private:
396  static void InitPlatformSignalHandlers();
397
398  Runtime();
399
400  void BlockSignals();
401
402  bool Init(const Options& options, bool ignore_unrecognized)
403      SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_);
404  void InitNativeMethods() LOCKS_EXCLUDED(Locks::mutator_lock_);
405  void InitThreadGroups(Thread* self);
406  void RegisterRuntimeNativeMethods(JNIEnv* env);
407
408  void StartDaemonThreads();
409  void StartSignalCatcher();
410
411  // A pointer to the active runtime or NULL.
412  static Runtime* instance_;
413
414  bool is_compiler_;
415  bool is_zygote_;
416  bool is_concurrent_gc_enabled_;
417  bool is_explicit_gc_disabled_;
418
419  CompilerFilter compiler_filter_;
420  size_t huge_method_threshold_;
421  size_t large_method_threshold_;
422  size_t small_method_threshold_;
423  size_t tiny_method_threshold_;
424  size_t num_dex_methods_threshold_;
425
426  bool sea_ir_mode_;
427
428  // The host prefix is used during cross compilation. It is removed
429  // from the start of host paths such as:
430  //    $ANDROID_PRODUCT_OUT/system/framework/boot.oat
431  // to produce target paths such as
432  //    /system/framework/boot.oat
433  // Similarly it is prepended to target paths to arrive back at a
434  // host past. In both cases this is necessary because image and oat
435  // files embedded expect paths of dependent files (an image points
436  // to an oat file and an oat files to one or more dex files). These
437  // files contain the expected target path.
438  std::string host_prefix_;
439
440  std::string boot_class_path_string_;
441  std::string class_path_string_;
442  std::vector<std::string> properties_;
443
444  // The default stack size for managed threads created by the runtime.
445  size_t default_stack_size_;
446
447  gc::Heap* heap_;
448
449  MonitorList* monitor_list_;
450
451  ThreadList* thread_list_;
452
453  InternTable* intern_table_;
454
455  ClassLinker* class_linker_;
456
457  SignalCatcher* signal_catcher_;
458  std::string stack_trace_file_;
459
460  JavaVMExt* java_vm_;
461
462  mirror::Throwable* pre_allocated_OutOfMemoryError_;
463
464  mirror::ArtMethod* callee_save_methods_[kLastCalleeSaveType];
465
466  mirror::ArtMethod* resolution_method_;
467
468  // As returned by ClassLoader.getSystemClassLoader()
469  mirror::ClassLoader* system_class_loader_;
470
471  // A non-zero value indicates that a thread has been created but not yet initialized. Guarded by
472  // the shutdown lock so that threads aren't born while we're shutting down.
473  size_t threads_being_born_ GUARDED_BY(Locks::runtime_shutdown_lock_);
474
475  // Waited upon until no threads are being born.
476  UniquePtr<ConditionVariable> shutdown_cond_ GUARDED_BY(Locks::runtime_shutdown_lock_);
477
478  // Set when runtime shutdown is past the point that new threads may attach.
479  bool shutting_down_ GUARDED_BY(Locks::runtime_shutdown_lock_);
480
481  // The runtime is starting to shutdown but is blocked waiting on shutdown_cond_.
482  bool shutting_down_started_ GUARDED_BY(Locks::runtime_shutdown_lock_);
483
484  bool started_;
485
486  // New flag added which tells us if the runtime has finished starting. If
487  // this flag is set then the Daemon threads are created and the class loader
488  // is created. This flag is needed for knowing if its safe to request CMS.
489  bool finished_starting_;
490
491  // Hooks supported by JNI_CreateJavaVM
492  jint (*vfprintf_)(FILE* stream, const char* format, va_list ap);
493  void (*exit_)(jint status);
494  void (*abort_)();
495
496  bool stats_enabled_;
497  RuntimeStats stats_;
498
499  bool method_trace_;
500  std::string method_trace_file_;
501  size_t method_trace_file_size_;
502  instrumentation::Instrumentation instrumentation_;
503
504  typedef SafeMap<jobject, std::vector<const DexFile*>, JobjectComparator> CompileTimeClassPaths;
505  CompileTimeClassPaths compile_time_class_paths_;
506  bool use_compile_time_class_path_;
507
508  jobject main_thread_group_;
509  jobject system_thread_group_;
510
511  DISALLOW_COPY_AND_ASSIGN(Runtime);
512};
513
514}  // namespace art
515
516#endif  // ART_RUNTIME_RUNTIME_H_
517