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