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