runtime.h revision c11d9b8870de5f860b13c84003ade7b3f3125a52
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 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() const
291    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
292
293  const std::vector<std::string>& GetProperties() const {
294    return properties_;
295  }
296
297  ThreadList* GetThreadList() const {
298    return thread_list_;
299  }
300
301  const char* GetVersion() const {
302    return "2.0.0";
303  }
304
305  void DisallowNewSystemWeaks() EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_);
306  void AllowNewSystemWeaks() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
307
308  // Visit all the roots. If only_dirty is true then non-dirty roots won't be visited. If
309  // clean_dirty is true then dirty roots will be marked as non-dirty after visiting.
310  void VisitRoots(RootVisitor* visitor, void* arg, bool only_dirty, bool clean_dirty)
311      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
312
313  // Visit all of the roots we can do safely do concurrently.
314  void VisitConcurrentRoots(RootVisitor* visitor, void* arg, bool only_dirty, bool clean_dirty);
315
316  // Visit all of the non thread roots, we can do this with mutators unpaused.
317  void VisitNonThreadRoots(RootVisitor* visitor, void* arg);
318
319  // Visit all other roots which must be done with mutators suspended.
320  void VisitNonConcurrentRoots(RootVisitor* visitor, void* arg)
321    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
322
323  // Returns a special method that calls into a trampoline for runtime method resolution
324  mirror::ArtMethod* GetResolutionMethod() const {
325    CHECK(HasResolutionMethod());
326    return resolution_method_;
327  }
328
329  bool HasResolutionMethod() const {
330    return resolution_method_ != NULL;
331  }
332
333  void SetResolutionMethod(mirror::ArtMethod* method) {
334    resolution_method_ = method;
335  }
336
337  mirror::ArtMethod* CreateResolutionMethod() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
338
339  // Returns a special method that describes all callee saves being spilled to the stack.
340  enum CalleeSaveType {
341    kSaveAll,
342    kRefsOnly,
343    kRefsAndArgs,
344    kLastCalleeSaveType  // Value used for iteration
345  };
346
347  bool HasCalleeSaveMethod(CalleeSaveType type) const {
348    return callee_save_methods_[type] != NULL;
349  }
350
351  mirror::ArtMethod* GetCalleeSaveMethod(CalleeSaveType type) const {
352    DCHECK(HasCalleeSaveMethod(type));
353    return callee_save_methods_[type];
354  }
355
356  void SetCalleeSaveMethod(mirror::ArtMethod* method, CalleeSaveType type);
357
358  mirror::ArtMethod* CreateCalleeSaveMethod(InstructionSet instruction_set,
359                                                 CalleeSaveType type)
360      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
361
362  mirror::ArtMethod* CreateRefOnlyCalleeSaveMethod(InstructionSet instruction_set)
363      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
364
365  mirror::ArtMethod* CreateRefAndArgsCalleeSaveMethod(InstructionSet instruction_set)
366      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
367
368  int32_t GetStat(int kind);
369
370  RuntimeStats* GetStats() {
371    return &stats_;
372  }
373
374  bool HasStatsEnabled() const {
375    return stats_enabled_;
376  }
377
378  void ResetStats(int kinds);
379
380  void SetStatsEnabled(bool new_state);
381
382  bool PreZygoteFork();
383  bool InitZygote();
384  void DidForkFromZygote();
385
386  instrumentation::Instrumentation* GetInstrumentation() {
387    return &instrumentation_;
388  }
389
390  bool UseCompileTimeClassPath() const {
391    return use_compile_time_class_path_;
392  }
393
394  const std::vector<const DexFile*>& GetCompileTimeClassPath(jobject class_loader);
395  void SetCompileTimeClassPath(jobject class_loader, std::vector<const DexFile*>& class_path);
396
397 private:
398  static void InitPlatformSignalHandlers();
399
400  Runtime();
401
402  void BlockSignals();
403
404  bool Init(const Options& options, bool ignore_unrecognized)
405      SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_);
406  void InitNativeMethods() LOCKS_EXCLUDED(Locks::mutator_lock_);
407  void InitThreadGroups(Thread* self);
408  void RegisterRuntimeNativeMethods(JNIEnv* env);
409
410  void StartDaemonThreads();
411  void StartSignalCatcher();
412
413  // A pointer to the active runtime or NULL.
414  static Runtime* instance_;
415
416  bool is_compiler_;
417  bool is_zygote_;
418  bool is_concurrent_gc_enabled_;
419  bool is_explicit_gc_disabled_;
420
421  CompilerFilter compiler_filter_;
422  size_t huge_method_threshold_;
423  size_t large_method_threshold_;
424  size_t small_method_threshold_;
425  size_t tiny_method_threshold_;
426  size_t num_dex_methods_threshold_;
427
428  bool sea_ir_mode_;
429
430  // The host prefix is used during cross compilation. It is removed
431  // from the start of host paths such as:
432  //    $ANDROID_PRODUCT_OUT/system/framework/boot.oat
433  // to produce target paths such as
434  //    /system/framework/boot.oat
435  // Similarly it is prepended to target paths to arrive back at a
436  // host past. In both cases this is necessary because image and oat
437  // files embedded expect paths of dependent files (an image points
438  // to an oat file and an oat files to one or more dex files). These
439  // files contain the expected target path.
440  std::string host_prefix_;
441
442  std::string boot_class_path_string_;
443  std::string class_path_string_;
444  std::vector<std::string> properties_;
445
446  // The default stack size for managed threads created by the runtime.
447  size_t default_stack_size_;
448
449  gc::Heap* heap_;
450
451  MonitorList* monitor_list_;
452
453  ThreadList* thread_list_;
454
455  InternTable* intern_table_;
456
457  ClassLinker* class_linker_;
458
459  SignalCatcher* signal_catcher_;
460  std::string stack_trace_file_;
461
462  JavaVMExt* java_vm_;
463
464  mirror::Throwable* pre_allocated_OutOfMemoryError_;
465
466  mirror::ArtMethod* callee_save_methods_[kLastCalleeSaveType];
467
468  mirror::ArtMethod* resolution_method_;
469
470  // As returned by ClassLoader.getSystemClassLoader()
471  mirror::ClassLoader* system_class_loader_;
472
473  // A non-zero value indicates that a thread has been created but not yet initialized. Guarded by
474  // the shutdown lock so that threads aren't born while we're shutting down.
475  size_t threads_being_born_ GUARDED_BY(Locks::runtime_shutdown_lock_);
476
477  // Waited upon until no threads are being born.
478  UniquePtr<ConditionVariable> shutdown_cond_ GUARDED_BY(Locks::runtime_shutdown_lock_);
479
480  // Set when runtime shutdown is past the point that new threads may attach.
481  bool shutting_down_ GUARDED_BY(Locks::runtime_shutdown_lock_);
482
483  // The runtime is starting to shutdown but is blocked waiting on shutdown_cond_.
484  bool shutting_down_started_ GUARDED_BY(Locks::runtime_shutdown_lock_);
485
486  bool started_;
487
488  // New flag added which tells us if the runtime has finished starting. If
489  // this flag is set then the Daemon threads are created and the class loader
490  // is created. This flag is needed for knowing if its safe to request CMS.
491  bool finished_starting_;
492
493  // Hooks supported by JNI_CreateJavaVM
494  jint (*vfprintf_)(FILE* stream, const char* format, va_list ap);
495  void (*exit_)(jint status);
496  void (*abort_)();
497
498  bool stats_enabled_;
499  RuntimeStats stats_;
500
501  bool method_trace_;
502  std::string method_trace_file_;
503  size_t method_trace_file_size_;
504  instrumentation::Instrumentation instrumentation_;
505
506  typedef SafeMap<jobject, std::vector<const DexFile*>, JobjectComparator> CompileTimeClassPaths;
507  CompileTimeClassPaths compile_time_class_paths_;
508  bool use_compile_time_class_path_;
509
510  jobject main_thread_group_;
511  jobject system_thread_group_;
512
513  DISALLOW_COPY_AND_ASSIGN(Runtime);
514};
515
516}  // namespace art
517
518#endif  // ART_RUNTIME_RUNTIME_H_
519