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